-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathActivityKeyerComposer.tsx
More file actions
335 lines (274 loc) · 14.3 KB
/
ActivityKeyerComposer.tsx
File metadata and controls
335 lines (274 loc) · 14.3 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
import { getActivityLivestreamingMetadata, type WebChatActivity } from 'botframework-webchat-core';
import React, { useCallback, useEffect, useMemo, useRef, type ReactNode } from 'react';
import reduceIterable from '../../hooks/private/reduceIterable';
import useActivities from '../../hooks/useActivities';
import usePonyfill from '../Ponyfill/usePonyfill';
import type { ActivityKeyerContextType } from './private/Context';
import ActivityKeyerContext from './private/Context';
import getActivityId from './private/getActivityId';
import getClientActivityId from './private/getClientActivityId';
import lastOf from './private/lastOf';
import someIterable from './private/someIterable';
import uniqueId from './private/uniqueId';
import useActivityKeyerContext from './private/useContext';
type ActivityIdToKeyMap = Map<string, string>;
type ActivityToKeyMap = Map<WebChatActivity, string>;
type ClientActivityIdToKeyMap = Map<string, string>;
type KeyToActivitiesMap = Map<string, readonly WebChatActivity[]>;
/** After this many ms of no activity changes, verify that the frozen portion was not modified. */
const FROZEN_CHECK_TIMEOUT = 10_000;
/** Only the last N activities are compared reference-by-reference on each render. */
const MUTABLE_ACTIVITY_WINDOW = 1_000;
/**
* React context composer component to assign a perma-key to every activity.
* This will support both `useGetActivityByKey` and `useGetKeyByActivity` custom hooks.
*
* Today, `activity.id` is only guaranteed for activity from others.
* Not all activities sent by the local user has `activity.id`.
*
* To track outgoing activities, we added `activity.channelData.clientActivityId`.
*
* This component will create a local key, which can be used to track both
* incoming and outgoing activities in a consistent way.
*
* Local key are only persisted in memory. On refresh, they will be a new random key.
*/
const ActivityKeyerComposer = ({ children }: Readonly<{ children?: ReactNode | undefined }>) => {
const [{ cancelIdleCallback, clearTimeout, requestIdleCallback, setTimeout }] = usePonyfill();
const existingContext = useActivityKeyerContext(false);
if (existingContext) {
throw new Error('botframework-webchat internal: <ActivityKeyerComposer> should not be nested.');
}
const [activities] = useActivities();
// TODO: [P0] We should remove the mapping in favor of `localId`,
// the id should represent the latest available activity in the stream
//
// Maps are intentionally mutable so the incremental fast path can append to them in-place.
const activityIdToKeyMapRef = useRef<ActivityIdToKeyMap>(new Map());
const activityToKeyMapRef = useRef<ActivityToKeyMap>(new Map());
const clientActivityIdToKeyMapRef = useRef<ClientActivityIdToKeyMap>(new Map());
const keyToActivitiesMapRef = useRef<KeyToActivitiesMap>(new Map());
const prevActivitiesRef = useRef<readonly WebChatActivity[]>(Object.freeze([]));
const prevActivityKeysStateRef = useRef<readonly [readonly string[]]>(
Object.freeze([Object.freeze([])]) as readonly [readonly string[]]
);
const pendingFrozenCheckRef = useRef<
| {
readonly current: readonly WebChatActivity[];
readonly frozenBoundary: number;
readonly prev: readonly WebChatActivity[];
}
| undefined
>();
const warnedPositionsRef = useRef<Set<number>>(new Set());
// Incremental keying: the fast path only processes newly-appended activities (O(delta) per render)
// instead of re-iterating all activities (O(n) per render, O(n²) total for n streaming pushes).
const activityKeysState = useMemo<readonly [readonly string[]]>(() => {
const prevActivities = prevActivitiesRef.current;
// Only the last MUTABLE_ACTIVITY_WINDOW activities are compared each render.
// Activities before the frozen boundary are assumed unchanged — O(1) instead of O(n).
const frozenBoundary = Math.max(0, Math.min(prevActivities.length, activities.length) - MUTABLE_ACTIVITY_WINDOW);
let commonPrefixLength = frozenBoundary;
const maxPrefix = Math.min(prevActivities.length, activities.length);
// eslint-disable-next-line security/detect-object-injection
while (commonPrefixLength < maxPrefix && prevActivities[commonPrefixLength] === activities[commonPrefixLength]) {
commonPrefixLength++;
}
const isAppendOnly = commonPrefixLength === prevActivities.length;
if (isAppendOnly) {
// Fast path: only new activities were appended — process them incrementally.
if (commonPrefixLength === activities.length) {
// Array reference changed but content is identical.
prevActivitiesRef.current = activities;
return prevActivityKeysStateRef.current;
}
// Schedule deferred verification of the frozen portion only now that we know:
// (1) the update is append-only and (2) there are actual content changes.
if (frozenBoundary) {
pendingFrozenCheckRef.current = Object.freeze({ current: activities, frozenBoundary, prev: prevActivities });
}
const { current: activityIdToKeyMap } = activityIdToKeyMapRef;
const { current: activityToKeyMap } = activityToKeyMapRef;
const { current: clientActivityIdToKeyMap } = clientActivityIdToKeyMapRef;
const { current: keyToActivitiesMap } = keyToActivitiesMapRef;
const newKeys: string[] = [];
for (let i = commonPrefixLength; i < activities.length; i++) {
// eslint-disable-next-line security/detect-object-injection
const activity = activities[i];
const activityId = getActivityId(activity);
const clientActivityId = getClientActivityId(activity);
const typingActivityId = getActivityLivestreamingMetadata(activity)?.sessionId;
// Since we mutate maps in-place, a single lookup covers both "previous" and
// "current-iteration" entries — equivalent to the slow path's dual-map check.
const key =
(clientActivityId && clientActivityIdToKeyMap.get(clientActivityId)) ||
(typingActivityId && activityIdToKeyMap.get(typingActivityId)) ||
(activityId && activityIdToKeyMap.get(activityId)) ||
activityToKeyMap.get(activity) ||
uniqueId();
activityId && activityIdToKeyMap.set(activityId, key);
typingActivityId && activityIdToKeyMap.set(typingActivityId, key);
clientActivityId && clientActivityIdToKeyMap.set(clientActivityId, key);
activityToKeyMap.set(activity, key);
const activitiesForKey = keyToActivitiesMap.get(key);
keyToActivitiesMap.set(
key,
activitiesForKey ? Object.freeze([...activitiesForKey, activity]) : Object.freeze([activity])
);
!activitiesForKey && newKeys.push(key);
}
prevActivitiesRef.current = activities;
if (!newKeys.length) {
// New activities might be added to existing keys — no new keys, but the keyToActivitiesMap
// was mutated. Return a new tuple reference so context consumers re-render and see the
// updated activities-per-key via getActivitiesByKey.
return Object.freeze([prevActivityKeysStateRef.current[0]]) as readonly [readonly string[]];
}
const nextKeys = Object.freeze([...prevActivityKeysStateRef.current[0], ...newKeys]);
const result = Object.freeze([nextKeys]) as readonly [readonly string[]];
prevActivityKeysStateRef.current = result;
return result;
}
// Slow path: activities were removed or reordered — full recalculation.
const { current: activityIdToKeyMap } = activityIdToKeyMapRef;
const { current: activityToKeyMap } = activityToKeyMapRef;
const { current: clientActivityIdToKeyMap } = clientActivityIdToKeyMapRef;
const nextActivityIdToKeyMap: ActivityIdToKeyMap = new Map();
const nextActivityKeys: Set<string> = new Set();
const nextActivityToKeyMap: ActivityToKeyMap = new Map();
const nextClientActivityIdToKeyMap: ClientActivityIdToKeyMap = new Map();
const nextKeyToActivitiesMap: KeyToActivitiesMap = new Map();
activities.forEach(activity => {
const activityId = getActivityId(activity);
const clientActivityId = getClientActivityId(activity);
const typingActivityId = getActivityLivestreamingMetadata(activity)?.sessionId;
const key =
(clientActivityId &&
(clientActivityIdToKeyMap.get(clientActivityId) || nextClientActivityIdToKeyMap.get(clientActivityId))) ||
(typingActivityId &&
(activityIdToKeyMap.get(typingActivityId) || nextActivityIdToKeyMap.get(typingActivityId))) ||
(activityId && (activityIdToKeyMap.get(activityId) || nextActivityIdToKeyMap.get(activityId))) ||
activityToKeyMap.get(activity) ||
nextActivityToKeyMap.get(activity) ||
uniqueId();
activityId && nextActivityIdToKeyMap.set(activityId, key);
typingActivityId && nextActivityIdToKeyMap.set(typingActivityId, key);
clientActivityId && nextClientActivityIdToKeyMap.set(clientActivityId, key);
nextActivityToKeyMap.set(activity, key);
nextActivityKeys.add(key);
const activitiesForKey = nextKeyToActivitiesMap.has(key) ? [...nextKeyToActivitiesMap.get(key)] : [];
activitiesForKey.push(activity);
nextKeyToActivitiesMap.set(key, Object.freeze(activitiesForKey));
});
activityIdToKeyMapRef.current = nextActivityIdToKeyMap;
activityToKeyMapRef.current = nextActivityToKeyMap;
clientActivityIdToKeyMapRef.current = nextClientActivityIdToKeyMap;
keyToActivitiesMapRef.current = nextKeyToActivitiesMap;
prevActivitiesRef.current = activities;
// Slow path did a full recalculation — no frozen check needed, reset warnings.
pendingFrozenCheckRef.current = undefined;
warnedPositionsRef.current.clear();
const nextKeys = Object.freeze([...nextActivityKeys.values()]);
const result = Object.freeze([nextKeys]) as readonly [readonly string[]];
prevActivityKeysStateRef.current = result;
return result;
}, [
activities,
activityIdToKeyMapRef,
activityToKeyMapRef,
clientActivityIdToKeyMapRef,
keyToActivitiesMapRef,
pendingFrozenCheckRef,
prevActivitiesRef,
prevActivityKeysStateRef,
warnedPositionsRef
]);
// Deferred verification: after FROZEN_CHECK_TIMEOUT of quiet, validate that activities
// inside the frozen portion have not actually changed. Warn once per position if they did.
// Uses requestIdleCallback inside the timeout to avoid contending with the first post-stream repaint.
useEffect(() => {
const pending = pendingFrozenCheckRef.current;
if (!pending) {
return;
}
let idleHandle: ReturnType<NonNullable<typeof requestIdleCallback>> | undefined;
const runCheck = () => {
const { current: currentActivities, frozenBoundary, prev: prevFrozenActivities } = pending;
for (let i = 0; i < frozenBoundary; i++) {
// eslint-disable-next-line security/detect-object-injection
if (prevFrozenActivities[i] !== currentActivities[i] && !warnedPositionsRef.current.has(i)) {
warnedPositionsRef.current.add(i);
console.warn(
`botframework-webchat internal: change in activity at position ${i} was not applied because it is outside the mutable window of ${MUTABLE_ACTIVITY_WINDOW}.`
);
}
}
};
const timer = setTimeout(() => {
if (requestIdleCallback) {
idleHandle = requestIdleCallback(runCheck);
} else {
runCheck();
}
}, FROZEN_CHECK_TIMEOUT);
return () => {
clearTimeout(timer);
idleHandle !== undefined && cancelIdleCallback?.(idleHandle);
};
}, [activities, cancelIdleCallback, clearTimeout, requestIdleCallback, setTimeout]);
const getActivitiesByKey: (key?: string | undefined) => readonly WebChatActivity[] | undefined = useCallback(
(key?: string | undefined): readonly WebChatActivity[] | undefined => key && keyToActivitiesMapRef.current.get(key),
[keyToActivitiesMapRef]
);
const getActivityByKey: (key?: string | undefined) => undefined | WebChatActivity = useCallback(
(key?: string | undefined): undefined | WebChatActivity => lastOf(getActivitiesByKey(key)),
[getActivitiesByKey]
);
const getKeyByActivity: (activity?: WebChatActivity | undefined) => string | undefined = useCallback(
(activity?: WebChatActivity | undefined) => activity && activityToKeyMapRef.current.get(activity),
[activityToKeyMapRef]
);
const getKeyByActivityId: (activityId?: string | undefined) => string | undefined = useCallback(
(activityId?: string | undefined) => activityId && activityIdToKeyMapRef.current.get(activityId),
[activityIdToKeyMapRef]
);
const contextValue = useMemo<ActivityKeyerContextType>(
() => ({ activityKeysState, getActivityByKey, getActivitiesByKey, getKeyByActivity, getKeyByActivityId }),
[activityKeysState, getActivitiesByKey, getActivityByKey, getKeyByActivity, getKeyByActivityId]
);
const { length: numActivities } = activities;
if (activityIdToKeyMapRef.current.size > numActivities) {
console.warn(
'botframework-webchat internal assertion: "activityIdToKeyMap.size" should be equal or less than "activities.length".'
);
}
if (activityToKeyMapRef.current.size !== numActivities) {
console.warn(
'botframework-webchat internal assertion: "activityToKeyMap.size" should be same as "activities.length".'
);
}
if (clientActivityIdToKeyMapRef.current.size > numActivities) {
console.warn(
'botframework-webchat internal assertion: "clientActivityIdToKeyMap.size" should be equal or less than "activities.length".'
);
}
if (someIterable(keyToActivitiesMapRef.current.values(), ({ length }) => !length)) {
console.warn(
'botframework-webchat internal assertion: all values in "keyToActivitiesMap" should have at least one item.'
);
}
if (
reduceIterable(keyToActivitiesMapRef.current.values(), (total, { length }) => total + length, 0) !== numActivities
) {
console.warn(
'botframework-webchat internal assertion: "keyToActivitiesMap.size" should be same as "activities.length".'
);
}
if (activityKeysState[0].length !== keyToActivitiesMapRef.current.size) {
console.warn(
'botframework-webchat internal assertion: "activityKeys.length" should be same as "keyToActivitiesMap.size".'
);
}
return <ActivityKeyerContext.Provider value={contextValue}>{children}</ActivityKeyerContext.Provider>;
};
export default ActivityKeyerComposer;