@webex/plugin-meetings 3.12.0 → 3.13.0-next.2

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 (320) 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 +208 -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/assets/README.md +28 -0
  40. package/assets/e2ee-0.0.1.js +2 -0
  41. package/assets/e2ee-0.0.1.wasm +0 -0
  42. package/dist/aiEnableRequest/index.js +15 -2
  43. package/dist/aiEnableRequest/index.js.map +1 -1
  44. package/dist/annotation/index.js +55 -19
  45. package/dist/annotation/index.js.map +1 -1
  46. package/dist/assets/e2ee-0.0.1.js +2 -0
  47. package/dist/assets/e2ee-0.0.1.wasm +0 -0
  48. package/dist/breakouts/breakout.js +8 -3
  49. package/dist/breakouts/breakout.js.map +1 -1
  50. package/dist/breakouts/events.js +29 -14
  51. package/dist/breakouts/events.js.map +1 -1
  52. package/dist/breakouts/index.js +128 -7
  53. package/dist/breakouts/index.js.map +1 -1
  54. package/dist/common/errors/webex-errors.js +54 -5
  55. package/dist/common/errors/webex-errors.js.map +1 -1
  56. package/dist/config.js +4 -2
  57. package/dist/config.js.map +1 -1
  58. package/dist/constants.js +39 -11
  59. package/dist/constants.js.map +1 -1
  60. package/dist/controls-options-manager/constants.js +11 -1
  61. package/dist/controls-options-manager/constants.js.map +1 -1
  62. package/dist/controls-options-manager/index.js +67 -29
  63. package/dist/controls-options-manager/index.js.map +1 -1
  64. package/dist/controls-options-manager/util.js +91 -0
  65. package/dist/controls-options-manager/util.js.map +1 -1
  66. package/dist/hashTree/constants.js +13 -1
  67. package/dist/hashTree/constants.js.map +1 -1
  68. package/dist/hashTree/hashTreeParser.js +1245 -404
  69. package/dist/hashTree/hashTreeParser.js.map +1 -1
  70. package/dist/hashTree/utils.js +42 -0
  71. package/dist/hashTree/utils.js.map +1 -1
  72. package/dist/index.js +8 -0
  73. package/dist/index.js.map +1 -1
  74. package/dist/interceptors/dataChannelAuthToken.js +58 -16
  75. package/dist/interceptors/dataChannelAuthToken.js.map +1 -1
  76. package/dist/interceptors/locusRetry.js +24 -9
  77. package/dist/interceptors/locusRetry.js.map +1 -1
  78. package/dist/interpretation/index.js +55 -12
  79. package/dist/interpretation/index.js.map +1 -1
  80. package/dist/interpretation/interpretation.types.js +7 -0
  81. package/dist/interpretation/interpretation.types.js.map +1 -0
  82. package/dist/interpretation/siLanguage.js +1 -1
  83. package/dist/locus-info/controlsUtils.js +4 -1
  84. package/dist/locus-info/controlsUtils.js.map +1 -1
  85. package/dist/locus-info/index.js +914 -196
  86. package/dist/locus-info/index.js.map +1 -1
  87. package/dist/locus-info/infoUtils.js +36 -5
  88. package/dist/locus-info/infoUtils.js.map +1 -1
  89. package/dist/locus-info/types.js +20 -0
  90. package/dist/locus-info/types.js.map +1 -1
  91. package/dist/media/MediaConnectionAwaiter.js +229 -166
  92. package/dist/media/MediaConnectionAwaiter.js.map +1 -1
  93. package/dist/media/index.js +8 -2
  94. package/dist/media/index.js.map +1 -1
  95. package/dist/media/properties.js +4 -5
  96. package/dist/media/properties.js.map +1 -1
  97. package/dist/meeting/in-meeting-actions.js +5 -1
  98. package/dist/meeting/in-meeting-actions.js.map +1 -1
  99. package/dist/meeting/index.js +1931 -887
  100. package/dist/meeting/index.js.map +1 -1
  101. package/dist/meeting/locusMediaRequest.js +229 -82
  102. package/dist/meeting/locusMediaRequest.js.map +1 -1
  103. package/dist/meeting/muteState.js +10 -1
  104. package/dist/meeting/muteState.js.map +1 -1
  105. package/dist/meeting/request.js +5 -2
  106. package/dist/meeting/request.js.map +1 -1
  107. package/dist/meeting/util.js +42 -3
  108. package/dist/meeting/util.js.map +1 -1
  109. package/dist/meeting/voicea-meeting.js +2 -1
  110. package/dist/meeting/voicea-meeting.js.map +1 -1
  111. package/dist/meeting-info/meeting-info-v2.js +12 -5
  112. package/dist/meeting-info/meeting-info-v2.js.map +1 -1
  113. package/dist/meetings/index.js +322 -129
  114. package/dist/meetings/index.js.map +1 -1
  115. package/dist/meetings/meetings.types.js +6 -1
  116. package/dist/meetings/meetings.types.js.map +1 -1
  117. package/dist/meetings/request.js +39 -0
  118. package/dist/meetings/request.js.map +1 -1
  119. package/dist/meetings/util.js +116 -18
  120. package/dist/meetings/util.js.map +1 -1
  121. package/dist/member/index.js +10 -0
  122. package/dist/member/index.js.map +1 -1
  123. package/dist/member/types.js.map +1 -1
  124. package/dist/member/util.js +30 -0
  125. package/dist/member/util.js.map +1 -1
  126. package/dist/members/index.js +101 -43
  127. package/dist/members/index.js.map +1 -1
  128. package/dist/members/util.js +8 -1
  129. package/dist/members/util.js.map +1 -1
  130. package/dist/metrics/constants.js +11 -1
  131. package/dist/metrics/constants.js.map +1 -1
  132. package/dist/multistream/codec/constants.js +63 -0
  133. package/dist/multistream/codec/constants.js.map +1 -0
  134. package/dist/multistream/mediaRequestManager.js +62 -15
  135. package/dist/multistream/mediaRequestManager.js.map +1 -1
  136. package/dist/multistream/receiveSlot.js +9 -0
  137. package/dist/multistream/receiveSlot.js.map +1 -1
  138. package/dist/multistream/remoteMediaManager.js +32 -4
  139. package/dist/multistream/remoteMediaManager.js.map +1 -1
  140. package/dist/multistream/sendSlotManager.js +127 -3
  141. package/dist/multistream/sendSlotManager.js.map +1 -1
  142. package/dist/reachability/clusterReachability.js.map +1 -1
  143. package/dist/reachability/index.js +121 -83
  144. package/dist/reachability/index.js.map +1 -1
  145. package/dist/reachability/reachability.types.js +2 -0
  146. package/dist/reachability/reachability.types.js.map +1 -1
  147. package/dist/reachability/util.js +45 -0
  148. package/dist/reachability/util.js.map +1 -1
  149. package/dist/reactions/reactions.type.js.map +1 -1
  150. package/dist/recording-controller/index.js +1 -3
  151. package/dist/recording-controller/index.js.map +1 -1
  152. package/dist/roap/turnDiscovery.js +8 -1
  153. package/dist/roap/turnDiscovery.js.map +1 -1
  154. package/dist/types/annotation/index.d.ts +19 -0
  155. package/dist/types/common/errors/webex-errors.d.ts +36 -2
  156. package/dist/types/config.d.ts +4 -2
  157. package/dist/types/constants.d.ts +15 -2
  158. package/dist/types/controls-options-manager/constants.d.ts +6 -1
  159. package/dist/types/controls-options-manager/index.d.ts +16 -0
  160. package/dist/types/hashTree/constants.d.ts +2 -0
  161. package/dist/types/hashTree/hashTreeParser.d.ts +230 -18
  162. package/dist/types/hashTree/utils.d.ts +18 -0
  163. package/dist/types/index.d.ts +4 -0
  164. package/dist/types/interceptors/locusRetry.d.ts +4 -4
  165. package/dist/types/interpretation/interpretation.types.d.ts +10 -0
  166. package/dist/types/locus-info/index.d.ts +151 -15
  167. package/dist/types/locus-info/infoUtils.d.ts +8 -0
  168. package/dist/types/locus-info/types.d.ts +28 -1
  169. package/dist/types/media/MediaConnectionAwaiter.d.ts +66 -49
  170. package/dist/types/media/properties.d.ts +6 -2
  171. package/dist/types/meeting/in-meeting-actions.d.ts +4 -0
  172. package/dist/types/meeting/index.d.ts +247 -13
  173. package/dist/types/meeting/locusMediaRequest.d.ts +12 -0
  174. package/dist/types/meeting/request.d.ts +1 -0
  175. package/dist/types/meeting/util.d.ts +12 -1
  176. package/dist/types/meeting-info/meeting-info-v2.d.ts +1 -0
  177. package/dist/types/meetings/index.d.ts +40 -19
  178. package/dist/types/meetings/meetings.types.d.ts +15 -0
  179. package/dist/types/meetings/request.d.ts +14 -0
  180. package/dist/types/member/index.d.ts +1 -0
  181. package/dist/types/member/types.d.ts +1 -0
  182. package/dist/types/member/util.d.ts +9 -0
  183. package/dist/types/members/index.d.ts +15 -2
  184. package/dist/types/members/util.d.ts +1 -5
  185. package/dist/types/metrics/constants.d.ts +10 -0
  186. package/dist/types/multistream/codec/constants.d.ts +7 -0
  187. package/dist/types/multistream/mediaRequestManager.d.ts +22 -5
  188. package/dist/types/multistream/remoteMediaManager.d.ts +18 -0
  189. package/dist/types/multistream/sendSlotManager.d.ts +28 -2
  190. package/dist/types/reachability/clusterReachability.d.ts +3 -3
  191. package/dist/types/reachability/index.d.ts +10 -3
  192. package/dist/types/reachability/reachability.types.d.ts +7 -0
  193. package/dist/types/reachability/util.d.ts +17 -0
  194. package/dist/types/reactions/reactions.type.d.ts +3 -0
  195. package/dist/webinar/index.js +539 -245
  196. package/dist/webinar/index.js.map +1 -1
  197. package/package.json +26 -24
  198. package/src/aiEnableRequest/ai-docs/ai-enable-request-spec.md +223 -0
  199. package/src/aiEnableRequest/index.ts +16 -0
  200. package/src/annotation/ai-docs/annotation-spec.md +236 -0
  201. package/src/annotation/index.ts +61 -29
  202. package/src/breakouts/ai-docs/breakouts-spec.md +324 -0
  203. package/src/breakouts/breakout.ts +3 -1
  204. package/src/breakouts/events.ts +33 -11
  205. package/src/breakouts/index.ts +145 -3
  206. package/src/common/errors/webex-errors.ts +56 -3
  207. package/src/config.ts +8 -3
  208. package/src/constants.ts +23 -4
  209. package/src/controls-options-manager/ai-docs/controls-options-manager-spec.md +243 -0
  210. package/src/controls-options-manager/constants.ts +14 -1
  211. package/src/controls-options-manager/index.ts +87 -28
  212. package/src/controls-options-manager/util.ts +81 -1
  213. package/src/hashTree/ai-docs/hash-tree-spec.md +267 -0
  214. package/src/hashTree/constants.ts +16 -0
  215. package/src/hashTree/hashTreeParser.ts +1021 -214
  216. package/src/hashTree/utils.ts +36 -0
  217. package/src/index.ts +7 -0
  218. package/src/interceptors/ai-docs/interceptors-spec.md +247 -0
  219. package/src/interceptors/dataChannelAuthToken.ts +59 -12
  220. package/src/interceptors/locusRetry.ts +26 -5
  221. package/src/interpretation/ai-docs/interpretation-spec.md +256 -0
  222. package/src/interpretation/index.ts +65 -10
  223. package/src/interpretation/interpretation.types.ts +11 -0
  224. package/src/locus-info/ai-docs/locus-info-spec.md +293 -0
  225. package/src/locus-info/controlsUtils.ts +3 -1
  226. package/src/locus-info/index.ts +907 -184
  227. package/src/locus-info/infoUtils.ts +41 -6
  228. package/src/locus-info/types.ts +33 -1
  229. package/src/media/MediaConnectionAwaiter.ts +229 -196
  230. package/src/media/ai-docs/media-spec.md +267 -0
  231. package/src/media/index.ts +10 -1
  232. package/src/media/properties.ts +8 -3
  233. package/src/meeting/ai-docs/meeting-spec.md +404 -0
  234. package/src/meeting/in-meeting-actions.ts +8 -0
  235. package/src/meeting/index.ts +1237 -254
  236. package/src/meeting/locusMediaRequest.ts +106 -6
  237. package/src/meeting/muteState.ts +10 -1
  238. package/src/meeting/request.ts +11 -0
  239. package/src/meeting/util.ts +53 -8
  240. package/src/meeting/voicea-meeting.ts +1 -1
  241. package/src/meeting-info/ai-docs/meeting-info-spec.md +261 -0
  242. package/src/meeting-info/meeting-info-v2.ts +11 -4
  243. package/src/meetings/ai-docs/meetings-spec.md +296 -0
  244. package/src/meetings/index.ts +224 -80
  245. package/src/meetings/meetings.types.ts +19 -0
  246. package/src/meetings/request.ts +43 -0
  247. package/src/meetings/util.ts +117 -4
  248. package/src/member/ai-docs/member-spec.md +196 -0
  249. package/src/member/index.ts +10 -0
  250. package/src/member/types.ts +1 -0
  251. package/src/member/util.ts +29 -0
  252. package/src/members/ai-docs/members-spec.md +256 -0
  253. package/src/members/index.ts +70 -7
  254. package/src/members/util.ts +12 -4
  255. package/src/metrics/ai-docs/metrics-spec.md +185 -0
  256. package/src/metrics/constants.ts +11 -0
  257. package/src/multistream/ai-docs/multistream-spec.md +295 -0
  258. package/src/multistream/codec/constants.ts +58 -0
  259. package/src/multistream/mediaRequestManager.ts +119 -28
  260. package/src/multistream/receiveSlot.ts +18 -0
  261. package/src/multistream/remoteMediaManager.ts +23 -1
  262. package/src/multistream/sendSlotManager.ts +112 -4
  263. package/src/personal-meeting-room/ai-docs/personal-meeting-room-spec.md +234 -0
  264. package/src/reachability/ai-docs/reachability-spec.md +261 -0
  265. package/src/reachability/clusterReachability.ts +3 -2
  266. package/src/reachability/index.ts +47 -16
  267. package/src/reachability/reachability.types.ts +11 -0
  268. package/src/reachability/util.ts +36 -0
  269. package/src/reactions/ai-docs/reactions-spec.md +198 -0
  270. package/src/reactions/reactions.type.ts +3 -0
  271. package/src/reconnection-manager/ai-docs/reconnection-manager-spec.md +272 -0
  272. package/src/recording-controller/ai-docs/recording-controller-spec.md +223 -0
  273. package/src/recording-controller/index.ts +1 -2
  274. package/src/roap/ai-docs/roap-spec.md +241 -0
  275. package/src/roap/turnDiscovery.ts +9 -1
  276. package/src/webinar/ai-docs/webinar-spec.md +243 -0
  277. package/src/webinar/index.ts +333 -73
  278. package/test/unit/spec/aiEnableRequest/index.ts +86 -0
  279. package/test/unit/spec/annotation/index.ts +214 -182
  280. package/test/unit/spec/breakouts/breakout.ts +9 -3
  281. package/test/unit/spec/breakouts/events.ts +120 -2
  282. package/test/unit/spec/breakouts/index.ts +336 -15
  283. package/test/unit/spec/common/errors/webex-errors.ts +78 -0
  284. package/test/unit/spec/controls-options-manager/index.js +244 -29
  285. package/test/unit/spec/controls-options-manager/util.js +165 -0
  286. package/test/unit/spec/hashTree/hashTreeParser.ts +3126 -238
  287. package/test/unit/spec/hashTree/utils.ts +125 -1
  288. package/test/unit/spec/interceptors/dataChannelAuthToken.ts +179 -1
  289. package/test/unit/spec/interceptors/locusRetry.ts +234 -5
  290. package/test/unit/spec/interpretation/index.ts +119 -4
  291. package/test/unit/spec/locus-info/controlsUtils.js +172 -57
  292. package/test/unit/spec/locus-info/index.js +1880 -136
  293. package/test/unit/spec/locus-info/infoUtils.js +184 -1
  294. package/test/unit/spec/media/MediaConnectionAwaiter.ts +479 -17
  295. package/test/unit/spec/media/index.ts +92 -0
  296. package/test/unit/spec/media/properties.ts +26 -26
  297. package/test/unit/spec/meeting/in-meeting-actions.ts +4 -0
  298. package/test/unit/spec/meeting/index.js +3697 -501
  299. package/test/unit/spec/meeting/locusMediaRequest.ts +406 -4
  300. package/test/unit/spec/meeting/muteState.js +81 -0
  301. package/test/unit/spec/meeting/request.js +12 -0
  302. package/test/unit/spec/meeting/utils.js +206 -16
  303. package/test/unit/spec/meeting/voicea-meeting.ts +85 -1
  304. package/test/unit/spec/meeting-info/meetinginfov2.js +88 -11
  305. package/test/unit/spec/meetings/index.js +586 -53
  306. package/test/unit/spec/meetings/request.js +141 -0
  307. package/test/unit/spec/meetings/utils.js +402 -51
  308. package/test/unit/spec/member/index.js +7 -0
  309. package/test/unit/spec/member/util.js +89 -0
  310. package/test/unit/spec/members/index.js +216 -0
  311. package/test/unit/spec/members/request.js +37 -1
  312. package/test/unit/spec/members/utils.js +63 -0
  313. package/test/unit/spec/multistream/mediaRequestManager.ts +501 -37
  314. package/test/unit/spec/multistream/remoteMediaManager.ts +46 -0
  315. package/test/unit/spec/multistream/sendSlotManager.ts +165 -38
  316. package/test/unit/spec/reachability/index.ts +128 -46
  317. package/test/unit/spec/reachability/util.ts +31 -0
  318. package/test/unit/spec/recording-controller/index.js +9 -8
  319. package/test/unit/spec/roap/turnDiscovery.ts +20 -0
  320. package/test/unit/spec/webinar/index.ts +982 -328
@@ -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, 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, isSelf} 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,20 +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 LocusInfoUpdateCallback = (
61
- updateType: LocusInfoUpdateType,
62
- data?: {updatedObjects: HashTreeObject[]}
63
- ) => void;
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;
96
+ }
97
+ ) => void;
98
+ saveTimestamp: (options: {
99
+ key: LocusSyncLatencyEventName;
100
+ options: {
101
+ meetingId: string;
102
+ dataSetName: string;
103
+ trackingId?: string;
104
+ };
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
+ ];
64
121
 
65
122
  interface LeafInfo {
66
123
  type: ObjectType;
@@ -75,6 +132,13 @@ interface LeafInfo {
75
132
  */
76
133
  export class MeetingEndedError extends Error {}
77
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
+
78
142
  /* Currently Locus always sends Metadata objects only in the "self" dataset.
79
143
  * If this ever changes, update all the code that relies on this constant.
80
144
  */
@@ -93,12 +157,29 @@ class HashTreeParser {
93
157
  dataSets: Record<string, InternalDataSet> = {};
94
158
  visibleDataSetsUrl: string; // url from which we can get info about all data sets
95
159
  webexRequest: WebexRequestMethod;
96
- locusInfoUpdateCallback: LocusInfoUpdateCallback;
160
+ private callbacks: HashTreeParserCallbacks;
161
+ private syncLatencyMeetingId: string;
97
162
  visibleDataSets: VisibleDataSetInfo[];
98
163
  debugId: string;
99
- heartbeatIntervalMs?: number;
100
164
  private excludedDataSets: string[];
101
-
165
+ state: 'active' | 'stopped';
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();
102
183
  /**
103
184
  * Constructor for HashTreeParser
104
185
  * @param {Object} options
@@ -111,20 +192,22 @@ class HashTreeParser {
111
192
  };
112
193
  metadata: Metadata | null;
113
194
  webexRequest: WebexRequestMethod;
114
- locusInfoUpdateCallback: LocusInfoUpdateCallback;
195
+ callbacks: HashTreeParserCallbacks;
115
196
  debugId: string;
116
197
  excludedDataSets?: string[];
198
+ syncLatencyMeetingId: string;
117
199
  }) {
118
200
  const {dataSets, locus} = options.initialLocus; // extract dataSets from initialLocus
119
201
 
120
202
  this.debugId = options.debugId;
121
203
  this.webexRequest = options.webexRequest;
122
- this.locusInfoUpdateCallback = options.locusInfoUpdateCallback;
204
+ this.callbacks = options.callbacks;
205
+ this.syncLatencyMeetingId = options.syncLatencyMeetingId;
123
206
  this.excludedDataSets = options.excludedDataSets || [];
124
207
  this.visibleDataSetsUrl = locus?.links?.resources?.visibleDataSets?.url;
125
- this.visibleDataSets = (
126
- cloneDeep(options.metadata?.visibleDataSets || []) as VisibleDataSetInfo[]
127
- ).filter((vds) => !this.isExcludedDataSet(vds.name));
208
+ this.setVisibleDataSets(options.metadata?.visibleDataSets || [], dataSets);
209
+
210
+ this.state = 'active';
128
211
 
129
212
  if (options.metadata?.visibleDataSets?.length === 0) {
130
213
  LoggerProxy.logger.warn(
@@ -140,9 +223,11 @@ class HashTreeParser {
140
223
  }
141
224
 
142
225
  LoggerProxy.logger.info(
143
- `HashTreeParser#constructor --> creating HashTreeParser for datasets: ${JSON.stringify(
226
+ `HashTreeParser#constructor --> ${
227
+ this.debugId
228
+ } creating HashTreeParser for datasets: ${JSON.stringify(
144
229
  dataSets.map((ds) => ds.name)
145
- )}`
230
+ )} with visible datasets: ${JSON.stringify(this.visibleDataSets.map((vds) => vds.name))}`
146
231
  );
147
232
 
148
233
  for (const dataSet of dataSets) {
@@ -157,6 +242,24 @@ class HashTreeParser {
157
242
  }
158
243
  }
159
244
 
245
+ /**
246
+ * Sets the visible data sets list for the HashTreeParser. This method should be called only at the start, to initialize
247
+ * the visible data sets, before any message processsing, so for example from the constructor or when resuming the parser.
248
+ *
249
+ * @param {Array<VisibleDataSetInfo>} visibleDataSets - The visible data sets to set
250
+ * @param {Array<DataSet>} dataSets - The "dataSets" list from Locus (yes, Locus sends visibleDataSets and dataSets as separate lists and they can differ)
251
+ * @returns {void}
252
+ */
253
+ private setVisibleDataSets(visibleDataSets: VisibleDataSetInfo[], dataSets: Array<DataSet>) {
254
+ this.visibleDataSets = cloneDeep(visibleDataSets).filter(
255
+ (vds) =>
256
+ // exclude data sets we will never care about
257
+ !this.isExcludedDataSet(vds.name) &&
258
+ // and make sure that visibleDataSets list is consistent with dataSets list
259
+ dataSets.some((ds) => ds.name === vds.name)
260
+ );
261
+ }
262
+
160
263
  /**
161
264
  * Checks if the given data set name is in the list of visible data sets
162
265
  * @param {string} dataSetName data set name to check
@@ -203,16 +306,16 @@ class HashTreeParser {
203
306
  * @param {DataSet} dataSetInfo The new data set to be added
204
307
  * @returns {Promise}
205
308
  */
206
- private initializeNewVisibleDataSet(
309
+ private async initializeNewVisibleDataSet(
207
310
  visibleDataSetInfo: VisibleDataSetInfo,
208
311
  dataSetInfo: DataSet
209
- ): Promise<{updateType: LocusInfoUpdateType; updatedObjects?: HashTreeObject[]}> {
312
+ ): Promise<void> {
210
313
  if (this.isVisibleDataSet(dataSetInfo.name)) {
211
314
  LoggerProxy.logger.info(
212
315
  `HashTreeParser#initializeNewVisibleDataSet --> ${this.debugId} Data set "${dataSetInfo.name}" already exists, skipping init`
213
316
  );
214
317
 
215
- return Promise.resolve({updateType: LocusInfoUpdateType.OBJECTS_UPDATED, updatedObjects: []});
318
+ return;
216
319
  }
217
320
 
218
321
  LoggerProxy.logger.info(
@@ -220,7 +323,7 @@ class HashTreeParser {
220
323
  );
221
324
 
222
325
  if (!this.addToVisibleDataSetsList(visibleDataSetInfo)) {
223
- return Promise.resolve({updateType: LocusInfoUpdateType.OBJECTS_UPDATED, updatedObjects: []});
326
+ return;
224
327
  }
225
328
 
226
329
  const hashTree = new HashTree([], dataSetInfo.leafCount);
@@ -230,51 +333,8 @@ class HashTreeParser {
230
333
  hashTree,
231
334
  };
232
335
 
233
- return this.sendInitializationSyncRequestToLocus(dataSetInfo.name, 'new visible data set');
234
- }
235
-
236
- /**
237
- * Sends a special sync request to Locus with all leaves empty - this is a way to get all the data for a given dataset.
238
- *
239
- * @param {string} datasetName - name of the dataset for which to send the request
240
- * @param {string} debugText - text to include in logs
241
- * @returns {Promise}
242
- */
243
- private sendInitializationSyncRequestToLocus(
244
- datasetName: string,
245
- debugText: string
246
- ): Promise<{updateType: LocusInfoUpdateType; updatedObjects?: HashTreeObject[]}> {
247
- const dataset = this.dataSets[datasetName];
248
-
249
- if (!dataset) {
250
- LoggerProxy.logger.warn(
251
- `HashTreeParser#sendInitializationSyncRequestToLocus --> ${this.debugId} No data set found for ${datasetName}, cannot send the request for leaf data`
252
- );
253
-
254
- return Promise.resolve(null);
255
- }
256
-
257
- const emptyLeavesData = new Array(dataset.leafCount).fill([]);
258
-
259
- LoggerProxy.logger.info(
260
- `HashTreeParser#sendInitializationSyncRequestToLocus --> ${this.debugId} Sending initial sync request to Locus for data set "${datasetName}" with empty leaf data`
261
- );
262
-
263
- return this.sendSyncRequestToLocus(this.dataSets[datasetName], emptyLeavesData).then(
264
- (syncResponse) => {
265
- if (syncResponse) {
266
- return {
267
- updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
268
- updatedObjects: this.parseMessage(
269
- syncResponse,
270
- `via empty leaves /sync API call for ${debugText}`
271
- ),
272
- };
273
- }
274
-
275
- return {updateType: LocusInfoUpdateType.OBJECTS_UPDATED, updatedObjects: []};
276
- }
277
- );
336
+ this.enqueueSyncForDataset(dataSetInfo.name, 'new visible data set initialization', true);
337
+ await this.syncQueueProcessingPromise;
278
338
  }
279
339
 
280
340
  /**
@@ -358,9 +418,11 @@ class HashTreeParser {
358
418
  * @returns {Promise}
359
419
  */
360
420
  private async initializeDataSets(visibleDataSets: Array<DataSet>, debugText: string) {
361
- const updatedObjects: HashTreeObject[] = [];
421
+ if (this.state === 'stopped') {
422
+ return;
423
+ }
362
424
 
363
- for (const dataSet of visibleDataSets) {
425
+ for (const dataSet of sortByInitPriority(visibleDataSets, DATA_SET_INIT_PRIORITY)) {
364
426
  const {name, leafCount, url} = dataSet;
365
427
 
366
428
  if (!this.dataSets[name]) {
@@ -396,19 +458,12 @@ class HashTreeParser {
396
458
  );
397
459
  this.dataSets[name].hashTree = new HashTree([], leafCount);
398
460
 
399
- // eslint-disable-next-line no-await-in-loop
400
- const data = await this.sendInitializationSyncRequestToLocus(name, debugText);
401
-
402
- if (data.updateType === LocusInfoUpdateType.OBJECTS_UPDATED) {
403
- updatedObjects.push(...(data.updatedObjects || []));
404
- }
461
+ this.enqueueSyncForDataset(name, `initialization sync for ${debugText}`, true);
405
462
  }
406
463
  }
407
464
 
408
- this.callLocusInfoUpdateCallback({
409
- updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
410
- updatedObjects,
411
- });
465
+ // wait for all enqueued initialization syncs to complete
466
+ await this.syncQueueProcessingPromise;
412
467
  }
413
468
 
414
469
  /**
@@ -426,7 +481,7 @@ class HashTreeParser {
426
481
  // object mapping dataset names to arrays of leaf data
427
482
  const leafInfo: Record<string, Array<LeafInfo>> = {};
428
483
 
429
- const findAndStoreMetaData = (currentLocusPart: any) => {
484
+ const findAndStoreMetaData = (currentLocusPart: any, currentLocusPartName: string) => {
430
485
  if (typeof currentLocusPart !== 'object' || currentLocusPart === null) {
431
486
  return;
432
487
  }
@@ -441,10 +496,18 @@ class HashTreeParser {
441
496
  };
442
497
 
443
498
  if (copyData) {
444
- newLeafInfo.data = cloneDeep(currentLocusPart);
499
+ if ((type as string).toLowerCase() === ObjectType.control) {
500
+ // control entries require special handling, because they are signalled by Locus
501
+ // differently when coming in messages vs API responses
502
+ newLeafInfo.data = {
503
+ [currentLocusPartName]: cloneDeep(currentLocusPart),
504
+ };
505
+ } else {
506
+ newLeafInfo.data = cloneDeep(currentLocusPart);
445
507
 
446
- // remove any nested other objects that have their own htMeta
447
- deleteNestedObjectsWithHtMeta(newLeafInfo.data);
508
+ // remove any nested other objects that have their own htMeta
509
+ deleteNestedObjectsWithHtMeta(newLeafInfo.data);
510
+ }
448
511
  }
449
512
 
450
513
  for (const dataSetName of dataSetNames) {
@@ -456,19 +519,19 @@ class HashTreeParser {
456
519
  }
457
520
 
458
521
  if (Array.isArray(currentLocusPart)) {
459
- for (const item of currentLocusPart) {
460
- findAndStoreMetaData(item);
522
+ for (const [index, item] of currentLocusPart.entries()) {
523
+ findAndStoreMetaData(item, index.toString());
461
524
  }
462
525
  } else {
463
526
  for (const key of Object.keys(currentLocusPart)) {
464
527
  if (Object.prototype.hasOwnProperty.call(currentLocusPart, key)) {
465
- findAndStoreMetaData(currentLocusPart[key]);
528
+ findAndStoreMetaData(currentLocusPart[key], key);
466
529
  }
467
530
  }
468
531
  }
469
532
  };
470
533
 
471
- findAndStoreMetaData(locus);
534
+ findAndStoreMetaData(locus, 'locus');
472
535
 
473
536
  return leafInfo;
474
537
  }
@@ -554,12 +617,40 @@ class HashTreeParser {
554
617
  )}`
555
618
  );
556
619
 
620
+ this.cancelPendingSyncsForDataSets(dataSets.map((ds) => ds.name));
621
+
557
622
  dataSets.forEach((dataSet) => {
558
623
  this.updateDataSetInfo(dataSet);
559
624
  this.runSyncAlgorithm(dataSet);
560
625
  });
561
626
  }
562
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
+
563
654
  /**
564
655
  * Asynchronously initializes new visible data sets
565
656
  *
@@ -567,13 +658,16 @@ class HashTreeParser {
567
658
  * @returns {void}
568
659
  */
569
660
  private queueInitForNewVisibleDataSets(dataSetsRequiringInitialization: VisibleDataSetInfo[]) {
661
+ LoggerProxy.logger.info(
662
+ `HashTreeParser#queueInitForNewVisibleDataSets --> ${
663
+ this.debugId
664
+ } queuing initialization of new visible datasets: ${dataSetsRequiringInitialization
665
+ .map((ds) => ds.name)
666
+ .join(', ')}`
667
+ );
570
668
  queueMicrotask(() => {
571
669
  this.initializeNewVisibleDataSets(dataSetsRequiringInitialization).catch((error) => {
572
- if (error instanceof MeetingEndedError) {
573
- this.callLocusInfoUpdateCallback({
574
- updateType: LocusInfoUpdateType.MEETING_ENDED,
575
- });
576
- } else {
670
+ if (!this.handleSyncErrors(error)) {
577
671
  LoggerProxy.logger.warn(
578
672
  `HashTreeParser#queueInitForNewVisibleDataSets --> ${
579
673
  this.debugId
@@ -645,9 +739,20 @@ class HashTreeParser {
645
739
  * @returns {void}
646
740
  */
647
741
  handleLocusUpdate(update: {dataSets?: Array<DataSet>; locus: any; metadata?: Metadata}): void {
742
+ if (this.state === 'stopped') {
743
+ return;
744
+ }
745
+
648
746
  const {dataSets, locus, metadata} = update;
649
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
+
650
754
  if (!dataSets) {
755
+ // this happens for example when we handle GET /loci response
651
756
  LoggerProxy.logger.info(
652
757
  `HashTreeParser#handleLocusUpdate --> ${this.debugId} received hash tree update without dataSets`
653
758
  );
@@ -700,7 +805,7 @@ class HashTreeParser {
700
805
  );
701
806
  }
702
807
  } else {
703
- LoggerProxy.logger.warn(
808
+ LoggerProxy.logger.info(
704
809
  `HashTreeParser#handleLocusUpdate --> ${this.debugId} received leaf data for unknown data set "${dataSetName}", ignoring`
705
810
  );
706
811
  }
@@ -745,12 +850,25 @@ class HashTreeParser {
745
850
  maxMs: receivedDataSet.backoff.maxMs,
746
851
  exponent: receivedDataSet.backoff.exponent,
747
852
  };
853
+ this.dataSets[receivedDataSet.name].heartbeatIntervalMs = receivedDataSet.heartbeatIntervalMs;
748
854
  LoggerProxy.logger.info(
749
855
  `HashTreeParser#updateDataSetInfo --> ${this.debugId} updated "${receivedDataSet.name}" dataset to version=${receivedDataSet.version}, root=${receivedDataSet.root}`
750
856
  );
751
857
  }
752
858
  }
753
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
+
754
872
  /**
755
873
  * Checks for changes in the visible data sets based on the updated objects.
756
874
  * @param {HashTreeObject[]} updatedObjects - The list of updated hash tree objects.
@@ -801,6 +919,8 @@ class HashTreeParser {
801
919
  */
802
920
  private deleteHashTree(dataSetName: string) {
803
921
  this.dataSets[dataSetName].hashTree = undefined;
922
+ this.dataSets[dataSetName].syncAbortController?.abort();
923
+ this.dataSets[dataSetName].syncAbortController = undefined;
804
924
 
805
925
  // we also need to stop the timers as there is no hash tree anymore to sync
806
926
  if (this.dataSets[dataSetName].timer) {
@@ -888,6 +1008,10 @@ class HashTreeParser {
888
1008
  ...dataSetInfo,
889
1009
  hashTree,
890
1010
  };
1011
+
1012
+ // this call is needed here for the edge case where we receive a message with new visible data sets
1013
+ // and there are no objects belonging to these data sets in the message but we already have the info about them in this.dataSets
1014
+ this.runSyncAlgorithm(this.dataSets[dataSetInfo.name]);
891
1015
  } else {
892
1016
  LoggerProxy.logger.info(
893
1017
  `HashTreeParser#processVisibleDataSetChanges --> ${this.debugId} visible data set "${ds.name}" added but no info about it in our dataSets structures`
@@ -908,9 +1032,12 @@ class HashTreeParser {
908
1032
  * @returns {Promise<void>}
909
1033
  */
910
1034
  private async initializeNewVisibleDataSets(addedDataSets: VisibleDataSetInfo[]): Promise<void> {
1035
+ if (this.state === 'stopped') {
1036
+ return;
1037
+ }
911
1038
  const allDataSets = await this.getAllVisibleDataSetsFromLocus();
912
1039
 
913
- for (const ds of addedDataSets) {
1040
+ for (const ds of sortByInitPriority(addedDataSets, DATA_SET_INIT_PRIORITY)) {
914
1041
  const dataSetInfo = allDataSets.find((d) => d.name === ds.name);
915
1042
 
916
1043
  LoggerProxy.logger.info(
@@ -919,15 +1046,11 @@ class HashTreeParser {
919
1046
 
920
1047
  if (!dataSetInfo) {
921
1048
  LoggerProxy.logger.warn(
922
- `HashTreeParser#handleHashTreeMessage --> ${this.debugId} missing info about data set "${ds.name}" in Locus response from visibleDataSetsUrl`
1049
+ `HashTreeParser#initializeNewVisibleDataSets --> ${this.debugId} missing info about data set "${ds.name}" in Locus response from visibleDataSetsUrl`
923
1050
  );
924
1051
  } else {
925
- // we're awaiting in a loop, because in practice there will be only one new data set at a time,
926
- // so no point in trying to parallelize this
927
1052
  // eslint-disable-next-line no-await-in-loop
928
- const updates = await this.initializeNewVisibleDataSet(ds, dataSetInfo);
929
-
930
- this.callLocusInfoUpdateCallback(updates);
1053
+ await this.initializeNewVisibleDataSet(ds, dataSetInfo);
931
1054
  }
932
1055
  }
933
1056
  }
@@ -940,28 +1063,46 @@ class HashTreeParser {
940
1063
  * @returns {HashTreeObject[]} list of hash tree objects that were updated as a result of processing the message
941
1064
  */
942
1065
  private parseMessage(message: HashTreeMessage, debugText?: string): HashTreeObject[] {
1066
+ if (this.state === 'stopped') {
1067
+ return [];
1068
+ }
1069
+
943
1070
  const {dataSets, visibleDataSetsUrl} = message;
944
1071
 
945
1072
  LoggerProxy.logger.info(
946
- `HashTreeParser#parseMessage --> ${this.debugId} received message ${debugText || ''}:`,
947
- 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(',')}`
948
1085
  );
1086
+
949
1087
  if (message.locusStateElements?.length === 0) {
950
1088
  LoggerProxy.logger.warn(
951
1089
  `HashTreeParser#parseMessage --> ${this.debugId} got empty locusStateElements!!!`
952
1090
  );
953
- // todo: send a metric
1091
+ Metrics.sendBehavioralMetric(BEHAVIORAL_METRICS.HASH_TREE_EMPTY_LOCUS_STATE_ELEMENTS, {
1092
+ debugId: this.debugId,
1093
+ });
954
1094
  }
955
1095
 
956
1096
  // first, update our metadata about the datasets with info from the message
957
1097
  this.visibleDataSetsUrl = visibleDataSetsUrl;
958
1098
  dataSets.forEach((dataSet) => this.updateDataSetInfo(dataSet));
1099
+ this.cancelPendingSyncsForDataSets(dataSets.map((ds) => ds.name));
959
1100
 
960
1101
  const updatedObjects: HashTreeObject[] = [];
961
1102
 
962
1103
  // when we detect new visible datasets, it may be that the metadata about them is not
963
1104
  // available in the message, they will require separate async initialization
964
- let dataSetsRequiringInitialization = [];
1105
+ let dataSetsRequiringInitialization: VisibleDataSetInfo[] = [];
965
1106
 
966
1107
  // first find out if there are any visible data set changes - they're signalled in Metadata object updates
967
1108
  const metadataUpdates = (message.locusStateElements || []).filter((object) =>
@@ -969,7 +1110,7 @@ class HashTreeParser {
969
1110
  );
970
1111
 
971
1112
  if (metadataUpdates.length > 0) {
972
- const updatedMetadataObjects = [];
1113
+ const updatedMetadataObjects: HashTreeObject[] = [];
973
1114
 
974
1115
  metadataUpdates.forEach((object) => {
975
1116
  // todo: once Locus supports it, we will use the "view" field here instead of dataSetNames
@@ -998,7 +1139,7 @@ class HashTreeParser {
998
1139
  }
999
1140
  }
1000
1141
 
1001
- if (message.locusStateElements?.length > 0) {
1142
+ if (message.locusStateElements && message.locusStateElements.length > 0) {
1002
1143
  // by this point we now have this.dataSets setup for data sets from this message
1003
1144
  // and hash trees created for the new visible data sets,
1004
1145
  // so we can now process all the updates from the message
@@ -1060,12 +1201,17 @@ class HashTreeParser {
1060
1201
  * @returns {void}
1061
1202
  */
1062
1203
  handleMessage(message: HashTreeMessage, debugText?: string) {
1063
- if (message.heartbeatIntervalMs) {
1064
- this.heartbeatIntervalMs = message.heartbeatIntervalMs;
1204
+ if (this.state === 'stopped') {
1205
+ return;
1206
+ }
1207
+
1208
+ if (message.heartbeatIntervalMs !== undefined) {
1209
+ this.topLevelHeartbeatIntervalMs = message.heartbeatIntervalMs;
1065
1210
  }
1211
+
1066
1212
  if (this.isEndMessage(message)) {
1067
1213
  LoggerProxy.logger.info(
1068
- `HashTreeParser#parseMessage --> ${this.debugId} received sentinel END MEETING message`
1214
+ `HashTreeParser#handleMessage --> ${this.debugId} received sentinel END MEETING message`
1069
1215
  );
1070
1216
  this.stopAllTimers();
1071
1217
 
@@ -1074,32 +1220,71 @@ class HashTreeParser {
1074
1220
  this.handleRootHashHeartBeatMessage(message);
1075
1221
  this.resetHeartbeatWatchdogs(message.dataSets);
1076
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.
1077
1227
  const updatedObjects = this.parseMessage(message, debugText);
1078
1228
 
1079
- this.resetHeartbeatWatchdogs(message.dataSets);
1080
1229
  this.callLocusInfoUpdateCallback({
1081
1230
  updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
1082
1231
  updatedObjects,
1083
1232
  });
1233
+ this.resetHeartbeatWatchdogs(message.dataSets);
1084
1234
  }
1085
1235
  }
1086
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
+
1087
1271
  /**
1088
1272
  * Calls the updateInfo callback if there are any updates to report
1089
1273
  *
1090
1274
  * @param {Object} updates parsed from a Locus message
1091
1275
  * @returns {void}
1092
1276
  */
1093
- private callLocusInfoUpdateCallback(updates: {
1094
- updateType: LocusInfoUpdateType;
1095
- updatedObjects?: HashTreeObject[];
1096
- }) {
1097
- const {updateType, updatedObjects} = updates;
1277
+ private callLocusInfoUpdateCallback(updates: LocusInfoUpdate) {
1278
+ if (this.state === 'stopped') {
1279
+ return;
1280
+ }
1281
+
1282
+ const {updateType} = updates;
1098
1283
 
1099
- if (updateType === LocusInfoUpdateType.OBJECTS_UPDATED && updatedObjects?.length > 0) {
1284
+ if (updateType === LocusInfoUpdateType.OBJECTS_UPDATED && updates.updatedObjects?.length > 0) {
1100
1285
  // Filter out updates for objects that already have a higher version in their datasets,
1101
1286
  // or removals for objects that still exist in any of their datasets
1102
- const filteredUpdates = updatedObjects.filter((object) => {
1287
+ const filteredUpdates = updates.updatedObjects.filter((object) => {
1103
1288
  const {elementId} = object.htMeta;
1104
1289
  const {type, id, version} = elementId;
1105
1290
 
@@ -1136,10 +1321,10 @@ class HashTreeParser {
1136
1321
  });
1137
1322
 
1138
1323
  if (filteredUpdates.length > 0) {
1139
- this.locusInfoUpdateCallback(updateType, {updatedObjects: filteredUpdates});
1324
+ this.callbacks.locusInfoUpdateCallback({updateType, updatedObjects: filteredUpdates});
1140
1325
  }
1141
1326
  } else if (updateType !== LocusInfoUpdateType.OBJECTS_UPDATED) {
1142
- this.locusInfoUpdateCallback(updateType, {updatedObjects});
1327
+ this.callbacks.locusInfoUpdateCallback({updateType});
1143
1328
  }
1144
1329
  }
1145
1330
 
@@ -1157,88 +1342,460 @@ class HashTreeParser {
1157
1342
  return Math.round(randomValue ** exponent * maxMs);
1158
1343
  }
1159
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
+
1160
1385
  /**
1161
1386
  * Performs a sync for the given data set.
1162
1387
  *
1163
1388
  * @param {InternalDataSet} dataSet - The data set to sync
1164
- * @param {string} rootHash - Our current root hash for this data set
1165
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)
1166
1391
  * @returns {Promise<void>}
1167
1392
  */
1168
1393
  private async performSync(
1169
1394
  dataSet: InternalDataSet,
1170
- rootHash: string,
1171
- reason: string
1395
+ reason: string,
1396
+ isInitialization?: boolean
1172
1397
  ): Promise<void> {
1173
1398
  if (!dataSet.hashTree) {
1174
1399
  return;
1175
1400
  }
1176
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
+
1177
1431
  try {
1178
1432
  LoggerProxy.logger.info(
1179
1433
  `HashTreeParser#performSync --> ${this.debugId} ${reason}, syncing data set "${dataSet.name}"`
1180
1434
  );
1181
1435
 
1182
- const mismatchedLeavesData: Record<number, LeafDataItem[]> = {};
1436
+ let leavesData: Record<number, LeafDataItem[]> = {};
1183
1437
 
1184
- if (dataSet.leafCount !== 1) {
1185
- let receivedHashes;
1438
+ if (!isInitialization) {
1439
+ if (dataSet.leafCount !== 1) {
1440
+ let receivedHashes;
1186
1441
 
1187
- try {
1188
- // request hashes from sender
1189
- const {hashes, dataSet: latestDataSetInfo} = await this.getHashesFromLocus(
1190
- dataSet.name,
1191
- rootHash
1192
- );
1442
+ try {
1443
+ // request hashes from sender
1444
+ const hashesResult = await this.getHashesFromLocus(dataSet.name, rootHash, {
1445
+ requestTrackingId: hashtreeTrackingId,
1446
+ metricTrackingId: syncTrackingId,
1447
+ });
1193
1448
 
1194
- receivedHashes = hashes;
1449
+ if (!hashesResult) {
1450
+ // hashes match, no sync needed
1451
+ return;
1452
+ }
1195
1453
 
1196
- dataSet.hashTree.resize(latestDataSetInfo.leafCount);
1197
- } catch (error) {
1198
- if (error.statusCode === 409) {
1199
- // this is a leaf count mismatch, we should do nothing, just wait for another heartbeat message from Locus
1200
- LoggerProxy.logger.info(
1201
- `HashTreeParser#getHashesFromLocus --> ${this.debugId} Got 409 when fetching hashes for data set "${dataSet.name}": ${error.message}`
1202
- );
1454
+ receivedHashes = hashesResult.hashes;
1203
1455
 
1204
- return;
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
+ );
1463
+
1464
+ return;
1465
+ }
1466
+ throw error;
1205
1467
  }
1206
- 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)};
1207
1477
  }
1478
+ }
1208
1479
 
1209
- // identify mismatched leaves
1210
- 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
+ );
1211
1484
 
1212
- mismatchedLeaveIndexes.forEach((index) => {
1213
- mismatchedLeavesData[index] = dataSet.hashTree.getLeafData(index);
1214
- });
1215
- } else {
1216
- mismatchedLeavesData[0] = dataSet.hashTree.getLeafData(0);
1485
+ return;
1217
1486
  }
1218
1487
  // request sync for mismatched leaves
1219
- if (Object.keys(mismatchedLeavesData).length > 0) {
1220
- const syncResponse = await this.sendSyncRequestToLocus(dataSet, mismatchedLeavesData);
1488
+ let syncResponse: HashTreeMessage | null = null;
1221
1489
 
1222
- // sync API may return nothing (in that case data will arrive via messages)
1223
- // or it may return a response in the same format as messages
1224
- if (syncResponse) {
1225
- this.handleMessage(syncResponse, 'via sync API');
1226
- }
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
+ );
1227
1530
  }
1228
1531
  } catch (error) {
1229
- if (error instanceof MeetingEndedError) {
1230
- this.callLocusInfoUpdateCallback({
1231
- updateType: LocusInfoUpdateType.MEETING_ENDED,
1232
- });
1233
- } else {
1532
+ if (!this.handleSyncErrors(error)) {
1234
1533
  LoggerProxy.logger.warn(
1235
1534
  `HashTreeParser#performSync --> ${this.debugId} error during sync for data set "${dataSet.name}":`,
1236
1535
  error
1237
1536
  );
1238
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
+ }
1239
1606
  }
1240
1607
  }
1241
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;
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);
1797
+ }
1798
+
1242
1799
  /**
1243
1800
  * Runs the sync algorithm for the given data set.
1244
1801
  *
@@ -1257,33 +1814,25 @@ class HashTreeParser {
1257
1814
  }
1258
1815
 
1259
1816
  if (!dataSet.hashTree) {
1260
- LoggerProxy.logger.info(
1261
- `HashTreeParser#runSyncAlgorithm --> ${this.debugId} Data set "${dataSet.name}" has no hash tree, skipping sync algorithm`
1262
- );
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
1263
1819
 
1264
1820
  return;
1265
1821
  }
1266
1822
 
1267
1823
  dataSet.hashTree.resize(receivedDataSet.leafCount);
1268
1824
 
1269
- // temporary log for the workshop // todo: remove
1270
- const ourCurrentRootHash = dataSet.hashTree.getRootHash();
1271
- LoggerProxy.logger.info(
1272
- `HashTreeParser#runSyncAlgorithm --> ${this.debugId} dataSet="${dataSet.name}" version=${dataSet.version} hashes before starting timer: ours=${ourCurrentRootHash} Locus=${dataSet.root}`
1273
- );
1274
-
1275
- const delay = dataSet.idleMs + this.getWeightedBackoffTime(dataSet.backoff);
1825
+ const randomBackoffTime = this.getWeightedBackoffTime(dataSet.backoff);
1826
+ const delay = dataSet.idleMs + randomBackoffTime;
1276
1827
 
1277
1828
  if (delay > 0) {
1278
1829
  if (dataSet.timer) {
1279
1830
  clearTimeout(dataSet.timer);
1280
1831
  }
1281
1832
 
1282
- LoggerProxy.logger.info(
1283
- `HashTreeParser#runSyncAlgorithm --> ${this.debugId} setting "${dataSet.name}" sync timer for ${delay}`
1284
- );
1833
+ this.saveSyncBackoffLatency(dataSet.name, randomBackoffTime);
1285
1834
 
1286
- dataSet.timer = setTimeout(async () => {
1835
+ dataSet.timer = setTimeout(() => {
1287
1836
  dataSet.timer = undefined;
1288
1837
 
1289
1838
  if (!dataSet.hashTree) {
@@ -1297,15 +1846,10 @@ class HashTreeParser {
1297
1846
  const rootHash = dataSet.hashTree.getRootHash();
1298
1847
 
1299
1848
  if (dataSet.root !== rootHash) {
1300
- await this.performSync(
1301
- dataSet,
1302
- rootHash,
1849
+ this.enqueueSyncForDataset(
1850
+ dataSet.name,
1303
1851
  `Root hash mismatch: received=${dataSet.root}, ours=${rootHash}`
1304
1852
  );
1305
- } else {
1306
- LoggerProxy.logger.info(
1307
- `HashTreeParser#runSyncAlgorithm --> ${this.debugId} "${dataSet.name}" root hash matching: ${rootHash}, version=${dataSet.version}`
1308
- );
1309
1853
  }
1310
1854
  }, delay);
1311
1855
  } else {
@@ -1325,42 +1869,104 @@ class HashTreeParser {
1325
1869
  * @returns {void}
1326
1870
  */
1327
1871
  private resetHeartbeatWatchdogs(receivedDataSets: Array<DataSet>): void {
1328
- if (!this.heartbeatIntervalMs) {
1329
- return;
1330
- }
1331
-
1332
1872
  for (const receivedDataSet of receivedDataSets) {
1333
1873
  const dataSet = this.dataSets[receivedDataSet.name];
1334
1874
 
1335
- 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) {
1336
1884
  // eslint-disable-next-line no-continue
1337
1885
  continue;
1338
1886
  }
1339
1887
 
1340
- if (dataSet.heartbeatWatchdogTimer) {
1341
- clearTimeout(dataSet.heartbeatWatchdogTimer);
1342
- 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;
1343
1901
  }
1344
1902
 
1345
1903
  const backoffTime = this.getWeightedBackoffTime(dataSet.backoff);
1346
- const delay = this.heartbeatIntervalMs + backoffTime;
1904
+ const delay = heartbeatIntervalMs + backoffTime;
1347
1905
 
1348
- dataSet.heartbeatWatchdogTimer = setTimeout(async () => {
1906
+ dataSet.heartbeatWatchdogTimer = setTimeout(() => {
1349
1907
  dataSet.heartbeatWatchdogTimer = undefined;
1350
1908
 
1351
1909
  LoggerProxy.logger.warn(
1352
- `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`
1353
1911
  );
1354
1912
 
1355
- await this.performSync(
1356
- dataSet,
1357
- dataSet.hashTree.getRootHash(),
1358
- `heartbeat watchdog expired`
1359
- );
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]);
1360
1922
  }, delay);
1361
1923
  }
1362
1924
  }
1363
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
+
1364
1970
  /**
1365
1971
  * Stops all timers for the data sets to prevent any further sync attempts.
1366
1972
  * @returns {void}
@@ -1378,18 +1984,124 @@ class HashTreeParser {
1378
1984
  });
1379
1985
  }
1380
1986
 
1987
+ /**
1988
+ * Stops the HashTreeParser, preventing it from processing any further messages and clearing all timers.
1989
+ * It also clears all the hash trees, so if the parser is resumed later, it will need to do a sync
1990
+ * to be up-to-date.
1991
+ * @returns {void}
1992
+ */
1993
+ public stop() {
1994
+ LoggerProxy.logger.info(
1995
+ `HashTreeParser#stop --> ${this.debugId} Stopping HashTreeParser, clearing timers and hash trees`
1996
+ );
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();
2003
+ Object.values(this.dataSets).forEach((dataSet) => {
2004
+ dataSet.syncAbortController?.abort();
2005
+ dataSet.syncAbortController = undefined;
2006
+ dataSet.hashTree = undefined;
2007
+ });
2008
+ this.visibleDataSets = [];
2009
+ this.state = 'stopped';
2010
+ }
2011
+
2012
+ /**
2013
+ * Cleans up the HashTreeParser, stopping all timers and clearing all internal state.
2014
+ * After calling this, the parser should not be used anymore.
2015
+ * @returns {void}
2016
+ */
2017
+ public cleanUp() {
2018
+ this.stop();
2019
+ this.dataSets = {};
2020
+ }
2021
+
2022
+ /**
2023
+ * Resumes the HashTreeParser that was previously stopped, using a hash tree message.
2024
+ * @param {HashTreeMessage} message - The message to resume with, it must contain metadata with visible data sets info
2025
+ * @returns {void}
2026
+ */
2027
+ public resumeFromMessage(message: HashTreeMessage) {
2028
+ const metadataObject = message.locusStateElements?.find((el) => isMetadata(el));
2029
+
2030
+ if (!metadataObject?.data?.visibleDataSets) {
2031
+ LoggerProxy.logger.warn(
2032
+ `HashTreeParser#resumeFromMessage --> ${this.debugId} Cannot resume HashTreeParser because the message is missing metadata with visible data sets info`
2033
+ );
2034
+
2035
+ return;
2036
+ }
2037
+ this.setVisibleDataSets(
2038
+ metadataObject.data.visibleDataSets as VisibleDataSetInfo[],
2039
+ message.dataSets
2040
+ );
2041
+
2042
+ this.dataSets = {};
2043
+
2044
+ for (const dataSet of message.dataSets) {
2045
+ const {name, leafCount} = dataSet;
2046
+
2047
+ this.dataSets[name] = {
2048
+ ...dataSet,
2049
+ hashTree: this.isVisibleDataSet(name) ? new HashTree([], leafCount) : undefined,
2050
+ };
2051
+ }
2052
+ LoggerProxy.logger.info(
2053
+ `HashTreeParser#resumeFromMessage --> ${
2054
+ this.debugId
2055
+ } Resuming HashTreeParser with data sets: ${Object.keys(this.dataSets).join(
2056
+ ', '
2057
+ )}, visible data sets: ${this.visibleDataSets.map((ds) => ds.name).join(', ')}`
2058
+ );
2059
+ this.state = 'active';
2060
+
2061
+ this.handleMessage(message, 'on resume');
2062
+ }
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
+
1381
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
+
1382
2094
  const isValidDataSetForSentinel =
1383
2095
  dataSetName === undefined ||
1384
2096
  PossibleSentinelMessageDataSetNames.includes(dataSetName.toLowerCase());
1385
2097
 
1386
2098
  if (
1387
- ((error.statusCode === 409 && error.body?.errorCode === 2403004) ||
1388
- error.statusCode === 404) &&
2099
+ error.statusCode === 409 &&
2100
+ error.body?.errorCode === LocusErrorCodes.LOCUS_INACTIVE &&
1389
2101
  isValidDataSetForSentinel
1390
2102
  ) {
1391
2103
  LoggerProxy.logger.info(
1392
- `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`
1393
2105
  );
1394
2106
  this.stopAllTimers();
1395
2107
 
@@ -1401,9 +2113,18 @@ class HashTreeParser {
1401
2113
  * Gets the current hashes from the locus for a specific data set.
1402
2114
  * @param {string} dataSetName
1403
2115
  * @param {string} currentRootHash
1404
- * @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
1405
2120
  */
1406
- 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
+
1407
2128
  LoggerProxy.logger.info(
1408
2129
  `HashTreeParser#getHashesFromLocus --> ${this.debugId} Requesting hashes for data set "${dataSetName}"`
1409
2130
  );
@@ -1412,14 +2133,48 @@ class HashTreeParser {
1412
2133
 
1413
2134
  const url = `${dataSet.url}/hashtree`;
1414
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
+
1415
2147
  return this.webexRequest({
1416
2148
  method: HTTP_VERBS.GET,
1417
2149
  uri: url,
1418
2150
  qs: {
1419
2151
  rootHash: currentRootHash,
1420
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}} : {}),
1421
2156
  })
1422
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
+
1423
2178
  const hashes = response.body?.hashes as string[] | undefined;
1424
2179
  const dataSetFromResponse = response.body?.dataSet;
1425
2180
 
@@ -1448,6 +2203,13 @@ class HashTreeParser {
1448
2203
  error
1449
2204
  );
1450
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
+ });
1451
2213
 
1452
2214
  throw error;
1453
2215
  });
@@ -1457,31 +2219,59 @@ class HashTreeParser {
1457
2219
  * Sends a sync request to Locus for the specified data set.
1458
2220
  *
1459
2221
  * @param {InternalDataSet} dataSet The data set to sync.
1460
- * @param {Record<number, LeafDataItem[]>} mismatchedLeavesData The mismatched leaves data to include in the sync request.
1461
- * @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>}
1462
2225
  */
1463
2226
  private sendSyncRequestToLocus(
1464
2227
  dataSet: InternalDataSet,
1465
- mismatchedLeavesData: Record<number, LeafDataItem[]>
2228
+ options: {isInitialization: true} | {mismatchedLeavesData: Record<number, LeafDataItem[]>},
2229
+ trackingId?: string
1466
2230
  ): Promise<HashTreeMessage | null> {
1467
2231
  LoggerProxy.logger.info(
1468
2232
  `HashTreeParser#sendSyncRequestToLocus --> ${this.debugId} Sending sync request for data set "${dataSet.name}"`
1469
2233
  );
1470
2234
 
2235
+ const isInitialization = 'isInitialization' in options;
2236
+
1471
2237
  const url = `${dataSet.url}/sync`;
1472
- const body = {
1473
- leafCount: dataSet.leafCount,
2238
+ const body: {
2239
+ leafCount: number;
2240
+ leafDataEntries: {leafIndex: number; elementIds: LeafDataItem[]}[];
2241
+ } = {
2242
+ leafCount: isInitialization ? 1 : dataSet.leafCount,
1474
2243
  leafDataEntries: [],
1475
2244
  };
1476
2245
 
1477
- Object.keys(mismatchedLeavesData).forEach((index) => {
1478
- body.leafDataEntries.push({
1479
- leafIndex: parseInt(index, 10),
1480
- elementIds: mismatchedLeavesData[index],
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);
2254
+
2255
+ body.leafDataEntries.push({
2256
+ leafIndex,
2257
+ elementIds: mismatchedLeavesData[leafIndex],
2258
+ });
1481
2259
  });
1482
- });
2260
+ }
1483
2261
 
1484
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
+ }
1485
2275
 
1486
2276
  return this.webexRequest({
1487
2277
  method: HTTP_VERBS.POST,
@@ -1489,12 +2279,22 @@ class HashTreeParser {
1489
2279
  qs: {
1490
2280
  rootHash: ourCurrentRootHash,
1491
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}} : {}),
1492
2285
  body,
1493
2286
  })
1494
2287
  .then((resp) => {
1495
- LoggerProxy.logger.info(
1496
- `HashTreeParser#sendSyncRequestToLocus --> ${this.debugId} Sync request succeeded for "${dataSet.name}"`
1497
- );
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
+ }
1498
2298
 
1499
2299
  if (!resp.body || isEmpty(resp.body)) {
1500
2300
  LoggerProxy.logger.info(
@@ -1512,6 +2312,13 @@ class HashTreeParser {
1512
2312
  error
1513
2313
  );
1514
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
+ });
1515
2322
 
1516
2323
  throw error;
1517
2324
  });