-
Notifications
You must be signed in to change notification settings - Fork 130
Expand file tree
/
Copy pathdirectLineStreaming.ts
More file actions
466 lines (381 loc) · 16 KB
/
directLineStreaming.ts
File metadata and controls
466 lines (381 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
// In order to keep file size down, only import the parts of rxjs that we use
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Buffer } from 'buffer';
import { Observable } from 'rxjs/Observable';
import { Subscriber } from 'rxjs/Subscriber';
import * as BFSE from 'botframework-streaming';
import createDeferred from './createDeferred';
import { Activity, ConnectionStatus, Conversation, DirectLine, IBotConnection, Media, Message } from './directLine';
import WebSocketClientWithNetworkInformation from './streaming/WebSocketClientWithNetworkInformation';
import type { Deferred } from './createDeferred';
const DIRECT_LINE_VERSION = 'DirectLine/3.0';
const MAX_RETRY_COUNT = 3;
const refreshTokenLifetime = 30 * 60 * 1000;
//const refreshTokenLifetime = 5000;
// const timeout = 20 * 1000;
const refreshTokenInterval = refreshTokenLifetime / 2;
interface DirectLineStreamingOptions {
token: string;
conversationId?: string;
domain: string;
// Attached to all requests to identify requesting agent.
botAgent?: string;
/**
* Sets the [`NetworkInformation` API](https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API).
* When the `NetworkInformation` detect network changes or offline, it will disconnect the Web Socket and reconnect it.
*/
networkInformation?: NetworkInformation;
}
class StreamHandler implements BFSE.RequestHandler {
private connectionStatus$;
private subscriber: Subscriber<Activity>;
private shouldQueue: () => boolean;
private activityQueue: Array<Activity> = [];
constructor(s: Subscriber<Activity>, c$: Observable<ConnectionStatus>, sq: () => boolean) {
this.subscriber = s;
this.connectionStatus$ = c$;
this.shouldQueue = sq;
}
public setSubscriber(s: Subscriber<Activity>) {
this.subscriber = s;
}
async processRequest(request: BFSE.IReceiveRequest, logger?: any): Promise<BFSE.StreamingResponse> {
const streams = [...request.streams];
const stream0 = streams.shift();
const activitySetJson = await stream0.readAsString();
const activitySet = JSON.parse(activitySetJson);
if (activitySet.activities.length !== 1) {
// Only one activity is expected in a set in streaming
this.subscriber.error(new Error('there should be exactly one activity'));
return BFSE.StreamingResponse.create(500);
}
const activity = activitySet.activities[0];
if (streams.length > 0) {
const attachments = [...activity.attachments];
let stream: BFSE.ContentStream;
while ((stream = streams.shift())) {
const attachment = await stream.readAsString();
const dataUri = 'data:text/plain;base64,' + attachment;
attachments.push({ contentType: stream.contentType, contentUrl: dataUri });
}
activity.attachments = attachments;
}
if (this.shouldQueue()) {
this.activityQueue.push(activity);
} else {
this.subscriber.next(activity);
}
return BFSE.StreamingResponse.create(200);
}
public flush() {
this.connectionStatus$.subscribe(() => {});
this.activityQueue.forEach(a => this.subscriber.next(a));
this.activityQueue = [];
}
public end() {
this.subscriber.complete();
}
}
export class DirectLineStreaming implements IBotConnection {
public connectionStatus$ = new BehaviorSubject(ConnectionStatus.Uninitialized);
public activity$: Observable<Activity>;
private activitySubscriber: Subscriber<Activity>;
private connectDeferred: Deferred<void>;
private theStreamHandler: StreamHandler;
private domain: string;
private conversationId: string;
private token: string;
private streamConnection: BFSE.WebSocketClient;
private queueActivities: boolean;
private _botAgent = '';
#networkInformation: NetworkInformation | undefined;
constructor(options: DirectLineStreamingOptions) {
// Rectifies `options.networkInformation`.
const networkInformation = options?.networkInformation;
if (
typeof networkInformation === 'undefined' ||
(typeof networkInformation.addEventListener === 'function' &&
typeof networkInformation.removeEventListener === 'function' &&
typeof networkInformation.type === 'string')
) {
this.#networkInformation = networkInformation;
} else {
console.warn(
'botframework-directlinejs: "networkInformation" option specified must be a `NetworkInformation`-like instance extending `EventTarget` interface with a `type` property returning a string.'
);
}
this.token = options.token;
this.refreshToken().catch(() => {
this.connectionStatus$.next(ConnectionStatus.ExpiredToken);
});
this.domain = options.domain;
if (options.conversationId) {
this.conversationId = options.conversationId;
}
this._botAgent = this.getBotAgent(options.botAgent);
this.queueActivities = true;
this.activity$ = Observable.create(async (subscriber: Subscriber<Activity>) => {
this.activitySubscriber = subscriber;
this.theStreamHandler = new StreamHandler(subscriber, this.connectionStatus$, () => this.queueActivities);
// Resolving connectDeferred will kick-off the connection.
this.connectDeferred.resolve();
}).share();
// connectWithRetryAsync() will create the connectDeferred object required in activity$.
this.connectWithRetryAsync();
}
public reconnect({ conversationId, token }: Conversation) {
if (this.connectionStatus$.getValue() === ConnectionStatus.Ended) {
throw new Error('Connection has ended.');
}
this.conversationId = conversationId;
this.token = token;
this.connectDeferred.resolve();
}
end() {
// Once end() is called, no reconnection can be made.
this.activitySubscriber.complete();
this.connectionStatus$.next(ConnectionStatus.Ended);
this.connectionStatus$.complete();
this.streamConnection.disconnect();
}
private commonHeaders() {
return {
Authorization: `Bearer ${this.token}`,
'x-ms-bot-agent': this._botAgent
};
}
private getBotAgent(customAgent: string = ''): string {
let clientAgent = 'directlineStreaming';
if (customAgent) {
clientAgent += `; ${customAgent}`;
}
return `${DIRECT_LINE_VERSION} (${clientAgent})`;
}
private async refreshToken(firstCall = true, retryCount = 0) {
await this.waitUntilOnline();
let numberOfAttempts = 0;
while (numberOfAttempts < MAX_RETRY_COUNT) {
numberOfAttempts++;
await new Promise(r => setTimeout(r, refreshTokenInterval));
try {
const res = await fetch(`${this.domain}/tokens/refresh`, { method: 'POST', headers: this.commonHeaders() });
if (res.ok) {
numberOfAttempts = 0;
const { token } = await res.json();
this.token = token;
} else {
if (res.status === 403 || res.status === 403) {
console.error(`Fatal error while refreshing the token: ${res.status} ${res.statusText}`);
this.streamConnection.disconnect();
} else {
console.warn(`Refresh attempt #${numberOfAttempts} failed: ${res.status} ${res.statusText}`);
}
}
} catch (e) {
console.warn(`Refresh attempt #${numberOfAttempts} threw an exception: ${e}`);
}
}
console.error('Retries exhausted');
this.streamConnection.disconnect();
}
postActivity(activity: Activity) {
if (
this.connectionStatus$.value === ConnectionStatus.Ended ||
this.connectionStatus$.value === ConnectionStatus.FailedToConnect
) {
return Observable.throw(new Error('Connection is closed'));
}
if (activity.type === 'message' && activity.attachments && activity.attachments.length > 0) {
return this.postMessageWithAttachments(activity);
}
const resp$ = Observable.create(async subscriber => {
const request = BFSE.StreamingRequest.create(
'POST',
'/v3/directline/conversations/' + this.conversationId + '/activities'
);
request.setBody(JSON.stringify(activity));
try {
const resp = await this.streamConnection.send(request);
if (resp.statusCode !== 200) throw new Error('PostActivity returned ' + resp.statusCode);
const numberOfStreams = resp.streams.length;
if (numberOfStreams !== 1) throw new Error('Expected one stream but got ' + numberOfStreams);
const idString = await resp.streams[0].readAsString();
const { Id: id } = JSON.parse(idString);
subscriber.next(id);
return subscriber.complete();
} catch (e) {
// If there is a network issue then its handled by
// the disconnectionHandler. Everything else can
// be retried
console.warn(e);
this.streamConnection.disconnect();
return subscriber.error(e);
}
});
return resp$;
}
private postMessageWithAttachments(message: Message) {
const { attachments, ...messageWithoutAttachments } = message;
return Observable.create(subscriber => {
const httpContentList = [];
(async () => {
try {
const arrayBuffers = await Promise.all(
attachments.map(async attachment => {
const media = attachment as Media;
const res = await fetch(media.contentUrl);
if (res.ok) {
return { arrayBuffer: await res.arrayBuffer(), media };
} else {
throw new Error('...');
}
})
);
arrayBuffers.forEach(({ arrayBuffer, media }) => {
const buffer = Buffer.from(arrayBuffer);
const stream = new BFSE.SubscribableStream();
stream.write(buffer);
const httpContent = new BFSE.HttpContent({ type: media.contentType, contentLength: buffer.length }, stream);
httpContentList.push(httpContent);
});
const url = `/v3/directline/conversations/${this.conversationId}/users/${messageWithoutAttachments.from.id}/upload`;
const request = BFSE.StreamingRequest.create('PUT', url);
const activityStream = new BFSE.SubscribableStream();
activityStream.write(JSON.stringify(messageWithoutAttachments), 'utf-8');
request.addStream(
new BFSE.HttpContent(
{ type: 'application/vnd.microsoft.activity', contentLength: activityStream.length },
activityStream
)
);
httpContentList.forEach(e => request.addStream(e));
const resp = await this.streamConnection.send(request);
if (resp.streams && resp.streams.length !== 1) {
subscriber.error(new Error(`Invalid stream count ${resp.streams.length}`));
} else {
const { Id: id } = await resp.streams[0].readAsJson<{ Id: string }>();
subscriber.next(id);
subscriber.complete();
}
} catch (e) {
subscriber.error(e);
}
})();
});
}
private async waitUntilOnline() {
return new Promise<void>((resolve, reject) => {
this.connectionStatus$.subscribe(
cs => {
if (cs === ConnectionStatus.Online) {
return resolve();
}
},
e => reject(e)
);
});
}
private async connectAsync() {
const re = new RegExp('^http(s?)');
if (!re.test(this.domain)) {
throw 'Domain must begin with http or https';
}
const params = { token: this.token };
if (this.conversationId) {
params['conversationId'] = this.conversationId;
}
const abortController = new AbortController();
const urlSearchParams = new URLSearchParams(params).toString();
const wsUrl = `${this.domain.replace(re, 'ws$1')}/conversations/connect?${urlSearchParams}`;
// This promise will resolve when it is disconnected.
return new Promise(async (resolve, reject) => {
try {
this.streamConnection = new WebSocketClientWithNetworkInformation({
disconnectionHandler: resolve,
networkInformation: this.#networkInformation,
requestHandler: {
processRequest: streamingRequest => {
// If `streamConnection` is still current, allow call to `processRequest()`, otherwise, ignore calls to `processRequest()`.
// This prevents zombie connections from sending us requests.
if (abortController.signal.aborted) {
throw new Error('Cannot process streaming request, `streamingConnection` should be disconnected.');
}
return this.theStreamHandler.processRequest(streamingRequest);
}
},
url: wsUrl
});
this.queueActivities = true;
await this.streamConnection.connect();
const request = BFSE.StreamingRequest.create('POST', '/v3/directline/conversations');
const response = await this.streamConnection.send(request);
if (response.statusCode !== 200) {
throw new Error('Connection response code ' + response.statusCode);
}
if (response.streams.length !== 1) {
throw new Error('Expected 1 stream but got ' + response.streams.length);
}
const responseString = await response.streams[0].readAsString();
const conversation = JSON.parse(responseString);
this.conversationId = conversation.conversationId;
this.connectionStatus$.next(ConnectionStatus.Online);
// Wait until DL consumers have had a chance to be notified
// of the connection status change.
// This is specific to RxJS implementation of observable, which calling subscribe() after next() will still get the value.
await this.waitUntilOnline();
this.theStreamHandler.flush();
this.queueActivities = false;
} catch (e) {
reject(e);
}
}).finally(() => abortController.abort());
}
private async connectWithRetryAsync() {
// This for-loop will break when someone call end() and it will signal ConnectionStatus.Ended.
for (;;) {
// Create a new signal and wait for someone kicking off the connection:
// - subscribe to activity$, or;
// - retries exhausted (FailedToConnect), then, someone call reconnect()
await (this.connectDeferred = createDeferred()).promise;
let numRetries = MAX_RETRY_COUNT;
this.connectionStatus$.next(ConnectionStatus.Connecting);
while (numRetries > 0) {
numRetries--;
const start = Date.now();
try {
// This promise will reject/resolve when disconnected.
await this.connectAsync();
} catch (err) {
console.error(err);
}
// If someone call end() to break the connection, we will never listen to any reconnect().
if (this.connectionStatus$.getValue() === ConnectionStatus.Ended) {
// This is the only place the loop in this function will be broke.
return;
}
// Make sure we don't signal ConnectionStatus.Connecting twice or more without an actual connection.
// Subsequent retries should be transparent.
if (this.connectionStatus$.getValue() !== ConnectionStatus.Connecting) {
this.connectionStatus$.next(ConnectionStatus.Connecting);
}
// If the current connection lasted for more than a minute, the previous connection is good, which means:
// - we should reset the retry counter, and;
// - we should reconnect immediately.
if (60000 < Date.now() - start) {
numRetries = MAX_RETRY_COUNT;
} else if (numRetries > 0) {
// Sleep only if we are doing retry. Otherwise, we are going to break the loop and signal FailedToConnect.
await new Promise(r => setTimeout(r, this.getRetryDelay()));
}
}
// TODO: [TEST] Make sure FailedToConnect is reported immediately after last disconnection, should be no getRetryDelay().
// Failed to reconnect after multiple retries.
this.connectionStatus$.next(ConnectionStatus.FailedToConnect);
}
// Note: No code will hit this line.
}
// Returns the delay duration in milliseconds
private getRetryDelay() {
return Math.floor(3000 + Math.random() * 12000);
}
}