@webex/plugin-meetings 3.12.0-next.13 → 3.12.0-next.131

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 (232) hide show
  1. package/AGENTS.md +9 -0
  2. package/dist/aiEnableRequest/index.js +15 -2
  3. package/dist/aiEnableRequest/index.js.map +1 -1
  4. package/dist/annotation/index.js +2 -2
  5. package/dist/annotation/index.js.map +1 -1
  6. package/dist/breakouts/breakout.js +8 -3
  7. package/dist/breakouts/breakout.js.map +1 -1
  8. package/dist/breakouts/events.js +29 -14
  9. package/dist/breakouts/events.js.map +1 -1
  10. package/dist/breakouts/index.js +99 -4
  11. package/dist/breakouts/index.js.map +1 -1
  12. package/dist/common/errors/webex-errors.js +49 -5
  13. package/dist/common/errors/webex-errors.js.map +1 -1
  14. package/dist/config.js +2 -2
  15. package/dist/config.js.map +1 -1
  16. package/dist/constants.js +37 -10
  17. package/dist/constants.js.map +1 -1
  18. package/dist/controls-options-manager/index.js +46 -10
  19. package/dist/controls-options-manager/index.js.map +1 -1
  20. package/dist/hashTree/constants.js +4 -1
  21. package/dist/hashTree/constants.js.map +1 -1
  22. package/dist/hashTree/hashTreeParser.js +1045 -393
  23. package/dist/hashTree/hashTreeParser.js.map +1 -1
  24. package/dist/hashTree/utils.js +20 -0
  25. package/dist/hashTree/utils.js.map +1 -1
  26. package/dist/index.js +7 -0
  27. package/dist/index.js.map +1 -1
  28. package/dist/interceptors/dataChannelAuthToken.js +75 -15
  29. package/dist/interceptors/dataChannelAuthToken.js.map +1 -1
  30. package/dist/interceptors/locusRetry.js +23 -8
  31. package/dist/interceptors/locusRetry.js.map +1 -1
  32. package/dist/interpretation/index.js +10 -1
  33. package/dist/interpretation/index.js.map +1 -1
  34. package/dist/interpretation/interpretation.types.js +7 -0
  35. package/dist/interpretation/interpretation.types.js.map +1 -0
  36. package/dist/interpretation/siLanguage.js +1 -1
  37. package/dist/locus-info/controlsUtils.js +4 -1
  38. package/dist/locus-info/controlsUtils.js.map +1 -1
  39. package/dist/locus-info/index.js +409 -122
  40. package/dist/locus-info/index.js.map +1 -1
  41. package/dist/locus-info/infoUtils.js +36 -5
  42. package/dist/locus-info/infoUtils.js.map +1 -1
  43. package/dist/locus-info/types.js +19 -0
  44. package/dist/locus-info/types.js.map +1 -1
  45. package/dist/media/MediaConnectionAwaiter.js +15 -2
  46. package/dist/media/MediaConnectionAwaiter.js.map +1 -1
  47. package/dist/media/index.js +8 -2
  48. package/dist/media/index.js.map +1 -1
  49. package/dist/media/properties.js +4 -5
  50. package/dist/media/properties.js.map +1 -1
  51. package/dist/meeting/in-meeting-actions.js +5 -1
  52. package/dist/meeting/in-meeting-actions.js.map +1 -1
  53. package/dist/meeting/index.js +1669 -835
  54. package/dist/meeting/index.js.map +1 -1
  55. package/dist/meeting/locusMediaRequest.js +229 -82
  56. package/dist/meeting/locusMediaRequest.js.map +1 -1
  57. package/dist/meeting/muteState.js +10 -1
  58. package/dist/meeting/muteState.js.map +1 -1
  59. package/dist/meeting/request.js +5 -2
  60. package/dist/meeting/request.js.map +1 -1
  61. package/dist/meeting/util.js +34 -2
  62. package/dist/meeting/util.js.map +1 -1
  63. package/dist/meeting-info/meeting-info-v2.js +9 -3
  64. package/dist/meeting-info/meeting-info-v2.js.map +1 -1
  65. package/dist/meetings/index.js +281 -124
  66. package/dist/meetings/index.js.map +1 -1
  67. package/dist/meetings/meetings.types.js +6 -1
  68. package/dist/meetings/meetings.types.js.map +1 -1
  69. package/dist/meetings/request.js +39 -0
  70. package/dist/meetings/request.js.map +1 -1
  71. package/dist/meetings/util.js +116 -18
  72. package/dist/meetings/util.js.map +1 -1
  73. package/dist/member/index.js +10 -0
  74. package/dist/member/index.js.map +1 -1
  75. package/dist/member/types.js.map +1 -1
  76. package/dist/member/util.js +30 -0
  77. package/dist/member/util.js.map +1 -1
  78. package/dist/members/index.js +101 -43
  79. package/dist/members/index.js.map +1 -1
  80. package/dist/members/util.js +8 -1
  81. package/dist/members/util.js.map +1 -1
  82. package/dist/metrics/constants.js +7 -1
  83. package/dist/metrics/constants.js.map +1 -1
  84. package/dist/multistream/codec/constants.js +63 -0
  85. package/dist/multistream/codec/constants.js.map +1 -0
  86. package/dist/multistream/mediaRequestManager.js +62 -15
  87. package/dist/multistream/mediaRequestManager.js.map +1 -1
  88. package/dist/multistream/receiveSlot.js +9 -0
  89. package/dist/multistream/receiveSlot.js.map +1 -1
  90. package/dist/reachability/clusterReachability.js.map +1 -1
  91. package/dist/reachability/index.js +121 -83
  92. package/dist/reachability/index.js.map +1 -1
  93. package/dist/reachability/reachability.types.js +2 -0
  94. package/dist/reachability/reachability.types.js.map +1 -1
  95. package/dist/reachability/util.js +45 -0
  96. package/dist/reachability/util.js.map +1 -1
  97. package/dist/reactions/reactions.type.js.map +1 -1
  98. package/dist/recording-controller/index.js +1 -3
  99. package/dist/recording-controller/index.js.map +1 -1
  100. package/dist/roap/turnDiscovery.js +8 -1
  101. package/dist/roap/turnDiscovery.js.map +1 -1
  102. package/dist/types/common/errors/webex-errors.d.ts +32 -2
  103. package/dist/types/config.d.ts +2 -2
  104. package/dist/types/constants.d.ts +13 -1
  105. package/dist/types/controls-options-manager/index.d.ts +16 -0
  106. package/dist/types/hashTree/constants.d.ts +1 -0
  107. package/dist/types/hashTree/hashTreeParser.d.ts +189 -22
  108. package/dist/types/hashTree/utils.d.ts +7 -0
  109. package/dist/types/index.d.ts +3 -0
  110. package/dist/types/interceptors/locusRetry.d.ts +4 -4
  111. package/dist/types/interpretation/interpretation.types.d.ts +10 -0
  112. package/dist/types/locus-info/index.d.ts +61 -7
  113. package/dist/types/locus-info/infoUtils.d.ts +8 -0
  114. package/dist/types/locus-info/types.d.ts +21 -1
  115. package/dist/types/media/MediaConnectionAwaiter.d.ts +10 -1
  116. package/dist/types/media/properties.d.ts +6 -2
  117. package/dist/types/meeting/in-meeting-actions.d.ts +4 -0
  118. package/dist/types/meeting/index.d.ts +175 -11
  119. package/dist/types/meeting/locusMediaRequest.d.ts +12 -0
  120. package/dist/types/meeting/request.d.ts +1 -0
  121. package/dist/types/meeting/util.d.ts +9 -0
  122. package/dist/types/meeting-info/meeting-info-v2.d.ts +1 -0
  123. package/dist/types/meetings/index.d.ts +38 -18
  124. package/dist/types/meetings/meetings.types.d.ts +15 -0
  125. package/dist/types/meetings/request.d.ts +14 -0
  126. package/dist/types/member/index.d.ts +1 -0
  127. package/dist/types/member/types.d.ts +1 -0
  128. package/dist/types/member/util.d.ts +9 -0
  129. package/dist/types/members/index.d.ts +15 -2
  130. package/dist/types/members/util.d.ts +1 -5
  131. package/dist/types/metrics/constants.d.ts +6 -0
  132. package/dist/types/multistream/codec/constants.d.ts +7 -0
  133. package/dist/types/multistream/mediaRequestManager.d.ts +22 -5
  134. package/dist/types/reachability/clusterReachability.d.ts +3 -3
  135. package/dist/types/reachability/index.d.ts +10 -3
  136. package/dist/types/reachability/reachability.types.d.ts +7 -0
  137. package/dist/types/reachability/util.d.ts +17 -0
  138. package/dist/types/reactions/reactions.type.d.ts +3 -0
  139. package/dist/webinar/index.js +307 -161
  140. package/dist/webinar/index.js.map +1 -1
  141. package/package.json +23 -23
  142. package/src/aiEnableRequest/index.ts +16 -0
  143. package/src/annotation/index.ts +6 -4
  144. package/src/breakouts/breakout.ts +3 -1
  145. package/src/breakouts/events.ts +33 -11
  146. package/src/breakouts/index.ts +122 -2
  147. package/src/common/errors/webex-errors.ts +50 -3
  148. package/src/config.ts +2 -2
  149. package/src/constants.ts +21 -3
  150. package/src/controls-options-manager/index.ts +62 -10
  151. package/src/hashTree/constants.ts +7 -0
  152. package/src/hashTree/hashTreeParser.ts +796 -192
  153. package/src/hashTree/utils.ts +19 -0
  154. package/src/index.ts +6 -0
  155. package/src/interceptors/dataChannelAuthToken.ts +88 -12
  156. package/src/interceptors/locusRetry.ts +25 -4
  157. package/src/interpretation/index.ts +27 -9
  158. package/src/interpretation/interpretation.types.ts +11 -0
  159. package/src/locus-info/controlsUtils.ts +3 -1
  160. package/src/locus-info/index.ts +413 -130
  161. package/src/locus-info/infoUtils.ts +41 -6
  162. package/src/locus-info/types.ts +25 -1
  163. package/src/media/MediaConnectionAwaiter.ts +21 -4
  164. package/src/media/index.ts +10 -1
  165. package/src/media/properties.ts +8 -3
  166. package/src/meeting/in-meeting-actions.ts +8 -0
  167. package/src/meeting/index.ts +923 -117
  168. package/src/meeting/locusMediaRequest.ts +106 -6
  169. package/src/meeting/muteState.ts +10 -1
  170. package/src/meeting/request.ts +11 -0
  171. package/src/meeting/util.ts +46 -5
  172. package/src/meeting-info/meeting-info-v2.ts +10 -4
  173. package/src/meetings/index.ts +178 -78
  174. package/src/meetings/meetings.types.ts +19 -0
  175. package/src/meetings/request.ts +43 -0
  176. package/src/meetings/util.ts +117 -4
  177. package/src/member/index.ts +10 -0
  178. package/src/member/types.ts +1 -0
  179. package/src/member/util.ts +29 -0
  180. package/src/members/index.ts +70 -7
  181. package/src/members/util.ts +12 -4
  182. package/src/metrics/constants.ts +6 -0
  183. package/src/multistream/codec/constants.ts +58 -0
  184. package/src/multistream/mediaRequestManager.ts +119 -28
  185. package/src/multistream/receiveSlot.ts +18 -0
  186. package/src/reachability/clusterReachability.ts +3 -2
  187. package/src/reachability/index.ts +47 -16
  188. package/src/reachability/reachability.types.ts +11 -0
  189. package/src/reachability/util.ts +36 -0
  190. package/src/reactions/reactions.type.ts +3 -0
  191. package/src/recording-controller/index.ts +1 -2
  192. package/src/roap/turnDiscovery.ts +9 -1
  193. package/src/webinar/index.ts +216 -38
  194. package/test/unit/spec/aiEnableRequest/index.ts +86 -0
  195. package/test/unit/spec/annotation/index.ts +3 -3
  196. package/test/unit/spec/breakouts/breakout.ts +9 -3
  197. package/test/unit/spec/breakouts/events.ts +120 -2
  198. package/test/unit/spec/breakouts/index.ts +223 -3
  199. package/test/unit/spec/common/errors/webex-errors.ts +78 -0
  200. package/test/unit/spec/controls-options-manager/index.js +139 -32
  201. package/test/unit/spec/hashTree/hashTreeParser.ts +2299 -243
  202. package/test/unit/spec/hashTree/utils.ts +37 -0
  203. package/test/unit/spec/interceptors/dataChannelAuthToken.ts +196 -0
  204. package/test/unit/spec/interceptors/locusRetry.ts +205 -4
  205. package/test/unit/spec/interpretation/index.ts +26 -4
  206. package/test/unit/spec/locus-info/controlsUtils.js +172 -57
  207. package/test/unit/spec/locus-info/index.js +671 -63
  208. package/test/unit/spec/locus-info/infoUtils.js +184 -1
  209. package/test/unit/spec/media/MediaConnectionAwaiter.ts +55 -0
  210. package/test/unit/spec/media/index.ts +92 -0
  211. package/test/unit/spec/media/properties.ts +23 -23
  212. package/test/unit/spec/meeting/in-meeting-actions.ts +4 -0
  213. package/test/unit/spec/meeting/index.js +2733 -116
  214. package/test/unit/spec/meeting/locusMediaRequest.ts +406 -4
  215. package/test/unit/spec/meeting/muteState.js +81 -0
  216. package/test/unit/spec/meeting/request.js +12 -0
  217. package/test/unit/spec/meeting/utils.js +153 -1
  218. package/test/unit/spec/meeting-info/meetinginfov2.js +76 -10
  219. package/test/unit/spec/meetings/index.js +486 -49
  220. package/test/unit/spec/meetings/request.js +141 -0
  221. package/test/unit/spec/meetings/utils.js +402 -51
  222. package/test/unit/spec/member/index.js +7 -0
  223. package/test/unit/spec/member/util.js +89 -0
  224. package/test/unit/spec/members/index.js +216 -0
  225. package/test/unit/spec/members/request.js +37 -1
  226. package/test/unit/spec/members/utils.js +63 -0
  227. package/test/unit/spec/multistream/mediaRequestManager.ts +501 -37
  228. package/test/unit/spec/reachability/index.ts +128 -46
  229. package/test/unit/spec/reachability/util.ts +31 -0
  230. package/test/unit/spec/recording-controller/index.js +9 -8
  231. package/test/unit/spec/roap/turnDiscovery.ts +20 -0
  232. package/test/unit/spec/webinar/index.ts +332 -31
@@ -1,11 +1,20 @@
1
1
  import {cloneDeep, isEmpty, zip} from 'lodash';
2
+ import type {LocusSyncLatencyEventName} from '@webex/internal-plugin-metrics';
2
3
  import HashTree, {LeafDataItem} from './hashTree';
3
4
  import LoggerProxy from '../common/logs/logger-proxy';
5
+ import Metrics from '../metrics';
6
+ import BEHAVIORAL_METRICS from '../metrics/constants';
4
7
  import {Enum, HTTP_VERBS} from '../constants';
5
- import {DataSetNames, DATA_SET_INIT_PRIORITY, EMPTY_HASH} from './constants';
8
+ import {DataSetNames, DATA_SET_INIT_PRIORITY, EMPTY_HASH, LLM_DATASET_NAMES} from './constants';
6
9
  import {ObjectType, HtMeta, HashTreeObject} from './types';
7
- import {LocusDTO} from '../locus-info/types';
8
- import {deleteNestedObjectsWithHtMeta, isMetadata, sortByInitPriority} from './utils';
10
+ import {LocusDTO, LocusErrorCodes} from '../locus-info/types';
11
+ import {deleteNestedObjectsWithHtMeta, isMetadata, sleep, sortByInitPriority} from './utils';
12
+
13
+ export enum SyncAllBackoffType {
14
+ NONE = 'none',
15
+ ONLY_LLM = 'onlyLLM',
16
+ ALL = 'all',
17
+ }
9
18
 
10
19
  export interface DataSet {
11
20
  url: string;
@@ -18,10 +27,12 @@ export interface DataSet {
18
27
  maxMs: number;
19
28
  exponent: number;
20
29
  };
30
+ heartbeatIntervalMs?: number;
21
31
  }
22
32
 
23
33
  export interface RootHashMessage {
24
34
  dataSets: Array<DataSet>;
35
+ heartbeatIntervalMs?: number;
25
36
  }
26
37
  export interface HashTreeMessage {
27
38
  dataSets: Array<DataSet>;
@@ -47,25 +58,65 @@ interface InternalDataSet extends DataSet {
47
58
  hashTree?: HashTree; // set only for visible data sets
48
59
  timer?: ReturnType<typeof setTimeout>;
49
60
  heartbeatWatchdogTimer?: ReturnType<typeof setTimeout>;
61
+ syncAbortController?: AbortController;
50
62
  }
51
63
 
52
64
  type WebexRequestMethod = (options: Record<string, any>) => Promise<any>;
65
+ type GenerateTrackingId = () => string | undefined;
53
66
 
54
67
  export const LocusInfoUpdateType = {
55
68
  OBJECTS_UPDATED: 'OBJECTS_UPDATED',
56
69
  MEETING_ENDED: 'MEETING_ENDED',
70
+ LOCUS_NOT_FOUND: 'LOCUS_NOT_FOUND',
57
71
  } as const;
58
72
 
59
73
  export type LocusInfoUpdateType = Enum<typeof LocusInfoUpdateType>;
60
- export type LocusInfoUpdate =
61
- | {
62
- updateType: typeof LocusInfoUpdateType.OBJECTS_UPDATED;
63
- updatedObjects: HashTreeObject[];
74
+
75
+ interface LocusUpdatePayloads {
76
+ [LocusInfoUpdateType.OBJECTS_UPDATED]: {updatedObjects: HashTreeObject[]};
77
+ [LocusInfoUpdateType.MEETING_ENDED]: unknown; // No extra data
78
+ [LocusInfoUpdateType.LOCUS_NOT_FOUND]: unknown; // No extra data
79
+ }
80
+
81
+ export type LocusInfoUpdate = {
82
+ [K in keyof LocusUpdatePayloads]: {
83
+ updateType: K;
84
+ } & LocusUpdatePayloads[K];
85
+ }[keyof LocusUpdatePayloads];
86
+
87
+ export type LocusInfoUpdateCallback = (update: LocusInfoUpdate) => void;
88
+
89
+ export type SyncLatencyTracker = {
90
+ saveLatency: (
91
+ key: 'internal.client.locus.sync.random.backoff',
92
+ value: number,
93
+ options: {
94
+ meetingId: string;
95
+ dataSetName: string;
64
96
  }
65
- | {
66
- updateType: typeof LocusInfoUpdateType.MEETING_ENDED;
97
+ ) => void;
98
+ saveTimestamp: (options: {
99
+ key: LocusSyncLatencyEventName;
100
+ options: {
101
+ meetingId: string;
102
+ dataSetName: string;
103
+ trackingId?: string;
67
104
  };
68
- export type LocusInfoUpdateCallback = (update: LocusInfoUpdate) => void;
105
+ }) => void;
106
+ clearLocusSyncLatency: (dataSetName: string, meetingId: string, trackingId?: string) => void;
107
+ };
108
+
109
+ export type HashTreeParserCallbacks = {
110
+ locusInfoUpdateCallback: LocusInfoUpdateCallback;
111
+ syncLatencyTracker?: SyncLatencyTracker;
112
+ generateTrackingId?: GenerateTrackingId;
113
+ };
114
+
115
+ const SYNC_METRICS_DATA_SETS = [
116
+ DataSetNames.MAIN,
117
+ DataSetNames.ATD_ACTIVE,
118
+ DataSetNames.ATD_UNMUTED,
119
+ ];
69
120
 
70
121
  interface LeafInfo {
71
122
  type: ObjectType;
@@ -80,6 +131,13 @@ interface LeafInfo {
80
131
  */
81
132
  export class MeetingEndedError extends Error {}
82
133
 
134
+ /**
135
+ * This error is thrown when a 404 is received from Locus hash tree endpoints, indicating that the locus URL
136
+ * is no longer valid (e.g. participant moved to a breakout room, or meeting ended).
137
+ * It's handled internally by HashTreeParser and results in LOCUS_NOT_FOUND being sent up.
138
+ */
139
+ export class LocusNotFoundError extends Error {}
140
+
83
141
  /* Currently Locus always sends Metadata objects only in the "self" dataset.
84
142
  * If this ever changes, update all the code that relies on this constant.
85
143
  */
@@ -98,13 +156,26 @@ class HashTreeParser {
98
156
  dataSets: Record<string, InternalDataSet> = {};
99
157
  visibleDataSetsUrl: string; // url from which we can get info about all data sets
100
158
  webexRequest: WebexRequestMethod;
101
- locusInfoUpdateCallback: LocusInfoUpdateCallback;
159
+ private callbacks: HashTreeParserCallbacks;
160
+ private syncLatencyMeetingId: string;
102
161
  visibleDataSets: VisibleDataSetInfo[];
103
162
  debugId: string;
104
- heartbeatIntervalMs?: number;
105
163
  private excludedDataSets: string[];
106
164
  state: 'active' | 'stopped';
107
-
165
+ private syncQueue: Array<{
166
+ dataSetName: string;
167
+ reason: string;
168
+ isInitialization?: boolean;
169
+ }> = [];
170
+
171
+ private isSyncInProgress = false;
172
+ // tracks whether syncAllDatasets is currently in its backoff delay phase and with what scope
173
+ private syncAllBackoffType: SyncAllBackoffType = SyncAllBackoffType.NONE;
174
+ // datasets that received messages during the syncAllDatasets backoff sleep and should be skipped
175
+ private dataSetsSyncedDuringBackoff: Set<string> = new Set();
176
+ private syncQueueProcessingPromise: Promise<void> = Promise.resolve();
177
+ // top-level heartbeat interval from the most recent message, used as fallback when dataset-level value is missing
178
+ private topLevelHeartbeatIntervalMs?: number;
108
179
  /**
109
180
  * Constructor for HashTreeParser
110
181
  * @param {Object} options
@@ -117,15 +188,17 @@ class HashTreeParser {
117
188
  };
118
189
  metadata: Metadata | null;
119
190
  webexRequest: WebexRequestMethod;
120
- locusInfoUpdateCallback: LocusInfoUpdateCallback;
191
+ callbacks: HashTreeParserCallbacks;
121
192
  debugId: string;
122
193
  excludedDataSets?: string[];
194
+ syncLatencyMeetingId: string;
123
195
  }) {
124
196
  const {dataSets, locus} = options.initialLocus; // extract dataSets from initialLocus
125
197
 
126
198
  this.debugId = options.debugId;
127
199
  this.webexRequest = options.webexRequest;
128
- this.locusInfoUpdateCallback = options.locusInfoUpdateCallback;
200
+ this.callbacks = options.callbacks;
201
+ this.syncLatencyMeetingId = options.syncLatencyMeetingId;
129
202
  this.excludedDataSets = options.excludedDataSets || [];
130
203
  this.visibleDataSetsUrl = locus?.links?.resources?.visibleDataSets?.url;
131
204
  this.setVisibleDataSets(options.metadata?.visibleDataSets || [], dataSets);
@@ -229,16 +302,16 @@ class HashTreeParser {
229
302
  * @param {DataSet} dataSetInfo The new data set to be added
230
303
  * @returns {Promise}
231
304
  */
232
- private initializeNewVisibleDataSet(
305
+ private async initializeNewVisibleDataSet(
233
306
  visibleDataSetInfo: VisibleDataSetInfo,
234
307
  dataSetInfo: DataSet
235
- ): Promise<LocusInfoUpdate> {
308
+ ): Promise<void> {
236
309
  if (this.isVisibleDataSet(dataSetInfo.name)) {
237
310
  LoggerProxy.logger.info(
238
311
  `HashTreeParser#initializeNewVisibleDataSet --> ${this.debugId} Data set "${dataSetInfo.name}" already exists, skipping init`
239
312
  );
240
313
 
241
- return Promise.resolve({updateType: LocusInfoUpdateType.OBJECTS_UPDATED, updatedObjects: []});
314
+ return;
242
315
  }
243
316
 
244
317
  LoggerProxy.logger.info(
@@ -246,7 +319,7 @@ class HashTreeParser {
246
319
  );
247
320
 
248
321
  if (!this.addToVisibleDataSetsList(visibleDataSetInfo)) {
249
- return Promise.resolve({updateType: LocusInfoUpdateType.OBJECTS_UPDATED, updatedObjects: []});
322
+ return;
250
323
  }
251
324
 
252
325
  const hashTree = new HashTree([], dataSetInfo.leafCount);
@@ -256,51 +329,8 @@ class HashTreeParser {
256
329
  hashTree,
257
330
  };
258
331
 
259
- return this.sendInitializationSyncRequestToLocus(dataSetInfo.name, 'new visible data set');
260
- }
261
-
262
- /**
263
- * Sends a special sync request to Locus with all leaves empty - this is a way to get all the data for a given dataset.
264
- *
265
- * @param {string} datasetName - name of the dataset for which to send the request
266
- * @param {string} debugText - text to include in logs
267
- * @returns {Promise}
268
- */
269
- private sendInitializationSyncRequestToLocus(
270
- datasetName: string,
271
- debugText: string
272
- ): Promise<LocusInfoUpdate> {
273
- const dataset = this.dataSets[datasetName];
274
-
275
- if (!dataset) {
276
- LoggerProxy.logger.warn(
277
- `HashTreeParser#sendInitializationSyncRequestToLocus --> ${this.debugId} No data set found for ${datasetName}, cannot send the request for leaf data`
278
- );
279
-
280
- return Promise.resolve({updateType: LocusInfoUpdateType.OBJECTS_UPDATED, updatedObjects: []});
281
- }
282
-
283
- const emptyLeavesData = new Array(dataset.leafCount).fill([]);
284
-
285
- LoggerProxy.logger.info(
286
- `HashTreeParser#sendInitializationSyncRequestToLocus --> ${this.debugId} Sending initial sync request to Locus for data set "${datasetName}" with empty leaf data`
287
- );
288
-
289
- return this.sendSyncRequestToLocus(this.dataSets[datasetName], emptyLeavesData).then(
290
- (syncResponse) => {
291
- if (syncResponse) {
292
- return {
293
- updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
294
- updatedObjects: this.parseMessage(
295
- syncResponse,
296
- `via empty leaves /sync API call for ${debugText}`
297
- ),
298
- };
299
- }
300
-
301
- return {updateType: LocusInfoUpdateType.OBJECTS_UPDATED, updatedObjects: []};
302
- }
303
- );
332
+ this.enqueueSyncForDataset(dataSetInfo.name, 'new visible data set initialization', true);
333
+ await this.syncQueueProcessingPromise;
304
334
  }
305
335
 
306
336
  /**
@@ -388,8 +418,6 @@ class HashTreeParser {
388
418
  return;
389
419
  }
390
420
 
391
- const updatedObjects: HashTreeObject[] = [];
392
-
393
421
  for (const dataSet of sortByInitPriority(visibleDataSets, DATA_SET_INIT_PRIORITY)) {
394
422
  const {name, leafCount, url} = dataSet;
395
423
 
@@ -426,19 +454,12 @@ class HashTreeParser {
426
454
  );
427
455
  this.dataSets[name].hashTree = new HashTree([], leafCount);
428
456
 
429
- // eslint-disable-next-line no-await-in-loop
430
- const data = await this.sendInitializationSyncRequestToLocus(name, debugText);
431
-
432
- if (data.updateType === LocusInfoUpdateType.OBJECTS_UPDATED) {
433
- updatedObjects.push(...(data.updatedObjects || []));
434
- }
457
+ this.enqueueSyncForDataset(name, `initialization sync for ${debugText}`, true);
435
458
  }
436
459
  }
437
460
 
438
- this.callLocusInfoUpdateCallback({
439
- updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
440
- updatedObjects,
441
- });
461
+ // wait for all enqueued initialization syncs to complete
462
+ await this.syncQueueProcessingPromise;
442
463
  }
443
464
 
444
465
  /**
@@ -592,12 +613,40 @@ class HashTreeParser {
592
613
  )}`
593
614
  );
594
615
 
616
+ this.cancelPendingSyncsForDataSets(dataSets.map((ds) => ds.name));
617
+
595
618
  dataSets.forEach((dataSet) => {
596
619
  this.updateDataSetInfo(dataSet);
597
620
  this.runSyncAlgorithm(dataSet);
598
621
  });
599
622
  }
600
623
 
624
+ /**
625
+ * Handles known errors that can happen during syncs
626
+ *
627
+ * @param {any} error - The error to handle
628
+ * @returns {boolean} true if the error was recognized and handled, false otherwise
629
+ */
630
+ private handleSyncErrors(error: any) {
631
+ if (error instanceof MeetingEndedError) {
632
+ this.callLocusInfoUpdateCallback({
633
+ updateType: LocusInfoUpdateType.MEETING_ENDED,
634
+ });
635
+
636
+ return true;
637
+ }
638
+ if (error instanceof LocusNotFoundError) {
639
+ this.callLocusInfoUpdateCallback({
640
+ updateType: LocusInfoUpdateType.LOCUS_NOT_FOUND,
641
+ });
642
+ this.stop();
643
+
644
+ return true;
645
+ }
646
+
647
+ return false;
648
+ }
649
+
601
650
  /**
602
651
  * Asynchronously initializes new visible data sets
603
652
  *
@@ -614,11 +663,7 @@ class HashTreeParser {
614
663
  );
615
664
  queueMicrotask(() => {
616
665
  this.initializeNewVisibleDataSets(dataSetsRequiringInitialization).catch((error) => {
617
- if (error instanceof MeetingEndedError) {
618
- this.callLocusInfoUpdateCallback({
619
- updateType: LocusInfoUpdateType.MEETING_ENDED,
620
- });
621
- } else {
666
+ if (!this.handleSyncErrors(error)) {
622
667
  LoggerProxy.logger.warn(
623
668
  `HashTreeParser#queueInitForNewVisibleDataSets --> ${
624
669
  this.debugId
@@ -696,7 +741,14 @@ class HashTreeParser {
696
741
 
697
742
  const {dataSets, locus, metadata} = update;
698
743
 
744
+ LoggerProxy.logger.info(
745
+ `HashTreeParser#handleLocusUpdate --> ${this.debugId} received update with dataSets=${dataSets
746
+ ?.map((ds) => ds.name)
747
+ .join(',')} metadata=${metadata ? 'yes' : 'no'}`
748
+ );
749
+
699
750
  if (!dataSets) {
751
+ // this happens for example when we handle GET /loci response
700
752
  LoggerProxy.logger.info(
701
753
  `HashTreeParser#handleLocusUpdate --> ${this.debugId} received hash tree update without dataSets`
702
754
  );
@@ -794,12 +846,25 @@ class HashTreeParser {
794
846
  maxMs: receivedDataSet.backoff.maxMs,
795
847
  exponent: receivedDataSet.backoff.exponent,
796
848
  };
849
+ this.dataSets[receivedDataSet.name].heartbeatIntervalMs = receivedDataSet.heartbeatIntervalMs;
797
850
  LoggerProxy.logger.info(
798
851
  `HashTreeParser#updateDataSetInfo --> ${this.debugId} updated "${receivedDataSet.name}" dataset to version=${receivedDataSet.version}, root=${receivedDataSet.root}`
799
852
  );
800
853
  }
801
854
  }
802
855
 
856
+ /**
857
+ * Updates the leaf count for a data set, resizing its hash tree accordingly.
858
+ *
859
+ * @param {InternalDataSet} dataSet - The data set to update
860
+ * @param {number} newLeafCount - The new leaf count
861
+ * @returns {void}
862
+ */
863
+ private updateDataSetLeafCount(dataSet: InternalDataSet, newLeafCount: number): void {
864
+ dataSet.hashTree?.resize(newLeafCount);
865
+ dataSet.leafCount = newLeafCount;
866
+ }
867
+
803
868
  /**
804
869
  * Checks for changes in the visible data sets based on the updated objects.
805
870
  * @param {HashTreeObject[]} updatedObjects - The list of updated hash tree objects.
@@ -850,6 +915,8 @@ class HashTreeParser {
850
915
  */
851
916
  private deleteHashTree(dataSetName: string) {
852
917
  this.dataSets[dataSetName].hashTree = undefined;
918
+ this.dataSets[dataSetName].syncAbortController?.abort();
919
+ this.dataSets[dataSetName].syncAbortController = undefined;
853
920
 
854
921
  // we also need to stop the timers as there is no hash tree anymore to sync
855
922
  if (this.dataSets[dataSetName].timer) {
@@ -979,9 +1046,7 @@ class HashTreeParser {
979
1046
  );
980
1047
  } else {
981
1048
  // eslint-disable-next-line no-await-in-loop
982
- const updates = await this.initializeNewVisibleDataSet(ds, dataSetInfo);
983
-
984
- this.callLocusInfoUpdateCallback(updates);
1049
+ await this.initializeNewVisibleDataSet(ds, dataSetInfo);
985
1050
  }
986
1051
  }
987
1052
  }
@@ -1001,19 +1066,33 @@ class HashTreeParser {
1001
1066
  const {dataSets, visibleDataSetsUrl} = message;
1002
1067
 
1003
1068
  LoggerProxy.logger.info(
1004
- `HashTreeParser#parseMessage --> ${this.debugId} received message ${debugText || ''}:`,
1005
- message
1069
+ `HashTreeParser#parseMessage --> ${this.debugId} ${
1070
+ debugText || ''
1071
+ } dataSets: ${message.dataSets
1072
+ ?.map(({name, version}) => `${name}:${version}`)
1073
+ .join(',')}, elements: ${message.locusStateElements
1074
+ ?.map(
1075
+ (el) =>
1076
+ `${el.htMeta.elementId.type}:${el.htMeta.elementId.id}:${el.htMeta.elementId.version}${
1077
+ el.data ? '+' : '-'
1078
+ }`
1079
+ )
1080
+ .join(',')}`
1006
1081
  );
1082
+
1007
1083
  if (message.locusStateElements?.length === 0) {
1008
1084
  LoggerProxy.logger.warn(
1009
1085
  `HashTreeParser#parseMessage --> ${this.debugId} got empty locusStateElements!!!`
1010
1086
  );
1011
- // todo: send a metric
1087
+ Metrics.sendBehavioralMetric(BEHAVIORAL_METRICS.HASH_TREE_EMPTY_LOCUS_STATE_ELEMENTS, {
1088
+ debugId: this.debugId,
1089
+ });
1012
1090
  }
1013
1091
 
1014
1092
  // first, update our metadata about the datasets with info from the message
1015
1093
  this.visibleDataSetsUrl = visibleDataSetsUrl;
1016
1094
  dataSets.forEach((dataSet) => this.updateDataSetInfo(dataSet));
1095
+ this.cancelPendingSyncsForDataSets(dataSets.map((ds) => ds.name));
1017
1096
 
1018
1097
  const updatedObjects: HashTreeObject[] = [];
1019
1098
 
@@ -1122,9 +1201,10 @@ class HashTreeParser {
1122
1201
  return;
1123
1202
  }
1124
1203
 
1125
- if (message.heartbeatIntervalMs) {
1126
- this.heartbeatIntervalMs = message.heartbeatIntervalMs;
1204
+ if (message.heartbeatIntervalMs !== undefined) {
1205
+ this.topLevelHeartbeatIntervalMs = message.heartbeatIntervalMs;
1127
1206
  }
1207
+
1128
1208
  if (this.isEndMessage(message)) {
1129
1209
  LoggerProxy.logger.info(
1130
1210
  `HashTreeParser#handleMessage --> ${this.debugId} received sentinel END MEETING message`
@@ -1136,6 +1216,10 @@ class HashTreeParser {
1136
1216
  this.handleRootHashHeartBeatMessage(message);
1137
1217
  this.resetHeartbeatWatchdogs(message.dataSets);
1138
1218
  } else {
1219
+ // Completion of the sync latency metric (client.locus.sync.complete) is driven solely from
1220
+ // Meeting#processLocusLLMEvent once the matching LLM message arrives. body-mode syncs return
1221
+ // the locus state elements in the /sync HTTP response body, but per design the CA metric is
1222
+ // emitted only from the LLM message path, so no completion happens here.
1139
1223
  const updatedObjects = this.parseMessage(message, debugText);
1140
1224
 
1141
1225
  this.resetHeartbeatWatchdogs(message.dataSets);
@@ -1146,6 +1230,40 @@ class HashTreeParser {
1146
1230
  }
1147
1231
  }
1148
1232
 
1233
+ /**
1234
+ * Checks if Locus sync latency metrics should be collected for a dataset.
1235
+ *
1236
+ * @param {string} dataSetName dataset name
1237
+ * @param {boolean} [isInitialization=false] whether this is an initialization sync
1238
+ * @returns {boolean}
1239
+ */
1240
+ private shouldCollectSyncMetrics(dataSetName: string, isInitialization = false): boolean {
1241
+ return Boolean(
1242
+ this.callbacks.syncLatencyTracker &&
1243
+ !isInitialization &&
1244
+ SYNC_METRICS_DATA_SETS.includes(dataSetName)
1245
+ );
1246
+ }
1247
+
1248
+ private saveSyncBackoffLatency(
1249
+ dataSetName: string,
1250
+ randomBackoffTime: number,
1251
+ isInitialization = false
1252
+ ) {
1253
+ if (!this.shouldCollectSyncMetrics(dataSetName, isInitialization)) {
1254
+ return;
1255
+ }
1256
+
1257
+ this.callbacks.syncLatencyTracker?.saveLatency(
1258
+ 'internal.client.locus.sync.random.backoff',
1259
+ Math.round(randomBackoffTime),
1260
+ {
1261
+ meetingId: this.syncLatencyMeetingId,
1262
+ dataSetName,
1263
+ }
1264
+ );
1265
+ }
1266
+
1149
1267
  /**
1150
1268
  * Calls the updateInfo callback if there are any updates to report
1151
1269
  *
@@ -1199,10 +1317,10 @@ class HashTreeParser {
1199
1317
  });
1200
1318
 
1201
1319
  if (filteredUpdates.length > 0) {
1202
- this.locusInfoUpdateCallback({updateType, updatedObjects: filteredUpdates});
1320
+ this.callbacks.locusInfoUpdateCallback({updateType, updatedObjects: filteredUpdates});
1203
1321
  }
1204
1322
  } else if (updateType !== LocusInfoUpdateType.OBJECTS_UPDATED) {
1205
- this.locusInfoUpdateCallback({updateType});
1323
+ this.callbacks.locusInfoUpdateCallback({updateType});
1206
1324
  }
1207
1325
  }
1208
1326
 
@@ -1220,88 +1338,460 @@ class HashTreeParser {
1220
1338
  return Math.round(randomValue ** exponent * maxMs);
1221
1339
  }
1222
1340
 
1341
+ /**
1342
+ * Returns a copy of a hash tree message restricted to a single dataset, keeping only the
1343
+ * requested dataset and the elements belonging to it. Used to strip out datasets that Locus
1344
+ * may include in a sync response but that we didn't request (e.g. "unjoined" sharing elements
1345
+ * with "main"), which would otherwise be applied once per dataset.
1346
+ *
1347
+ * @param {HashTreeMessage} message the sync response message
1348
+ * @param {string} dataSetName the dataset that was requested
1349
+ * @returns {HashTreeMessage} a new message containing only the requested dataset
1350
+ */
1351
+ private filterMessageToDataSet(message: HashTreeMessage, dataSetName: string): HashTreeMessage {
1352
+ const filteredOutDataSets = message.dataSets?.filter((ds) => ds.name !== dataSetName) ?? [];
1353
+ const filteredOutElements =
1354
+ message.locusStateElements?.filter((el) => !el.htMeta.dataSetNames?.includes(dataSetName)) ??
1355
+ [];
1356
+
1357
+ if (filteredOutDataSets.length > 0 || filteredOutElements.length > 0) {
1358
+ LoggerProxy.logger.info(
1359
+ `HashTreeParser#filterMessageToDataSet --> ${
1360
+ this.debugId
1361
+ } keeping only dataset "${dataSetName}", filtering out datasets: [${filteredOutDataSets
1362
+ .map((ds) => `${ds.name}:${ds.version}`)
1363
+ .join(',')}], elements: [${filteredOutElements
1364
+ .map(
1365
+ (el) =>
1366
+ `${el.htMeta?.elementId?.type}:${el.htMeta?.elementId?.id}:${el.htMeta?.elementId?.version}`
1367
+ )
1368
+ .join(',')}]`
1369
+ );
1370
+ }
1371
+
1372
+ return {
1373
+ ...message,
1374
+ dataSets: message.dataSets?.filter((ds) => ds.name === dataSetName),
1375
+ locusStateElements: message.locusStateElements?.filter((el) =>
1376
+ el.htMeta.dataSetNames?.includes(dataSetName)
1377
+ ),
1378
+ };
1379
+ }
1380
+
1223
1381
  /**
1224
1382
  * Performs a sync for the given data set.
1225
1383
  *
1226
1384
  * @param {InternalDataSet} dataSet - The data set to sync
1227
- * @param {string} rootHash - Our current root hash for this data set
1228
1385
  * @param {string} reason - The reason for the sync (used for logging)
1386
+ * @param {boolean} [isInitialization] - Whether this is an initialization sync (sends empty leaves data instead of comparing hashes)
1229
1387
  * @returns {Promise<void>}
1230
1388
  */
1231
1389
  private async performSync(
1232
1390
  dataSet: InternalDataSet,
1233
- rootHash: string,
1234
- reason: string
1391
+ reason: string,
1392
+ isInitialization?: boolean
1235
1393
  ): Promise<void> {
1236
1394
  if (!dataSet.hashTree) {
1237
1395
  return;
1238
1396
  }
1239
1397
 
1398
+ const abortController = dataSet.syncAbortController ?? new AbortController();
1399
+ dataSet.syncAbortController = abortController;
1400
+
1401
+ const {hashTree} = dataSet;
1402
+ const rootHash = hashTree.getRootHash();
1403
+ const shouldCollectMetrics = this.shouldCollectSyncMetrics(dataSet.name, isInitialization);
1404
+ // Generate two distinct tracking ids up-front. Each Locus request must carry its own unique
1405
+ // tracking id, so the /hashtree and /sync requests must not share one. hashtreeTrackingId is
1406
+ // generated first so that syncTrackingId (forced onto the /sync request, stored in metrics, and
1407
+ // used to match the LLM broadcast message) ends up with the later/higher sequence number,
1408
+ // matching the order in which Locus sees the requests. If we never call /hashtree (single-leaf
1409
+ // or initialization syncs), hashtreeTrackingId is simply unused.
1410
+ const hashtreeTrackingId = shouldCollectMetrics
1411
+ ? this.callbacks.generateTrackingId?.()
1412
+ : undefined;
1413
+ const syncTrackingId = shouldCollectMetrics ? this.callbacks.generateTrackingId?.() : undefined;
1414
+ let syncRequestSent = false;
1415
+
1416
+ if (shouldCollectMetrics) {
1417
+ this.callbacks.syncLatencyTracker?.saveTimestamp({
1418
+ key: 'internal.client.locus.sync.start',
1419
+ options: {
1420
+ meetingId: this.syncLatencyMeetingId,
1421
+ dataSetName: dataSet.name,
1422
+ trackingId: syncTrackingId,
1423
+ },
1424
+ });
1425
+ }
1426
+
1240
1427
  try {
1241
1428
  LoggerProxy.logger.info(
1242
1429
  `HashTreeParser#performSync --> ${this.debugId} ${reason}, syncing data set "${dataSet.name}"`
1243
1430
  );
1244
1431
 
1245
- const mismatchedLeavesData: Record<number, LeafDataItem[]> = {};
1432
+ let leavesData: Record<number, LeafDataItem[]> = {};
1246
1433
 
1247
- if (dataSet.leafCount !== 1) {
1248
- let receivedHashes;
1434
+ if (!isInitialization) {
1435
+ if (dataSet.leafCount !== 1) {
1436
+ let receivedHashes;
1249
1437
 
1250
- try {
1251
- // request hashes from sender
1252
- const {hashes, dataSet: latestDataSetInfo} = await this.getHashesFromLocus(
1253
- dataSet.name,
1254
- rootHash
1255
- );
1438
+ try {
1439
+ // request hashes from sender
1440
+ const hashesResult = await this.getHashesFromLocus(dataSet.name, rootHash, {
1441
+ requestTrackingId: hashtreeTrackingId,
1442
+ metricTrackingId: syncTrackingId,
1443
+ });
1256
1444
 
1257
- receivedHashes = hashes;
1445
+ if (!hashesResult) {
1446
+ // hashes match, no sync needed
1447
+ return;
1448
+ }
1258
1449
 
1259
- dataSet.hashTree.resize(latestDataSetInfo.leafCount);
1260
- } catch (error) {
1261
- if (error.statusCode === 409) {
1262
- // this is a leaf count mismatch, we should do nothing, just wait for another heartbeat message from Locus
1263
- LoggerProxy.logger.info(
1264
- `HashTreeParser#getHashesFromLocus --> ${this.debugId} Got 409 when fetching hashes for data set "${dataSet.name}": ${error.message}`
1265
- );
1450
+ receivedHashes = hashesResult.hashes;
1266
1451
 
1267
- return;
1452
+ this.updateDataSetLeafCount(dataSet, hashesResult.dataSet.leafCount);
1453
+ } catch (error: any) {
1454
+ if (error?.statusCode === 409) {
1455
+ // this is a leaf count mismatch, we should do nothing, just wait for another heartbeat message from Locus
1456
+ LoggerProxy.logger.info(
1457
+ `HashTreeParser#getHashesFromLocus --> ${this.debugId} Got 409 when fetching hashes for data set "${dataSet.name}": ${error.message}`
1458
+ );
1459
+
1460
+ return;
1461
+ }
1462
+ throw error;
1268
1463
  }
1269
- throw error;
1464
+
1465
+ // identify mismatched leaves
1466
+ const mismatchedLeaveIndexes = hashTree.diffHashes(receivedHashes);
1467
+
1468
+ mismatchedLeaveIndexes.forEach((index) => {
1469
+ leavesData[index] = hashTree.getLeafData(index);
1470
+ });
1471
+ } else {
1472
+ leavesData = {0: hashTree.getLeafData(0)};
1270
1473
  }
1474
+ }
1271
1475
 
1272
- // identify mismatched leaves
1273
- const mismatchedLeaveIndexes = dataSet.hashTree.diffHashes(receivedHashes);
1476
+ if (abortController.signal.aborted) {
1477
+ LoggerProxy.logger.info(
1478
+ `HashTreeParser#performSync --> ${this.debugId} abandoning sync for "${dataSet.name}" before /sync - message received during sync`
1479
+ );
1274
1480
 
1275
- mismatchedLeaveIndexes.forEach((index) => {
1276
- mismatchedLeavesData[index] = dataSet.hashTree.getLeafData(index);
1277
- });
1278
- } else {
1279
- mismatchedLeavesData[0] = dataSet.hashTree.getLeafData(0);
1481
+ return;
1280
1482
  }
1281
1483
  // request sync for mismatched leaves
1282
- if (Object.keys(mismatchedLeavesData).length > 0) {
1283
- const syncResponse = await this.sendSyncRequestToLocus(dataSet, mismatchedLeavesData);
1484
+ let syncResponse: HashTreeMessage | null = null;
1284
1485
 
1285
- // sync API may return nothing (in that case data will arrive via messages)
1286
- // or it may return a response in the same format as messages
1287
- if (syncResponse) {
1288
- this.handleMessage(syncResponse, 'via sync API');
1289
- }
1486
+ if (isInitialization) {
1487
+ syncResponse = await this.sendSyncRequestToLocus(
1488
+ dataSet,
1489
+ {isInitialization: true},
1490
+ syncTrackingId
1491
+ );
1492
+
1493
+ syncRequestSent = true;
1494
+ } else if (Object.keys(leavesData).length > 0) {
1495
+ syncResponse = await this.sendSyncRequestToLocus(
1496
+ dataSet,
1497
+ {mismatchedLeavesData: leavesData},
1498
+ syncTrackingId
1499
+ );
1500
+
1501
+ syncRequestSent = true;
1502
+ }
1503
+
1504
+ // sync API may return nothing (in that case data will arrive via messages)
1505
+ // or it may return a response in the same format as messages
1506
+ // We still need to restart the sync timer as a safety net in case the messages don't arrive.
1507
+ this.runSyncAlgorithm(dataSet);
1508
+
1509
+ if (syncResponse) {
1510
+ // clear the abort controller before processing the response so that
1511
+ // parseMessage() -> cancelPendingSyncsForDataSets() doesn't log a
1512
+ // misleading "aborting sync" message for this already-completed sync
1513
+ dataSet.syncAbortController = undefined;
1514
+
1515
+ // we only requested this dataset, so restrict the response to it before processing
1516
+ // (Locus may include shared datasets like "unjoined" alongside "main")
1517
+ const filteredResponse = this.filterMessageToDataSet(syncResponse, dataSet.name);
1518
+
1519
+ // the format of sync response is the same as messages, so we can reuse the same handler
1520
+ this.handleMessage(
1521
+ filteredResponse,
1522
+ `via sync API (${
1523
+ isInitialization ? 'init' : `${Object.keys(leavesData).length} mismatched leaves`
1524
+ })`
1525
+ );
1290
1526
  }
1291
1527
  } catch (error) {
1292
- if (error instanceof MeetingEndedError) {
1293
- this.callLocusInfoUpdateCallback({
1294
- updateType: LocusInfoUpdateType.MEETING_ENDED,
1295
- });
1296
- } else {
1528
+ if (!this.handleSyncErrors(error)) {
1297
1529
  LoggerProxy.logger.warn(
1298
1530
  `HashTreeParser#performSync --> ${this.debugId} error during sync for data set "${dataSet.name}":`,
1299
1531
  error
1300
1532
  );
1301
1533
  }
1534
+ } finally {
1535
+ if (shouldCollectMetrics && !syncRequestSent) {
1536
+ // Drop only this sync's in-progress record (matched by its tracking id) rather than the
1537
+ // whole dataset, so a still-pending record from an earlier successful sync isn't wiped.
1538
+ // This mirrors the native client's onSyncError(syncId) which discards a single record.
1539
+ this.callbacks.syncLatencyTracker?.clearLocusSyncLatency(
1540
+ dataSet.name,
1541
+ this.syncLatencyMeetingId,
1542
+ syncTrackingId
1543
+ );
1544
+ }
1545
+ dataSet.syncAbortController = undefined;
1302
1546
  }
1303
1547
  }
1304
1548
 
1549
+ /**
1550
+ * Cancels any pending or in-flight syncs for the specified data sets.
1551
+ * This removes matching entries from the sync queue and aborts any in-flight sync HTTP requests.
1552
+ *
1553
+ * @param {string[]} dataSetNames - The names of the data sets to cancel syncs for
1554
+ * @returns {void}
1555
+ */
1556
+ private cancelPendingSyncsForDataSets(dataSetNames: string[]): void {
1557
+ const previousLength = this.syncQueue.length;
1558
+
1559
+ this.syncQueue = this.syncQueue.filter((entry) => !dataSetNames.includes(entry.dataSetName));
1560
+
1561
+ if (previousLength !== this.syncQueue.length) {
1562
+ LoggerProxy.logger.info(
1563
+ `HashTreeParser#cancelPendingSyncsForDataSets --> ${this.debugId} removed ${
1564
+ previousLength - this.syncQueue.length
1565
+ } entries from sync queue for data sets: ${dataSetNames.join(', ')}`
1566
+ );
1567
+ }
1568
+
1569
+ this.markDataSetsForSyncAllBackoffSkip(dataSetNames);
1570
+ this.abortInFlightSyncs(dataSetNames);
1571
+ }
1572
+
1573
+ /**
1574
+ * If a syncAllDatasets backoff sleep is in progress, marks the given data sets to be skipped
1575
+ * after the sleep completes.
1576
+ *
1577
+ * @param {string[]} dataSetNames - The names of the data sets to mark
1578
+ * @returns {void}
1579
+ */
1580
+ private markDataSetsForSyncAllBackoffSkip(dataSetNames: string[]): void {
1581
+ if (this.syncAllBackoffType !== SyncAllBackoffType.NONE) {
1582
+ for (const name of dataSetNames) {
1583
+ this.dataSetsSyncedDuringBackoff.add(name);
1584
+ }
1585
+ }
1586
+ }
1587
+
1588
+ /**
1589
+ * Aborts any in-flight sync HTTP requests for the specified data sets.
1590
+ *
1591
+ * @param {string[]} dataSetNames - The names of the data sets whose syncs should be aborted
1592
+ * @returns {void}
1593
+ */
1594
+ private abortInFlightSyncs(dataSetNames: string[]): void {
1595
+ for (const name of dataSetNames) {
1596
+ if (this.dataSets[name]?.syncAbortController) {
1597
+ LoggerProxy.logger.info(
1598
+ `HashTreeParser#cancelPendingSyncsForDataSets --> ${this.debugId} aborting in-flight sync for data set "${name}"`
1599
+ );
1600
+ this.dataSets[name].syncAbortController.abort();
1601
+ }
1602
+ }
1603
+ }
1604
+
1605
+ /**
1606
+ * Enqueues a sync for the given data set. If the data set is already in the queue, the request is ignored.
1607
+ * This ensures that all syncs are executed sequentially and no more than 1 sync runs at a time.
1608
+ *
1609
+ * @param {string} dataSetName - The name of the data set to sync
1610
+ * @param {string} reason - The reason for the sync (used for logging)
1611
+ * @param {boolean} [isInitialization=false] - Whether this is an initialization sync (uses empty leaves data instead of hash comparison)
1612
+ * @returns {void}
1613
+ */
1614
+ private enqueueSyncForDataset(
1615
+ dataSetName: string,
1616
+ reason: string,
1617
+ isInitialization = false
1618
+ ): void {
1619
+ if (this.state === 'stopped') return;
1620
+
1621
+ const existingEntry = this.syncQueue.find((entry) => entry.dataSetName === dataSetName);
1622
+
1623
+ if (existingEntry) {
1624
+ if (isInitialization) {
1625
+ existingEntry.isInitialization = true;
1626
+ }
1627
+ LoggerProxy.logger.info(
1628
+ `HashTreeParser#enqueueSyncForDataset --> ${this.debugId} data set "${dataSetName}" already in sync queue, skipping`
1629
+ );
1630
+
1631
+ return;
1632
+ }
1633
+
1634
+ this.syncQueue.push({dataSetName, reason, isInitialization});
1635
+
1636
+ if (!this.isSyncInProgress) {
1637
+ this.syncQueueProcessingPromise = this.processSyncQueue();
1638
+ }
1639
+ }
1640
+
1641
+ /**
1642
+ * Processes the sync queue sequentially. Only one instance of this method runs at a time.
1643
+ *
1644
+ * @returns {Promise<void>}
1645
+ */
1646
+ private async processSyncQueue(): Promise<void> {
1647
+ if (this.isSyncInProgress) return;
1648
+
1649
+ this.isSyncInProgress = true;
1650
+ try {
1651
+ while (this.syncQueue.length > 0 && this.state !== 'stopped') {
1652
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1653
+ const {dataSetName, reason, isInitialization} = this.syncQueue.shift()!;
1654
+ const dataSet = this.dataSets[dataSetName];
1655
+
1656
+ if (!dataSet?.hashTree) {
1657
+ // eslint-disable-next-line no-continue
1658
+ continue;
1659
+ }
1660
+
1661
+ // eslint-disable-next-line no-await-in-loop
1662
+ await this.performSync(dataSet, reason, isInitialization);
1663
+ }
1664
+ } finally {
1665
+ this.isSyncInProgress = false;
1666
+ }
1667
+ }
1668
+
1669
+ /**
1670
+ * sets the backoff type for syncAllDatasets calls, which determines the scope of datasets that will be synced after the backoff delay.
1671
+ *
1672
+ * @param {boolean} onlyLLM - Whether the backoff is for a syncAllDatasets call that is syncing only LLM datasets
1673
+ * @returns {void}
1674
+ */
1675
+ private setSyncAllBackoffType(onlyLLM: boolean): void {
1676
+ this.syncAllBackoffType = onlyLLM ? SyncAllBackoffType.ONLY_LLM : SyncAllBackoffType.ALL;
1677
+ }
1678
+
1679
+ /**
1680
+ * Checks if a syncAll backoff is already in progress. If so, upgrades the scope from
1681
+ * onlyLLM to all datasets when the new call has a broader scope.
1682
+ *
1683
+ * @param {boolean} onlyLLM - Whether the current call is for LLM datasets only
1684
+ * @returns {boolean} true if a backoff is already pending (caller should return early)
1685
+ */
1686
+ private tryUpgradePendingBackoff(onlyLLM: boolean): boolean {
1687
+ if (this.syncAllBackoffType !== SyncAllBackoffType.NONE) {
1688
+ if (!onlyLLM && this.syncAllBackoffType === SyncAllBackoffType.ONLY_LLM) {
1689
+ this.setSyncAllBackoffType(false);
1690
+ LoggerProxy.logger.info(
1691
+ `HashTreeParser#syncAllDatasets --> ${this.debugId} upgraded pending syncAll from onlyLLM to all datasets`
1692
+ );
1693
+ }
1694
+
1695
+ return true;
1696
+ }
1697
+
1698
+ return false;
1699
+ }
1700
+
1701
+ /**
1702
+ * Syncs all data sets that have hash trees, one by one in sequence, using the priority order
1703
+ * provided by sortByInitPriority().
1704
+ *
1705
+ * If a call is already waiting in the backoff delay phase, a new call with a broader scope
1706
+ * (onlyLLM=false) will upgrade the pending scope, and the dataset list will be computed after
1707
+ * the backoff using the upgraded scope. After the backoff, the sync queue handles deduplication
1708
+ * so no guard is needed.
1709
+ *
1710
+ * @param {Object} [options={}] - Options for syncing
1711
+ * @param {boolean} [options.onlyLLM=false] - Whether to sync only LLM based data sets
1712
+ * @returns {Promise<void>}
1713
+ */
1714
+ public async syncAllDatasets(options: {onlyLLM?: boolean} = {}): Promise<void> {
1715
+ const {onlyLLM = false} = options;
1716
+ if (this.state === 'stopped') return;
1717
+
1718
+ // if we're already in the backoff delay phase, try to upgrade the scope instead of starting a new one
1719
+ if (this.tryUpgradePendingBackoff(onlyLLM)) {
1720
+ return;
1721
+ }
1722
+
1723
+ const dataSetsToSync = this.getSortedDataSetsWithHashTrees(onlyLLM);
1724
+
1725
+ if (dataSetsToSync.length === 0) return;
1726
+
1727
+ this.setSyncAllBackoffType(onlyLLM);
1728
+
1729
+ const delay = this.getWeightedBackoffTime(dataSetsToSync[0].backoff);
1730
+
1731
+ LoggerProxy.logger.info(
1732
+ `HashTreeParser#syncAllDatasets --> ${this.debugId} starting backoff delay of ${delay}ms (onlyLLM=${onlyLLM})`
1733
+ );
1734
+
1735
+ // delay the start of the syncs - this is a Locus requirement to avoid thundering herd issues
1736
+ await sleep(delay);
1737
+
1738
+ // read the (possibly upgraded) scope and clear the backoff flag
1739
+ const effectiveBackoffType = this.syncAllBackoffType;
1740
+ const skippedDataSets = this.dataSetsSyncedDuringBackoff;
1741
+
1742
+ this.syncAllBackoffType = SyncAllBackoffType.NONE;
1743
+ this.dataSetsSyncedDuringBackoff = new Set();
1744
+
1745
+ if ((this.state as string) === 'stopped') return;
1746
+
1747
+ // re-evaluate the dataset list after the sleep, since the scope may have been upgraded
1748
+ // and exclude datasets that received messages during the backoff sleep
1749
+ const effectiveDataSetsToSync = this.getSortedDataSetsWithHashTrees(
1750
+ effectiveBackoffType === SyncAllBackoffType.ONLY_LLM
1751
+ ).filter((ds) => !skippedDataSets.has(ds.name));
1752
+
1753
+ if (skippedDataSets.size > 0) {
1754
+ LoggerProxy.logger.info(
1755
+ `HashTreeParser#syncAllDatasets --> ${
1756
+ this.debugId
1757
+ } skipping datasets that received messages during backoff: ${[...skippedDataSets].join(
1758
+ ', '
1759
+ )}`
1760
+ );
1761
+ }
1762
+
1763
+ LoggerProxy.logger.info(
1764
+ `HashTreeParser#syncAllDatasets --> ${this.debugId} syncing ${
1765
+ effectiveBackoffType === SyncAllBackoffType.ONLY_LLM ? 'only LLM' : 'all'
1766
+ } datasets: ${effectiveDataSetsToSync.map((ds) => ds.name).join(', ')}`
1767
+ );
1768
+
1769
+ for (const ds of effectiveDataSetsToSync) {
1770
+ this.saveSyncBackoffLatency(ds.name, delay);
1771
+ this.enqueueSyncForDataset(ds.name, 'syncAllDatasets');
1772
+ }
1773
+
1774
+ await this.syncQueueProcessingPromise;
1775
+ }
1776
+
1777
+ /**
1778
+ * Returns the list of data sets that have hash trees, sorted by the priority order provided by sortByInitPriority().
1779
+ *
1780
+ * @param {boolean} onlyLLM - Whether to include only LLM based data sets
1781
+ * @returns {Array<{name: string, backoff: {maxMs: number, exponent: number}}>} The sorted list of data sets with their backoff configurations
1782
+ */
1783
+ private getSortedDataSetsWithHashTrees(onlyLLM: boolean) {
1784
+ let dataSets = Object.values(this.dataSets)
1785
+ .filter((dataSet) => dataSet?.hashTree)
1786
+ .map((dataSet) => ({name: dataSet.name, backoff: dataSet.backoff}));
1787
+
1788
+ if (onlyLLM) {
1789
+ dataSets = dataSets.filter((ds) => LLM_DATASET_NAMES.includes(ds.name));
1790
+ }
1791
+
1792
+ return sortByInitPriority(dataSets, DATA_SET_INIT_PRIORITY);
1793
+ }
1794
+
1305
1795
  /**
1306
1796
  * Runs the sync algorithm for the given data set.
1307
1797
  *
@@ -1320,33 +1810,25 @@ class HashTreeParser {
1320
1810
  }
1321
1811
 
1322
1812
  if (!dataSet.hashTree) {
1323
- LoggerProxy.logger.info(
1324
- `HashTreeParser#runSyncAlgorithm --> ${this.debugId} Data set "${dataSet.name}" has no hash tree, skipping sync algorithm`
1325
- );
1813
+ // no hash tree, so no need to do any syncing
1814
+ // we fall into this branch often, because Locus sends dataSets in messages that are not visible to us
1326
1815
 
1327
1816
  return;
1328
1817
  }
1329
1818
 
1330
1819
  dataSet.hashTree.resize(receivedDataSet.leafCount);
1331
1820
 
1332
- // temporary log for the workshop // todo: remove
1333
- const ourCurrentRootHash = dataSet.hashTree.getRootHash();
1334
- LoggerProxy.logger.info(
1335
- `HashTreeParser#runSyncAlgorithm --> ${this.debugId} dataSet="${dataSet.name}" version=${dataSet.version} hashes before starting timer: ours=${ourCurrentRootHash} Locus=${dataSet.root}`
1336
- );
1337
-
1338
- const delay = dataSet.idleMs + this.getWeightedBackoffTime(dataSet.backoff);
1821
+ const randomBackoffTime = this.getWeightedBackoffTime(dataSet.backoff);
1822
+ const delay = dataSet.idleMs + randomBackoffTime;
1339
1823
 
1340
1824
  if (delay > 0) {
1341
1825
  if (dataSet.timer) {
1342
1826
  clearTimeout(dataSet.timer);
1343
1827
  }
1344
1828
 
1345
- LoggerProxy.logger.info(
1346
- `HashTreeParser#runSyncAlgorithm --> ${this.debugId} setting "${dataSet.name}" sync timer for ${delay}`
1347
- );
1829
+ this.saveSyncBackoffLatency(dataSet.name, randomBackoffTime);
1348
1830
 
1349
- dataSet.timer = setTimeout(async () => {
1831
+ dataSet.timer = setTimeout(() => {
1350
1832
  dataSet.timer = undefined;
1351
1833
 
1352
1834
  if (!dataSet.hashTree) {
@@ -1360,15 +1842,10 @@ class HashTreeParser {
1360
1842
  const rootHash = dataSet.hashTree.getRootHash();
1361
1843
 
1362
1844
  if (dataSet.root !== rootHash) {
1363
- await this.performSync(
1364
- dataSet,
1365
- rootHash,
1845
+ this.enqueueSyncForDataset(
1846
+ dataSet.name,
1366
1847
  `Root hash mismatch: received=${dataSet.root}, ours=${rootHash}`
1367
1848
  );
1368
- } else {
1369
- LoggerProxy.logger.info(
1370
- `HashTreeParser#runSyncAlgorithm --> ${this.debugId} "${dataSet.name}" root hash matching: ${rootHash}, version=${dataSet.version}`
1371
- );
1372
1849
  }
1373
1850
  }, delay);
1374
1851
  } else {
@@ -1388,38 +1865,41 @@ class HashTreeParser {
1388
1865
  * @returns {void}
1389
1866
  */
1390
1867
  private resetHeartbeatWatchdogs(receivedDataSets: Array<DataSet>): void {
1391
- if (!this.heartbeatIntervalMs) {
1392
- return;
1393
- }
1394
-
1395
1868
  for (const receivedDataSet of receivedDataSets) {
1396
1869
  const dataSet = this.dataSets[receivedDataSet.name];
1397
1870
 
1398
- if (!dataSet?.hashTree) {
1399
- // eslint-disable-next-line no-continue
1400
- continue;
1401
- }
1402
-
1403
1871
  if (dataSet.heartbeatWatchdogTimer) {
1404
1872
  clearTimeout(dataSet.heartbeatWatchdogTimer);
1405
1873
  dataSet.heartbeatWatchdogTimer = undefined;
1406
1874
  }
1407
1875
 
1876
+ // dataset-level heartbeatIntervalMs takes priority; fall back to top-level common value
1877
+ const heartbeatIntervalMs = dataSet?.heartbeatIntervalMs ?? this.topLevelHeartbeatIntervalMs;
1878
+
1879
+ if (!dataSet?.hashTree || !heartbeatIntervalMs) {
1880
+ // eslint-disable-next-line no-continue
1881
+ continue;
1882
+ }
1883
+
1408
1884
  const backoffTime = this.getWeightedBackoffTime(dataSet.backoff);
1409
- const delay = this.heartbeatIntervalMs + backoffTime;
1885
+ const delay = heartbeatIntervalMs + backoffTime;
1410
1886
 
1411
- dataSet.heartbeatWatchdogTimer = setTimeout(async () => {
1887
+ dataSet.heartbeatWatchdogTimer = setTimeout(() => {
1412
1888
  dataSet.heartbeatWatchdogTimer = undefined;
1413
1889
 
1414
1890
  LoggerProxy.logger.warn(
1415
1891
  `HashTreeParser#resetHeartbeatWatchdogs --> ${this.debugId} Heartbeat watchdog fired for data set "${dataSet.name}" - no heartbeat received within expected interval, initiating sync`
1416
1892
  );
1417
1893
 
1418
- await this.performSync(
1419
- dataSet,
1420
- dataSet.hashTree.getRootHash(),
1421
- `heartbeat watchdog expired`
1422
- );
1894
+ Metrics.sendBehavioralMetric(BEHAVIORAL_METRICS.HASH_TREE_HEARTBEAT_WATCHDOG_EXPIRED, {
1895
+ debugId: this.debugId,
1896
+ dataSetName: dataSet.name,
1897
+ });
1898
+
1899
+ this.saveSyncBackoffLatency(dataSet.name, backoffTime);
1900
+
1901
+ this.enqueueSyncForDataset(dataSet.name, `heartbeat watchdog expired`);
1902
+ this.resetHeartbeatWatchdogs([dataSet]);
1423
1903
  }, delay);
1424
1904
  }
1425
1905
  }
@@ -1452,7 +1932,13 @@ class HashTreeParser {
1452
1932
  `HashTreeParser#stop --> ${this.debugId} Stopping HashTreeParser, clearing timers and hash trees`
1453
1933
  );
1454
1934
  this.stopAllTimers();
1935
+ this.syncQueue = [];
1936
+ this.topLevelHeartbeatIntervalMs = undefined;
1937
+ this.syncAllBackoffType = SyncAllBackoffType.NONE;
1938
+ this.dataSetsSyncedDuringBackoff = new Set();
1455
1939
  Object.values(this.dataSets).forEach((dataSet) => {
1940
+ dataSet.syncAbortController?.abort();
1941
+ dataSet.syncAbortController = undefined;
1456
1942
  dataSet.hashTree = undefined;
1457
1943
  });
1458
1944
  this.visibleDataSets = [];
@@ -1470,17 +1956,16 @@ class HashTreeParser {
1470
1956
  }
1471
1957
 
1472
1958
  /**
1473
- * Resumes the HashTreeParser that was previously stopped.
1959
+ * Resumes the HashTreeParser that was previously stopped, using a hash tree message.
1474
1960
  * @param {HashTreeMessage} message - The message to resume with, it must contain metadata with visible data sets info
1475
1961
  * @returns {void}
1476
1962
  */
1477
- public resume(message: HashTreeMessage) {
1478
- // check that message contains metadata with visible data sets - this is essential to be able to resume
1963
+ public resumeFromMessage(message: HashTreeMessage) {
1479
1964
  const metadataObject = message.locusStateElements?.find((el) => isMetadata(el));
1480
1965
 
1481
1966
  if (!metadataObject?.data?.visibleDataSets) {
1482
1967
  LoggerProxy.logger.warn(
1483
- `HashTreeParser#resume --> ${this.debugId} Cannot resume HashTreeParser because the message is missing metadata with visible data sets info`
1968
+ `HashTreeParser#resumeFromMessage --> ${this.debugId} Cannot resume HashTreeParser because the message is missing metadata with visible data sets info`
1484
1969
  );
1485
1970
 
1486
1971
  return;
@@ -1501,7 +1986,7 @@ class HashTreeParser {
1501
1986
  };
1502
1987
  }
1503
1988
  LoggerProxy.logger.info(
1504
- `HashTreeParser#resume --> ${
1989
+ `HashTreeParser#resumeFromMessage --> ${
1505
1990
  this.debugId
1506
1991
  } Resuming HashTreeParser with data sets: ${Object.keys(this.dataSets).join(
1507
1992
  ', '
@@ -1512,18 +1997,47 @@ class HashTreeParser {
1512
1997
  this.handleMessage(message, 'on resume');
1513
1998
  }
1514
1999
 
2000
+ /**
2001
+ * Resumes the HashTreeParser that was previously stopped, using a Locus API response.
2002
+ * Unlike resumeFromMessage(), this does not require metadata/dataSets in the input,
2003
+ * as it fetches all necessary information from Locus via initializeFromGetLociResponse.
2004
+ * @param {LocusDTO} locus - locus object from an API response
2005
+ * @returns {Promise}
2006
+ */
2007
+ public async resumeFromApiResponse(locus: LocusDTO) {
2008
+ this.state = 'active';
2009
+ this.dataSets = {};
2010
+
2011
+ LoggerProxy.logger.info(
2012
+ `HashTreeParser#resumeFromApiResponse --> ${this.debugId} Resuming HashTreeParser from API response`
2013
+ );
2014
+
2015
+ await this.initializeFromGetLociResponse(locus);
2016
+ }
2017
+
1515
2018
  private checkForSentinelHttpResponse(error: any, dataSetName?: string) {
2019
+ // 404 for any dataset means the locus is no longer available at this URL - could be replaced or ended
2020
+ // if a dataset is just not visible, we would get a 400
2021
+ if (error.statusCode === 404) {
2022
+ LoggerProxy.logger.info(
2023
+ `HashTreeParser#checkForSentinelHttpResponse --> ${this.debugId} Received 404 for data set "${dataSetName}", locus not found`
2024
+ );
2025
+ this.stopAllTimers();
2026
+
2027
+ throw new LocusNotFoundError();
2028
+ }
2029
+
1516
2030
  const isValidDataSetForSentinel =
1517
2031
  dataSetName === undefined ||
1518
2032
  PossibleSentinelMessageDataSetNames.includes(dataSetName.toLowerCase());
1519
2033
 
1520
2034
  if (
1521
- ((error.statusCode === 409 && error.body?.errorCode === 2403004) ||
1522
- error.statusCode === 404) &&
2035
+ error.statusCode === 409 &&
2036
+ error.body?.errorCode === LocusErrorCodes.LOCUS_INACTIVE &&
1523
2037
  isValidDataSetForSentinel
1524
2038
  ) {
1525
2039
  LoggerProxy.logger.info(
1526
- `HashTreeParser#checkForSentinelHttpResponse --> ${this.debugId} Received ${error.statusCode} for data set "${dataSetName}", indicating that the meeting has ended`
2040
+ `HashTreeParser#checkForSentinelHttpResponse --> ${this.debugId} Received ${error.statusCode}/${error.body?.errorCode} for data set "${dataSetName}", indicating that the meeting has ended`
1527
2041
  );
1528
2042
  this.stopAllTimers();
1529
2043
 
@@ -1535,9 +2049,18 @@ class HashTreeParser {
1535
2049
  * Gets the current hashes from the locus for a specific data set.
1536
2050
  * @param {string} dataSetName
1537
2051
  * @param {string} currentRootHash
1538
- * @returns {string[]}
2052
+ * @param {Object} [trackingIds] tracking ids for the /hashtree request
2053
+ * @param {string} [trackingIds.requestTrackingId] tracking id forced onto the /hashtree HTTP request header (kept distinct from the /sync request's tracking id)
2054
+ * @param {string} [trackingIds.metricTrackingId] tracking id (the /sync request's) under which the hashtree latency milestones are recorded, so they belong to the same sync latency record
2055
+ * @returns {Object|null} An object containing the hashes and leaf count, or null if the hashes match and no sync is needed
1539
2056
  */
1540
- private getHashesFromLocus(dataSetName: string, currentRootHash: string) {
2057
+ private getHashesFromLocus(
2058
+ dataSetName: string,
2059
+ currentRootHash: string,
2060
+ trackingIds?: {requestTrackingId?: string; metricTrackingId?: string}
2061
+ ) {
2062
+ const {requestTrackingId, metricTrackingId} = trackingIds ?? {};
2063
+
1541
2064
  LoggerProxy.logger.info(
1542
2065
  `HashTreeParser#getHashesFromLocus --> ${this.debugId} Requesting hashes for data set "${dataSetName}"`
1543
2066
  );
@@ -1546,14 +2069,48 @@ class HashTreeParser {
1546
2069
 
1547
2070
  const url = `${dataSet.url}/hashtree`;
1548
2071
 
2072
+ if (this.shouldCollectSyncMetrics(dataSetName)) {
2073
+ this.callbacks.syncLatencyTracker?.saveTimestamp({
2074
+ key: 'internal.client.locus.hashtree.request',
2075
+ options: {
2076
+ meetingId: this.syncLatencyMeetingId,
2077
+ dataSetName,
2078
+ trackingId: metricTrackingId,
2079
+ },
2080
+ });
2081
+ }
2082
+
1549
2083
  return this.webexRequest({
1550
2084
  method: HTTP_VERBS.GET,
1551
2085
  uri: url,
1552
2086
  qs: {
1553
2087
  rootHash: currentRootHash,
1554
2088
  },
2089
+ // Force a dedicated tracking id onto the /hashtree request so it does not share the /sync
2090
+ // request's tracking id; the tracking id interceptor leaves an already-set header untouched.
2091
+ ...(requestTrackingId ? {headers: {trackingid: requestTrackingId}} : {}),
1555
2092
  })
1556
2093
  .then((response) => {
2094
+ if (this.shouldCollectSyncMetrics(dataSetName)) {
2095
+ this.callbacks.syncLatencyTracker?.saveTimestamp({
2096
+ key: 'internal.client.locus.hashtree.response',
2097
+ options: {
2098
+ meetingId: this.syncLatencyMeetingId,
2099
+ dataSetName,
2100
+ trackingId: metricTrackingId,
2101
+ },
2102
+ });
2103
+ }
2104
+
2105
+ if (!response.body || isEmpty(response.body)) {
2106
+ // 204 with empty body means our hashes match Locus, no sync needed
2107
+ LoggerProxy.logger.info(
2108
+ `HashTreeParser#getHashesFromLocus --> ${this.debugId} Got ${response.statusCode} with empty body for data set "${dataSetName}", hashes match - no sync needed`
2109
+ );
2110
+
2111
+ return null;
2112
+ }
2113
+
1557
2114
  const hashes = response.body?.hashes as string[] | undefined;
1558
2115
  const dataSetFromResponse = response.body?.dataSet;
1559
2116
 
@@ -1582,6 +2139,13 @@ class HashTreeParser {
1582
2139
  error
1583
2140
  );
1584
2141
  this.checkForSentinelHttpResponse(error, dataSet.name);
2142
+ Metrics.sendBehavioralMetric(BEHAVIORAL_METRICS.HASH_TREE_SYNC_FAILURE, {
2143
+ debugId: this.debugId,
2144
+ dataSetName,
2145
+ request: 'GET /hashtree',
2146
+ statusCode: error.statusCode,
2147
+ reason: error.message,
2148
+ });
1585
2149
 
1586
2150
  throw error;
1587
2151
  });
@@ -1591,36 +2155,59 @@ class HashTreeParser {
1591
2155
  * Sends a sync request to Locus for the specified data set.
1592
2156
  *
1593
2157
  * @param {InternalDataSet} dataSet The data set to sync.
1594
- * @param {Record<number, LeafDataItem[]>} mismatchedLeavesData The mismatched leaves data to include in the sync request.
1595
- * @returns {Promise<HashTreeMessage|null>}
2158
+ * @param {Object} options Either `{ isInitialization: true }` for init syncs (uses leafCount=1 with empty leaf data) or `{ mismatchedLeavesData }` for normal syncs.
2159
+ * @param {string} [trackingId] tracking id
2160
+ * @returns {Promise<HashTreeMessage | null>}
1596
2161
  */
1597
2162
  private sendSyncRequestToLocus(
1598
2163
  dataSet: InternalDataSet,
1599
- mismatchedLeavesData: Record<number, LeafDataItem[]>
2164
+ options: {isInitialization: true} | {mismatchedLeavesData: Record<number, LeafDataItem[]>},
2165
+ trackingId?: string
1600
2166
  ): Promise<HashTreeMessage | null> {
1601
2167
  LoggerProxy.logger.info(
1602
2168
  `HashTreeParser#sendSyncRequestToLocus --> ${this.debugId} Sending sync request for data set "${dataSet.name}"`
1603
2169
  );
1604
2170
 
2171
+ const isInitialization = 'isInitialization' in options;
2172
+
1605
2173
  const url = `${dataSet.url}/sync`;
1606
2174
  const body: {
1607
2175
  leafCount: number;
1608
2176
  leafDataEntries: {leafIndex: number; elementIds: LeafDataItem[]}[];
1609
2177
  } = {
1610
- leafCount: dataSet.leafCount,
2178
+ leafCount: isInitialization ? 1 : dataSet.leafCount,
1611
2179
  leafDataEntries: [],
1612
2180
  };
1613
2181
 
1614
- Object.keys(mismatchedLeavesData).forEach((index) => {
1615
- const leafIndex = parseInt(index, 10);
2182
+ if (isInitialization) {
2183
+ // initialization sync: Locus requires leafCount=1 with a single empty leaf
2184
+ body.leafDataEntries.push({leafIndex: 0, elementIds: []});
2185
+ } else {
2186
+ const {mismatchedLeavesData} = options;
2187
+
2188
+ Object.keys(mismatchedLeavesData).forEach((index) => {
2189
+ const leafIndex = parseInt(index, 10);
1616
2190
 
1617
- body.leafDataEntries.push({
1618
- leafIndex,
1619
- elementIds: mismatchedLeavesData[leafIndex],
2191
+ body.leafDataEntries.push({
2192
+ leafIndex,
2193
+ elementIds: mismatchedLeavesData[leafIndex],
2194
+ });
1620
2195
  });
1621
- });
2196
+ }
1622
2197
 
1623
2198
  const ourCurrentRootHash = dataSet.hashTree ? dataSet.hashTree.getRootHash() : EMPTY_HASH;
2199
+ const shouldCollectMetrics = this.shouldCollectSyncMetrics(dataSet.name, isInitialization);
2200
+
2201
+ if (shouldCollectMetrics) {
2202
+ this.callbacks.syncLatencyTracker?.saveTimestamp({
2203
+ key: 'internal.client.locus.sync.request',
2204
+ options: {
2205
+ meetingId: this.syncLatencyMeetingId,
2206
+ dataSetName: dataSet.name,
2207
+ trackingId,
2208
+ },
2209
+ });
2210
+ }
1624
2211
 
1625
2212
  return this.webexRequest({
1626
2213
  method: HTTP_VERBS.POST,
@@ -1628,12 +2215,22 @@ class HashTreeParser {
1628
2215
  qs: {
1629
2216
  rootHash: ourCurrentRootHash,
1630
2217
  },
2218
+ // Force the pre-generated tracking id onto the /sync request so Locus echoes it back on the
2219
+ // resulting LLM message; the tracking id interceptor leaves an already-set header untouched.
2220
+ ...(trackingId ? {headers: {trackingid: trackingId}} : {}),
1631
2221
  body,
1632
2222
  })
1633
2223
  .then((resp) => {
1634
- LoggerProxy.logger.info(
1635
- `HashTreeParser#sendSyncRequestToLocus --> ${this.debugId} Sync request succeeded for "${dataSet.name}"`
1636
- );
2224
+ if (shouldCollectMetrics) {
2225
+ this.callbacks.syncLatencyTracker?.saveTimestamp({
2226
+ key: 'internal.client.locus.sync.response',
2227
+ options: {
2228
+ meetingId: this.syncLatencyMeetingId,
2229
+ dataSetName: dataSet.name,
2230
+ trackingId,
2231
+ },
2232
+ });
2233
+ }
1637
2234
 
1638
2235
  if (!resp.body || isEmpty(resp.body)) {
1639
2236
  LoggerProxy.logger.info(
@@ -1651,6 +2248,13 @@ class HashTreeParser {
1651
2248
  error
1652
2249
  );
1653
2250
  this.checkForSentinelHttpResponse(error, dataSet.name);
2251
+ Metrics.sendBehavioralMetric(BEHAVIORAL_METRICS.HASH_TREE_SYNC_FAILURE, {
2252
+ debugId: this.debugId,
2253
+ dataSetName: dataSet.name,
2254
+ request: 'POST /sync',
2255
+ statusCode: error.statusCode,
2256
+ reason: error.message,
2257
+ });
1654
2258
 
1655
2259
  throw error;
1656
2260
  });