来自直线端点的零星超时

Sporadic timeouts from directline endpoint

我们在创建 Web App Bot 时使用 Azure 模板部署了一个简单的 Echobot。

目前在url直播:http://18.194.88.194/echobot/

我们经常遇到以下超时错误(大约 40% 的时间)

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

这是我们的客户端代码: 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>

正在使用以下代码从 AWS lambda 函数检索令牌:

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

我们怀疑本地网络配置有问题,数据包被丢弃。是否有任何关于如何处理此问题的指示?

我查看了我们的后端日志以查找您包含的对话 ID,看起来令牌需要刷新。请参阅 the Authentication docs 以了解刷新令牌。

您的代码似乎试图解决令牌过期问题,但是:

  • 1800000 是默认到期时间。最好将您的延迟时间缩短一点,以考虑到请求旅行时间和其他因素,以确保您的令牌不会过期。
  • 当聊天 window 打开时,您似乎只获得了一次令牌。它可能会在对话中途过期

也就是说,这可能不是象征性的问题。您可以尝试禁用 websockets 吗:

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


如果这本地数据包丢失问题,恐怕我无法提供太多支持,因为它不再是 botframework 问题并且可能非常特定于您的本地网络。如果您可以提供额外的对话 ID,我也许可以进一步深入研究。但是在过去的两天里,你的机器人在我们这边看起来很正常。