@webex/plugin-meetings 3.12.0-next.15 → 3.12.0-next.150

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