@webex/plugin-meetings 3.10.0-next.9 → 3.10.0-webex-services-ready.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/breakouts/breakout.js +1 -1
  2. package/dist/breakouts/index.js +1 -1
  3. package/dist/constants.js +11 -3
  4. package/dist/constants.js.map +1 -1
  5. package/dist/hashTree/constants.js +20 -0
  6. package/dist/hashTree/constants.js.map +1 -0
  7. package/dist/hashTree/hashTree.js +515 -0
  8. package/dist/hashTree/hashTree.js.map +1 -0
  9. package/dist/hashTree/hashTreeParser.js +1266 -0
  10. package/dist/hashTree/hashTreeParser.js.map +1 -0
  11. package/dist/hashTree/types.js +21 -0
  12. package/dist/hashTree/types.js.map +1 -0
  13. package/dist/hashTree/utils.js +48 -0
  14. package/dist/hashTree/utils.js.map +1 -0
  15. package/dist/interpretation/index.js +1 -1
  16. package/dist/interpretation/siLanguage.js +1 -1
  17. package/dist/locus-info/index.js +511 -48
  18. package/dist/locus-info/index.js.map +1 -1
  19. package/dist/locus-info/types.js +7 -0
  20. package/dist/locus-info/types.js.map +1 -0
  21. package/dist/meeting/index.js +41 -15
  22. package/dist/meeting/index.js.map +1 -1
  23. package/dist/meeting/util.js +1 -0
  24. package/dist/meeting/util.js.map +1 -1
  25. package/dist/meetings/index.js +112 -70
  26. package/dist/meetings/index.js.map +1 -1
  27. package/dist/metrics/constants.js +3 -1
  28. package/dist/metrics/constants.js.map +1 -1
  29. package/dist/reachability/clusterReachability.js +44 -358
  30. package/dist/reachability/clusterReachability.js.map +1 -1
  31. package/dist/reachability/reachability.types.js +14 -1
  32. package/dist/reachability/reachability.types.js.map +1 -1
  33. package/dist/reachability/reachabilityPeerConnection.js +445 -0
  34. package/dist/reachability/reachabilityPeerConnection.js.map +1 -0
  35. package/dist/types/constants.d.ts +26 -21
  36. package/dist/types/hashTree/constants.d.ts +8 -0
  37. package/dist/types/hashTree/hashTree.d.ts +129 -0
  38. package/dist/types/hashTree/hashTreeParser.d.ts +260 -0
  39. package/dist/types/hashTree/types.d.ts +25 -0
  40. package/dist/types/hashTree/utils.d.ts +9 -0
  41. package/dist/types/locus-info/index.d.ts +91 -42
  42. package/dist/types/locus-info/types.d.ts +46 -0
  43. package/dist/types/meeting/index.d.ts +22 -9
  44. package/dist/types/meetings/index.d.ts +9 -2
  45. package/dist/types/metrics/constants.d.ts +2 -0
  46. package/dist/types/reachability/clusterReachability.d.ts +10 -88
  47. package/dist/types/reachability/reachability.types.d.ts +12 -1
  48. package/dist/types/reachability/reachabilityPeerConnection.d.ts +111 -0
  49. package/dist/webinar/index.js +1 -1
  50. package/package.json +22 -21
  51. package/src/constants.ts +13 -1
  52. package/src/hashTree/constants.ts +9 -0
  53. package/src/hashTree/hashTree.ts +463 -0
  54. package/src/hashTree/hashTreeParser.ts +1161 -0
  55. package/src/hashTree/types.ts +30 -0
  56. package/src/hashTree/utils.ts +42 -0
  57. package/src/locus-info/index.ts +556 -85
  58. package/src/locus-info/types.ts +48 -0
  59. package/src/meeting/index.ts +58 -26
  60. package/src/meeting/util.ts +1 -0
  61. package/src/meetings/index.ts +104 -51
  62. package/src/metrics/constants.ts +2 -0
  63. package/src/reachability/clusterReachability.ts +50 -347
  64. package/src/reachability/reachability.types.ts +15 -1
  65. package/src/reachability/reachabilityPeerConnection.ts +416 -0
  66. package/test/unit/spec/hashTree/hashTree.ts +655 -0
  67. package/test/unit/spec/hashTree/hashTreeParser.ts +1532 -0
  68. package/test/unit/spec/hashTree/utils.ts +103 -0
  69. package/test/unit/spec/locus-info/index.js +667 -1
  70. package/test/unit/spec/meeting/index.js +91 -20
  71. package/test/unit/spec/meeting/utils.js +77 -0
  72. package/test/unit/spec/meetings/index.js +71 -26
  73. package/test/unit/spec/reachability/clusterReachability.ts +281 -138
@@ -0,0 +1,1161 @@
1
+ import {cloneDeep, isEmpty, zip} from 'lodash';
2
+ import HashTree, {LeafDataItem} from './hashTree';
3
+ import LoggerProxy from '../common/logs/logger-proxy';
4
+ import {Enum, HTTP_VERBS} from '../constants';
5
+ import {DataSetNames, EMPTY_HASH} from './constants';
6
+ import {ObjectType, HtMeta} from './types';
7
+ import {LocusDTO} from '../locus-info/types';
8
+ import {deleteNestedObjectsWithHtMeta} from './utils';
9
+
10
+ export interface DataSet {
11
+ url: string;
12
+ root: string;
13
+ version: number;
14
+ leafCount: number;
15
+ name: string;
16
+ idleMs: number;
17
+ backoff: {
18
+ maxMs: number;
19
+ exponent: number;
20
+ };
21
+ }
22
+
23
+ export interface HashTreeObject {
24
+ htMeta: HtMeta;
25
+ data: Record<string, any>;
26
+ }
27
+
28
+ export interface RootHashMessage {
29
+ dataSets: Array<DataSet>;
30
+ }
31
+ export interface HashTreeMessage {
32
+ dataSets: Array<DataSet>;
33
+ visibleDataSetsUrl: string; // url from which we can get more info about all data sets - now it seems to be visibleDataSetsUrl
34
+ locusStateElements?: Array<HashTreeObject>;
35
+ locusSessionId?: string;
36
+ locusUrl: string;
37
+ }
38
+
39
+ interface InternalDataSet extends DataSet {
40
+ hashTree?: HashTree; // set only for visible data sets
41
+ timer?: ReturnType<typeof setTimeout>;
42
+ }
43
+
44
+ type WebexRequestMethod = (options: Record<string, any>) => Promise<any>;
45
+
46
+ export const LocusInfoUpdateType = {
47
+ OBJECTS_UPDATED: 'OBJECTS_UPDATED',
48
+ MEETING_ENDED: 'MEETING_ENDED',
49
+ } as const;
50
+
51
+ export type LocusInfoUpdateType = Enum<typeof LocusInfoUpdateType>;
52
+ export type LocusInfoUpdateCallback = (
53
+ updateType: LocusInfoUpdateType,
54
+ data?: {updatedObjects: HashTreeObject[]}
55
+ ) => void;
56
+
57
+ /**
58
+ * This error is thrown if we receive information that the meeting has ended while we're processing some hash messages.
59
+ * It's handled internally by HashTreeParser and results in MEETING_ENDED being sent up.
60
+ */
61
+ class MeetingEndedError extends Error {}
62
+
63
+ /**
64
+ * Checks if the given hash tree object is of type "self"
65
+ * @param {HashTreeObject} object object to check
66
+ * @returns {boolean} True if the object is of type "self", false otherwise
67
+ */
68
+ export function isSelf(object: HashTreeObject) {
69
+ return object.htMeta.elementId.type.toLowerCase() === ObjectType.self;
70
+ }
71
+
72
+ /**
73
+ * Parses hash tree eventing locus data
74
+ */
75
+ class HashTreeParser {
76
+ dataSets: Record<string, InternalDataSet> = {};
77
+ visibleDataSetsUrl: string; // url from which we can get info about all data sets
78
+ webexRequest: WebexRequestMethod;
79
+ locusInfoUpdateCallback: LocusInfoUpdateCallback;
80
+ visibleDataSets: string[];
81
+ debugId: string;
82
+
83
+ /**
84
+ * Constructor for HashTreeParser
85
+ * @param {Object} options
86
+ * @param {Object} options.initialLocus The initial locus data containing the hash tree information
87
+ */
88
+ constructor(options: {
89
+ initialLocus: {
90
+ dataSets: Array<DataSet>;
91
+ locus: any;
92
+ };
93
+ webexRequest: WebexRequestMethod;
94
+ locusInfoUpdateCallback: LocusInfoUpdateCallback;
95
+ debugId: string;
96
+ }) {
97
+ const {dataSets, locus} = options.initialLocus; // extract dataSets from initialLocus
98
+
99
+ this.debugId = options.debugId;
100
+ this.webexRequest = options.webexRequest;
101
+ this.locusInfoUpdateCallback = options.locusInfoUpdateCallback;
102
+ this.visibleDataSets = locus?.self?.visibleDataSets || [];
103
+
104
+ if (this.visibleDataSets.length === 0) {
105
+ LoggerProxy.logger.warn(
106
+ `HashTreeParser#constructor --> ${this.debugId} No visibleDataSets found in locus.self`
107
+ );
108
+ }
109
+ // object mapping dataset names to arrays of leaf data
110
+ const leafData = this.analyzeLocusHtMeta(locus);
111
+
112
+ LoggerProxy.logger.info(
113
+ `HashTreeParser#constructor --> creating HashTreeParser for datasets: ${JSON.stringify(
114
+ dataSets.map((ds) => ds.name)
115
+ )}`
116
+ );
117
+
118
+ for (const dataSet of dataSets) {
119
+ const {name, leafCount} = dataSet;
120
+
121
+ this.dataSets[name] = {
122
+ ...dataSet,
123
+ hashTree: this.visibleDataSets.includes(name)
124
+ ? new HashTree(leafData[name] || [], leafCount)
125
+ : undefined,
126
+ };
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Initializes a new visible data set by creating a hash tree for it, adding it to all the internal structures,
132
+ * and sending an initial sync request to Locus with empty leaf data - that will trigger Locus to gives us all the data
133
+ * from that dataset (in the response or via messages).
134
+ *
135
+ * @param {DataSet} dataSet The new data set to be added
136
+ * @returns {Promise}
137
+ */
138
+ private initializeNewVisibleDataSet(
139
+ dataSet: DataSet
140
+ ): Promise<{updateType: LocusInfoUpdateType; updatedObjects?: HashTreeObject[]}> {
141
+ if (this.visibleDataSets.includes(dataSet.name)) {
142
+ LoggerProxy.logger.info(
143
+ `HashTreeParser#initializeNewVisibleDataSet --> ${this.debugId} Data set "${dataSet.name}" already exists, skipping init`
144
+ );
145
+
146
+ return Promise.resolve({updateType: LocusInfoUpdateType.OBJECTS_UPDATED, updatedObjects: []});
147
+ }
148
+
149
+ LoggerProxy.logger.info(
150
+ `HashTreeParser#initializeNewVisibleDataSet --> ${this.debugId} Adding visible data set "${dataSet.name}"`
151
+ );
152
+
153
+ this.visibleDataSets.push(dataSet.name);
154
+
155
+ const hashTree = new HashTree([], dataSet.leafCount);
156
+
157
+ this.dataSets[dataSet.name] = {
158
+ ...dataSet,
159
+ hashTree,
160
+ };
161
+
162
+ return this.sendInitializationSyncRequestToLocus(dataSet.name, 'new visible data set');
163
+ }
164
+
165
+ /**
166
+ * Sends a special sync request to Locus with all leaves empty - this is a way to get all the data for a given dataset.
167
+ *
168
+ * @param {string} datasetName - name of the dataset for which to send the request
169
+ * @param {string} debugText - text to include in logs
170
+ * @returns {Promise}
171
+ */
172
+ private sendInitializationSyncRequestToLocus(
173
+ datasetName: string,
174
+ debugText: string
175
+ ): Promise<{updateType: LocusInfoUpdateType; updatedObjects?: HashTreeObject[]}> {
176
+ const dataset = this.dataSets[datasetName];
177
+
178
+ if (!dataset) {
179
+ LoggerProxy.logger.warn(
180
+ `HashTreeParser#sendInitializationSyncRequestToLocus --> ${this.debugId} No data set found for ${datasetName}, cannot send the request for leaf data`
181
+ );
182
+
183
+ return Promise.resolve(null);
184
+ }
185
+
186
+ const emptyLeavesData = new Array(dataset.leafCount).fill([]);
187
+
188
+ LoggerProxy.logger.info(
189
+ `HashTreeParser#sendInitializationSyncRequestToLocus --> ${this.debugId} Sending initial sync request to Locus for data set "${datasetName}" with empty leaf data`
190
+ );
191
+
192
+ return this.sendSyncRequestToLocus(this.dataSets[datasetName], emptyLeavesData).then(
193
+ (syncResponse) => {
194
+ if (syncResponse) {
195
+ return this.parseMessage(
196
+ syncResponse,
197
+ `via empty leaves /sync API call for ${debugText}`
198
+ );
199
+ }
200
+
201
+ return {updateType: LocusInfoUpdateType.OBJECTS_UPDATED, updatedObjects: []};
202
+ }
203
+ );
204
+ }
205
+
206
+ /**
207
+ * Queries Locus for information about all the data sets
208
+ *
209
+ * @param {string} url - url from which we can get info about all data sets
210
+ * @returns {Promise}
211
+ */
212
+ private getAllDataSetsMetadata(url) {
213
+ return this.webexRequest({
214
+ method: HTTP_VERBS.GET,
215
+ uri: url,
216
+ }).then((response) => {
217
+ return response.body.dataSets as Array<DataSet>;
218
+ });
219
+ }
220
+
221
+ /**
222
+ * Initializes the hash tree parser from a message received from Locus.
223
+ *
224
+ * @param {HashTreeMessage} message - initial hash tree message received from Locus
225
+ * @returns {Promise}
226
+ */
227
+ async initializeFromMessage(message: HashTreeMessage) {
228
+ LoggerProxy.logger.info(
229
+ `HashTreeParser#initializeFromMessage --> ${this.debugId} visibleDataSetsUrl=${message.visibleDataSetsUrl}`
230
+ );
231
+ const dataSets = await this.getAllDataSetsMetadata(message.visibleDataSetsUrl);
232
+
233
+ await this.initializeDataSets(dataSets, 'initialization from message');
234
+ }
235
+
236
+ /**
237
+ * Initializes the hash tree parser from GET /loci API response by fetching all data sets metadata
238
+ * first and then doing an initialization sync on each data set
239
+ *
240
+ * This function requires that this.visibleDataSets have been already populated correctly by the constructor.
241
+ *
242
+ * @param {LocusDTO} locus - locus object received from GET /loci
243
+ * @returns {Promise}
244
+ */
245
+ async initializeFromGetLociResponse(locus: LocusDTO) {
246
+ if (!locus?.links?.resources?.visibleDataSets?.url) {
247
+ LoggerProxy.logger.warn(
248
+ `HashTreeParser#initializeFromGetLociResponse --> ${this.debugId} missing visibleDataSets url in GET Loci response, cannot initialize hash trees`
249
+ );
250
+
251
+ return;
252
+ }
253
+
254
+ LoggerProxy.logger.info(
255
+ `HashTreeParser#initializeFromGetLociResponse --> ${this.debugId} visibleDataSets url: ${locus.links.resources.visibleDataSets.url}`
256
+ );
257
+
258
+ const dataSets = await this.getAllDataSetsMetadata(locus.links.resources.visibleDataSets.url);
259
+
260
+ await this.initializeDataSets(dataSets, 'initialization from GET /loci response');
261
+ }
262
+
263
+ /**
264
+ * Initializes data sets by doing an initialization sync on each visible data set that doesn't have a hash tree yet.
265
+ *
266
+ * @param {DataSet[]} dataSets Array of DataSet objects to initialize
267
+ * @param {string} debugText Text to include in logs for debugging purposes
268
+ * @returns {Promise}
269
+ */
270
+ private async initializeDataSets(dataSets: Array<DataSet>, debugText: string) {
271
+ const updatedObjects: HashTreeObject[] = [];
272
+
273
+ for (const dataSet of dataSets) {
274
+ const {name, leafCount} = dataSet;
275
+
276
+ if (!this.dataSets[name]) {
277
+ LoggerProxy.logger.info(
278
+ `HashTreeParser#initializeDataSets --> ${this.debugId} initializing dataset "${name}" (${debugText})`
279
+ );
280
+
281
+ this.dataSets[name] = {
282
+ ...dataSet,
283
+ };
284
+ } else {
285
+ LoggerProxy.logger.info(
286
+ `HashTreeParser#initializeDataSets --> ${this.debugId} dataset "${name}" already exists (${debugText})`
287
+ );
288
+ }
289
+
290
+ if (this.visibleDataSets.includes(name) && !this.dataSets[name].hashTree) {
291
+ LoggerProxy.logger.info(
292
+ `HashTreeParser#initializeDataSets --> ${this.debugId} creating hash tree for visible dataset "${name}" (${debugText})`
293
+ );
294
+ this.dataSets[name].hashTree = new HashTree([], leafCount);
295
+
296
+ // eslint-disable-next-line no-await-in-loop
297
+ const data = await this.sendInitializationSyncRequestToLocus(name, debugText);
298
+
299
+ if (data.updateType === LocusInfoUpdateType.MEETING_ENDED) {
300
+ LoggerProxy.logger.warn(
301
+ `HashTreeParser#initializeDataSets --> ${this.debugId} meeting ended while initializing new visible data set "${name}"`
302
+ );
303
+
304
+ // throw an error, it will be caught higher up and the meeting will be destroyed
305
+ throw new MeetingEndedError();
306
+ }
307
+
308
+ if (data.updateType === LocusInfoUpdateType.OBJECTS_UPDATED) {
309
+ updatedObjects.push(...(data.updatedObjects || []));
310
+ }
311
+ }
312
+ }
313
+
314
+ this.callLocusInfoUpdateCallback({
315
+ updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
316
+ updatedObjects,
317
+ });
318
+ }
319
+
320
+ /**
321
+ * Each dataset exists at a different place in the dto
322
+ * iterate recursively over the locus and if it has a htMeta key,
323
+ * create an object with the type, id and version and add it to the appropriate leafData array
324
+ *
325
+ * @param {any} locus - The current part of the locus being processed
326
+ * @param {Object} [options]
327
+ * @param {boolean} [options.copyData=false] - Whether to copy the data for each leaf into returned result
328
+ * @returns {any} - An object mapping dataset names to arrays of leaf data
329
+ */
330
+ private analyzeLocusHtMeta(locus: any, options?: {copyData?: boolean}) {
331
+ const {copyData = false} = options || {};
332
+ // object mapping dataset names to arrays of leaf data
333
+ const leafInfo: Record<
334
+ string,
335
+ Array<{type: ObjectType; id: number; version: number; data?: any}>
336
+ > = {};
337
+
338
+ const findAndStoreMetaData = (currentLocusPart: any) => {
339
+ if (typeof currentLocusPart !== 'object' || currentLocusPart === null) {
340
+ return;
341
+ }
342
+
343
+ if (currentLocusPart.htMeta && currentLocusPart.htMeta.dataSetNames) {
344
+ const {type, id, version} = currentLocusPart.htMeta.elementId;
345
+ const {dataSetNames} = currentLocusPart.htMeta;
346
+ const newLeafInfo: {type: ObjectType; id: number; version: number; data?: any} = {
347
+ type,
348
+ id,
349
+ version,
350
+ };
351
+
352
+ if (copyData) {
353
+ newLeafInfo.data = cloneDeep(currentLocusPart);
354
+
355
+ // remove any nested other objects that have their own htMeta
356
+ deleteNestedObjectsWithHtMeta(newLeafInfo.data);
357
+ }
358
+
359
+ for (const dataSetName of dataSetNames) {
360
+ if (!leafInfo[dataSetName]) {
361
+ leafInfo[dataSetName] = [];
362
+ }
363
+ leafInfo[dataSetName].push(newLeafInfo);
364
+ }
365
+ }
366
+
367
+ if (Array.isArray(currentLocusPart)) {
368
+ for (const item of currentLocusPart) {
369
+ findAndStoreMetaData(item);
370
+ }
371
+ } else {
372
+ for (const key of Object.keys(currentLocusPart)) {
373
+ if (Object.prototype.hasOwnProperty.call(currentLocusPart, key)) {
374
+ findAndStoreMetaData(currentLocusPart[key]);
375
+ }
376
+ }
377
+ }
378
+ };
379
+
380
+ findAndStoreMetaData(locus);
381
+
382
+ return leafInfo;
383
+ }
384
+
385
+ /**
386
+ * Checks if the provided hash tree message indicates the end of the meeting and that there won't be any more updates.
387
+ *
388
+ * @param {HashTreeMessage} message - The hash tree message to check
389
+ * @returns {boolean} - Returns true if the message indicates the end of the meeting, false otherwise
390
+ */
391
+ private isEndMessage(message: HashTreeMessage) {
392
+ const mainDataSet = message.dataSets.find(
393
+ (dataSet) => dataSet.name.toLowerCase() === DataSetNames.MAIN
394
+ );
395
+
396
+ if (
397
+ mainDataSet &&
398
+ mainDataSet.leafCount === 1 &&
399
+ mainDataSet.root === EMPTY_HASH &&
400
+ this.dataSets[DataSetNames.MAIN].version < mainDataSet.version
401
+ ) {
402
+ // this is a special way for Locus to indicate that this meeting has ended
403
+ return true;
404
+ }
405
+
406
+ return false;
407
+ }
408
+
409
+ /**
410
+ * Handles the root hash heartbeat message
411
+ *
412
+ * @param {RootHashMessage} message - The root hash heartbeat message
413
+ * @returns {void}
414
+ */
415
+ private handleRootHashHeartBeatMessage(message: RootHashMessage): void {
416
+ const {dataSets} = message;
417
+
418
+ LoggerProxy.logger.info(
419
+ `HashTreeParser#handleRootHashMessage --> ${
420
+ this.debugId
421
+ } Received heartbeat root hash message with data sets: ${JSON.stringify(
422
+ dataSets.map(({name, root, leafCount, version}) => ({
423
+ name,
424
+ root,
425
+ leafCount,
426
+ version,
427
+ }))
428
+ )}`
429
+ );
430
+
431
+ dataSets.forEach((dataSet) => {
432
+ this.updateDataSetInfo(dataSet);
433
+ this.runSyncAlgorithm(dataSet);
434
+ });
435
+ }
436
+
437
+ /**
438
+ * This method should be called when we receive a partial locus DTO that contains dataSets and htMeta information
439
+ * It updates the hash trees with the new leaf data based on the received Locus
440
+ *
441
+ * @param {Object} update - The locus update containing data sets and locus information
442
+ * @returns {void}
443
+ */
444
+ handleLocusUpdate(update: {dataSets?: Array<DataSet>; locus: any}): void {
445
+ const {dataSets, locus} = update;
446
+
447
+ if (!dataSets) {
448
+ LoggerProxy.logger.warn(
449
+ `HashTreeParser#handleLocusUpdate --> ${this.debugId} received hash tree update without dataSets`
450
+ );
451
+ }
452
+ for (const dataSet of dataSets) {
453
+ this.updateDataSetInfo(dataSet);
454
+ }
455
+ const updatedObjects: HashTreeObject[] = [];
456
+
457
+ // first, analyze the locus object to extract the hash tree objects' htMeta and data from it
458
+ const leafInfo = this.analyzeLocusHtMeta(locus, {copyData: true});
459
+
460
+ // then process the data in hash trees, if it is a new version, then add it to updatedObjects
461
+ Object.keys(leafInfo).forEach((dataSetName) => {
462
+ if (this.dataSets[dataSetName]) {
463
+ if (this.dataSets[dataSetName].hashTree) {
464
+ const appliedChangesList = this.dataSets[dataSetName].hashTree.putItems(
465
+ leafInfo[dataSetName].map((leaf) => ({
466
+ id: leaf.id,
467
+ type: leaf.type,
468
+ version: leaf.version,
469
+ }))
470
+ );
471
+
472
+ zip(appliedChangesList, leafInfo[dataSetName]).forEach(([changeApplied, leaf]) => {
473
+ if (changeApplied) {
474
+ updatedObjects.push({
475
+ htMeta: {
476
+ elementId: {
477
+ type: leaf.type,
478
+ id: leaf.id,
479
+ version: leaf.version,
480
+ },
481
+ dataSetNames: [dataSetName],
482
+ },
483
+ data: leaf.data,
484
+ });
485
+ }
486
+ });
487
+ } else {
488
+ // no hash tree means that the data set is not visible
489
+ LoggerProxy.logger.warn(
490
+ `HashTreeParser#handleLocusUpdate --> ${this.debugId} received leaf data for data set "${dataSetName}" that has no hash tree created, ignoring`
491
+ );
492
+ }
493
+ } else {
494
+ LoggerProxy.logger.warn(
495
+ `HashTreeParser#handleLocusUpdate --> ${this.debugId} received leaf data for unknown data set "${dataSetName}", ignoring`
496
+ );
497
+ }
498
+ });
499
+
500
+ if (updatedObjects.length === 0) {
501
+ LoggerProxy.logger.info(
502
+ `HashTreeParser#handleLocusUpdate --> ${this.debugId} No objects updated as a result of received API response`
503
+ );
504
+ } else {
505
+ this.callLocusInfoUpdateCallback({
506
+ updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
507
+ updatedObjects,
508
+ });
509
+ }
510
+
511
+ // todo: once Locus design on how visible data sets will be communicated in subsequent API responses is confirmed,
512
+ // we'll need to check here if visible data sets have changed and update this.visibleDataSets, remove/create hash trees etc
513
+ }
514
+
515
+ /**
516
+ * Updates the internal data set information based on the received data set from Locus.
517
+ *
518
+ * @param {DataSet} receivedDataSet - The latest data set information received from Locus to update the internal state.
519
+ * @returns {void}
520
+ */
521
+ private updateDataSetInfo(receivedDataSet: DataSet) {
522
+ if (!this.dataSets[receivedDataSet.name]) {
523
+ this.dataSets[receivedDataSet.name] = {
524
+ ...receivedDataSet,
525
+ };
526
+
527
+ LoggerProxy.logger.info(
528
+ `HashTreeParser#handleMessage --> ${this.debugId} created entry for "${receivedDataSet.name}" dataset: version=${receivedDataSet.version}, root=${receivedDataSet.root}`
529
+ );
530
+
531
+ return;
532
+ }
533
+ // update our version of the dataSet
534
+ if (this.dataSets[receivedDataSet.name].version < receivedDataSet.version) {
535
+ this.dataSets[receivedDataSet.name].version = receivedDataSet.version;
536
+ this.dataSets[receivedDataSet.name].root = receivedDataSet.root;
537
+ this.dataSets[receivedDataSet.name].idleMs = receivedDataSet.idleMs;
538
+ this.dataSets[receivedDataSet.name].backoff = {
539
+ maxMs: receivedDataSet.backoff.maxMs,
540
+ exponent: receivedDataSet.backoff.exponent,
541
+ };
542
+ LoggerProxy.logger.info(
543
+ `HashTreeParser#handleMessage --> ${this.debugId} updated "${receivedDataSet.name}" to version=${receivedDataSet.version}, root=${receivedDataSet.root}`
544
+ );
545
+ }
546
+ }
547
+
548
+ /**
549
+ * Checks for changes in the visible data sets based on the updated objects.
550
+ * @param {HashTreeObject[]} updatedObjects - The list of updated hash tree objects.
551
+ * @returns {Object} An object containing the removed and added visible data sets.
552
+ */
553
+ private checkForVisibleDataSetChanges(updatedObjects: HashTreeObject[]) {
554
+ let removedDataSets: string[] = [];
555
+ let addedDataSets: string[] = [];
556
+
557
+ // visibleDataSets can only be changed by self object updates
558
+ updatedObjects.forEach((object) => {
559
+ // todo: in the future visibleDataSets will be in "Metadata" object, not in "self"
560
+ if (isSelf(object) && object.data?.visibleDataSets) {
561
+ const newVisibleDataSets = object.data.visibleDataSets;
562
+
563
+ removedDataSets = this.visibleDataSets.filter((ds) => !newVisibleDataSets.includes(ds));
564
+ addedDataSets = newVisibleDataSets.filter((ds) => !this.visibleDataSets.includes(ds));
565
+
566
+ if (removedDataSets.length > 0 || addedDataSets.length > 0) {
567
+ LoggerProxy.logger.info(
568
+ `HashTreeParser#checkForVisibleDataSetChanges --> ${
569
+ this.debugId
570
+ } visible data sets change: removed: ${removedDataSets.join(
571
+ ', '
572
+ )}, added: ${addedDataSets.join(', ')}`
573
+ );
574
+ }
575
+ }
576
+ });
577
+
578
+ return {
579
+ changeDetected: removedDataSets.length > 0 || addedDataSets.length > 0,
580
+ removedDataSets,
581
+ addedDataSets,
582
+ };
583
+ }
584
+
585
+ /**
586
+ * Deletes the hash tree for the specified data set.
587
+ *
588
+ * @param {string} dataSetName name of the data set to delete
589
+ * @returns {void}
590
+ */
591
+ private deleteHashTree(dataSetName: string) {
592
+ this.dataSets[dataSetName].hashTree = undefined;
593
+
594
+ // we also need to stop the timer as there is no hash tree anymore to sync
595
+ if (this.dataSets[dataSetName].timer) {
596
+ clearTimeout(this.dataSets[dataSetName].timer);
597
+ this.dataSets[dataSetName].timer = undefined;
598
+ }
599
+ }
600
+
601
+ /**
602
+ * Adds entries to the passed in updateObjects array
603
+ * for the changes that result from removing visible data sets and creates hash
604
+ * trees for the new visible data sets, but without populating the hash trees.
605
+ *
606
+ * This function is synchronous. If we are missing information about some new
607
+ * visible data sets and they require async initialization, the names of these data sets
608
+ * are returned in an array.
609
+ *
610
+ * @param {string[]} removedDataSets - The list of removed data sets.
611
+ * @param {string[]} addedDataSets - The list of added data sets.
612
+ * @param {HashTreeObject[]} updatedObjects - The list of updated hash tree objects to which changes will be added.
613
+ * @returns {string[]} names of data sets that couldn't be initialized synchronously
614
+ */
615
+ private processVisibleDataSetChanges(
616
+ removedDataSets: string[],
617
+ addedDataSets: string[],
618
+ updatedObjects: HashTreeObject[]
619
+ ): string[] {
620
+ const dataSetsRequiringInitialization = [];
621
+
622
+ // if a visible data set was removed, we need to tell our client that all objects from it are removed
623
+ const removedObjects: HashTreeObject[] = [];
624
+
625
+ removedDataSets.forEach((ds) => {
626
+ if (this.dataSets[ds]?.hashTree) {
627
+ for (let i = 0; i < this.dataSets[ds].hashTree.numLeaves; i += 1) {
628
+ removedObjects.push(
629
+ ...this.dataSets[ds].hashTree.getLeafData(i).map((elementId) => ({
630
+ htMeta: {
631
+ elementId,
632
+ dataSetNames: [ds],
633
+ },
634
+ data: null,
635
+ }))
636
+ );
637
+ }
638
+
639
+ this.deleteHashTree(ds);
640
+ }
641
+ });
642
+ this.visibleDataSets = this.visibleDataSets.filter((vds) => !removedDataSets.includes(vds));
643
+ updatedObjects.push(...removedObjects);
644
+
645
+ // now setup the new visible data sets
646
+ for (const ds of addedDataSets) {
647
+ const dataSetInfo = this.dataSets[ds];
648
+
649
+ if (dataSetInfo) {
650
+ if (this.visibleDataSets.includes(dataSetInfo.name)) {
651
+ LoggerProxy.logger.info(
652
+ `HashTreeParser#processVisibleDataSetChanges --> ${this.debugId} Data set "${ds}" is already visible, skipping`
653
+ );
654
+
655
+ // eslint-disable-next-line no-continue
656
+ continue;
657
+ }
658
+
659
+ LoggerProxy.logger.info(
660
+ `HashTreeParser#processVisibleDataSetChanges --> ${this.debugId} Adding visible data set "${ds}"`
661
+ );
662
+
663
+ this.visibleDataSets.push(ds);
664
+
665
+ const hashTree = new HashTree([], dataSetInfo.leafCount);
666
+
667
+ this.dataSets[dataSetInfo.name] = {
668
+ ...dataSetInfo,
669
+ hashTree,
670
+ };
671
+ } else {
672
+ LoggerProxy.logger.info(
673
+ `HashTreeParser#processVisibleDataSetChanges --> ${this.debugId} visible data set "${ds}" added but no info about it in our dataSets structures`
674
+ );
675
+ // todo: add a metric here
676
+ dataSetsRequiringInitialization.push(ds);
677
+ }
678
+ }
679
+
680
+ return dataSetsRequiringInitialization;
681
+ }
682
+
683
+ /**
684
+ * Adds entries to the passed in updateObjects array
685
+ * for the changes that result from adding and removing visible data sets.
686
+ *
687
+ * @param {HashTreeMessage} message - The hash tree message that triggered the visible data set changes.
688
+ * @param {string[]} addedDataSets - The list of added data sets.
689
+ * @returns {Promise<void>}
690
+ */
691
+ private async initializeNewVisibleDataSets(
692
+ message: HashTreeMessage,
693
+ addedDataSets: string[]
694
+ ): Promise<void> {
695
+ const allDataSets = await this.getAllDataSetsMetadata(message.visibleDataSetsUrl);
696
+
697
+ for (const ds of addedDataSets) {
698
+ const dataSetInfo = allDataSets.find((d) => d.name === ds);
699
+
700
+ LoggerProxy.logger.info(
701
+ `HashTreeParser#initializeNewVisibleDataSets --> ${this.debugId} initializing data set "${ds}"`
702
+ );
703
+
704
+ if (!dataSetInfo) {
705
+ LoggerProxy.logger.warn(
706
+ `HashTreeParser#handleHashTreeMessage --> ${this.debugId} missing info about data set "${ds}" in Locus response from visibleDataSetsUrl`
707
+ );
708
+ } else {
709
+ // we're awaiting in a loop, because in practice there will be only one new data set at a time,
710
+ // so no point in trying to parallelize this
711
+ // eslint-disable-next-line no-await-in-loop
712
+ const updates = await this.initializeNewVisibleDataSet(dataSetInfo);
713
+
714
+ this.callLocusInfoUpdateCallback(updates);
715
+ }
716
+ }
717
+ }
718
+
719
+ /**
720
+ * Parses incoming hash tree messages, updates the hash trees and returns information about the changes
721
+ *
722
+ * @param {HashTreeMessage} message - The hash tree message containing data sets and objects to be processed
723
+ * @param {string} [debugText] - Optional debug text to include in logs
724
+ * @returns {Promise}
725
+ */
726
+ private async parseMessage(
727
+ message: HashTreeMessage,
728
+ debugText?: string
729
+ ): Promise<{updateType: LocusInfoUpdateType; updatedObjects?: HashTreeObject[]}> {
730
+ const {dataSets, visibleDataSetsUrl} = message;
731
+
732
+ LoggerProxy.logger.info(
733
+ `HashTreeParser#parseMessage --> ${this.debugId} received message ${debugText || ''}:`,
734
+ message
735
+ );
736
+ if (message.locusStateElements?.length === 0) {
737
+ LoggerProxy.logger.warn(
738
+ `HashTreeParser#parseMessage --> ${this.debugId} got empty locusStateElements!!!`
739
+ );
740
+ // todo: send a metric
741
+ }
742
+
743
+ // first, update our metadata about the datasets with info from the message
744
+ this.visibleDataSetsUrl = visibleDataSetsUrl;
745
+ dataSets.forEach((dataSet) => this.updateDataSetInfo(dataSet));
746
+
747
+ if (this.isEndMessage(message)) {
748
+ LoggerProxy.logger.info(
749
+ `HashTreeParser#parseMessage --> ${this.debugId} received END message`
750
+ );
751
+ this.stopAllTimers();
752
+
753
+ return {updateType: LocusInfoUpdateType.MEETING_ENDED};
754
+ }
755
+
756
+ let isRosterDropped = false;
757
+ const updatedObjects: HashTreeObject[] = [];
758
+
759
+ // when we detect new visible datasets, it may be that the metadata about them is not
760
+ // available in the message, they will require separate async initialization
761
+ let dataSetsRequiringInitialization = [];
762
+
763
+ // first find out if there are any visible data set changes - they're signalled in SELF object updates
764
+ const selfUpdates = (message.locusStateElements || []).filter((object) =>
765
+ // todo: SPARK-744859 once Locus supports it, we will filter for "Metadata" type here instead of "self"
766
+ isSelf(object)
767
+ );
768
+
769
+ if (selfUpdates.length > 0) {
770
+ const updatedSelfObjects = [];
771
+
772
+ selfUpdates.forEach((object) => {
773
+ // todo: once Locus supports it, we will use the "view" field here instead of dataSetNames
774
+ for (const dataSetName of object.htMeta.dataSetNames) {
775
+ const hashTree = this.dataSets[dataSetName]?.hashTree;
776
+
777
+ if (hashTree && object.data) {
778
+ if (hashTree.putItem(object.htMeta.elementId)) {
779
+ updatedSelfObjects.push(object);
780
+ }
781
+ }
782
+ }
783
+ });
784
+
785
+ updatedObjects.push(...updatedSelfObjects);
786
+
787
+ const {changeDetected, removedDataSets, addedDataSets} =
788
+ this.checkForVisibleDataSetChanges(updatedSelfObjects);
789
+
790
+ if (changeDetected) {
791
+ dataSetsRequiringInitialization = this.processVisibleDataSetChanges(
792
+ removedDataSets,
793
+ addedDataSets,
794
+ updatedObjects
795
+ );
796
+ }
797
+ }
798
+
799
+ // by this point we now have this.dataSets setup for data sets from this message
800
+ // and hash trees created for the new visible data sets,
801
+ // so we can now process all the updates from the message
802
+ dataSets.forEach((dataSet) => {
803
+ if (this.dataSets[dataSet.name]) {
804
+ const {hashTree} = this.dataSets[dataSet.name];
805
+
806
+ if (hashTree) {
807
+ const locusStateElementsForThisSet = message.locusStateElements.filter((object) =>
808
+ object.htMeta.dataSetNames.includes(dataSet.name)
809
+ );
810
+
811
+ const appliedChangesList = hashTree.updateItems(
812
+ locusStateElementsForThisSet.map((object) =>
813
+ object.data
814
+ ? {operation: 'update', item: object.htMeta.elementId}
815
+ : {operation: 'remove', item: object.htMeta.elementId}
816
+ )
817
+ );
818
+
819
+ zip(appliedChangesList, locusStateElementsForThisSet).forEach(
820
+ ([changeApplied, object]) => {
821
+ if (changeApplied) {
822
+ if (isSelf(object) && !object.data) {
823
+ isRosterDropped = true;
824
+ }
825
+ // add to updatedObjects so that our locus DTO will get updated with the new object
826
+ updatedObjects.push(object);
827
+ }
828
+ }
829
+ );
830
+ } else {
831
+ LoggerProxy.logger.info(
832
+ `Locus-info:index#parseMessage --> ${this.debugId} unexpected (not visible) dataSet ${dataSet.name} received in hash tree message`
833
+ );
834
+ }
835
+ }
836
+
837
+ if (!isRosterDropped) {
838
+ this.runSyncAlgorithm(dataSet);
839
+ }
840
+ });
841
+
842
+ if (isRosterDropped) {
843
+ LoggerProxy.logger.info(
844
+ `HashTreeParser#parseMessage --> ${this.debugId} detected roster drop`
845
+ );
846
+ this.stopAllTimers();
847
+
848
+ // in case of roster drop we don't care about other updates
849
+ return {updateType: LocusInfoUpdateType.MEETING_ENDED};
850
+ }
851
+
852
+ if (dataSetsRequiringInitialization.length > 0) {
853
+ // there are some data sets that we need to initialize asynchronously
854
+ queueMicrotask(() => {
855
+ this.initializeNewVisibleDataSets(message, dataSetsRequiringInitialization);
856
+ });
857
+ }
858
+
859
+ if (updatedObjects.length === 0) {
860
+ LoggerProxy.logger.info(
861
+ `HashTreeParser#parseMessage --> ${this.debugId} No objects updated as a result of received message`
862
+ );
863
+ }
864
+
865
+ return {updateType: LocusInfoUpdateType.OBJECTS_UPDATED, updatedObjects};
866
+ }
867
+
868
+ /**
869
+ * Handles incoming hash tree messages, updates the hash trees and calls locusInfoUpdateCallback
870
+ *
871
+ * @param {HashTreeMessage} message - The hash tree message containing data sets and objects to be processed
872
+ * @param {string} [debugText] - Optional debug text to include in logs
873
+ * @returns {void}
874
+ */
875
+ async handleMessage(message: HashTreeMessage, debugText?: string): Promise<void> {
876
+ if (message.locusStateElements === undefined) {
877
+ this.handleRootHashHeartBeatMessage(message);
878
+ } else {
879
+ const updates = await this.parseMessage(message, debugText);
880
+
881
+ this.callLocusInfoUpdateCallback(updates);
882
+ }
883
+ }
884
+
885
+ /**
886
+ * Calls the updateInfo callback if there are any updates to report
887
+ *
888
+ * @param {Object} updates parsed from a Locus message
889
+ * @returns {void}
890
+ */
891
+ private callLocusInfoUpdateCallback(updates: {
892
+ updateType: LocusInfoUpdateType;
893
+ updatedObjects?: HashTreeObject[];
894
+ }) {
895
+ const {updateType, updatedObjects} = updates;
896
+
897
+ if (updateType !== LocusInfoUpdateType.OBJECTS_UPDATED || updatedObjects?.length > 0) {
898
+ this.locusInfoUpdateCallback(updateType, {updatedObjects});
899
+ }
900
+ }
901
+
902
+ /**
903
+ * Calculates a weighted backoff time that should be used for syncs
904
+ *
905
+ * @param {Object} backoff - The backoff configuration containing maxMs and exponent
906
+ * @returns {number} - A weighted backoff time based on the provided configuration, using algorithm supplied by Locus team
907
+ */
908
+ private getWeightedBackoffTime(backoff: {maxMs: number; exponent: number}): number {
909
+ const {maxMs, exponent} = backoff;
910
+
911
+ const randomValue = Math.random();
912
+
913
+ return Math.round(randomValue ** exponent * maxMs);
914
+ }
915
+
916
+ /**
917
+ * Runs the sync algorithm for the given data set.
918
+ *
919
+ * @param {DataSet} receivedDataSet - The data set to run the sync algorithm for.
920
+ * @returns {void}
921
+ */
922
+ private runSyncAlgorithm(receivedDataSet: DataSet) {
923
+ const dataSet = this.dataSets[receivedDataSet.name];
924
+
925
+ if (!dataSet) {
926
+ LoggerProxy.logger.warn(
927
+ `HashTreeParser#runSyncAlgorithm --> ${this.debugId} No data set found for ${receivedDataSet.name}, skipping sync algorithm`
928
+ );
929
+
930
+ return;
931
+ }
932
+
933
+ if (!dataSet.hashTree) {
934
+ LoggerProxy.logger.info(
935
+ `HashTreeParser#runSyncAlgorithm --> ${this.debugId} Data set "${dataSet.name}" has no hash tree, skipping sync algorithm`
936
+ );
937
+
938
+ return;
939
+ }
940
+
941
+ dataSet.hashTree.resize(receivedDataSet.leafCount);
942
+
943
+ // temporary log for the workshop // todo: remove
944
+ const ourCurrentRootHash = dataSet.hashTree.getRootHash();
945
+ LoggerProxy.logger.info(
946
+ `HashTreeParser#runSyncAlgorithm --> ${this.debugId} dataSet="${dataSet.name}" version=${dataSet.version} hashes before starting timer: ours=${ourCurrentRootHash} Locus=${dataSet.root}`
947
+ );
948
+
949
+ const delay = dataSet.idleMs + this.getWeightedBackoffTime(dataSet.backoff);
950
+
951
+ if (delay > 0) {
952
+ if (dataSet.timer) {
953
+ clearTimeout(dataSet.timer);
954
+ }
955
+
956
+ LoggerProxy.logger.info(
957
+ `HashTreeParser#runSyncAlgorithm --> ${this.debugId} setting "${dataSet.name}" sync timer for ${delay}`
958
+ );
959
+
960
+ dataSet.timer = setTimeout(async () => {
961
+ dataSet.timer = undefined;
962
+
963
+ if (!dataSet.hashTree) {
964
+ LoggerProxy.logger.warn(
965
+ `HashTreeParser#runSyncAlgorithm --> ${this.debugId} Data set "${dataSet.name}" no longer has a hash tree, cannot run sync algorithm`
966
+ );
967
+
968
+ return;
969
+ }
970
+
971
+ const rootHash = dataSet.hashTree.getRootHash();
972
+
973
+ if (dataSet.root !== rootHash) {
974
+ LoggerProxy.logger.info(
975
+ `HashTreeParser#runSyncAlgorithm --> ${this.debugId} Root hash mismatch: received=${dataSet.root}, ours=${rootHash}, syncing data set "${dataSet.name}"`
976
+ );
977
+
978
+ const mismatchedLeavesData: Record<number, LeafDataItem[]> = {};
979
+
980
+ if (dataSet.leafCount !== 1) {
981
+ let receivedHashes;
982
+
983
+ try {
984
+ // request hashes from sender
985
+ const {hashes, dataSet: latestDataSetInfo} = await this.getHashesFromLocus(
986
+ dataSet.name
987
+ );
988
+
989
+ receivedHashes = hashes;
990
+
991
+ dataSet.hashTree.resize(latestDataSetInfo.leafCount);
992
+ } catch (error) {
993
+ if (error.statusCode === 409) {
994
+ // this is a leaf count mismatch, we should do nothing, just wait for another heartbeat message from Locus
995
+ LoggerProxy.logger.info(
996
+ `HashTreeParser#getHashesFromLocus --> ${this.debugId} Got 409 when fetching hashes for data set "${dataSet.name}": ${error.message}`
997
+ );
998
+
999
+ return;
1000
+ }
1001
+ throw error;
1002
+ }
1003
+
1004
+ // identify mismatched leaves
1005
+ const mismatchedLeaveIndexes = dataSet.hashTree.diffHashes(receivedHashes);
1006
+
1007
+ mismatchedLeaveIndexes.forEach((index) => {
1008
+ mismatchedLeavesData[index] = dataSet.hashTree.getLeafData(index);
1009
+ });
1010
+ } else {
1011
+ mismatchedLeavesData[0] = dataSet.hashTree.getLeafData(0);
1012
+ }
1013
+ // request sync for mismatched leaves
1014
+ if (Object.keys(mismatchedLeavesData).length > 0) {
1015
+ const syncResponse = await this.sendSyncRequestToLocus(dataSet, mismatchedLeavesData);
1016
+
1017
+ // sync API may return nothing (in that case data will arrive via messages)
1018
+ // or it may return a response in the same format as messages
1019
+ if (syncResponse) {
1020
+ this.handleMessage(syncResponse, 'via sync API');
1021
+ }
1022
+ }
1023
+ } else {
1024
+ LoggerProxy.logger.info(
1025
+ `HashTreeParser#runSyncAlgorithm --> ${this.debugId} "${dataSet.name}" root hash matching: ${rootHash}, version=${dataSet.version}`
1026
+ );
1027
+ }
1028
+ }, delay);
1029
+ } else {
1030
+ LoggerProxy.logger.info(
1031
+ `HashTreeParser#runSyncAlgorithm --> ${this.debugId} No delay for "${dataSet.name}" data set, skipping sync timer reset/setup`
1032
+ );
1033
+ }
1034
+ }
1035
+
1036
+ /**
1037
+ * Stops all timers for the data sets to prevent any further sync attempts.
1038
+ * @returns {void}
1039
+ */
1040
+ private stopAllTimers() {
1041
+ Object.values(this.dataSets).forEach((dataSet) => {
1042
+ if (dataSet.timer) {
1043
+ clearTimeout(dataSet.timer);
1044
+ dataSet.timer = undefined;
1045
+ }
1046
+ });
1047
+ }
1048
+
1049
+ /**
1050
+ * Gets the current hashes from the locus for a specific data set.
1051
+ * @param {string} dataSetName
1052
+ * @returns {string[]}
1053
+ */
1054
+ private getHashesFromLocus(dataSetName: string) {
1055
+ LoggerProxy.logger.info(
1056
+ `HashTreeParser#getHashesFromLocus --> ${this.debugId} Requesting hashes for data set "${dataSetName}"`
1057
+ );
1058
+
1059
+ const dataSet = this.dataSets[dataSetName];
1060
+
1061
+ const url = `${dataSet.url}/hashtree`;
1062
+
1063
+ return this.webexRequest({
1064
+ method: HTTP_VERBS.GET,
1065
+ uri: url,
1066
+ })
1067
+ .then((response) => {
1068
+ const hashes = response.body?.hashes as string[] | undefined;
1069
+ const dataSetFromResponse = response.body?.dataSet;
1070
+
1071
+ if (!hashes || !Array.isArray(hashes)) {
1072
+ LoggerProxy.logger.warn(
1073
+ `HashTreeParser#getHashesFromLocus --> ${this.debugId} Locus returned invalid hashes, response body=`,
1074
+ response.body
1075
+ );
1076
+ throw new Error(`Locus returned invalid hashes: ${hashes}`);
1077
+ }
1078
+
1079
+ LoggerProxy.logger.info(
1080
+ `HashTreeParser#getHashesFromLocus --> ${
1081
+ this.debugId
1082
+ } Received hashes for data set "${dataSetName}": ${JSON.stringify(hashes)}`
1083
+ );
1084
+
1085
+ return {
1086
+ hashes,
1087
+ dataSet: dataSetFromResponse as DataSet,
1088
+ };
1089
+ })
1090
+ .catch((error) => {
1091
+ LoggerProxy.logger.error(
1092
+ `HashTreeParser#getHashesFromLocus --> ${this.debugId} Error ${error.statusCode} fetching hashes for data set "${dataSetName}":`,
1093
+ error
1094
+ );
1095
+ throw error;
1096
+ });
1097
+ }
1098
+
1099
+ /**
1100
+ * Sends a sync request to Locus for the specified data set.
1101
+ *
1102
+ * @param {InternalDataSet} dataSet The data set to sync.
1103
+ * @param {Record<number, LeafDataItem[]>} mismatchedLeavesData The mismatched leaves data to include in the sync request.
1104
+ * @returns {Promise<HashTreeMessage|null>}
1105
+ */
1106
+ private sendSyncRequestToLocus(
1107
+ dataSet: InternalDataSet,
1108
+ mismatchedLeavesData: Record<number, LeafDataItem[]>
1109
+ ): Promise<HashTreeMessage | null> {
1110
+ LoggerProxy.logger.info(
1111
+ `HashTreeParser#sendSyncRequestToLocus --> ${this.debugId} Sending sync request for data set "${dataSet.name}"`
1112
+ );
1113
+
1114
+ const url = `${dataSet.url}/sync`;
1115
+ const body = {
1116
+ dataSet: {
1117
+ name: dataSet.name,
1118
+ leafCount: dataSet.leafCount,
1119
+ root: dataSet.hashTree?.getRootHash(),
1120
+ },
1121
+ leafDataEntries: [],
1122
+ };
1123
+
1124
+ Object.keys(mismatchedLeavesData).forEach((index) => {
1125
+ body.leafDataEntries.push({
1126
+ leafIndex: parseInt(index, 10),
1127
+ elementIds: mismatchedLeavesData[index],
1128
+ });
1129
+ });
1130
+
1131
+ return this.webexRequest({
1132
+ method: HTTP_VERBS.POST,
1133
+ uri: url,
1134
+ body,
1135
+ })
1136
+ .then((resp) => {
1137
+ LoggerProxy.logger.info(
1138
+ `HashTreeParser#sendSyncRequestToLocus --> ${this.debugId} Sync request succeeded for "${dataSet.name}"`
1139
+ );
1140
+
1141
+ if (!resp.body || isEmpty(resp.body)) {
1142
+ LoggerProxy.logger.info(
1143
+ `HashTreeParser#sendSyncRequestToLocus --> ${this.debugId} Got ${resp.statusCode} with empty body for sync request for data set "${dataSet.name}", data should arrive via messages`
1144
+ );
1145
+
1146
+ return null;
1147
+ }
1148
+
1149
+ return resp.body as HashTreeMessage;
1150
+ })
1151
+ .catch((error) => {
1152
+ LoggerProxy.logger.error(
1153
+ `HashTreeParser#sendSyncRequestToLocus --> ${this.debugId} Error ${error.statusCode} sending sync request for data set "${dataSet.name}":`,
1154
+ error
1155
+ );
1156
+ throw error;
1157
+ });
1158
+ }
1159
+ }
1160
+
1161
+ export default HashTreeParser;