This repository has been archived by the owner on Jun 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 528
/
skillWebSocketBotAdapter.ts
214 lines (174 loc) · 8.85 KB
/
skillWebSocketBotAdapter.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
import { BotAdapter, BotTelemetryClient, InvokeResponse, Middleware, NullTelemetryClient,
ResourceResponse, Severity, TurnContext } from 'botbuilder';
import { ActivityExtensions, IRemoteUserTokenProvider, TokenEvents } from 'botbuilder-solutions';
import { Activity, ActivityTypes, ConversationReference } from 'botframework-schema';
import { CancellationToken, ContentStream, ReceiveResponse, Request } from 'microsoft-bot-protocol';
import { Server } from 'microsoft-bot-protocol-websocket';
import { v4 as uuid } from 'uuid';
import { BotCallbackHandler, IActivityHandler } from '../activityHandler';
/**
* This adapter is responsible for processing incoming activity from a bot-to-bot call over websocket transport.
* It'll performs the following tasks:
* 1. Process the incoming activity by calling into pipeline.
* 2. Implement BotAdapter protocol. Each method will send the activity back to calling bot using websocket.
*/
export class SkillWebSocketBotAdapter extends BotAdapter implements IActivityHandler, IRemoteUserTokenProvider {
private readonly telemetryClient: BotTelemetryClient;
public server!: Server;
constructor(middleware?: Middleware, telemetryClient?: BotTelemetryClient) {
super();
this.telemetryClient = telemetryClient || new NullTelemetryClient();
if (middleware) {
this.use(middleware);
}
}
/**
* Primary adapter method for processing activities sent from calling bot.
* @param activity The activity to process.
* @param callback The BotCallBackHandler to call on completion.
* @returns The response to the activity.
*/
public async processActivity(activity: Activity, callback: BotCallbackHandler): Promise<InvokeResponse> {
const message: string = `Received an incoming activity. ActivityId: ${activity.id}`;
this.telemetryClient.trackTrace({
message: message,
severityLevel: Severity.Information
});
const context: TurnContext = new TurnContext(this, activity);
await this.runMiddleware(context, callback);
// We do not support Invoke in websocket transport
if (activity.type === ActivityTypes.Invoke) {
return { status: 501 };
}
return { status: 200 };
}
/**
* Sends activities to the conversation.
* If the activities are successfully sent, the task result contains
* an array of ResourceResponse objects containing the IDs that
* the receiving channel assigned to the activities.
* @param context The context object for the turn.
* @param activities The activities to send.
* @returns A task that represents the work queued to execute.
*/
public async sendActivities(context: TurnContext, activities: Partial<Activity>[]): Promise<ResourceResponse[]> {
const responses: ResourceResponse[] = [];
activities.forEach(async (activity: Partial<Activity>, index: number) => {
if (!activity.id) {
activity.id = uuid();
}
let response: ResourceResponse|undefined = { id: '' };
if (activity.type === 'delay') {
// The Activity Schema doesn't have a delay type build in, so it's simulated
// here in the Bot. This matches the behavior in the Node connector.
const delayMs: number = activity.value;
await sleep(delayMs);
// No need to create a response. One will be created below.
}
if (activity.type !== ActivityTypes.Trace || (activity.type === ActivityTypes.Trace && activity.channelId === 'emulator')) {
const requestPath: string = `/activities/${activity.id}`;
const request: Request = Request.create('POST', requestPath);
request.setBody(activity);
const message: string = `Sending activity. ReplyToId: ${activity.replyToId}`;
this.telemetryClient.trackTrace({
message: message,
severityLevel: Severity.Information
});
const begin: [number, number] = process.hrtime();
response = await this.sendRequest<ResourceResponse>(request);
const end: [number, number] = process.hrtime(begin);
const latency: { latency: number } = { latency: toMilliseconds(end) };
const event: string = 'SkillWebSocketSendActivityLatency';
this.telemetryClient.trackEvent({
name: event,
metrics: latency
});
// If No response is set, then default to a "simple" response. This can't really be done
// above, as there are cases where the ReplyTo/SendTo methods will also return null
// (See below) so the check has to happen here.
if (!response) {
response = { id: activity.id || '' };
}
}
responses.push(response);
});
return responses;
}
public async updateActivity(context: TurnContext, activity: Partial<Activity>): Promise<void> {
const requestPath: string = `/activities/${activity.id}`;
const request: Request = Request.create('PUT', requestPath);
request.setBody(activity);
const message: string = `Updating activity. activity id: ${activity.replyToId}`;
this.telemetryClient.trackTrace({
message: message,
severityLevel: Severity.Information
});
const begin: [number, number] = process.hrtime();
await this.sendRequest<ResourceResponse>(request);
const end: [number, number] = process.hrtime(begin);
const latency: { latency: number } = { latency: toMilliseconds(end) };
const event: string = 'SkillWebSocketUpdateActivityLatency';
this.telemetryClient.trackEvent({
name: event,
metrics: latency
});
}
public async deleteActivity(context: TurnContext, reference: Partial<ConversationReference>): Promise<void> {
const requestPath: string = `/activities/${reference.activityId}`;
const request: Request = Request.create('DELETE', requestPath);
const message: string = `Deleting activity. activity id: ${reference.activityId}`;
this.telemetryClient.trackTrace({
message: message,
severityLevel: Severity.Information
});
const begin: [number, number] = process.hrtime();
await this.sendRequest<ResourceResponse>(request);
const end: [number, number] = process.hrtime(begin);
const latency: { latency: number } = { latency: toMilliseconds(end) };
const event: string = 'SkillWebSocketDeleteActivityLatency';
this.telemetryClient.trackEvent({
name: event,
metrics: latency
});
}
public async continueConversation(reference: Partial<ConversationReference>, logic: BotCallbackHandler): Promise<void> {
const activity: Partial<Activity> = ActivityExtensions.getContinuationActivity(reference);
const context: TurnContext = new TurnContext(this, activity);
await this.runMiddleware(context, logic);
}
public async sendRemoteTokenRequestEvent(turnContext: TurnContext): Promise<void> {
// We trigger a Token Request from the Parent Bot by sending a "TokenRequest" event back and then waiting for a "TokenResponse"
const response: Activity = ActivityExtensions.createReply(turnContext.activity);
response.type = ActivityTypes.Event;
response.name = TokenEvents.tokenRequestEventName;
// Send the tokens/request Event
await this.sendActivities(turnContext, [response]);
}
private async sendRequest<T>(request: Request, cToken?: CancellationToken): Promise<T|undefined> {
try {
const serverResponse: ReceiveResponse = await this.server.sendAsync(request, cToken || new CancellationToken());
if (serverResponse.StatusCode === 200) {
// MISSING: await request.ReadBodyAsJson();
const bodyParts: string[] = await Promise.all(serverResponse.Streams.map((s: ContentStream) => s.readAsString()));
const body: string = bodyParts.join();
return JSON.parse(body);
}
} catch (error) {
this.telemetryClient.trackException({
exception: error,
handledAt: SkillWebSocketBotAdapter.name
});
throw error;
}
return undefined;
}
}
function sleep(delay: number): Promise<void> {
return new Promise<void>((resolve: (value: void) => void): void => {
setTimeout(resolve, delay);
});
}
function toMilliseconds(hrtime: [number, number]): number {
const nanoseconds: number = (hrtime[0] * 1e9) + hrtime[1];
return nanoseconds / 1e6;
}