Sporadic timeouts from directline endpoint

236 views Asked by At

We have deployed a simple Echobot using the Azure template when creating a Web App Bot.

It is currently live at this url: http://18.194.88.194/echobot/

We often experience the following timeout error (about 40% of the time)

WebSocket connection to 'wss://directline.botframework.com/v3/directline/conversations/EH9EbbBIasz8o90sZSeAwT-9/stream?watermark=-&t=ew0KICAiYWxnIj...(snip) failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT

Here is our client code: botclient.js

(async function() {
  let {token, conversationId} = sessionStorage;

  const delay = 1800000;
  //const delay = 20000;
  const currentTime = new Date();
  const currentTimeUnix = currentTime.getTime();

  if (
    sessionStorage['startTime'] &&
    currentTimeUnix - sessionStorage['startTime'] > delay
  ) {
    sessionStorage.removeItem('token');
    token = sessionStorage['token'];
  }

  const payload = JSON.stringify({botname: 'echobot'});

  if (!token) {
    const res = await fetch(
      'https://ox38xh0fx5.execute-api.eu-central-1.amazonaws.com/dev/directline/token',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: payload,
      },
    );
    const {token: directLineToken} = await res.json();
    sessionStorage['token'] = directLineToken;
    token = directLineToken;

    console.log('token', token);
    const startTime = new Date();
    const startTimeUnix = startTime.getTime();
    sessionStorage['startTime'] = startTimeUnix;
  }

  const data = {
    // from: user,
    name: 'requestWelcomeDialog',
    type: 'event',
    value: {
      url: window.location.href,
    },
  };

  var botConnection = new window.WebChat.createDirectLine({token});

  window.WebChat.renderWebChat(
    {
      directLine: botConnection,
      userID: 'YOUR_USER_ID',
      username: 'Web Chat User',
      locale: 'en-US',
    },
    document.getElementById('webchat'),
  );
})().catch(err => console.log(err));

index.html

<!DOCTYPE html>
<html>
   <head>
      <script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
      <style>
         html,
         body {
            height: 100%;
         }

         body {
            margin: 0;
         }

         #webchat {
            height: 100%;
            width: 100%;
         }
      </style>
   </head>
   <body>
      <div id="webchat" role="main"></div>
      <script src="botclient.js">
      </script>
   </body>
</html>

The token is being retrieved from an AWS lambda function with the following code:

import json
import boto3
from urllib.parse import urlencode
from urllib.request import Request, urlopen


BOT_SECRET = 'defaultSecret'


URL = 'https://directline.botframework.com/v3/directline/tokens/generate'
POST_FIELDS = {'foo': 'bar'}


def set_headers(req, secret):
    req.add_header('Content-Type', 'application/json')
    req.add_header('Authorization', f'Bearer {secret}')
    return req


def lambda_handler(event, context):
    print(event)
    s3 = boto3.client('s3')

    if event.get('botname', None) == 'echobot':
        response = s3.get_object(Bucket='directline', Key='echobotSecret')
    else:
        response = s3.get_object(Bucket='directline', Key=BOT_SECRET)
    secret = response['Body'].read().decode('utf-8').rstrip()
    request = Request(URL, urlencode(POST_FIELDS).encode())
    request = set_headers(request, secret)
    jsonresponse = urlopen(request).read()

    print(jsonresponse)
    return jsonresponse

We suspect that there is an issue with the local network configuration, and packets are being dropped. Are there any pointers for how to handle this?

1

There are 1 answers

0
mdrichardson On BEST ANSWER

I looked into our backend logs for the conversation ID you included and it looks like the token needs to be refreshed. See the Authentication docs for refreshing tokens.

It looks like your code attempts to account for token expiration, but:

  • 1800000 is the default expiration. It might be best to shorten your delay a bit to account for request travel time and other factors to ensure your tokens don't expire.
  • You appear to only get the token once, when the chat window is opened. It may expire mid-conversation

That being said, this may not be a token issue. Can you try disabling websockets with:

[...]
window.WebChat.renderWebChat(
    {
      directLine: botConnection,
      userID: 'YOUR_USER_ID',
      username: 'Web Chat User',
      locale: 'en-US',
      webSocket: false // ADD THIS !!!!
    },
    document.getElementById('webchat'),
[...]


If this is a local packet loss issue, I'm afraid there's not much support I can provide as it's no longer a botframework problem and is likely very specific to your local network. If you can provide additional Conversation IDs, I might be able to dig into this further. But over the last 2 days, your bot appears pretty normal on our side.