-
Notifications
You must be signed in to change notification settings - Fork 281
/
inspectionMiddleware.ts
469 lines (413 loc) · 17.1 KB
/
inspectionMiddleware.ts
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
467
468
469
/**
* @module botbuilder
*/
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import { v4 as uuidv4 } from 'uuid';
import { MicrosoftAppCredentials, ConnectorClient } from 'botframework-connector';
import {
Activity,
ActivityTypes,
Middleware,
TurnContext,
BotState,
ConversationReference,
StatePropertyAccessor,
UserState,
ConversationState,
Storage,
} from 'botbuilder-core';
import { teamsGetTeamId } from './teamsActivityHelpers';
/** @private */
class TraceActivity {
static makeCommandActivity(command: string): Partial<Activity> {
return {
type: ActivityTypes.Trace,
timestamp: new Date(),
name: 'Command',
label: 'Command',
value: command,
valueType: 'https://www.botframework.com/schemas/command',
};
}
static fromActivity(activity: Activity | Partial<Activity>, name: string, label: string): Partial<Activity> {
return {
type: ActivityTypes.Trace,
timestamp: new Date(),
name: name,
label: label,
value: activity,
valueType: 'https://www.botframework.com/schemas/activity',
};
}
static fromState(botState: BotState): Partial<Activity> {
return {
type: ActivityTypes.Trace,
timestamp: new Date(),
name: 'BotState',
label: 'Bot State',
value: botState,
valueType: 'https://www.botframework.com/schemas/botState',
};
}
static fromConversationReference(conversationReference: Partial<ConversationReference>): Partial<Activity> {
return {
type: ActivityTypes.Trace,
timestamp: new Date(),
name: 'Deleted Message',
label: 'MessageDelete',
value: conversationReference,
valueType: 'https://www.botframework.com/schemas/conversationReference',
};
}
static fromError(errorMessage: string): Partial<Activity> {
return {
type: ActivityTypes.Trace,
timestamp: new Date(),
name: 'Turn Error',
label: 'TurnError',
value: errorMessage,
valueType: 'https://www.botframework.com/schemas/error',
};
}
}
/** @private */
abstract class InterceptionMiddleware implements Middleware {
/**
* Implement middleware signature
*
* @param turnContext {TurnContext} An incoming TurnContext object.
* @param next {function} The next delegate function.
*/
async onTurn(turnContext: TurnContext, next: () => Promise<void>): Promise<void> {
const { shouldForwardToApplication, shouldIntercept } = await this.invokeInbound(
turnContext,
TraceActivity.fromActivity(turnContext.activity, 'ReceivedActivity', 'Received Activity'),
);
if (shouldIntercept) {
turnContext.onSendActivities(async (ctx, activities, nextSend) => {
const traceActivities: Partial<Activity>[] = [];
activities.forEach((activity) => {
traceActivities.push(TraceActivity.fromActivity(activity, 'SentActivity', 'Sent Activity'));
});
await this.invokeOutbound(ctx, traceActivities);
return await nextSend();
});
turnContext.onUpdateActivity(async (ctx, activity, nextUpdate) => {
const traceActivity = TraceActivity.fromActivity(activity, 'MessageUpdate', 'Updated Message');
await this.invokeOutbound(ctx, [traceActivity]);
return await nextUpdate();
});
turnContext.onDeleteActivity(async (ctx, reference, nextDelete) => {
const traceActivity = TraceActivity.fromConversationReference(reference);
await this.invokeOutbound(ctx, [traceActivity]);
return await nextDelete();
});
}
if (shouldForwardToApplication) {
try {
await next();
} catch (err) {
const traceActivity = TraceActivity.fromError(err.toString());
await this.invokeOutbound(turnContext, [traceActivity]);
throw err;
}
}
if (shouldIntercept) {
await this.invokeTraceState(turnContext);
}
}
protected abstract inbound(turnContext: TurnContext, traceActivity: Partial<Activity>): Promise<any>;
protected abstract outbound(turnContext: TurnContext, traceActivities: Partial<Activity>[]): Promise<any>;
protected abstract traceState(turnContext: TurnContext): Promise<any>;
private async invokeInbound(turnContext: TurnContext, traceActivity: Partial<Activity>): Promise<any> {
try {
return await this.inbound(turnContext, traceActivity);
} catch (err) {
console.warn(`Exception in inbound interception ${err}`);
return { shouldForwardToApplication: true, shouldIntercept: false };
}
}
private async invokeOutbound(turnContext: TurnContext, traceActivities: Partial<Activity>[]): Promise<any> {
try {
await this.outbound(turnContext, traceActivities);
} catch (err) {
console.warn(`Exception in outbound interception ${err}`);
}
}
private async invokeTraceState(turnContext: TurnContext): Promise<any> {
try {
await this.traceState(turnContext);
} catch (err) {
console.warn(`Exception in state interception ${err}`);
}
}
}
/**
* InspectionMiddleware for emulator inspection of runtime Activities and BotState.
*
* @remarks
* InspectionMiddleware for emulator inspection of runtime Activities and BotState.
* @deprecated This class will be removed in a future version of the framework.
*/
export class InspectionMiddleware extends InterceptionMiddleware {
private static readonly command = '/INSPECT';
private readonly inspectionState: InspectionState;
private readonly inspectionStateAccessor: StatePropertyAccessor<InspectionSessionsByStatus>;
private readonly userState: UserState;
private readonly conversationState: ConversationState;
private readonly credentials: MicrosoftAppCredentials;
/**
* Create the Inspection middleware for sending trace activities out to an emulator session
*
* @param inspectionState A state management object for inspection state.
* @param userState A state management object for user state.
* @param conversationState A state management object for conversation state.
* @param credentials The authentication credentials.
*/
constructor(
inspectionState: InspectionState,
userState?: UserState,
conversationState?: ConversationState,
credentials?: Partial<MicrosoftAppCredentials>,
) {
super();
this.inspectionState = inspectionState;
this.inspectionStateAccessor = inspectionState.createProperty('InspectionSessionByStatus');
this.userState = userState;
this.conversationState = conversationState;
credentials = { appId: '', appPassword: '', ...credentials };
this.credentials = new MicrosoftAppCredentials(credentials.appId, credentials.appPassword);
}
/**
* Indentifies open and attach commands and calls the appropriate method.
*
* @param turnContext The [TurnContext](xref:botbuilder-core.TurnContext) for this turn.
* @returns True if the command is open or attached, otherwise false.
*/
async processCommand(turnContext: TurnContext): Promise<any> {
if (turnContext.activity.type == ActivityTypes.Message && turnContext.activity.text !== undefined) {
const originalText = turnContext.activity.text;
TurnContext.removeRecipientMention(turnContext.activity);
const command = turnContext.activity.text.trim().split(' ');
if (command.length > 1 && command[0] === InspectionMiddleware.command) {
if (command.length === 2 && command[1] === 'open') {
await this.processOpenCommand(turnContext);
return true;
}
if (command.length === 3 && command[1] === 'attach') {
await this.processAttachCommand(turnContext, command[2]);
return true;
}
}
turnContext.activity.text = originalText;
}
return false;
}
/**
* Processes inbound activities.
*
* @param turnContext The [TurnContext](xref:botbuilder-core.TurnContext) for this turn.
* @param traceActivity The trace activity.
* @returns {Promise<any>} A promise representing the asynchronous operation.
*/
protected async inbound(turnContext: TurnContext, traceActivity: Partial<Activity>): Promise<any> {
if (await this.processCommand(turnContext)) {
return { shouldForwardToApplication: false, shouldIntercept: false };
}
const session = await this.findSession(turnContext);
if (session !== undefined) {
if (await this.invokeSend(turnContext, session, traceActivity)) {
return { shouldForwardToApplication: true, shouldIntercept: true };
} else {
return { shouldForwardToApplication: true, shouldIntercept: false };
}
} else {
return { shouldForwardToApplication: true, shouldIntercept: false };
}
}
/**
* Processes outbound activities.
*
* @param turnContext The [TurnContext](xref:botbuilder-core.TurnContext) for this turn.
* @param traceActivities A collection of trace activities.
*/
protected async outbound(turnContext: TurnContext, traceActivities: Partial<Activity>[]): Promise<any> {
const session = await this.findSession(turnContext);
if (session !== undefined) {
for (let i = 0; i < traceActivities.length; i++) {
const traceActivity = traceActivities[i];
if (!(await this.invokeSend(turnContext, session, traceActivity))) {
break;
}
}
}
}
/**
* Processes the state management object.
*
* @param turnContext The [TurnContext](xref:botbuilder-core.TurnContext) for this turn.
*/
protected async traceState(turnContext: TurnContext): Promise<any> {
const session = await this.findSession(turnContext);
if (session !== undefined) {
if (this.userState !== undefined) {
await this.userState.load(turnContext, false);
}
if (this.conversationState != undefined) {
await this.conversationState.load(turnContext, false);
}
const botState: any = {};
if (this.userState !== undefined) {
botState.userState = this.userState.get(turnContext);
}
if (this.conversationState !== undefined) {
botState.conversationState = this.conversationState.get(turnContext);
}
await this.invokeSend(turnContext, session, TraceActivity.fromState(botState));
}
}
/**
* @private
*/
private async processOpenCommand(turnContext: TurnContext): Promise<any> {
const sessions = await this.inspectionStateAccessor.get(turnContext, InspectionSessionsByStatus.DefaultValue);
const sessionId = this.openCommand(sessions, TurnContext.getConversationReference(turnContext.activity));
await turnContext.sendActivity(
TraceActivity.makeCommandActivity(`${InspectionMiddleware.command} attach ${sessionId}`),
);
await this.inspectionState.saveChanges(turnContext, false);
}
/**
* @private
*/
private async processAttachCommand(turnContext: TurnContext, sessionId: string): Promise<any> {
const sessions = await this.inspectionStateAccessor.get(turnContext, InspectionSessionsByStatus.DefaultValue);
if (this.attachCommand(this.getAttachId(turnContext.activity), sessions, sessionId)) {
await turnContext.sendActivity('Attached to session, all traffic is being replicated for inspection.');
} else {
await turnContext.sendActivity(`Open session with id ${sessionId} does not exist.`);
}
await this.inspectionState.saveChanges(turnContext, false);
}
/**
* @private
*/
private openCommand(
sessions: InspectionSessionsByStatus,
conversationReference: Partial<ConversationReference>,
): string {
const sessionId = uuidv4();
sessions.openedSessions[sessionId] = conversationReference;
return sessionId;
}
/**
* @private
*/
private attachCommand(attachId: string, sessions: InspectionSessionsByStatus, sessionId: string): boolean {
const inspectionSessionState = sessions.openedSessions[sessionId];
if (inspectionSessionState !== undefined) {
sessions.attachedSessions[attachId] = inspectionSessionState;
delete sessions.openedSessions[sessionId];
return true;
}
return false;
}
/**
* @private
*/
private async findSession(turnContext: TurnContext): Promise<any> {
const sessions = await this.inspectionStateAccessor.get(turnContext, InspectionSessionsByStatus.DefaultValue);
const conversationReference = sessions.attachedSessions[this.getAttachId(turnContext.activity)];
if (conversationReference !== undefined) {
return new InspectionSession(conversationReference, this.credentials);
}
return undefined;
}
/**
* @private
*/
private async invokeSend(
turnContext: TurnContext,
session: InspectionSession,
activity: Partial<Activity>,
): Promise<any> {
if (await session.send(activity)) {
return true;
} else {
await this.cleanUpSession(turnContext);
return false;
}
}
/**
* @private
*/
private async cleanUpSession(turnContext: TurnContext): Promise<any> {
const sessions = await this.inspectionStateAccessor.get(turnContext, InspectionSessionsByStatus.DefaultValue);
delete sessions.attachedSessions[this.getAttachId(turnContext.activity)];
await this.inspectionState.saveChanges(turnContext, false);
}
/**
* @private
*/
private getAttachId(activity: Activity): string {
// If we are running in a Microsoft Teams Team the conversation Id will reflect a particular thread the bot is in.
// So if we are in a Team then we will associate the "attach" with the Team Id rather than the more restrictive conversation Id.
const teamId = teamsGetTeamId(activity);
return teamId ? teamId : activity.conversation.id;
}
}
/** @private */
class InspectionSession {
private readonly conversationReference: Partial<ConversationReference>;
private readonly connectorClient: ConnectorClient;
constructor(conversationReference: Partial<ConversationReference>, credentials: MicrosoftAppCredentials) {
this.conversationReference = conversationReference;
this.connectorClient = new ConnectorClient(credentials, { baseUri: conversationReference.serviceUrl });
}
async send(activity: Partial<Activity>): Promise<any> {
TurnContext.applyConversationReference(activity, this.conversationReference);
try {
await this.connectorClient.conversations.sendToConversation(activity.conversation.id, activity as Activity);
} catch {
return false;
}
return true;
}
}
/** @private */
class InspectionSessionsByStatus {
static DefaultValue: InspectionSessionsByStatus = new InspectionSessionsByStatus();
openedSessions: { [id: string]: Partial<ConversationReference> } = {};
attachedSessions: { [id: string]: Partial<ConversationReference> } = {};
}
/**
* InspectionState for use by the InspectionMiddleware for emulator inspection of runtime Activities and BotState.
*
* @remarks
* InspectionState for use by the InspectionMiddleware for emulator inspection of runtime Activities and BotState.
* @deprecated This class will be removed in a future version of the framework.
*/
export class InspectionState extends BotState {
/**
* Creates a new instance of the [InspectionState](xref:botbuilder.InspectionState) class.
*
* @param storage The [Storage](xref:botbuilder-core.Storage) layer this state management object will use to store and retrieve state.
*/
constructor(storage: Storage) {
super(storage, (context: TurnContext) => {
return Promise.resolve(this.getStorageKey(context));
});
}
/**
* Gets the key to use when reading and writing state to and from storage.
*
* @param _turnContext The [TurnContext](xref:botbuilder-core.TurnContext) for this turn.
* @returns The storage key.
*/
protected getStorageKey(_turnContext: TurnContext) {
return 'InspectionState';
}
}