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

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 (354) 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/babel.config.js +17 -1
  43. package/dist/aiEnableRequest/index.js +15 -2
  44. package/dist/aiEnableRequest/index.js.map +1 -1
  45. package/dist/annotation/index.js +55 -19
  46. package/dist/annotation/index.js.map +1 -1
  47. package/dist/assets/e2ee-0.0.1.js +2 -0
  48. package/dist/assets/e2ee-0.0.1.wasm +0 -0
  49. package/dist/breakouts/breakout.js +8 -3
  50. package/dist/breakouts/breakout.js.map +1 -1
  51. package/dist/breakouts/events.js +29 -14
  52. package/dist/breakouts/events.js.map +1 -1
  53. package/dist/breakouts/index.js +128 -7
  54. package/dist/breakouts/index.js.map +1 -1
  55. package/dist/common/errors/webex-errors.js +54 -5
  56. package/dist/common/errors/webex-errors.js.map +1 -1
  57. package/dist/common/wasm-loader.js +174 -0
  58. package/dist/common/wasm-loader.js.map +1 -0
  59. package/dist/config.js +5 -2
  60. package/dist/config.js.map +1 -1
  61. package/dist/constants.js +39 -11
  62. package/dist/constants.js.map +1 -1
  63. package/dist/controls-options-manager/constants.js +11 -1
  64. package/dist/controls-options-manager/constants.js.map +1 -1
  65. package/dist/controls-options-manager/index.js +67 -29
  66. package/dist/controls-options-manager/index.js.map +1 -1
  67. package/dist/controls-options-manager/util.js +91 -0
  68. package/dist/controls-options-manager/util.js.map +1 -1
  69. package/dist/e2ee/E2eeManager.js +91 -0
  70. package/dist/e2ee/E2eeManager.js.map +1 -0
  71. package/dist/e2ee/E2eeSignaling.js +200 -0
  72. package/dist/e2ee/E2eeSignaling.js.map +1 -0
  73. package/dist/e2ee/MediaEncryptionService.js +75 -0
  74. package/dist/e2ee/MediaEncryptionService.js.map +1 -0
  75. package/dist/e2ee/mls.js +558 -0
  76. package/dist/e2ee/mls.js.map +1 -0
  77. package/dist/e2ee/types.js +59 -0
  78. package/dist/e2ee/types.js.map +1 -0
  79. package/dist/e2ee/wasm.d.js +7 -0
  80. package/dist/e2ee/wasm.d.js.map +1 -0
  81. package/dist/hashTree/constants.js +13 -1
  82. package/dist/hashTree/constants.js.map +1 -1
  83. package/dist/hashTree/hashTreeParser.js +1245 -404
  84. package/dist/hashTree/hashTreeParser.js.map +1 -1
  85. package/dist/hashTree/utils.js +42 -0
  86. package/dist/hashTree/utils.js.map +1 -1
  87. package/dist/index.js +8 -0
  88. package/dist/index.js.map +1 -1
  89. package/dist/interceptors/dataChannelAuthToken.js +58 -16
  90. package/dist/interceptors/dataChannelAuthToken.js.map +1 -1
  91. package/dist/interceptors/locusRetry.js +24 -9
  92. package/dist/interceptors/locusRetry.js.map +1 -1
  93. package/dist/interpretation/index.js +55 -12
  94. package/dist/interpretation/index.js.map +1 -1
  95. package/dist/interpretation/interpretation.types.js +7 -0
  96. package/dist/interpretation/interpretation.types.js.map +1 -0
  97. package/dist/interpretation/siLanguage.js +1 -1
  98. package/dist/locus-info/controlsUtils.js +4 -1
  99. package/dist/locus-info/controlsUtils.js.map +1 -1
  100. package/dist/locus-info/index.js +914 -196
  101. package/dist/locus-info/index.js.map +1 -1
  102. package/dist/locus-info/infoUtils.js +36 -5
  103. package/dist/locus-info/infoUtils.js.map +1 -1
  104. package/dist/locus-info/types.js +20 -0
  105. package/dist/locus-info/types.js.map +1 -1
  106. package/dist/media/MediaConnectionAwaiter.js +229 -166
  107. package/dist/media/MediaConnectionAwaiter.js.map +1 -1
  108. package/dist/media/index.js +8 -2
  109. package/dist/media/index.js.map +1 -1
  110. package/dist/media/properties.js +4 -5
  111. package/dist/media/properties.js.map +1 -1
  112. package/dist/meeting/in-meeting-actions.js +5 -1
  113. package/dist/meeting/in-meeting-actions.js.map +1 -1
  114. package/dist/meeting/index.js +1931 -887
  115. package/dist/meeting/index.js.map +1 -1
  116. package/dist/meeting/locusMediaRequest.js +229 -82
  117. package/dist/meeting/locusMediaRequest.js.map +1 -1
  118. package/dist/meeting/muteState.js +10 -1
  119. package/dist/meeting/muteState.js.map +1 -1
  120. package/dist/meeting/request.js +5 -2
  121. package/dist/meeting/request.js.map +1 -1
  122. package/dist/meeting/util.js +42 -3
  123. package/dist/meeting/util.js.map +1 -1
  124. package/dist/meeting/voicea-meeting.js +2 -1
  125. package/dist/meeting/voicea-meeting.js.map +1 -1
  126. package/dist/meeting-info/meeting-info-v2.js +12 -5
  127. package/dist/meeting-info/meeting-info-v2.js.map +1 -1
  128. package/dist/meetings/index.js +342 -129
  129. package/dist/meetings/index.js.map +1 -1
  130. package/dist/meetings/meetings.types.js +6 -1
  131. package/dist/meetings/meetings.types.js.map +1 -1
  132. package/dist/meetings/request.js +39 -0
  133. package/dist/meetings/request.js.map +1 -1
  134. package/dist/meetings/util.js +116 -18
  135. package/dist/meetings/util.js.map +1 -1
  136. package/dist/member/index.js +10 -0
  137. package/dist/member/index.js.map +1 -1
  138. package/dist/member/types.js.map +1 -1
  139. package/dist/member/util.js +30 -0
  140. package/dist/member/util.js.map +1 -1
  141. package/dist/members/index.js +101 -43
  142. package/dist/members/index.js.map +1 -1
  143. package/dist/members/util.js +8 -1
  144. package/dist/members/util.js.map +1 -1
  145. package/dist/metrics/constants.js +11 -1
  146. package/dist/metrics/constants.js.map +1 -1
  147. package/dist/multistream/codec/constants.js +63 -0
  148. package/dist/multistream/codec/constants.js.map +1 -0
  149. package/dist/multistream/mediaRequestManager.js +62 -15
  150. package/dist/multistream/mediaRequestManager.js.map +1 -1
  151. package/dist/multistream/receiveSlot.js +9 -0
  152. package/dist/multistream/receiveSlot.js.map +1 -1
  153. package/dist/multistream/remoteMediaManager.js +32 -4
  154. package/dist/multistream/remoteMediaManager.js.map +1 -1
  155. package/dist/multistream/sendSlotManager.js +127 -3
  156. package/dist/multistream/sendSlotManager.js.map +1 -1
  157. package/dist/reachability/clusterReachability.js.map +1 -1
  158. package/dist/reachability/index.js +121 -83
  159. package/dist/reachability/index.js.map +1 -1
  160. package/dist/reachability/reachability.types.js +2 -0
  161. package/dist/reachability/reachability.types.js.map +1 -1
  162. package/dist/reachability/util.js +45 -0
  163. package/dist/reachability/util.js.map +1 -1
  164. package/dist/reactions/reactions.type.js.map +1 -1
  165. package/dist/recording-controller/index.js +1 -3
  166. package/dist/recording-controller/index.js.map +1 -1
  167. package/dist/roap/turnDiscovery.js +8 -1
  168. package/dist/roap/turnDiscovery.js.map +1 -1
  169. package/dist/types/annotation/index.d.ts +19 -0
  170. package/dist/types/common/errors/webex-errors.d.ts +36 -2
  171. package/dist/types/common/wasm-loader.d.ts +55 -0
  172. package/dist/types/config.d.ts +5 -2
  173. package/dist/types/constants.d.ts +15 -2
  174. package/dist/types/controls-options-manager/constants.d.ts +6 -1
  175. package/dist/types/controls-options-manager/index.d.ts +16 -0
  176. package/dist/types/e2ee/E2eeManager.d.ts +23 -0
  177. package/dist/types/e2ee/E2eeSignaling.d.ts +94 -0
  178. package/dist/types/e2ee/MediaEncryptionService.d.ts +27 -0
  179. package/dist/types/e2ee/mls.d.ts +191 -0
  180. package/dist/types/e2ee/types.d.ts +104 -0
  181. package/dist/types/hashTree/constants.d.ts +2 -0
  182. package/dist/types/hashTree/hashTreeParser.d.ts +230 -18
  183. package/dist/types/hashTree/utils.d.ts +18 -0
  184. package/dist/types/index.d.ts +4 -0
  185. package/dist/types/interceptors/locusRetry.d.ts +4 -4
  186. package/dist/types/interpretation/interpretation.types.d.ts +10 -0
  187. package/dist/types/locus-info/index.d.ts +151 -15
  188. package/dist/types/locus-info/infoUtils.d.ts +8 -0
  189. package/dist/types/locus-info/types.d.ts +28 -1
  190. package/dist/types/media/MediaConnectionAwaiter.d.ts +66 -49
  191. package/dist/types/media/properties.d.ts +6 -2
  192. package/dist/types/meeting/in-meeting-actions.d.ts +4 -0
  193. package/dist/types/meeting/index.d.ts +247 -13
  194. package/dist/types/meeting/locusMediaRequest.d.ts +12 -0
  195. package/dist/types/meeting/request.d.ts +1 -0
  196. package/dist/types/meeting/util.d.ts +12 -1
  197. package/dist/types/meeting-info/meeting-info-v2.d.ts +1 -0
  198. package/dist/types/meetings/index.d.ts +44 -19
  199. package/dist/types/meetings/meetings.types.d.ts +15 -0
  200. package/dist/types/meetings/request.d.ts +14 -0
  201. package/dist/types/member/index.d.ts +1 -0
  202. package/dist/types/member/types.d.ts +1 -0
  203. package/dist/types/member/util.d.ts +9 -0
  204. package/dist/types/members/index.d.ts +15 -2
  205. package/dist/types/members/util.d.ts +1 -5
  206. package/dist/types/metrics/constants.d.ts +10 -0
  207. package/dist/types/multistream/codec/constants.d.ts +7 -0
  208. package/dist/types/multistream/mediaRequestManager.d.ts +22 -5
  209. package/dist/types/multistream/remoteMediaManager.d.ts +18 -0
  210. package/dist/types/multistream/sendSlotManager.d.ts +28 -2
  211. package/dist/types/reachability/clusterReachability.d.ts +3 -3
  212. package/dist/types/reachability/index.d.ts +10 -3
  213. package/dist/types/reachability/reachability.types.d.ts +7 -0
  214. package/dist/types/reachability/util.d.ts +17 -0
  215. package/dist/types/reactions/reactions.type.d.ts +3 -0
  216. package/dist/webinar/index.js +539 -245
  217. package/dist/webinar/index.js.map +1 -1
  218. package/package.json +26 -24
  219. package/src/aiEnableRequest/ai-docs/ai-enable-request-spec.md +223 -0
  220. package/src/aiEnableRequest/index.ts +16 -0
  221. package/src/annotation/ai-docs/annotation-spec.md +236 -0
  222. package/src/annotation/index.ts +61 -29
  223. package/src/breakouts/ai-docs/breakouts-spec.md +324 -0
  224. package/src/breakouts/breakout.ts +3 -1
  225. package/src/breakouts/events.ts +33 -11
  226. package/src/breakouts/index.ts +145 -3
  227. package/src/common/errors/webex-errors.ts +56 -3
  228. package/src/common/wasm-loader.ts +124 -0
  229. package/src/config.ts +9 -3
  230. package/src/constants.ts +23 -4
  231. package/src/controls-options-manager/ai-docs/controls-options-manager-spec.md +243 -0
  232. package/src/controls-options-manager/constants.ts +14 -1
  233. package/src/controls-options-manager/index.ts +87 -28
  234. package/src/controls-options-manager/util.ts +81 -1
  235. package/src/e2ee/E2eeManager.ts +58 -0
  236. package/src/e2ee/E2eeSignaling.ts +215 -0
  237. package/src/e2ee/MediaEncryptionService.ts +41 -0
  238. package/src/e2ee/mls.ts +548 -0
  239. package/src/e2ee/types.ts +114 -0
  240. package/src/e2ee/wasm.d.ts +153 -0
  241. package/src/hashTree/ai-docs/hash-tree-spec.md +267 -0
  242. package/src/hashTree/constants.ts +16 -0
  243. package/src/hashTree/hashTreeParser.ts +1021 -214
  244. package/src/hashTree/utils.ts +36 -0
  245. package/src/index.ts +7 -0
  246. package/src/interceptors/ai-docs/interceptors-spec.md +247 -0
  247. package/src/interceptors/dataChannelAuthToken.ts +59 -12
  248. package/src/interceptors/locusRetry.ts +26 -5
  249. package/src/interpretation/ai-docs/interpretation-spec.md +256 -0
  250. package/src/interpretation/index.ts +65 -10
  251. package/src/interpretation/interpretation.types.ts +11 -0
  252. package/src/locus-info/ai-docs/locus-info-spec.md +293 -0
  253. package/src/locus-info/controlsUtils.ts +3 -1
  254. package/src/locus-info/index.ts +907 -184
  255. package/src/locus-info/infoUtils.ts +41 -6
  256. package/src/locus-info/types.ts +33 -1
  257. package/src/media/MediaConnectionAwaiter.ts +229 -196
  258. package/src/media/ai-docs/media-spec.md +267 -0
  259. package/src/media/index.ts +10 -1
  260. package/src/media/properties.ts +8 -3
  261. package/src/meeting/ai-docs/meeting-spec.md +404 -0
  262. package/src/meeting/in-meeting-actions.ts +8 -0
  263. package/src/meeting/index.ts +1237 -254
  264. package/src/meeting/locusMediaRequest.ts +106 -6
  265. package/src/meeting/muteState.ts +10 -1
  266. package/src/meeting/request.ts +11 -0
  267. package/src/meeting/util.ts +53 -8
  268. package/src/meeting/voicea-meeting.ts +1 -1
  269. package/src/meeting-info/ai-docs/meeting-info-spec.md +261 -0
  270. package/src/meeting-info/meeting-info-v2.ts +11 -4
  271. package/src/meetings/ai-docs/meetings-spec.md +298 -0
  272. package/src/meetings/index.ts +242 -80
  273. package/src/meetings/meetings.types.ts +19 -0
  274. package/src/meetings/request.ts +43 -0
  275. package/src/meetings/util.ts +117 -4
  276. package/src/member/ai-docs/member-spec.md +196 -0
  277. package/src/member/index.ts +10 -0
  278. package/src/member/types.ts +1 -0
  279. package/src/member/util.ts +29 -0
  280. package/src/members/ai-docs/members-spec.md +256 -0
  281. package/src/members/index.ts +70 -7
  282. package/src/members/util.ts +12 -4
  283. package/src/metrics/ai-docs/metrics-spec.md +185 -0
  284. package/src/metrics/constants.ts +11 -0
  285. package/src/multistream/ai-docs/multistream-spec.md +295 -0
  286. package/src/multistream/codec/constants.ts +58 -0
  287. package/src/multistream/mediaRequestManager.ts +119 -28
  288. package/src/multistream/receiveSlot.ts +18 -0
  289. package/src/multistream/remoteMediaManager.ts +23 -1
  290. package/src/multistream/sendSlotManager.ts +112 -4
  291. package/src/personal-meeting-room/ai-docs/personal-meeting-room-spec.md +234 -0
  292. package/src/reachability/ai-docs/reachability-spec.md +261 -0
  293. package/src/reachability/clusterReachability.ts +3 -2
  294. package/src/reachability/index.ts +47 -16
  295. package/src/reachability/reachability.types.ts +11 -0
  296. package/src/reachability/util.ts +36 -0
  297. package/src/reactions/ai-docs/reactions-spec.md +198 -0
  298. package/src/reactions/reactions.type.ts +3 -0
  299. package/src/reconnection-manager/ai-docs/reconnection-manager-spec.md +272 -0
  300. package/src/recording-controller/ai-docs/recording-controller-spec.md +223 -0
  301. package/src/recording-controller/index.ts +1 -2
  302. package/src/roap/ai-docs/roap-spec.md +241 -0
  303. package/src/roap/turnDiscovery.ts +9 -1
  304. package/src/webinar/ai-docs/webinar-spec.md +243 -0
  305. package/src/webinar/index.ts +333 -73
  306. package/test/unit/spec/aiEnableRequest/index.ts +86 -0
  307. package/test/unit/spec/annotation/index.ts +214 -182
  308. package/test/unit/spec/breakouts/breakout.ts +9 -3
  309. package/test/unit/spec/breakouts/events.ts +120 -2
  310. package/test/unit/spec/breakouts/index.ts +336 -15
  311. package/test/unit/spec/common/errors/webex-errors.ts +78 -0
  312. package/test/unit/spec/common/wasm-loader.ts +171 -0
  313. package/test/unit/spec/controls-options-manager/index.js +244 -29
  314. package/test/unit/spec/controls-options-manager/util.js +165 -0
  315. package/test/unit/spec/e2ee/E2eeManager.ts +82 -0
  316. package/test/unit/spec/e2ee/E2eeSignaling.ts +172 -0
  317. package/test/unit/spec/e2ee/MediaEncryptionService.ts +43 -0
  318. package/test/unit/spec/e2ee/mls.ts +765 -0
  319. package/test/unit/spec/hashTree/hashTreeParser.ts +3126 -238
  320. package/test/unit/spec/hashTree/utils.ts +125 -1
  321. package/test/unit/spec/interceptors/dataChannelAuthToken.ts +179 -1
  322. package/test/unit/spec/interceptors/locusRetry.ts +234 -5
  323. package/test/unit/spec/interpretation/index.ts +119 -4
  324. package/test/unit/spec/locus-info/controlsUtils.js +172 -57
  325. package/test/unit/spec/locus-info/index.js +1880 -136
  326. package/test/unit/spec/locus-info/infoUtils.js +184 -1
  327. package/test/unit/spec/media/MediaConnectionAwaiter.ts +479 -17
  328. package/test/unit/spec/media/index.ts +92 -0
  329. package/test/unit/spec/media/properties.ts +26 -26
  330. package/test/unit/spec/meeting/in-meeting-actions.ts +4 -0
  331. package/test/unit/spec/meeting/index.js +3697 -501
  332. package/test/unit/spec/meeting/locusMediaRequest.ts +406 -4
  333. package/test/unit/spec/meeting/muteState.js +81 -0
  334. package/test/unit/spec/meeting/request.js +12 -0
  335. package/test/unit/spec/meeting/utils.js +206 -16
  336. package/test/unit/spec/meeting/voicea-meeting.ts +85 -1
  337. package/test/unit/spec/meeting-info/index.js +2 -3
  338. package/test/unit/spec/meeting-info/meetinginfov2.js +88 -11
  339. package/test/unit/spec/meetings/index.js +606 -53
  340. package/test/unit/spec/meetings/request.js +141 -0
  341. package/test/unit/spec/meetings/utils.js +402 -51
  342. package/test/unit/spec/member/index.js +7 -0
  343. package/test/unit/spec/member/util.js +89 -0
  344. package/test/unit/spec/members/index.js +216 -0
  345. package/test/unit/spec/members/request.js +37 -1
  346. package/test/unit/spec/members/utils.js +63 -0
  347. package/test/unit/spec/multistream/mediaRequestManager.ts +501 -37
  348. package/test/unit/spec/multistream/remoteMediaManager.ts +46 -0
  349. package/test/unit/spec/multistream/sendSlotManager.ts +165 -38
  350. package/test/unit/spec/reachability/index.ts +128 -46
  351. package/test/unit/spec/reachability/util.ts +31 -0
  352. package/test/unit/spec/recording-controller/index.js +9 -8
  353. package/test/unit/spec/roap/turnDiscovery.ts +20 -0
  354. package/test/unit/spec/webinar/index.ts +982 -328
@@ -1,12 +1,19 @@
1
1
  import HashTreeParser, {
2
2
  LocusInfoUpdateType,
3
3
  MeetingEndedError,
4
+ LocusNotFoundError,
5
+ SyncAllBackoffType,
4
6
  } from '@webex/plugin-meetings/src/hashTree/hashTreeParser';
5
7
  import HashTree from '@webex/plugin-meetings/src/hashTree/hashTree';
6
8
  import {expect} from '@webex/test-helper-chai';
7
9
  import sinon from 'sinon';
8
10
  import {assert} from '@webex/test-helper-chai';
9
11
  import {EMPTY_HASH} from '@webex/plugin-meetings/src/hashTree/constants';
12
+ import testUtils from '@webex/plugin-meetings/test/utils/testUtils';
13
+ import { some } from 'lodash';
14
+ import Metrics from '@webex/plugin-meetings/src/metrics';
15
+ import BEHAVIORAL_METRICS from '@webex/plugin-meetings/src/metrics/constants';
16
+ import LoggerProxy from '@webex/plugin-meetings/src/common/logs/logger-proxy';
10
17
 
11
18
  const visibleDataSetsUrl = 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/visibleDataSets';
12
19
 
@@ -111,6 +118,7 @@ function createDataSet(name: string, leafCount: number, version = 1) {
111
118
  name,
112
119
  idleMs: 1000,
113
120
  backoff: {maxMs: 1000, exponent: 2},
121
+ heartbeatIntervalMs: 5000,
114
122
  };
115
123
  }
116
124
 
@@ -151,31 +159,47 @@ describe('HashTreeParser', () => {
151
159
  let webexRequest: sinon.SinonStub;
152
160
  let callback: sinon.SinonStub;
153
161
  let mathRandomStub: sinon.SinonStub;
162
+ let metricsStub: sinon.SinonStub;
163
+ let loggerInfoStub: sinon.SinonStub;
154
164
 
155
165
  beforeEach(() => {
156
166
  clock = sinon.useFakeTimers();
157
167
  webexRequest = sinon.stub();
158
168
  callback = sinon.stub();
159
169
  mathRandomStub = sinon.stub(Math, 'random').returns(0);
170
+ metricsStub = sinon.stub(Metrics, 'sendBehavioralMetric');
171
+ loggerInfoStub = sinon.stub(LoggerProxy.logger, 'info');
160
172
  });
161
173
  afterEach(() => {
162
174
  clock.restore();
163
175
  mathRandomStub.restore();
176
+ metricsStub.restore();
177
+ loggerInfoStub.restore();
164
178
  });
165
179
 
166
180
  // Helper to create a HashTreeParser instance with common defaults
167
181
  function createHashTreeParser(
168
182
  initialLocus: any = exampleInitialLocus,
169
183
  metadata: any = exampleMetadata,
170
- excludedDataSets?: string[]
184
+ excludedDataSets?: string[],
185
+ syncLatencyTracker?: any,
186
+ syncLatencyMeetingId = 'meeting-1',
187
+ generateTrackingId?: any,
188
+ isLlmExpected?: () => boolean
171
189
  ) {
172
190
  return new HashTreeParser({
173
191
  initialLocus,
174
192
  metadata,
175
193
  webexRequest,
176
- locusInfoUpdateCallback: callback,
194
+ callbacks: {
195
+ locusInfoUpdateCallback: callback,
196
+ syncLatencyTracker,
197
+ generateTrackingId,
198
+ isLlmExpected,
199
+ },
177
200
  debugId: 'test',
178
201
  excludedDataSets,
202
+ syncLatencyMeetingId,
179
203
  });
180
204
  }
181
205
 
@@ -216,7 +240,7 @@ describe('HashTreeParser', () => {
216
240
  }
217
241
 
218
242
  // Helper to mock sendSyncRequestToLocus response
219
- function mockSendSyncRequestResponse(dataSetUrl: string, response: any) {
243
+ function mockSendSyncRequestResponse(dataSetUrl: string, response: any, headers?: any) {
220
244
  webexRequest
221
245
  .withArgs(
222
246
  sinon.match({
@@ -226,6 +250,7 @@ describe('HashTreeParser', () => {
226
250
  )
227
251
  .resolves({
228
252
  body: response,
253
+ headers,
229
254
  });
230
255
  }
231
256
 
@@ -553,7 +578,7 @@ describe('HashTreeParser', () => {
553
578
  );
554
579
 
555
580
  // Verify callback was called with OBJECTS_UPDATED and correct updatedObjects list
556
- assert.calledWith(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
581
+ assert.calledWith(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
557
582
  updatedObjects: [
558
583
  {
559
584
  htMeta: {
@@ -566,6 +591,11 @@ describe('HashTreeParser', () => {
566
591
  },
567
592
  data: {info: {id: 'some-fake-locus-info'}},
568
593
  },
594
+ ],
595
+ });
596
+
597
+ assert.calledWith(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
598
+ updatedObjects: [
569
599
  {
570
600
  htMeta: {
571
601
  elementId: {
@@ -596,6 +626,67 @@ describe('HashTreeParser', () => {
596
626
  });
597
627
  });
598
628
 
629
+ it('initializes "main" before "self" regardless of order from Locus', async () => {
630
+ const parser = createHashTreeParser({dataSets: [], locus: null}, null);
631
+
632
+ // Locus returns datasets in non-priority order: atd-active, main, self
633
+ const atdActiveDataSet = createDataSet('atd-active', 4, 500);
634
+ const mainDataSet = createDataSet('main', 16, 1100);
635
+ const selfDataSet = createDataSet('self', 1, 2100);
636
+
637
+ mockGetAllDataSetsMetadata(webexRequest, visibleDataSetsUrl, [
638
+ atdActiveDataSet,
639
+ mainDataSet,
640
+ selfDataSet,
641
+ ]);
642
+
643
+ mockSyncRequest(webexRequest, selfDataSet.url);
644
+ mockSyncRequest(webexRequest, mainDataSet.url);
645
+ mockSyncRequest(webexRequest, atdActiveDataSet.url);
646
+
647
+ await parser.initializeFromMessage({
648
+ dataSets: [],
649
+ visibleDataSetsUrl,
650
+ locusUrl,
651
+ });
652
+
653
+ // Verify sync requests were sent in priority order: main, self, then atd-active
654
+ const syncCalls = webexRequest
655
+ .getCalls()
656
+ .filter((call) => call.args[0]?.method === 'POST' && call.args[0]?.uri?.endsWith('/sync'));
657
+
658
+ expect(syncCalls).to.have.lengthOf(3);
659
+ expect(syncCalls[0].args[0].uri).to.equal(`${mainDataSet.url}/sync`);
660
+ expect(syncCalls[1].args[0].uri).to.equal(`${selfDataSet.url}/sync`);
661
+ expect(syncCalls[2].args[0].uri).to.equal(`${atdActiveDataSet.url}/sync`);
662
+ });
663
+
664
+ it('sends leafCount=1 with a single empty leaf for initialization sync, regardless of actual dataset leafCount', async () => {
665
+ const parser = createHashTreeParser({dataSets: [], locus: null}, null);
666
+
667
+ // Use a dataset with leafCount=16 to verify the initialization sync always uses leafCount=1
668
+ const mainDataSet = createDataSet('main', 16, 1100);
669
+
670
+ mockGetAllDataSetsMetadata(webexRequest, visibleDataSetsUrl, [mainDataSet]);
671
+ mockSyncRequest(webexRequest, mainDataSet.url);
672
+
673
+ await parser.initializeFromMessage({
674
+ dataSets: [],
675
+ visibleDataSetsUrl,
676
+ locusUrl,
677
+ });
678
+
679
+ assert.calledWith(webexRequest, {
680
+ method: 'POST',
681
+ uri: `${mainDataSet.url}/sync`,
682
+ qs: {rootHash: sinon.match.string},
683
+ body: {
684
+ leafCount: 1,
685
+ leafDataEntries: [{leafIndex: 0, elementIds: []}],
686
+ },
687
+ });
688
+ });
689
+
599
690
  it('handles sync response that has locusStateElements undefined', async () => {
600
691
  const minimalInitialLocus = {
601
692
  dataSets: [],
@@ -636,8 +727,11 @@ describe('HashTreeParser', () => {
636
727
  assert.notCalled(callback);
637
728
  });
638
729
 
639
- [404, 409].forEach((errorCode) => {
640
- it(`emits MeetingEndedError if getting visible datasets returns ${errorCode}`, async () => {
730
+ [
731
+ {errorCode: 404, expectedError: LocusNotFoundError},
732
+ {errorCode: 409, expectedError: MeetingEndedError},
733
+ ].forEach(({errorCode, expectedError}) => {
734
+ it(`throws ${expectedError.name} if getting visible datasets returns ${errorCode}`, async () => {
641
735
  const minimalInitialLocus = {
642
736
  dataSets: [],
643
737
  locus: null,
@@ -660,7 +754,6 @@ describe('HashTreeParser', () => {
660
754
  )
661
755
  .rejects(error);
662
756
 
663
- // initializeFromMessage should throw MeetingEndedError
664
757
  let thrownError;
665
758
  try {
666
759
  await parser.initializeFromMessage({
@@ -672,7 +765,7 @@ describe('HashTreeParser', () => {
672
765
  thrownError = e;
673
766
  }
674
767
 
675
- expect(thrownError).to.be.instanceOf(MeetingEndedError);
768
+ expect(thrownError).to.be.instanceOf(expectedError);
676
769
  });
677
770
  });
678
771
  });
@@ -788,7 +881,7 @@ describe('HashTreeParser', () => {
788
881
  expect(parser.dataSets.self.version).to.equal(2100);
789
882
  expect(parser.dataSets['atd-unmuted'].version).to.equal(3100);
790
883
 
791
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
884
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
792
885
  updatedObjects: [
793
886
  {
794
887
  htMeta: {
@@ -861,6 +954,116 @@ describe('HashTreeParser', () => {
861
954
  });
862
955
  });
863
956
 
957
+ it('handles updates to control entries correctly', () => {
958
+ const parser = createHashTreeParser();
959
+
960
+ const mainPutItemsSpy = sinon.spy(parser.dataSets.main.hashTree, 'putItems');
961
+
962
+ // Create a locus update with new htMeta information for some things
963
+ const locusUpdate = {
964
+ dataSets: [
965
+ createDataSet('main', 16, 1100),
966
+ ],
967
+ locus: {
968
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f',
969
+ htMeta: {
970
+ elementId: {
971
+ type: 'locus',
972
+ id: 0,
973
+ version: 200, // same version
974
+ },
975
+ dataSetNames: ['main'],
976
+ },
977
+ participants: [],
978
+ controls: {
979
+ lock: {
980
+ locked: true,
981
+ htMeta: {
982
+ elementId: {
983
+ type: 'ControlEntry',
984
+ id: 10100,
985
+ version: 100,
986
+ },
987
+ dataSetNames: ['main'],
988
+ },
989
+ },
990
+ stream: {
991
+ streaming: true,
992
+ htMeta: {
993
+ elementId: {
994
+ type: 'ControlEntry',
995
+ id: 10101,
996
+ version: 100,
997
+ },
998
+ dataSetNames: ['main'],
999
+ },
1000
+ }
1001
+ }
1002
+ },
1003
+ };
1004
+
1005
+ // Call handleLocusUpdate
1006
+ parser.handleLocusUpdate(locusUpdate);
1007
+
1008
+ // Verify putItems was called on main hash tree with correct data
1009
+ assert.calledOnceWithExactly(mainPutItemsSpy, [
1010
+ {type: 'locus', id: 0, version: 200},
1011
+ {type: 'ControlEntry', id: 10100, version: 100},
1012
+ {type: 'ControlEntry', id: 10101, version: 100}
1013
+ ]);
1014
+
1015
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
1016
+ updatedObjects: [
1017
+ {
1018
+ htMeta: {
1019
+ elementId: {
1020
+ type: 'ControlEntry',
1021
+ id: 10100,
1022
+ version: 100,
1023
+ },
1024
+ dataSetNames: ['main'],
1025
+ },
1026
+ data: {
1027
+ lock: {
1028
+ locked: true,
1029
+ htMeta: {
1030
+ elementId: {
1031
+ type: 'ControlEntry',
1032
+ id: 10100,
1033
+ version: 100,
1034
+ },
1035
+ dataSetNames: ['main'],
1036
+ },
1037
+ },
1038
+ },
1039
+ },
1040
+ {
1041
+ htMeta: {
1042
+ elementId: {
1043
+ type: 'ControlEntry',
1044
+ id: 10101,
1045
+ version: 100,
1046
+ },
1047
+ dataSetNames: ['main'],
1048
+ },
1049
+ data: {
1050
+ stream: {
1051
+ streaming: true,
1052
+ htMeta: {
1053
+ elementId: {
1054
+ type: 'ControlEntry',
1055
+ id: 10101,
1056
+ version: 100,
1057
+ },
1058
+ dataSetNames: ['main'],
1059
+ },
1060
+ },
1061
+ },
1062
+ }
1063
+ ],
1064
+ });
1065
+ });
1066
+
864
1067
  it('handles unknown datasets gracefully', () => {
865
1068
  const parser = createHashTreeParser();
866
1069
 
@@ -899,7 +1102,7 @@ describe('HashTreeParser', () => {
899
1102
  assert.calledOnceWithExactly(mainPutItemsSpy, [{type: 'locus', id: 0, version: 201}]);
900
1103
 
901
1104
  // Verify callback was called only for known dataset
902
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
1105
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
903
1106
  updatedObjects: [
904
1107
  {
905
1108
  htMeta: {
@@ -999,7 +1202,7 @@ describe('HashTreeParser', () => {
999
1202
  assert.calledOnceWithExactly(selfPutItemSpy, {type: 'metadata', id: 5, version: 51});
1000
1203
 
1001
1204
  // Verify callback was called with metadata object and removed dataset objects
1002
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
1205
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
1003
1206
  updatedObjects: [
1004
1207
  // updated metadata object:
1005
1208
  {
@@ -1160,7 +1363,7 @@ describe('HashTreeParser', () => {
1160
1363
  assert.notCalled(atdUnmutedPutItemsSpy);
1161
1364
 
1162
1365
  // Verify callback was called with the updated object
1163
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
1366
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
1164
1367
  updatedObjects: [
1165
1368
  {
1166
1369
  htMeta: {
@@ -1388,7 +1591,7 @@ describe('HashTreeParser', () => {
1388
1591
  ]);
1389
1592
 
1390
1593
  // Verify callback was called with OBJECTS_UPDATED and all updated objects
1391
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
1594
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
1392
1595
  updatedObjects: [
1393
1596
  {
1394
1597
  htMeta: {
@@ -1453,9 +1656,7 @@ describe('HashTreeParser', () => {
1453
1656
  parser.handleMessage(sentinelMessage, 'sentinel message');
1454
1657
 
1455
1658
  // Verify callback was called with MEETING_ENDED
1456
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.MEETING_ENDED, {
1457
- updatedObjects: undefined,
1458
- });
1659
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.MEETING_ENDED});
1459
1660
 
1460
1661
  // Verify that all timers were stopped
1461
1662
  Object.values(parser.dataSets).forEach((ds: any) => {
@@ -1477,9 +1678,7 @@ describe('HashTreeParser', () => {
1477
1678
  parser.handleMessage(sentinelMessage, 'sentinel message');
1478
1679
 
1479
1680
  // Verify callback was called with MEETING_ENDED
1480
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.MEETING_ENDED, {
1481
- updatedObjects: undefined,
1482
- });
1681
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.MEETING_ENDED});
1483
1682
 
1484
1683
  // Verify that all timers were stopped
1485
1684
  Object.values(parser.dataSets).forEach((ds: any) => {
@@ -1575,7 +1774,7 @@ describe('HashTreeParser', () => {
1575
1774
  );
1576
1775
 
1577
1776
  // Verify that callback was called with synced objects
1578
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
1777
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
1579
1778
  updatedObjects: [
1580
1779
  {
1581
1780
  htMeta: {
@@ -1588,12 +1787,122 @@ describe('HashTreeParser', () => {
1588
1787
  });
1589
1788
  });
1590
1789
 
1591
- describe('emits MEETING_ENDED', () => {
1592
- [404, 409].forEach((statusCode) => {
1593
- it(`when /hashtree returns ${statusCode}`, async () => {
1790
+ it('filters a "main" sync response down to the requested dataset, ignoring shared datasets like "unjoined"', async () => {
1791
+ // Set up a parser where both "main" and "unjoined" are visible and share the core locus
1792
+ // element (they always advance to the same version on the server).
1793
+ const sharedInitialLocus = {
1794
+ dataSets: [createDataSet('main', 16, 1000), createDataSet('unjoined', 16, 1000)],
1795
+ locus: {
1796
+ url: locusUrl,
1797
+ htMeta: {
1798
+ elementId: {type: 'locus', id: 0, version: 200},
1799
+ dataSetNames: ['main', 'unjoined'],
1800
+ },
1801
+ links: {resources: {visibleDataSets: {url: visibleDataSetsUrl}}},
1802
+ participants: [],
1803
+ },
1804
+ };
1805
+ const sharedMetadata = {
1806
+ htMeta: {elementId: {type: 'metadata', id: 5, version: 50}, dataSetNames: ['self']},
1807
+ visibleDataSets: [
1808
+ {name: 'main', url: `${locusUrl}/datasets/main`},
1809
+ {name: 'unjoined', url: `${locusUrl}/datasets/unjoined`},
1810
+ ],
1811
+ };
1812
+
1813
+ const parser = createHashTreeParser(sharedInitialLocus, sharedMetadata);
1814
+
1815
+ // both datasets have their own hash tree, sharing the locus element
1816
+ assert.exists(parser.dataSets.main.hashTree);
1817
+ assert.exists(parser.dataSets.unjoined.hashTree);
1818
+
1819
+ // start the sync timer with a normal "main" message (mismatched root hash)
1820
+ const message = {
1821
+ dataSets: [{...createDataSet('main', 16, 1100), root: 'a'.repeat(32)}],
1822
+ visibleDataSetsUrl,
1823
+ locusUrl,
1824
+ locusStateElements: [
1825
+ {
1826
+ htMeta: {
1827
+ elementId: {type: 'locus' as const, id: 0, version: 201},
1828
+ dataSetNames: ['main'],
1829
+ },
1830
+ data: {info: {id: 'initial-update'}},
1831
+ },
1832
+ ],
1833
+ };
1834
+ parser.handleMessage(message, 'initial message');
1835
+ assert.calledOnce(callback);
1836
+ callback.resetHistory();
1837
+
1838
+ const mainDataSetUrl = parser.dataSets.main.url;
1839
+
1840
+ mockGetHashesFromLocusResponse(
1841
+ mainDataSetUrl,
1842
+ new Array(16).fill('0'.repeat(32)),
1843
+ createDataSet('main', 16, 1101)
1844
+ );
1845
+
1846
+ // The sync response for "main" also carries the "unjoined" dataset, the shared locus
1847
+ // element tagged with both datasets, and an "unjoined"-only element - all of which must
1848
+ // be filtered out so that only the requested "main" data is processed.
1849
+ const mainSyncDataSet = createDataSet('main', 16, 1101);
1850
+ mainSyncDataSet.root = parser.dataSets.main.hashTree.getRootHash();
1851
+ mockSendSyncRequestResponse(mainDataSetUrl, {
1852
+ dataSets: [mainSyncDataSet, createDataSet('unjoined', 16, 1101)],
1853
+ visibleDataSetsUrl,
1854
+ locusUrl,
1855
+ locusStateElements: [
1856
+ {
1857
+ htMeta: {
1858
+ elementId: {type: 'locus' as const, id: 0, version: 202},
1859
+ dataSetNames: ['main', 'unjoined'],
1860
+ },
1861
+ data: {info: {id: 'synced-shared-locus'}},
1862
+ },
1863
+ {
1864
+ htMeta: {
1865
+ elementId: {type: 'participant' as const, id: 99, version: 500},
1866
+ dataSetNames: ['unjoined'],
1867
+ },
1868
+ data: {person: {name: 'unjoined-only'}},
1869
+ },
1870
+ ],
1871
+ });
1872
+
1873
+ await clock.tickAsync(1000);
1874
+
1875
+ // the "unjoined" dataset info must NOT be updated from a "main" sync response
1876
+ expect(parser.dataSets.unjoined.version).to.equal(1000);
1877
+
1878
+ // the shared locus element is reported exactly once (not once per dataset), and the
1879
+ // "unjoined"-only element is not reported at all
1880
+ assert.calledOnceWithExactly(callback, {
1881
+ updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
1882
+ updatedObjects: [
1883
+ {
1884
+ htMeta: {
1885
+ elementId: {type: 'locus', id: 0, version: 202},
1886
+ dataSetNames: ['main', 'unjoined'],
1887
+ },
1888
+ data: {info: {id: 'synced-shared-locus'}},
1889
+ },
1890
+ ],
1891
+ });
1892
+
1893
+ // the filtered-out dataset and element are logged
1894
+ assert.calledWith(
1895
+ loggerInfoStub,
1896
+ sinon.match(
1897
+ 'keeping only dataset "main", filtering out datasets: [unjoined:1101], elements: [participant:99:500]'
1898
+ )
1899
+ );
1900
+ });
1901
+
1902
+ describe('emits MEETING_ENDED when 409/2403004 is returned', () => {
1903
+ it('when /hashtree returns 409', async () => {
1594
1904
  const parser = createHashTreeParser();
1595
1905
 
1596
- // Send a message to trigger sync algorithm
1597
1906
  const message = {
1598
1907
  dataSets: [createDataSet('main', 16, 1100)],
1599
1908
  visibleDataSetsUrl,
@@ -1618,12 +1927,9 @@ describe('HashTreeParser', () => {
1618
1927
 
1619
1928
  const mainDataSetUrl = parser.dataSets.main.url;
1620
1929
 
1621
- // Mock getHashesFromLocus to reject with the sentinel error
1622
- const error: any = new Error(`Request failed with status ${statusCode}`);
1623
- error.statusCode = statusCode;
1624
- if (statusCode === 409) {
1625
- error.body = {errorCode: 2403004};
1626
- }
1930
+ const error: any = new Error('Request failed with status 409');
1931
+ error.statusCode = 409;
1932
+ error.body = {errorCode: 2403004};
1627
1933
  webexRequest
1628
1934
  .withArgs(
1629
1935
  sinon.match({
@@ -1633,25 +1939,22 @@ describe('HashTreeParser', () => {
1633
1939
  )
1634
1940
  .rejects(error);
1635
1941
 
1636
- // Trigger sync by advancing time
1637
1942
  await clock.tickAsync(1000);
1638
1943
 
1639
- // Verify callback was called with MEETING_ENDED
1640
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.MEETING_ENDED, {
1641
- updatedObjects: undefined,
1642
- });
1944
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.MEETING_ENDED});
1643
1945
 
1644
- // Verify all timers are stopped
1645
1946
  Object.values(parser.dataSets).forEach((ds: any) => {
1646
1947
  assert.isUndefined(ds.timer);
1647
1948
  assert.isUndefined(ds.heartbeatWatchdogTimer);
1648
1949
  });
1950
+
1951
+ // Verify no sync failure metric was sent for end-meeting sentinel
1952
+ assert.notCalled(metricsStub);
1649
1953
  });
1650
1954
 
1651
- it(`when /sync returns ${statusCode}`, async () => {
1955
+ it('when /sync returns 409', async () => {
1652
1956
  const parser = createHashTreeParser();
1653
1957
 
1654
- // Send a message to trigger sync algorithm
1655
1958
  const message = {
1656
1959
  dataSets: [createDataSet('main', 16, 1100)],
1657
1960
  visibleDataSetsUrl,
@@ -1676,19 +1979,15 @@ describe('HashTreeParser', () => {
1676
1979
 
1677
1980
  const mainDataSetUrl = parser.dataSets.main.url;
1678
1981
 
1679
- // Mock getHashesFromLocus to succeed
1680
1982
  mockGetHashesFromLocusResponse(
1681
1983
  mainDataSetUrl,
1682
1984
  new Array(16).fill('00000000000000000000000000000000'),
1683
1985
  createDataSet('main', 16, 1101)
1684
1986
  );
1685
1987
 
1686
- // Mock sendSyncRequestToLocus to reject with the sentinel error
1687
- const error: any = new Error(`Request failed with status ${statusCode}`);
1688
- error.statusCode = statusCode;
1689
- if (statusCode === 409) {
1690
- error.body = {errorCode: 2403004};
1691
- }
1988
+ const error: any = new Error('Request failed with status 409');
1989
+ error.statusCode = 409;
1990
+ error.body = {errorCode: 2403004};
1692
1991
  webexRequest
1693
1992
  .withArgs(
1694
1993
  sinon.match({
@@ -1698,80 +1997,189 @@ describe('HashTreeParser', () => {
1698
1997
  )
1699
1998
  .rejects(error);
1700
1999
 
1701
- // Trigger sync by advancing time
1702
2000
  await clock.tickAsync(1000);
1703
2001
 
1704
- // Verify callback was called with MEETING_ENDED
1705
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.MEETING_ENDED, {
1706
- updatedObjects: undefined,
1707
- });
2002
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.MEETING_ENDED});
1708
2003
 
1709
- // Verify all timers are stopped
1710
2004
  Object.values(parser.dataSets).forEach((ds: any) => {
1711
2005
  assert.isUndefined(ds.timer);
1712
2006
  assert.isUndefined(ds.heartbeatWatchdogTimer);
1713
2007
  });
1714
2008
  });
1715
- });
1716
2009
  });
1717
2010
 
1718
- it('requests only mismatched hashes during sync', async () => {
1719
- const parser = createHashTreeParser();
2011
+ describe('emits LOCUS_NOT_FOUND and stops parser when 404 is returned', () => {
2012
+ it('when /hashtree returns 404', async () => {
2013
+ const parser = createHashTreeParser();
1720
2014
 
1721
- // Create a message with updates to trigger sync algorithm
1722
- const message = {
1723
- dataSets: [createDataSet('main', 16, 1100)],
1724
- visibleDataSetsUrl,
1725
- locusUrl,
1726
- locusStateElements: [
1727
- {
1728
- htMeta: {
1729
- elementId: {
1730
- type: 'locus' as const,
1731
- id: 0,
1732
- version: 201,
1733
- },
1734
- dataSetNames: ['main'],
1735
- },
1736
- data: {info: {id: 'initial-update'}},
1737
- },
1738
- {
1739
- htMeta: {
1740
- elementId: {
1741
- type: 'participant' as const,
1742
- id: 3,
1743
- version: 301,
1744
- },
1745
- dataSetNames: ['main'],
1746
- },
1747
- data: {id: 'participant with id=3'},
1748
- },
1749
- {
1750
- htMeta: {
1751
- elementId: {
1752
- type: 'participant' as const,
1753
- id: 4,
1754
- version: 301,
2015
+ const message = {
2016
+ dataSets: [createDataSet('main', 16, 1100)],
2017
+ visibleDataSetsUrl,
2018
+ locusUrl,
2019
+ locusStateElements: [
2020
+ {
2021
+ htMeta: {
2022
+ elementId: {
2023
+ type: 'locus' as const,
2024
+ id: 0,
2025
+ version: 201,
2026
+ },
2027
+ dataSetNames: ['main'],
2028
+ },
2029
+ data: {info: {id: 'initial-update'}},
1755
2030
  },
1756
- dataSetNames: ['main'],
1757
- },
1758
- data: {id: 'participant with id=4'},
1759
- },
1760
- ],
1761
- };
1762
-
1763
- parser.handleMessage(message, 'initial message');
2031
+ ],
2032
+ };
1764
2033
 
1765
- callback.resetHistory();
2034
+ parser.handleMessage(message, 'initial message');
2035
+ callback.resetHistory();
1766
2036
 
1767
- // Setup the hash tree to have specific hashes for each leaf
1768
- // We'll make leaf 0 and leaf 4 have mismatched hashes
1769
- const hashTree = parser.dataSets.main.hashTree;
2037
+ const mainDataSetUrl = parser.dataSets.main.url;
1770
2038
 
1771
- // Get the actual hashes for all leaves after the items were added
1772
- const actualHashes = new Array(16);
1773
- for (let i = 0; i < 16; i++) {
1774
- actualHashes[i] = hashTree.leafHashes[i];
2039
+ const error: any = new Error('Request failed with status 404');
2040
+ error.statusCode = 404;
2041
+ webexRequest
2042
+ .withArgs(
2043
+ sinon.match({
2044
+ method: 'GET',
2045
+ uri: `${mainDataSetUrl}/hashtree`,
2046
+ })
2047
+ )
2048
+ .rejects(error);
2049
+
2050
+ await clock.tickAsync(1000);
2051
+
2052
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.LOCUS_NOT_FOUND});
2053
+
2054
+ // Verify parser is stopped
2055
+ expect(parser.state).to.equal('stopped');
2056
+
2057
+ // Verify all timers are stopped
2058
+ Object.values(parser.dataSets).forEach((ds: any) => {
2059
+ assert.isUndefined(ds.timer);
2060
+ assert.isUndefined(ds.heartbeatWatchdogTimer);
2061
+ });
2062
+ });
2063
+
2064
+ it('when /sync returns 404', async () => {
2065
+ const parser = createHashTreeParser();
2066
+
2067
+ const message = {
2068
+ dataSets: [createDataSet('main', 16, 1100)],
2069
+ visibleDataSetsUrl,
2070
+ locusUrl,
2071
+ locusStateElements: [
2072
+ {
2073
+ htMeta: {
2074
+ elementId: {
2075
+ type: 'locus' as const,
2076
+ id: 0,
2077
+ version: 201,
2078
+ },
2079
+ dataSetNames: ['main'],
2080
+ },
2081
+ data: {info: {id: 'initial-update'}},
2082
+ },
2083
+ ],
2084
+ };
2085
+
2086
+ parser.handleMessage(message, 'initial message');
2087
+ callback.resetHistory();
2088
+
2089
+ const mainDataSetUrl = parser.dataSets.main.url;
2090
+
2091
+ mockGetHashesFromLocusResponse(
2092
+ mainDataSetUrl,
2093
+ new Array(16).fill('00000000000000000000000000000000'),
2094
+ createDataSet('main', 16, 1101)
2095
+ );
2096
+
2097
+ const error: any = new Error('Request failed with status 404');
2098
+ error.statusCode = 404;
2099
+ webexRequest
2100
+ .withArgs(
2101
+ sinon.match({
2102
+ method: 'POST',
2103
+ uri: `${mainDataSetUrl}/sync`,
2104
+ })
2105
+ )
2106
+ .rejects(error);
2107
+
2108
+ await clock.tickAsync(1000);
2109
+
2110
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.LOCUS_NOT_FOUND});
2111
+
2112
+ // Verify parser is stopped
2113
+ expect(parser.state).to.equal('stopped');
2114
+
2115
+ // Verify all timers are stopped
2116
+ Object.values(parser.dataSets).forEach((ds: any) => {
2117
+ assert.isUndefined(ds.timer);
2118
+ assert.isUndefined(ds.heartbeatWatchdogTimer);
2119
+ });
2120
+
2121
+ // Verify no sync failure metric was sent for end-meeting sentinel
2122
+ assert.notCalled(metricsStub);
2123
+ });
2124
+ });
2125
+
2126
+ it('requests only mismatched hashes during sync', async () => {
2127
+ const parser = createHashTreeParser();
2128
+
2129
+ // Create a message with updates to trigger sync algorithm
2130
+ const message = {
2131
+ dataSets: [createDataSet('main', 16, 1100)],
2132
+ visibleDataSetsUrl,
2133
+ locusUrl,
2134
+ locusStateElements: [
2135
+ {
2136
+ htMeta: {
2137
+ elementId: {
2138
+ type: 'locus' as const,
2139
+ id: 0,
2140
+ version: 201,
2141
+ },
2142
+ dataSetNames: ['main'],
2143
+ },
2144
+ data: {info: {id: 'initial-update'}},
2145
+ },
2146
+ {
2147
+ htMeta: {
2148
+ elementId: {
2149
+ type: 'participant' as const,
2150
+ id: 3,
2151
+ version: 301,
2152
+ },
2153
+ dataSetNames: ['main'],
2154
+ },
2155
+ data: {id: 'participant with id=3'},
2156
+ },
2157
+ {
2158
+ htMeta: {
2159
+ elementId: {
2160
+ type: 'participant' as const,
2161
+ id: 4,
2162
+ version: 301,
2163
+ },
2164
+ dataSetNames: ['main'],
2165
+ },
2166
+ data: {id: 'participant with id=4'},
2167
+ },
2168
+ ],
2169
+ };
2170
+
2171
+ parser.handleMessage(message, 'initial message');
2172
+
2173
+ callback.resetHistory();
2174
+
2175
+ // Setup the hash tree to have specific hashes for each leaf
2176
+ // We'll make leaf 0 and leaf 4 have mismatched hashes
2177
+ const hashTree = parser.dataSets.main.hashTree;
2178
+
2179
+ // Get the actual hashes for all leaves after the items were added
2180
+ const actualHashes = new Array(16);
2181
+ for (let i = 0; i < 16; i++) {
2182
+ actualHashes[i] = hashTree.leafHashes[i];
1775
2183
  }
1776
2184
 
1777
2185
  // Mock getHashesFromLocus to return hashes where most match but 0 and 4 don't
@@ -1883,96 +2291,317 @@ describe('HashTreeParser', () => {
1883
2291
  },
1884
2292
  });
1885
2293
  });
1886
- });
1887
2294
 
1888
- describe('handles visible data sets changes correctly', () => {
1889
- it('handles addition of visible data set (one that does not require async initialization)', async () => {
1890
- // Create a parser with visible datasets
2295
+ it('restarts the sync timer when sync response is empty so that a future sync can be triggered', async () => {
1891
2296
  const parser = createHashTreeParser();
1892
2297
 
1893
- // Stub updateItems on self hash tree to return true
1894
- sinon.stub(parser.dataSets.self.hashTree, 'updateItems').returns([true]);
1895
-
1896
- // Send a message with Metadata object that has a new visibleDataSets list
1897
- const message = {
1898
- dataSets: [createDataSet('self', 1, 2100), createDataSet('attendees', 8, 4000)],
1899
- visibleDataSetsUrl,
1900
- locusUrl,
1901
- locusStateElements: [
2298
+ // Send a heartbeat with a mismatched root hash to trigger runSyncAlgorithm
2299
+ const heartbeatMessage = {
2300
+ dataSets: [
1902
2301
  {
1903
- htMeta: {
1904
- elementId: {
1905
- type: 'metadata' as const,
1906
- id: 5,
1907
- version: 51,
1908
- },
1909
- dataSetNames: ['self'],
1910
- },
1911
- data: {
1912
- visibleDataSets: [
1913
- {
1914
- name: 'main',
1915
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/main',
1916
- },
1917
- {
1918
- name: 'self',
1919
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self',
1920
- },
1921
- {
1922
- name: 'atd-unmuted',
1923
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted',
1924
- },
1925
- {
1926
- name: 'attendees',
1927
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/attendees',
1928
- },
1929
- ], // added 'attendees'
1930
- },
2302
+ ...createDataSet('main', 16, 1100),
2303
+ root: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1', // different from ours
1931
2304
  },
1932
2305
  ],
2306
+ visibleDataSetsUrl,
2307
+ locusUrl,
1933
2308
  };
1934
2309
 
1935
- parser.handleMessage(message, 'add visible dataset');
2310
+ parser.handleMessage(heartbeatMessage, 'heartbeat with mismatch');
1936
2311
 
1937
- // Verify that 'attendees' was added to visibleDataSets
1938
- expect(parser.visibleDataSets.some((vds) => vds.name === 'attendees')).to.be.true;
2312
+ // The sync timer should be set
2313
+ expect(parser.dataSets.main.timer).to.not.be.undefined;
1939
2314
 
1940
- // Verify that a hash tree was created for 'attendees'
1941
- assert.exists(parser.dataSets.attendees.hashTree);
1942
- assert.equal(parser.dataSets.attendees.hashTree.numLeaves, 8);
2315
+ // Mock responses for the first sync - return null (204/empty body)
2316
+ const mainDataSetUrl = parser.dataSets.main.url;
2317
+ mockGetHashesFromLocusResponse(
2318
+ mainDataSetUrl,
2319
+ new Array(16).fill('00000000000000000000000000000000'),
2320
+ {
2321
+ ...createDataSet('main', 16, 1101),
2322
+ root: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', // still mismatched
2323
+ }
2324
+ );
2325
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
1943
2326
 
1944
- // Verify callback was called with the metadata update (appears twice - processed once for visible dataset changes, once in main loop)
1945
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
1946
- updatedObjects: [
2327
+ // Advance time to fire the sync timer (idleMs=1000 + backoff=0)
2328
+ await clock.tickAsync(1000);
2329
+
2330
+ // Verify sync was triggered
2331
+ assert.calledWith(
2332
+ webexRequest,
2333
+ sinon.match({
2334
+ method: 'POST',
2335
+ uri: `${mainDataSetUrl}/sync`,
2336
+ })
2337
+ );
2338
+
2339
+ // After empty response, runSyncAlgorithm should have been called,
2340
+ // setting a new sync timer as a safety net
2341
+ expect(parser.dataSets.main.timer).to.not.be.undefined;
2342
+
2343
+ // Reset and set up mocks for the second sync
2344
+ webexRequest.resetHistory();
2345
+ mockGetHashesFromLocusResponse(
2346
+ mainDataSetUrl,
2347
+ new Array(16).fill('00000000000000000000000000000000'),
2348
+ {
2349
+ ...createDataSet('main', 16, 1102),
2350
+ root: 'cccccccccccccccccccccccccccccccc', // still mismatched
2351
+ }
2352
+ );
2353
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
2354
+
2355
+ // Advance time again to fire the second sync timer
2356
+ await clock.tickAsync(1000);
2357
+
2358
+ // Verify a second sync was triggered
2359
+ assert.calledWith(
2360
+ webexRequest,
2361
+ sinon.match({
2362
+ method: 'POST',
2363
+ uri: `${mainDataSetUrl}/sync`,
2364
+ })
2365
+ );
2366
+ });
2367
+
2368
+ it('updates dataSet.leafCount when hash tree is resized during sync so that the sync request has the correct leafCount', async () => {
2369
+ const parser = createHashTreeParser();
2370
+
2371
+ // Send a heartbeat with a mismatched root hash to trigger runSyncAlgorithm
2372
+ const heartbeatMessage = {
2373
+ dataSets: [
1947
2374
  {
1948
- htMeta: {
1949
- elementId: {type: 'metadata', id: 5, version: 51},
1950
- dataSetNames: ['self'],
1951
- },
1952
- data: {
1953
- visibleDataSets: [
1954
- {
1955
- name: 'main',
1956
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/main',
1957
- },
1958
- {
1959
- name: 'self',
1960
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self',
1961
- },
1962
- {
1963
- name: 'atd-unmuted',
1964
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted',
1965
- },
1966
- {
1967
- name: 'attendees',
1968
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/attendees',
1969
- },
1970
- ],
1971
- },
2375
+ ...createDataSet('main', 16, 1100),
2376
+ root: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1', // different from ours
1972
2377
  },
1973
- {
1974
- htMeta: {
1975
- elementId: {type: 'metadata', id: 5, version: 51},
2378
+ ],
2379
+ visibleDataSetsUrl,
2380
+ locusUrl,
2381
+ };
2382
+
2383
+ parser.handleMessage(heartbeatMessage, 'heartbeat with mismatch');
2384
+
2385
+ // The sync timer should be set
2386
+ expect(parser.dataSets.main.timer).to.not.be.undefined;
2387
+
2388
+ const mainDataSetUrl = parser.dataSets.main.url;
2389
+ const newLeafCount = 32;
2390
+
2391
+ // Mock getHashesFromLocus response with a DIFFERENT leafCount (32 instead of 16)
2392
+ mockGetHashesFromLocusResponse(
2393
+ mainDataSetUrl,
2394
+ new Array(newLeafCount).fill('00000000000000000000000000000000'),
2395
+ createDataSet('main', newLeafCount, 1101)
2396
+ );
2397
+
2398
+ // Mock the sync request - use matching root hash
2399
+ const syncResponseDataSet = createDataSet('main', newLeafCount, 1102);
2400
+ syncResponseDataSet.root = parser.dataSets.main.hashTree.getRootHash();
2401
+ mockSendSyncRequestResponse(mainDataSetUrl, {
2402
+ dataSets: [syncResponseDataSet],
2403
+ visibleDataSetsUrl,
2404
+ locusUrl,
2405
+ locusStateElements: [],
2406
+ });
2407
+
2408
+ // Advance time to fire the sync timer (idleMs=1000 + backoff=0)
2409
+ await clock.tickAsync(1000);
2410
+
2411
+ // Verify the sync request was sent with the NEW leafCount (32), not the old one (16)
2412
+ assert.calledWith(
2413
+ webexRequest,
2414
+ sinon.match({
2415
+ method: 'POST',
2416
+ uri: `${mainDataSetUrl}/sync`,
2417
+ body: sinon.match({
2418
+ leafCount: newLeafCount,
2419
+ }),
2420
+ })
2421
+ );
2422
+ });
2423
+
2424
+ it('sends HASH_TREE_SYNC_FAILURE metric when GET /hashtree request fails', async () => {
2425
+ const parser = createHashTreeParser();
2426
+
2427
+ // Send a heartbeat with a mismatched root hash to trigger runSyncAlgorithm
2428
+ const heartbeatMessage = {
2429
+ dataSets: [
2430
+ {
2431
+ ...createDataSet('main', 16, 1100),
2432
+ root: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1',
2433
+ },
2434
+ ],
2435
+ visibleDataSetsUrl,
2436
+ locusUrl,
2437
+ };
2438
+
2439
+ parser.handleMessage(heartbeatMessage, 'heartbeat with mismatch');
2440
+
2441
+ const mainDataSetUrl = parser.dataSets.main.url;
2442
+ const hashTreeError = new Error('server error') as any;
2443
+ hashTreeError.statusCode = 500;
2444
+
2445
+ webexRequest
2446
+ .withArgs(
2447
+ sinon.match({
2448
+ method: 'GET',
2449
+ uri: `${mainDataSetUrl}/hashtree`,
2450
+ })
2451
+ )
2452
+ .rejects(hashTreeError);
2453
+
2454
+ await clock.tickAsync(1000);
2455
+
2456
+ assert.calledOnceWithExactly(metricsStub, BEHAVIORAL_METRICS.HASH_TREE_SYNC_FAILURE, {
2457
+ debugId: 'test',
2458
+ dataSetName: 'main',
2459
+ request: 'GET /hashtree',
2460
+ statusCode: 500,
2461
+ reason: 'server error',
2462
+ });
2463
+ });
2464
+
2465
+ it('sends HASH_TREE_SYNC_FAILURE metric when POST /sync request fails', async () => {
2466
+ const parser = createHashTreeParser();
2467
+
2468
+ // Send a heartbeat with a mismatched root hash to trigger runSyncAlgorithm
2469
+ const heartbeatMessage = {
2470
+ dataSets: [
2471
+ {
2472
+ ...createDataSet('main', 16, 1100),
2473
+ root: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1',
2474
+ },
2475
+ ],
2476
+ visibleDataSetsUrl,
2477
+ locusUrl,
2478
+ };
2479
+
2480
+ parser.handleMessage(heartbeatMessage, 'heartbeat with mismatch');
2481
+
2482
+ const mainDataSetUrl = parser.dataSets.main.url;
2483
+
2484
+ // Mock getHashesFromLocus to succeed
2485
+ mockGetHashesFromLocusResponse(
2486
+ mainDataSetUrl,
2487
+ new Array(16).fill('00000000000000000000000000000000'),
2488
+ createDataSet('main', 16, 1101)
2489
+ );
2490
+
2491
+ // Mock sendSyncRequestToLocus to fail
2492
+ const syncError = new Error('sync failed') as any;
2493
+ syncError.statusCode = 500;
2494
+
2495
+ webexRequest
2496
+ .withArgs(
2497
+ sinon.match({
2498
+ method: 'POST',
2499
+ uri: `${mainDataSetUrl}/sync`,
2500
+ })
2501
+ )
2502
+ .rejects(syncError);
2503
+
2504
+ await clock.tickAsync(1000);
2505
+
2506
+ assert.calledOnceWithExactly(metricsStub, BEHAVIORAL_METRICS.HASH_TREE_SYNC_FAILURE, {
2507
+ debugId: 'test',
2508
+ dataSetName: 'main',
2509
+ request: 'POST /sync',
2510
+ statusCode: 500,
2511
+ reason: 'sync failed',
2512
+ });
2513
+ });
2514
+
2515
+ });
2516
+
2517
+ describe('handles visible data sets changes correctly', () => {
2518
+ it('handles addition of visible data set (one that does not require async initialization)', async () => {
2519
+ // Create a parser with visible datasets
2520
+ const parser = createHashTreeParser();
2521
+
2522
+ // Stub updateItems on self hash tree to return true
2523
+ sinon.stub(parser.dataSets.self.hashTree, 'updateItems').returns([true]);
2524
+
2525
+ // Send a message with Metadata object that has a new visibleDataSets list
2526
+ const message = {
2527
+ dataSets: [createDataSet('self', 1, 2100), createDataSet('attendees', 8, 4000)],
2528
+ visibleDataSetsUrl,
2529
+ locusUrl,
2530
+ locusStateElements: [
2531
+ {
2532
+ htMeta: {
2533
+ elementId: {
2534
+ type: 'metadata' as const,
2535
+ id: 5,
2536
+ version: 51,
2537
+ },
2538
+ dataSetNames: ['self'],
2539
+ },
2540
+ data: {
2541
+ visibleDataSets: [
2542
+ {
2543
+ name: 'main',
2544
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/main',
2545
+ },
2546
+ {
2547
+ name: 'self',
2548
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self',
2549
+ },
2550
+ {
2551
+ name: 'atd-unmuted',
2552
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted',
2553
+ },
2554
+ {
2555
+ name: 'attendees',
2556
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/attendees',
2557
+ },
2558
+ ], // added 'attendees'
2559
+ },
2560
+ },
2561
+ ],
2562
+ };
2563
+
2564
+ parser.handleMessage(message, 'add visible dataset');
2565
+
2566
+ // Verify that 'attendees' was added to visibleDataSets
2567
+ expect(parser.visibleDataSets.some((vds) => vds.name === 'attendees')).to.be.true;
2568
+
2569
+ // Verify that a hash tree was created for 'attendees'
2570
+ assert.exists(parser.dataSets.attendees.hashTree);
2571
+ assert.equal(parser.dataSets.attendees.hashTree.numLeaves, 8);
2572
+
2573
+ // Verify callback was called with the metadata update (appears twice - processed once for visible dataset changes, once in main loop)
2574
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
2575
+ updatedObjects: [
2576
+ {
2577
+ htMeta: {
2578
+ elementId: {type: 'metadata', id: 5, version: 51},
2579
+ dataSetNames: ['self'],
2580
+ },
2581
+ data: {
2582
+ visibleDataSets: [
2583
+ {
2584
+ name: 'main',
2585
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/main',
2586
+ },
2587
+ {
2588
+ name: 'self',
2589
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self',
2590
+ },
2591
+ {
2592
+ name: 'atd-unmuted',
2593
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted',
2594
+ },
2595
+ {
2596
+ name: 'attendees',
2597
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/attendees',
2598
+ },
2599
+ ],
2600
+ },
2601
+ },
2602
+ {
2603
+ htMeta: {
2604
+ elementId: {type: 'metadata', id: 5, version: 51},
1976
2605
  dataSetNames: ['self'],
1977
2606
  },
1978
2607
  data: {
@@ -2062,7 +2691,99 @@ describe('HashTreeParser', () => {
2062
2691
  await checkAsyncDatasetInitialization(parser, newDataSet);
2063
2692
  });
2064
2693
 
2065
- it('emits MEETING_ENDED if async init of a new visible dataset fails with 404', async () => {
2694
+ it('initializes new visible data sets in priority order', async () => {
2695
+ // Create a parser that only has "self" as visible (no "main")
2696
+ const initialLocusWithoutMain = {
2697
+ dataSets: [createDataSet('self', 1, 2000)],
2698
+ locus: {
2699
+ ...exampleInitialLocus.locus,
2700
+ },
2701
+ };
2702
+ const metadataWithoutMain = {
2703
+ ...exampleMetadata,
2704
+ visibleDataSets: [
2705
+ {
2706
+ name: 'self',
2707
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self',
2708
+ },
2709
+ ],
2710
+ };
2711
+ const parser = createHashTreeParser(initialLocusWithoutMain, metadataWithoutMain);
2712
+
2713
+ // Verify "main" is not visible initially
2714
+ expect(parser.visibleDataSets.some((vds) => vds.name === 'main')).to.be.false;
2715
+
2716
+ // Stub updateItems on self hash tree to return true
2717
+ sinon.stub(parser.dataSets.self.hashTree, 'updateItems').returns([true]);
2718
+
2719
+ // Send a message that adds "main" and "atd-active" as new visible datasets.
2720
+ // Neither has info in dataSets, so both require async initialization.
2721
+ const newMainDataSet = createDataSet('main', 16, 6000);
2722
+ const newAtdActiveDataSet = createDataSet('atd-active', 4, 7000);
2723
+
2724
+ const message = {
2725
+ dataSets: [createDataSet('self', 1, 2100)],
2726
+ visibleDataSetsUrl,
2727
+ locusUrl,
2728
+ locusStateElements: [
2729
+ {
2730
+ htMeta: {
2731
+ elementId: {
2732
+ type: 'metadata' as const,
2733
+ id: 5,
2734
+ version: 51,
2735
+ },
2736
+ dataSetNames: ['self'],
2737
+ },
2738
+ data: {
2739
+ visibleDataSets: [
2740
+ {
2741
+ name: 'self',
2742
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self',
2743
+ },
2744
+ // listed in non-priority order: atd-active before main
2745
+ {name: 'atd-active', url: newAtdActiveDataSet.url},
2746
+ {name: 'main', url: newMainDataSet.url},
2747
+ ],
2748
+ },
2749
+ },
2750
+ ],
2751
+ };
2752
+
2753
+ // Mock getAllVisibleDataSetsFromLocus to return both new datasets (in non-priority order)
2754
+ mockGetAllDataSetsMetadata(webexRequest, visibleDataSetsUrl, [
2755
+ newAtdActiveDataSet,
2756
+ newMainDataSet,
2757
+ ]);
2758
+ mockSyncRequest(webexRequest, newMainDataSet.url);
2759
+ mockSyncRequest(webexRequest, newAtdActiveDataSet.url);
2760
+
2761
+ parser.handleMessage(message, 'add main and atd-active datasets');
2762
+
2763
+ // Wait for the async initialization (queueMicrotask) to complete
2764
+ await clock.tickAsync(0);
2765
+
2766
+ // Verify both datasets are initialized
2767
+ expect(parser.dataSets.main?.hashTree).to.exist;
2768
+ expect(parser.dataSets['atd-active']?.hashTree).to.exist;
2769
+
2770
+ // Verify sync requests were sent in priority order: "main" before "atd-active",
2771
+ // even though atd-active was listed first in both the message and the Locus response
2772
+ const syncCalls = webexRequest
2773
+ .getCalls()
2774
+ .filter(
2775
+ (call) =>
2776
+ call.args[0]?.method === 'POST' &&
2777
+ call.args[0]?.uri?.endsWith('/sync') &&
2778
+ (call.args[0]?.uri?.includes('/main/') || call.args[0]?.uri?.includes('/atd-active/'))
2779
+ );
2780
+
2781
+ expect(syncCalls).to.have.lengthOf(2);
2782
+ expect(syncCalls[0].args[0].uri).to.equal(`${newMainDataSet.url}/sync`);
2783
+ expect(syncCalls[1].args[0].uri).to.equal(`${newAtdActiveDataSet.url}/sync`);
2784
+ });
2785
+
2786
+ it('emits LOCUS_NOT_FOUND if async init of a new visible dataset fails with 404', async () => {
2066
2787
  const parser = createHashTreeParser();
2067
2788
 
2068
2789
  // Stub updateItems on self hash tree to return true
@@ -2127,10 +2848,8 @@ describe('HashTreeParser', () => {
2127
2848
  // Wait for the async initialization (queueMicrotask) to complete
2128
2849
  await clock.tickAsync(0);
2129
2850
 
2130
- // Verify callback was called with MEETING_ENDED
2131
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.MEETING_ENDED, {
2132
- updatedObjects: undefined,
2133
- });
2851
+ // Verify callback was called with LOCUS_NOT_FOUND (404 means locus URL is stale, not necessarily meeting ended)
2852
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.LOCUS_NOT_FOUND});
2134
2853
  });
2135
2854
 
2136
2855
  it('handles removal of visible data set', async () => {
@@ -2193,7 +2912,7 @@ describe('HashTreeParser', () => {
2193
2912
  assert.isUndefined(parser.dataSets['atd-unmuted'].timer);
2194
2913
 
2195
2914
  // Verify callback was called with the metadata update and the removed objects (metadata appears twice - processed once for dataset changes, once in main loop)
2196
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
2915
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
2197
2916
  updatedObjects: [
2198
2917
  {
2199
2918
  htMeta: {
@@ -2290,25 +3009,169 @@ describe('HashTreeParser', () => {
2290
3009
  // Verify callback was NOT called (no updates for non-visible datasets)
2291
3010
  assert.notCalled(callback);
2292
3011
  });
2293
- });
2294
-
2295
- describe('heartbeat watchdog', () => {
2296
- it('initiates sync immediately only for the specific data set whose heartbeat watchdog fires', async () => {
2297
- const parser = createHashTreeParser();
2298
- const heartbeatIntervalMs = 5000;
2299
3012
 
2300
- // Send initial heartbeat message for 'main' only
2301
- const heartbeatMessage = {
2302
- dataSets: [
2303
- {
2304
- ...createDataSet('main', 16, 1100),
2305
- root: parser.dataSets.main.hashTree.getRootHash(),
3013
+ it('reports update for object that moves from removed visible dataset to new visible dataset even if version is unchanged', async () => {
3014
+ // The purpose of this test is to verify that when an object
3015
+ // moves from one visible dataset to another without version change,
3016
+ // the parser still reports it as an update.
3017
+ // Locus has some additional signalling for this - the "view" property in htMeta.elementId.
3018
+ // When a view changes, the contents of the object may change even if version doesn't.
3019
+ // HashTreeParser doesn't use the "view" property, because it doesn't need to -
3020
+ // the same functionality is achieved thanks to the fact that a new visible data set means
3021
+ // a new hash tree is created, so HashTreeParser still detects the change as new
3022
+ // object is added to the new hash tree.
3023
+
3024
+ // Setup: parser with visible datasets "self" and "unjoined"
3025
+ const unjoinedDataSet = createDataSet('unjoined', 4, 3000);
3026
+ const selfDataSet = createDataSet('self', 1, 2000);
3027
+
3028
+ // start with Locus that has "info" in both "unjoined" and "main" datasets,
3029
+ // but only "unjoined" is visible.
3030
+ const initialLocus = {
3031
+ dataSets: [selfDataSet, unjoinedDataSet],
3032
+ locus: {
3033
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f',
3034
+ links: {resources: {visibleDataSets: {url: visibleDataSetsUrl}}},
3035
+ // info object in "unjoined" dataset with version 500
3036
+ info: {
3037
+ htMeta: {
3038
+ elementId: {
3039
+ type: 'info',
3040
+ id: 42,
3041
+ version: 500,
3042
+ view: ['unjoined'], // not used by our code, but here for completeness - that's what real Locus would send
3043
+ },
3044
+ dataSetNames: ['main', 'unjoined'],
3045
+ },
3046
+ someField: 'some-initial-value',
2306
3047
  },
2307
- ],
2308
- visibleDataSetsUrl,
2309
- locusUrl,
2310
- heartbeatIntervalMs,
2311
- };
3048
+ self: {
3049
+ htMeta: {
3050
+ elementId: {
3051
+ type: 'self',
3052
+ id: 4,
3053
+ version: 100,
3054
+ },
3055
+ dataSetNames: ['self'],
3056
+ },
3057
+ },
3058
+ },
3059
+ };
3060
+
3061
+ const metadata = {
3062
+ htMeta: {
3063
+ elementId: {
3064
+ type: 'metadata',
3065
+ id: 5,
3066
+ version: 50,
3067
+ },
3068
+ dataSetNames: ['self'],
3069
+ },
3070
+ visibleDataSets: [
3071
+ {name: 'self', url: selfDataSet.url},
3072
+ {name: 'unjoined', url: unjoinedDataSet.url},
3073
+ ],
3074
+ };
3075
+
3076
+ const parser = createHashTreeParser(initialLocus, metadata);
3077
+
3078
+ // Verify initial state: unjoined is visible and has the info object
3079
+ expect(parser.visibleDataSets.some((vds) => vds.name === 'unjoined')).to.be.true;
3080
+ assert.exists(parser.dataSets.unjoined.hashTree);
3081
+ assert.equal(parser.dataSets.unjoined.hashTree?.getItemVersion(42, 'info'), 500);
3082
+
3083
+ // Stub updateItems on self hash tree to return true for metadata update
3084
+ sinon.stub(parser.dataSets.self.hashTree, 'updateItems').returns([true]);
3085
+
3086
+ // Now send a message that:
3087
+ // 1. Changes visible datasets: removes "unjoined", adds "main"
3088
+ // 2. Contains the same info object (same id=42, same version=500) but we see the view from "main" dataset
3089
+ const mainDataSet = createDataSet('main', 16, 1000);
3090
+
3091
+ const message = {
3092
+ dataSets: [selfDataSet, mainDataSet],
3093
+ visibleDataSetsUrl,
3094
+ locusUrl,
3095
+ locusStateElements: [
3096
+ {
3097
+ htMeta: {
3098
+ elementId: {
3099
+ type: 'metadata' as const,
3100
+ id: 5,
3101
+ version: 51,
3102
+ },
3103
+ dataSetNames: ['self'],
3104
+ },
3105
+ data: {
3106
+ visibleDataSets: [
3107
+ {name: 'self', url: selfDataSet.url},
3108
+ {name: 'main', url: mainDataSet.url},
3109
+ // "unjoined" is no longer here
3110
+ ],
3111
+ },
3112
+ },
3113
+ {
3114
+ htMeta: {
3115
+ elementId: {
3116
+ type: 'info' as const,
3117
+ id: 42,
3118
+ version: 500, // same version as before
3119
+ view: ['main'], // now points to "main" instead of "unjoined"
3120
+ },
3121
+ dataSetNames: ['main', 'unjoined'], // still in both datasets, but only "main" is visible now
3122
+ },
3123
+ data: {someNewField: 'some-value'},
3124
+ },
3125
+ ],
3126
+ };
3127
+
3128
+ parser.handleMessage(message, 'visible dataset swap with same-version object');
3129
+
3130
+ // Verify "unjoined" is no longer visible and "main" is now visible
3131
+ expect(parser.visibleDataSets.some((vds) => vds.name === 'unjoined')).to.be.false;
3132
+ expect(parser.visibleDataSets.some((vds) => vds.name === 'main')).to.be.true;
3133
+
3134
+ // Verify the info object is now in the "main" hash tree
3135
+ assert.exists(parser.dataSets.main.hashTree);
3136
+ assert.equal(parser.dataSets.main.hashTree?.getItemVersion(42, 'info'), 500);
3137
+
3138
+ // The key assertion: callback should be called with the info object update even though
3139
+ // its version hasn't changed - because visible datasets changed (moved from unjoined to main)
3140
+ assert.calledOnce(callback);
3141
+ const callbackArgs = callback.firstCall.args[0];
3142
+ assert.equal(callbackArgs.updateType, LocusInfoUpdateType.OBJECTS_UPDATED);
3143
+
3144
+ // Should contain the info object update (with data)
3145
+ const infoUpdate = callbackArgs.updatedObjects.find(
3146
+ (obj) => obj.htMeta.elementId.type === 'info' && obj.htMeta.elementId.id === 42
3147
+ );
3148
+ assert.exists(infoUpdate);
3149
+ assert.deepEqual(infoUpdate.htMeta.elementId, {
3150
+ type: 'info',
3151
+ id: 42,
3152
+ version: 500,
3153
+ view: ['main'],
3154
+ });
3155
+ assert.deepEqual(infoUpdate.data, {someNewField: 'some-value'});
3156
+ });
3157
+ });
3158
+
3159
+ describe('heartbeat watchdog', () => {
3160
+ it('initiates sync immediately only for the specific data set whose heartbeat watchdog fires', async () => {
3161
+ const parser = createHashTreeParser();
3162
+ const heartbeatIntervalMs = 5000;
3163
+
3164
+ // Send initial heartbeat message for 'main' only
3165
+ const heartbeatMessage = {
3166
+ dataSets: [
3167
+ {
3168
+ ...createDataSet('main', 16, 1100),
3169
+ root: parser.dataSets.main.hashTree.getRootHash(),
3170
+ },
3171
+ ],
3172
+ visibleDataSetsUrl,
3173
+ locusUrl,
3174
+ };
2312
3175
 
2313
3176
  parser.handleMessage(heartbeatMessage, 'initial heartbeat');
2314
3177
 
@@ -2339,6 +3202,12 @@ describe('HashTreeParser', () => {
2339
3202
  })
2340
3203
  );
2341
3204
 
3205
+ // Verify behavioral metric was sent for the watchdog expiration
3206
+ assert.calledWith(metricsStub, BEHAVIORAL_METRICS.HASH_TREE_HEARTBEAT_WATCHDOG_EXPIRED, {
3207
+ debugId: 'test',
3208
+ dataSetName: 'main',
3209
+ });
3210
+
2342
3211
  // Verify no sync requests were sent for other datasets
2343
3212
  assert.neverCalledWith(
2344
3213
  webexRequest,
@@ -2356,6 +3225,106 @@ describe('HashTreeParser', () => {
2356
3225
  );
2357
3226
  });
2358
3227
 
3228
+ it('uses the watchdog random backoff when reporting sync metrics', async () => {
3229
+ const syncLatencyTracker = {
3230
+ saveLatency: sinon.stub(),
3231
+ saveTimestamp: sinon.stub(),
3232
+ getLocusSyncLatency: sinon.stub(),
3233
+ clearLocusSyncLatency: sinon.stub(),
3234
+ completeLocusSyncLatency: sinon.stub(),
3235
+ };
3236
+ const parser = createHashTreeParser(
3237
+ undefined,
3238
+ undefined,
3239
+ undefined,
3240
+ syncLatencyTracker
3241
+ );
3242
+ const heartbeatIntervalMs = 5000;
3243
+ const mainDataSetUrl = parser.dataSets.main.url;
3244
+
3245
+ mathRandomStub.onFirstCall().returns(0.1); // root-hash timer backoff = 10ms
3246
+ mathRandomStub.onSecondCall().returns(0.5); // watchdog backoff = 250ms
3247
+ mathRandomStub.returns(0);
3248
+
3249
+ parser.handleMessage(
3250
+ {
3251
+ dataSets: [
3252
+ {
3253
+ ...createDataSet('main', 16, 1100),
3254
+ root: parser.dataSets.main.hashTree.getRootHash(),
3255
+ },
3256
+ ],
3257
+ visibleDataSetsUrl,
3258
+ locusUrl,
3259
+ },
3260
+ 'initial heartbeat'
3261
+ );
3262
+
3263
+ mockGetHashesFromLocusResponse(
3264
+ mainDataSetUrl,
3265
+ new Array(16).fill('00000000000000000000000000000000'),
3266
+ createDataSet('main', 16, 1101)
3267
+ );
3268
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
3269
+
3270
+ await clock.tickAsync(heartbeatIntervalMs + 250);
3271
+
3272
+ assert.calledWithExactly(
3273
+ syncLatencyTracker.saveLatency,
3274
+ 'internal.client.locus.sync.random.backoff',
3275
+ 250,
3276
+ {
3277
+ meetingId: 'meeting-1',
3278
+ dataSetName: 'main',
3279
+ }
3280
+ );
3281
+ });
3282
+
3283
+ it('uses the root sync random backoff when root timer fires before watchdog', async () => {
3284
+ const syncLatencyTracker = {
3285
+ saveLatency: sinon.stub(),
3286
+ saveTimestamp: sinon.stub(),
3287
+ getLocusSyncLatency: sinon.stub(),
3288
+ clearLocusSyncLatency: sinon.stub(),
3289
+ completeLocusSyncLatency: sinon.stub(),
3290
+ };
3291
+ const parser = createHashTreeParser(
3292
+ undefined,
3293
+ undefined,
3294
+ undefined,
3295
+ syncLatencyTracker
3296
+ );
3297
+ const mainDataSetUrl = parser.dataSets.main.url;
3298
+
3299
+ mathRandomStub.onFirstCall().returns(0.1); // root-hash timer backoff = 10ms
3300
+ mathRandomStub.onSecondCall().returns(0.5); // watchdog backoff = 250ms
3301
+ mathRandomStub.returns(0);
3302
+
3303
+ parser.handleMessage(
3304
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
3305
+ 'root mismatch heartbeat'
3306
+ );
3307
+
3308
+ mockGetHashesFromLocusResponse(
3309
+ mainDataSetUrl,
3310
+ new Array(16).fill('00000000000000000000000000000000'),
3311
+ createDataSet('main', 16, 1101)
3312
+ );
3313
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
3314
+
3315
+ await clock.tickAsync(1010);
3316
+
3317
+ assert.calledWithExactly(
3318
+ syncLatencyTracker.saveLatency,
3319
+ 'internal.client.locus.sync.random.backoff',
3320
+ 10,
3321
+ {
3322
+ meetingId: 'meeting-1',
3323
+ dataSetName: 'main',
3324
+ }
3325
+ );
3326
+ });
3327
+
2359
3328
  it('calls POST sync directly for leafCount === 1 data sets', async () => {
2360
3329
  const parser = createHashTreeParser();
2361
3330
  const heartbeatIntervalMs = 5000;
@@ -2371,7 +3340,6 @@ describe('HashTreeParser', () => {
2371
3340
  ],
2372
3341
  visibleDataSetsUrl,
2373
3342
  locusUrl,
2374
- heartbeatIntervalMs,
2375
3343
  };
2376
3344
 
2377
3345
  parser.handleMessage(heartbeatMessage, 'self heartbeat');
@@ -2382,6 +3350,12 @@ describe('HashTreeParser', () => {
2382
3350
  // Advance time past watchdog delay
2383
3351
  await clock.tickAsync(heartbeatIntervalMs);
2384
3352
 
3353
+ // Verify behavioral metric was sent for the watchdog expiration
3354
+ assert.calledWith(metricsStub, BEHAVIORAL_METRICS.HASH_TREE_HEARTBEAT_WATCHDOG_EXPIRED, {
3355
+ debugId: 'test',
3356
+ dataSetName: 'self',
3357
+ });
3358
+
2385
3359
  // For leafCount === 1, performSync skips GET hashtree and goes straight to POST sync
2386
3360
  assert.neverCalledWith(
2387
3361
  webexRequest,
@@ -2401,7 +3375,6 @@ describe('HashTreeParser', () => {
2401
3375
 
2402
3376
  it('sets watchdog timers for each data set in the message', async () => {
2403
3377
  const parser = createHashTreeParser();
2404
- const heartbeatIntervalMs = 5000;
2405
3378
 
2406
3379
  // Send heartbeat with multiple datasets
2407
3380
  const heartbeatMessage = {
@@ -2418,7 +3391,6 @@ describe('HashTreeParser', () => {
2418
3391
  ],
2419
3392
  visibleDataSetsUrl,
2420
3393
  locusUrl,
2421
- heartbeatIntervalMs,
2422
3394
  };
2423
3395
 
2424
3396
  parser.handleMessage(heartbeatMessage, 'multi-dataset heartbeat');
@@ -2432,7 +3404,6 @@ describe('HashTreeParser', () => {
2432
3404
 
2433
3405
  it('resets the watchdog timer for a specific data set when a new heartbeat for it is received', async () => {
2434
3406
  const parser = createHashTreeParser();
2435
- const heartbeatIntervalMs = 5000;
2436
3407
 
2437
3408
  // Send first heartbeat for 'main'
2438
3409
  const heartbeat1 = {
@@ -2444,7 +3415,6 @@ describe('HashTreeParser', () => {
2444
3415
  ],
2445
3416
  visibleDataSetsUrl,
2446
3417
  locusUrl,
2447
- heartbeatIntervalMs,
2448
3418
  };
2449
3419
 
2450
3420
  parser.handleMessage(heartbeat1, 'first heartbeat');
@@ -2465,7 +3435,6 @@ describe('HashTreeParser', () => {
2465
3435
  ],
2466
3436
  visibleDataSetsUrl,
2467
3437
  locusUrl,
2468
- heartbeatIntervalMs,
2469
3438
  };
2470
3439
 
2471
3440
  parser.handleMessage(heartbeat2, 'second heartbeat');
@@ -2484,7 +3453,6 @@ describe('HashTreeParser', () => {
2484
3453
 
2485
3454
  it('resets the watchdog timer when a normal message (with locusStateElements) is received', async () => {
2486
3455
  const parser = createHashTreeParser();
2487
- const heartbeatIntervalMs = 5000;
2488
3456
 
2489
3457
  // Send initial heartbeat to start the watchdog for 'main'
2490
3458
  const heartbeat = {
@@ -2496,7 +3464,6 @@ describe('HashTreeParser', () => {
2496
3464
  ],
2497
3465
  visibleDataSetsUrl,
2498
3466
  locusUrl,
2499
- heartbeatIntervalMs,
2500
3467
  };
2501
3468
 
2502
3469
  parser.handleMessage(heartbeat, 'initial heartbeat');
@@ -2524,7 +3491,6 @@ describe('HashTreeParser', () => {
2524
3491
  data: {someData: 'value'},
2525
3492
  },
2526
3493
  ],
2527
- heartbeatIntervalMs,
2528
3494
  };
2529
3495
 
2530
3496
  parser.handleMessage(normalMessage, 'normal message');
@@ -2538,21 +3504,212 @@ describe('HashTreeParser', () => {
2538
3504
  const parser = createHashTreeParser();
2539
3505
 
2540
3506
  // Send a heartbeat message without heartbeatIntervalMs
2541
- const heartbeatMessage = createHeartbeatMessage(
2542
- 'main',
2543
- 16,
2544
- 1100,
2545
- parser.dataSets.main.hashTree.getRootHash()
2546
- );
3507
+ const heartbeatMessage = {
3508
+ dataSets: [
3509
+ {
3510
+ ...createDataSet('main', 16, 1100),
3511
+ root: parser.dataSets.main.hashTree.getRootHash(),
3512
+ heartbeatIntervalMs: undefined,
3513
+ },
3514
+ ],
3515
+ visibleDataSetsUrl,
3516
+ locusUrl,
3517
+ };
2547
3518
 
2548
3519
  parser.handleMessage(heartbeatMessage, 'heartbeat without interval');
2549
3520
 
2550
3521
  expect(parser.dataSets.main.heartbeatWatchdogTimer).to.be.undefined;
2551
3522
  });
2552
3523
 
3524
+ it('skips watchdog timers for LLM datasets when current meeting LLM is not expected', async () => {
3525
+ const parser = createHashTreeParser(
3526
+ undefined,
3527
+ undefined,
3528
+ undefined,
3529
+ undefined,
3530
+ 'meeting-1',
3531
+ undefined,
3532
+ () => false
3533
+ );
3534
+
3535
+ const heartbeatMessage = {
3536
+ dataSets: [
3537
+ {
3538
+ ...createDataSet('main', 16, 1100),
3539
+ root: parser.dataSets.main.hashTree.getRootHash(),
3540
+ },
3541
+ {
3542
+ ...createDataSet('self', 1, 2100),
3543
+ url: parser.dataSets.self.url,
3544
+ root: parser.dataSets.self.hashTree.getRootHash(),
3545
+ },
3546
+ {
3547
+ ...createDataSet('atd-unmuted', 16, 3100),
3548
+ url: parser.dataSets['atd-unmuted'].url,
3549
+ root: parser.dataSets['atd-unmuted'].hashTree.getRootHash(),
3550
+ },
3551
+ ],
3552
+ visibleDataSetsUrl,
3553
+ locusUrl,
3554
+ };
3555
+
3556
+ parser.handleMessage(heartbeatMessage, 'heartbeat with meeting-scoped llm not expected');
3557
+
3558
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.be.undefined;
3559
+ expect(parser.dataSets['atd-unmuted'].heartbeatWatchdogTimer).to.be.undefined;
3560
+ expect(parser.dataSets.self.heartbeatWatchdogTimer).to.not.be.undefined;
3561
+ });
3562
+
3563
+ it('arms skipped LLM watchdog timers when reevaluateLlmWatchdogs is called after LLM becomes expected', async () => {
3564
+ let llmExpected = false;
3565
+ const parser = createHashTreeParser(
3566
+ undefined,
3567
+ undefined,
3568
+ undefined,
3569
+ undefined,
3570
+ 'meeting-1',
3571
+ undefined,
3572
+ () => llmExpected
3573
+ );
3574
+
3575
+ const heartbeatMessage = {
3576
+ dataSets: [
3577
+ {
3578
+ ...createDataSet('main', 16, 1100),
3579
+ root: parser.dataSets.main.hashTree.getRootHash(),
3580
+ },
3581
+ {
3582
+ ...createDataSet('self', 1, 2100),
3583
+ url: parser.dataSets.self.url,
3584
+ root: parser.dataSets.self.hashTree.getRootHash(),
3585
+ },
3586
+ {
3587
+ ...createDataSet('atd-unmuted', 16, 3100),
3588
+ url: parser.dataSets['atd-unmuted'].url,
3589
+ root: parser.dataSets['atd-unmuted'].hashTree.getRootHash(),
3590
+ },
3591
+ ],
3592
+ visibleDataSetsUrl,
3593
+ locusUrl,
3594
+ };
3595
+
3596
+ // LLM data set messages arrive before LLM is expected, so their watchdogs are skipped
3597
+ parser.handleMessage(heartbeatMessage, 'heartbeat before llm expected');
3598
+
3599
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.be.undefined;
3600
+ expect(parser.dataSets['atd-unmuted'].heartbeatWatchdogTimer).to.be.undefined;
3601
+ const selfTimerBefore = parser.dataSets.self.heartbeatWatchdogTimer;
3602
+ expect(selfTimerBefore).to.not.be.undefined;
3603
+
3604
+ // LLM becomes expected and we re-evaluate the watchdogs
3605
+ llmExpected = true;
3606
+ parser.reevaluateLlmWatchdogs();
3607
+
3608
+ // the previously skipped LLM watchdogs are now armed
3609
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3610
+ expect(parser.dataSets['atd-unmuted'].heartbeatWatchdogTimer).to.not.be.undefined;
3611
+ // the self (non-LLM) watchdog timer is left untouched
3612
+ expect(parser.dataSets.self.heartbeatWatchdogTimer).to.equal(selfTimerBefore);
3613
+
3614
+ // the pending set is consumed, so a second call after clearing the timers is a no-op
3615
+ clearTimeout(parser.dataSets.main.heartbeatWatchdogTimer);
3616
+ clearTimeout(parser.dataSets['atd-unmuted'].heartbeatWatchdogTimer);
3617
+ parser.dataSets.main.heartbeatWatchdogTimer = undefined;
3618
+ parser.dataSets['atd-unmuted'].heartbeatWatchdogTimer = undefined;
3619
+
3620
+ parser.reevaluateLlmWatchdogs();
3621
+
3622
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.be.undefined;
3623
+ expect(parser.dataSets['atd-unmuted'].heartbeatWatchdogTimer).to.be.undefined;
3624
+ });
3625
+
3626
+ it('only arms watchdogs for LLM data sets that were actually received in a message', async () => {
3627
+ let llmExpected = false;
3628
+ const parser = createHashTreeParser(
3629
+ undefined,
3630
+ undefined,
3631
+ undefined,
3632
+ undefined,
3633
+ 'meeting-1',
3634
+ undefined,
3635
+ () => llmExpected
3636
+ );
3637
+
3638
+ // only 'main' is received in a message (atd-unmuted exists in this.dataSets with a hash
3639
+ // tree but is never received in any message)
3640
+ const heartbeatMessage = {
3641
+ dataSets: [
3642
+ {
3643
+ ...createDataSet('main', 16, 1100),
3644
+ root: parser.dataSets.main.hashTree.getRootHash(),
3645
+ },
3646
+ ],
3647
+ visibleDataSetsUrl,
3648
+ locusUrl,
3649
+ };
3650
+
3651
+ parser.handleMessage(heartbeatMessage, 'only main received before llm expected');
3652
+
3653
+ // sanity: atd-unmuted has a hash tree but was never received
3654
+ expect(parser.dataSets['atd-unmuted'].hashTree).to.not.be.undefined;
3655
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.be.undefined;
3656
+ expect(parser.dataSets['atd-unmuted'].heartbeatWatchdogTimer).to.be.undefined;
3657
+
3658
+ llmExpected = true;
3659
+ parser.reevaluateLlmWatchdogs();
3660
+
3661
+ // 'main' was received, so its watchdog is armed
3662
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3663
+ // 'atd-unmuted' was never received, so no watchdog is armed even though it has a hash tree
3664
+ expect(parser.dataSets['atd-unmuted'].heartbeatWatchdogTimer).to.be.undefined;
3665
+ });
3666
+
3667
+ it('does not re-arm or reset an already active LLM watchdog timer when reevaluateLlmWatchdogs is called', async () => {
3668
+ const parser = createHashTreeParser(
3669
+ undefined,
3670
+ undefined,
3671
+ undefined,
3672
+ undefined,
3673
+ 'meeting-1',
3674
+ undefined,
3675
+ () => true
3676
+ );
3677
+
3678
+ parser.handleMessage(
3679
+ createHeartbeatMessage('main', 16, 1100, parser.dataSets.main.hashTree.getRootHash()),
3680
+ 'heartbeat with llm expected'
3681
+ );
3682
+
3683
+ const mainTimerBefore = parser.dataSets.main.heartbeatWatchdogTimer;
3684
+ expect(mainTimerBefore).to.not.be.undefined;
3685
+
3686
+ parser.reevaluateLlmWatchdogs();
3687
+
3688
+ // existing active timer must not be cleared/reset (that would extend its deadline)
3689
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.equal(mainTimerBefore);
3690
+ });
3691
+
3692
+ it('does nothing when reevaluateLlmWatchdogs is called on a stopped parser', async () => {
3693
+ const parser = createHashTreeParser(
3694
+ undefined,
3695
+ undefined,
3696
+ undefined,
3697
+ undefined,
3698
+ 'meeting-1',
3699
+ undefined,
3700
+ () => true
3701
+ );
3702
+
3703
+ parser.stop();
3704
+
3705
+ parser.reevaluateLlmWatchdogs();
3706
+
3707
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.be.undefined;
3708
+ expect(parser.dataSets['atd-unmuted'].heartbeatWatchdogTimer).to.be.undefined;
3709
+ });
3710
+
2553
3711
  it('stops all watchdog timers when meeting ends via sentinel message', async () => {
2554
3712
  const parser = createHashTreeParser();
2555
- const heartbeatIntervalMs = 5000;
2556
3713
 
2557
3714
  // Send heartbeat for multiple datasets
2558
3715
  const heartbeat = {
@@ -2569,7 +3726,6 @@ describe('HashTreeParser', () => {
2569
3726
  ],
2570
3727
  visibleDataSetsUrl,
2571
3728
  locusUrl,
2572
- heartbeatIntervalMs,
2573
3729
  };
2574
3730
 
2575
3731
  parser.handleMessage(heartbeat, 'initial heartbeat');
@@ -2620,7 +3776,6 @@ describe('HashTreeParser', () => {
2620
3776
  };
2621
3777
 
2622
3778
  const parser = createHashTreeParser(initialLocus, metadata);
2623
- const heartbeatIntervalMs = 5000;
2624
3779
 
2625
3780
  // Set Math.random to return 1 so that backoff = 1^exponent * maxMs = maxMs
2626
3781
  mathRandomStub.returns(1);
@@ -2642,7 +3797,6 @@ describe('HashTreeParser', () => {
2642
3797
  ],
2643
3798
  visibleDataSetsUrl,
2644
3799
  locusUrl,
2645
- heartbeatIntervalMs,
2646
3800
  };
2647
3801
 
2648
3802
  parser.handleMessage(heartbeat, 'heartbeat');
@@ -2692,7 +3846,6 @@ describe('HashTreeParser', () => {
2692
3846
 
2693
3847
  it('does not set watchdog for data sets without a hash tree', async () => {
2694
3848
  const parser = createHashTreeParser();
2695
- const heartbeatIntervalMs = 5000;
2696
3849
 
2697
3850
  // 'atd-active' is in the initial locus but is not visible (no hash tree)
2698
3851
  // Send heartbeat mentioning a non-visible dataset
@@ -2706,7 +3859,6 @@ describe('HashTreeParser', () => {
2706
3859
  ],
2707
3860
  visibleDataSetsUrl,
2708
3861
  locusUrl,
2709
- heartbeatIntervalMs,
2710
3862
  };
2711
3863
 
2712
3864
  parser.handleMessage(heartbeatMessage, 'heartbeat with non-visible dataset');
@@ -2715,15 +3867,222 @@ describe('HashTreeParser', () => {
2715
3867
  expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
2716
3868
  expect(parser.dataSets['atd-active']?.heartbeatWatchdogTimer).to.be.undefined;
2717
3869
  });
2718
- });
2719
- });
2720
3870
 
2721
- describe('#callLocusInfoUpdateCallback filtering', () => {
2722
- // Helper to setup parser with initial objects and reset callback history
2723
- function setupParserWithObjects(locusStateElements: any[]) {
2724
- const parser = createHashTreeParser();
3871
+ it('does not set watchdog for a data set that has a hash tree but is not in visibleDataSets', async () => {
3872
+ const parser = createHashTreeParser();
2725
3873
 
2726
- if (locusStateElements.length > 0) {
3874
+ // simulate a dataset that still has a hash tree but is no longer visible
3875
+ parser.visibleDataSets = parser.visibleDataSets.filter((vds) => vds.name !== 'main');
3876
+
3877
+ const heartbeatMessage = {
3878
+ dataSets: [
3879
+ {
3880
+ ...createDataSet('main', 16, 1100),
3881
+ root: parser.dataSets.main.hashTree.getRootHash(),
3882
+ },
3883
+ ],
3884
+ visibleDataSetsUrl,
3885
+ locusUrl,
3886
+ };
3887
+
3888
+ parser.handleMessage(heartbeatMessage, 'heartbeat for non-visible dataset with hash tree');
3889
+
3890
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.be.undefined;
3891
+ });
3892
+
3893
+ it('restarts the watchdog timer after it fires so that future missed heartbeats still trigger syncs', async () => {
3894
+ const parser = createHashTreeParser();
3895
+ const heartbeatIntervalMs = 5000;
3896
+
3897
+ // Send initial heartbeat for 'main'
3898
+ const heartbeatMessage = {
3899
+ dataSets: [
3900
+ {
3901
+ ...createDataSet('main', 16, 1100),
3902
+ root: parser.dataSets.main.hashTree.getRootHash(),
3903
+ },
3904
+ ],
3905
+ visibleDataSetsUrl,
3906
+ locusUrl,
3907
+ };
3908
+
3909
+ parser.handleMessage(heartbeatMessage, 'initial heartbeat');
3910
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3911
+
3912
+ // Mock responses for performSync - return null (204/empty body)
3913
+ const mainDataSetUrl = parser.dataSets.main.url;
3914
+ mockGetHashesFromLocusResponse(
3915
+ mainDataSetUrl,
3916
+ new Array(16).fill('00000000000000000000000000000000'),
3917
+ createDataSet('main', 16, 1101)
3918
+ );
3919
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
3920
+
3921
+ // Advance time past heartbeatIntervalMs to fire the watchdog
3922
+ await clock.tickAsync(heartbeatIntervalMs);
3923
+
3924
+ // Verify sync was triggered
3925
+ assert.calledWith(
3926
+ webexRequest,
3927
+ sinon.match({
3928
+ method: 'GET',
3929
+ uri: `${mainDataSetUrl}/hashtree`,
3930
+ })
3931
+ );
3932
+
3933
+ // The watchdog timer should have been restarted after firing
3934
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3935
+
3936
+ // Reset call history and set up new mock responses for the second sync
3937
+ webexRequest.resetHistory();
3938
+ mockGetHashesFromLocusResponse(
3939
+ mainDataSetUrl,
3940
+ new Array(16).fill('00000000000000000000000000000000'),
3941
+ createDataSet('main', 16, 1102)
3942
+ );
3943
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
3944
+
3945
+ // Advance time again to fire the watchdog a second time
3946
+ await clock.tickAsync(heartbeatIntervalMs);
3947
+
3948
+ // Verify a second sync was triggered
3949
+ assert.calledWith(
3950
+ webexRequest,
3951
+ sinon.match({
3952
+ method: 'GET',
3953
+ uri: `${mainDataSetUrl}/hashtree`,
3954
+ })
3955
+ );
3956
+
3957
+ // And the watchdog should still be running
3958
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3959
+ });
3960
+
3961
+ it('uses dataset-level heartbeatIntervalMs over top-level value', async () => {
3962
+ const parser = createHashTreeParser();
3963
+ const datasetLevelInterval = 3000;
3964
+ const topLevelInterval = 8000;
3965
+
3966
+ // Send heartbeat with both top-level and dataset-level heartbeatIntervalMs
3967
+ const heartbeatMessage = {
3968
+ dataSets: [
3969
+ {
3970
+ ...createDataSet('main', 16, 1100),
3971
+ root: parser.dataSets.main.hashTree.getRootHash(),
3972
+ heartbeatIntervalMs: datasetLevelInterval,
3973
+ },
3974
+ ],
3975
+ visibleDataSetsUrl,
3976
+ locusUrl,
3977
+ heartbeatIntervalMs: topLevelInterval,
3978
+ };
3979
+
3980
+ parser.handleMessage(heartbeatMessage, 'heartbeat with both levels');
3981
+
3982
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3983
+
3984
+ // Mock sync responses
3985
+ const mainDataSetUrl = parser.dataSets.main.url;
3986
+ mockGetHashesFromLocusResponse(
3987
+ mainDataSetUrl,
3988
+ new Array(16).fill('00000000000000000000000000000000'),
3989
+ createDataSet('main', 16, 1101)
3990
+ );
3991
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
3992
+
3993
+ // Watchdog should NOT fire at the top-level interval (8000ms)
3994
+ // It should fire at the dataset-level interval (3000ms)
3995
+ await clock.tickAsync(datasetLevelInterval - 1);
3996
+ assert.notCalled(webexRequest);
3997
+
3998
+ await clock.tickAsync(1);
3999
+ // Now at datasetLevelInterval, watchdog should have fired
4000
+ assert.calledWith(
4001
+ webexRequest,
4002
+ sinon.match({
4003
+ method: 'GET',
4004
+ uri: `${mainDataSetUrl}/hashtree`,
4005
+ })
4006
+ );
4007
+ });
4008
+
4009
+ it('falls back to top-level heartbeatIntervalMs when dataset-level is missing', async () => {
4010
+ const parser = createHashTreeParser();
4011
+ const topLevelInterval = 7000;
4012
+
4013
+ // Send heartbeat with top-level heartbeatIntervalMs but no dataset-level
4014
+ const heartbeatMessage = {
4015
+ dataSets: [
4016
+ {
4017
+ ...createDataSet('main', 16, 1100),
4018
+ root: parser.dataSets.main.hashTree.getRootHash(),
4019
+ heartbeatIntervalMs: undefined,
4020
+ },
4021
+ ],
4022
+ visibleDataSetsUrl,
4023
+ locusUrl,
4024
+ heartbeatIntervalMs: topLevelInterval,
4025
+ };
4026
+
4027
+ parser.handleMessage(heartbeatMessage, 'heartbeat with top-level only');
4028
+
4029
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
4030
+
4031
+ // Mock sync responses
4032
+ const mainDataSetUrl = parser.dataSets.main.url;
4033
+ mockGetHashesFromLocusResponse(
4034
+ mainDataSetUrl,
4035
+ new Array(16).fill('00000000000000000000000000000000'),
4036
+ createDataSet('main', 16, 1101)
4037
+ );
4038
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
4039
+
4040
+ // Should fire at the top-level interval
4041
+ await clock.tickAsync(topLevelInterval - 1);
4042
+ assert.notCalled(webexRequest);
4043
+
4044
+ await clock.tickAsync(1);
4045
+ assert.calledWith(
4046
+ webexRequest,
4047
+ sinon.match({
4048
+ method: 'GET',
4049
+ uri: `${mainDataSetUrl}/hashtree`,
4050
+ })
4051
+ );
4052
+ });
4053
+
4054
+ it('does not start watchdog when dataset-level heartbeatIntervalMs is 0 even if top-level is set', async () => {
4055
+ const parser = createHashTreeParser();
4056
+
4057
+ // Send heartbeat with dataset-level 0 and a top-level value
4058
+ const heartbeatMessage = {
4059
+ dataSets: [
4060
+ {
4061
+ ...createDataSet('main', 16, 1100),
4062
+ root: parser.dataSets.main.hashTree.getRootHash(),
4063
+ heartbeatIntervalMs: 0,
4064
+ },
4065
+ ],
4066
+ visibleDataSetsUrl,
4067
+ locusUrl,
4068
+ heartbeatIntervalMs: 5000,
4069
+ };
4070
+
4071
+ parser.handleMessage(heartbeatMessage, 'heartbeat with dataset-level 0');
4072
+
4073
+ // Dataset-level 0 means no watchdog, should NOT fall back to top-level
4074
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.be.undefined;
4075
+ });
4076
+ });
4077
+
4078
+ });
4079
+
4080
+ describe('#callLocusInfoUpdateCallback filtering', () => {
4081
+ // Helper to setup parser with initial objects and reset callback history
4082
+ function setupParserWithObjects(locusStateElements: any[]) {
4083
+ const parser = createHashTreeParser();
4084
+
4085
+ if (locusStateElements.length > 0) {
2727
4086
  // Determine which datasets to include based on the objects' dataSetNames
2728
4087
  const dataSetNames = new Set<string>();
2729
4088
  locusStateElements.forEach((element) => {
@@ -2812,7 +4171,7 @@ describe('HashTreeParser', () => {
2812
4171
  parser.handleMessage(updateMessage, 'update with newer version');
2813
4172
 
2814
4173
  // Callback should be called with the update
2815
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
4174
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
2816
4175
  updatedObjects: [
2817
4176
  {
2818
4177
  htMeta: {
@@ -2883,7 +4242,7 @@ describe('HashTreeParser', () => {
2883
4242
  parser.handleMessage(removalMessage, 'removal of non-existent object');
2884
4243
 
2885
4244
  // Callback should be called with the removal
2886
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
4245
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
2887
4246
  updatedObjects: [
2888
4247
  {
2889
4248
  htMeta: {
@@ -3018,7 +4377,7 @@ describe('HashTreeParser', () => {
3018
4377
  parser.handleMessage(mixedMessage, 'mixed updates');
3019
4378
 
3020
4379
  // Callback should be called with only the valid updates (participant 1 v110 and participant 3 v10)
3021
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
4380
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
3022
4381
  updatedObjects: [
3023
4382
  {
3024
4383
  htMeta: {
@@ -3172,6 +4531,9 @@ describe('HashTreeParser', () => {
3172
4531
  parser.handleMessage(emptyMessage, 'empty elements');
3173
4532
 
3174
4533
  assert.notCalled(callback);
4534
+ assert.calledWith(metricsStub, BEHAVIORAL_METRICS.HASH_TREE_EMPTY_LOCUS_STATE_ELEMENTS, {
4535
+ debugId: 'test',
4536
+ });
3175
4537
  });
3176
4538
 
3177
4539
  it('always calls callback for MEETING_ENDED regardless of filtering', () => {
@@ -3196,9 +4558,1535 @@ describe('HashTreeParser', () => {
3196
4558
  parser.handleMessage(sentinelMessage as any, 'sentinel message');
3197
4559
 
3198
4560
  // Callback should be called with MEETING_ENDED
3199
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.MEETING_ENDED, {
3200
- updatedObjects: undefined,
3201
- });
4561
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.MEETING_ENDED});
4562
+ });
4563
+ });
4564
+
4565
+ describe('#state', () => {
4566
+ it('should be initialized to active', () => {
4567
+ const parser = createHashTreeParser();
4568
+
4569
+ expect(parser.state).to.equal('active');
4570
+ });
4571
+ });
4572
+
4573
+ describe('#stop', () => {
4574
+ it('should set state to stopped', () => {
4575
+ const parser = createHashTreeParser();
4576
+
4577
+ parser.stop();
4578
+
4579
+ expect(parser.state).to.equal('stopped');
4580
+ });
4581
+
4582
+ it('should clear all hash trees', () => {
4583
+ const parser = createHashTreeParser();
4584
+
4585
+ expect(parser.dataSets.main.hashTree).to.be.instanceOf(HashTree);
4586
+ expect(parser.dataSets.self.hashTree).to.be.instanceOf(HashTree);
4587
+
4588
+ parser.stop();
4589
+
4590
+ expect(parser.dataSets.main.hashTree).to.be.undefined;
4591
+ expect(parser.dataSets.self.hashTree).to.be.undefined;
4592
+ expect(parser.dataSets['atd-unmuted'].hashTree).to.be.undefined;
4593
+ });
4594
+
4595
+ it('should clear visibleDataSets', () => {
4596
+ const parser = createHashTreeParser();
4597
+
4598
+ expect(parser.visibleDataSets).to.have.length.greaterThan(0);
4599
+
4600
+ parser.stop();
4601
+
4602
+ expect(parser.visibleDataSets).to.deep.equal([]);
4603
+ });
4604
+
4605
+ it('should stop all timers', () => {
4606
+ const parser = createHashTreeParser();
4607
+
4608
+ // manually set timers on data sets
4609
+ parser.dataSets.main.timer = setTimeout(() => {}, 10000);
4610
+ parser.dataSets.main.heartbeatWatchdogTimer = setTimeout(() => {}, 10000);
4611
+
4612
+ parser.stop();
4613
+
4614
+ expect(parser.dataSets.main.timer).to.be.undefined;
4615
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.be.undefined;
3202
4616
  });
4617
+
4618
+ it('should not call locusInfoUpdateCallback when async initialization of a new visible dataset completes after stop()', async () => {
4619
+ const parser = createHashTreeParser();
4620
+
4621
+ // Stub updateItems on self hash tree to return true so the metadata update is applied
4622
+ sinon.stub(parser.dataSets.self.hashTree, 'updateItems').returns([true]);
4623
+
4624
+ // Send a message with Metadata that adds a new visible dataset requiring async initialization
4625
+ // (the new dataset is NOT in parser.dataSets, so it will go through queueInitForNewVisibleDataSets)
4626
+ const message = {
4627
+ dataSets: [createDataSet('self', 1, 2100)],
4628
+ visibleDataSetsUrl,
4629
+ locusUrl,
4630
+ locusStateElements: [
4631
+ {
4632
+ htMeta: {
4633
+ elementId: {
4634
+ type: 'metadata' as const,
4635
+ id: 5,
4636
+ version: 51,
4637
+ },
4638
+ dataSetNames: ['self'],
4639
+ },
4640
+ data: {
4641
+ visibleDataSets: [
4642
+ {
4643
+ name: 'main',
4644
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/main',
4645
+ },
4646
+ {
4647
+ name: 'self',
4648
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self',
4649
+ },
4650
+ {
4651
+ name: 'atd-unmuted',
4652
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted',
4653
+ },
4654
+ {
4655
+ name: 'new-dataset',
4656
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/new-dataset',
4657
+ },
4658
+ ],
4659
+ },
4660
+ },
4661
+ ],
4662
+ };
4663
+
4664
+ // Mock the async initialization - getAllVisibleDataSetsFromLocus and sync request
4665
+ const newDataSet = createDataSet('new-dataset', 4, 5000);
4666
+ mockGetAllDataSetsMetadata(webexRequest, visibleDataSetsUrl, [newDataSet]);
4667
+ mockSyncRequest(webexRequest, newDataSet.url, {
4668
+ dataSets: [newDataSet],
4669
+ visibleDataSetsUrl,
4670
+ locusUrl,
4671
+ locusStateElements: [
4672
+ {
4673
+ htMeta: {
4674
+ elementId: {type: 'participant' as const, id: 20, version: 100},
4675
+ dataSetNames: ['new-dataset'],
4676
+ },
4677
+ data: {person: {name: 'some participant'}},
4678
+ },
4679
+ ],
4680
+ });
4681
+
4682
+ // handleMessage triggers queueInitForNewVisibleDataSets (via queueMicrotask)
4683
+ parser.handleMessage(message, 'add new dataset then stop');
4684
+
4685
+ // callback is called once synchronously by handleMessage for the metadata update
4686
+ callback.resetHistory();
4687
+
4688
+ // Stop the parser before the async initialization completes
4689
+ parser.stop();
4690
+
4691
+ // Let the queued microtask and async initialization complete
4692
+ await clock.tickAsync(0);
4693
+
4694
+ // The callback should NOT have been called again after stop()
4695
+ assert.notCalled(callback);
4696
+
4697
+ // parseMessage should not have processed the sync response data,
4698
+ // so no hash tree should exist for new-dataset (stop() clears all hash trees)
4699
+ assert.isUndefined(parser.dataSets['new-dataset']?.hashTree);
4700
+ });
4701
+
4702
+ it('should not call locusInfoUpdateCallback when initializeFromMessage completes after stop()', async () => {
4703
+ const minimalInitialLocus = {
4704
+ dataSets: [],
4705
+ locus: null,
4706
+ };
4707
+ const parser = createHashTreeParser(minimalInitialLocus, null);
4708
+
4709
+ const mainDataSet = createDataSet('main', 16, 1100);
4710
+
4711
+ // Use a deferred promise so we can control when getAllVisibleDataSetsFromLocus resolves
4712
+ let resolveGetDataSets;
4713
+ webexRequest
4714
+ .withArgs(
4715
+ sinon.match({
4716
+ method: 'GET',
4717
+ uri: visibleDataSetsUrl,
4718
+ })
4719
+ )
4720
+ .returns(
4721
+ new Promise((resolve) => {
4722
+ resolveGetDataSets = resolve;
4723
+ })
4724
+ );
4725
+
4726
+ mockSyncRequest(webexRequest, mainDataSet.url, {
4727
+ dataSets: [mainDataSet],
4728
+ visibleDataSetsUrl,
4729
+ locusUrl,
4730
+ locusStateElements: [
4731
+ {
4732
+ htMeta: {
4733
+ elementId: {type: 'locus' as const, id: 1, version: 210},
4734
+ dataSetNames: ['main'],
4735
+ },
4736
+ data: {info: {id: 'some-locus-info'}},
4737
+ },
4738
+ ],
4739
+ });
4740
+
4741
+ // Start initializeFromMessage but don't await it
4742
+ const initPromise = parser.initializeFromMessage({
4743
+ dataSets: [],
4744
+ visibleDataSetsUrl,
4745
+ locusUrl,
4746
+ });
4747
+
4748
+ // Stop the parser before the GET response arrives
4749
+ parser.stop();
4750
+
4751
+ // Now resolve the pending GET request
4752
+ resolveGetDataSets({body: {dataSets: [mainDataSet]}});
4753
+
4754
+ // Wait for the initializeFromMessage to finish
4755
+ await initPromise;
4756
+
4757
+ // The callback should NOT have been called because the parser was stopped
4758
+ assert.notCalled(callback);
4759
+
4760
+ // Even though initializeDataSets may create a hash tree entry, parseMessage
4761
+ // should have returned [] without processing the sync response objects.
4762
+ // After stop(), hash trees are cleared, so verify that main has no hash tree.
4763
+ assert.isUndefined(parser.dataSets.main?.hashTree);
4764
+ });
4765
+ });
4766
+
4767
+ describe('#resumeFromMessage', () => {
4768
+ const createResumeMessage = (visibleDataSets?, dataSets?) => ({
4769
+ locusUrl,
4770
+ visibleDataSetsUrl,
4771
+ dataSets: dataSets || [
4772
+ createDataSet('main', 16, 2000),
4773
+ createDataSet('self', 1, 3000),
4774
+ ],
4775
+ locusStateElements: [
4776
+ {
4777
+ htMeta: {elementId: {type: 'metadata' as const, id: 5, version: 60}, dataSetNames: ['self']},
4778
+ data: {
4779
+ visibleDataSets: visibleDataSets || [
4780
+ {name: 'main', url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/main'},
4781
+ {name: 'self', url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self'},
4782
+ ],
4783
+ },
4784
+ },
4785
+ ],
4786
+ });
4787
+
4788
+ it('should set state back to active', () => {
4789
+ const parser = createHashTreeParser();
4790
+ parser.stop();
4791
+
4792
+ expect(parser.state).to.equal('stopped');
4793
+
4794
+ parser.resumeFromMessage(createResumeMessage());
4795
+
4796
+ expect(parser.state).to.equal('active');
4797
+ });
4798
+
4799
+ it('should not resume if message is missing metadata with visibleDataSets', () => {
4800
+ const parser = createHashTreeParser();
4801
+ parser.stop();
4802
+
4803
+ parser.resumeFromMessage({
4804
+ locusUrl,
4805
+ visibleDataSetsUrl,
4806
+ dataSets: [createDataSet('main', 16, 2000)],
4807
+ locusStateElements: [],
4808
+ });
4809
+
4810
+ expect(parser.state).to.equal('stopped');
4811
+ });
4812
+
4813
+ it('should re-initialize dataSets from the message', () => {
4814
+ const parser = createHashTreeParser();
4815
+ parser.stop();
4816
+
4817
+ const newDataSets = [
4818
+ createDataSet('main', 8, 5000),
4819
+ createDataSet('self', 2, 6000),
4820
+ ];
4821
+
4822
+ parser.resumeFromMessage(createResumeMessage(undefined, newDataSets));
4823
+
4824
+ expect(Object.keys(parser.dataSets)).to.have.lengthOf(2);
4825
+ expect(parser.dataSets.main.leafCount).to.equal(8);
4826
+ expect(parser.dataSets.main.version).to.equal(5000);
4827
+ expect(parser.dataSets.self.leafCount).to.equal(2);
4828
+ });
4829
+
4830
+ it('should create hash trees only for visible data sets', () => {
4831
+ const parser = createHashTreeParser();
4832
+ parser.stop();
4833
+
4834
+ const dataSets = [
4835
+ createDataSet('main', 16, 2000),
4836
+ createDataSet('self', 1, 3000),
4837
+ createDataSet('atd-unmuted', 16, 4000),
4838
+ ];
4839
+ const visibleDataSets = [
4840
+ {name: 'main', url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/main'},
4841
+ {name: 'self', url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self'},
4842
+ ];
4843
+
4844
+ parser.resumeFromMessage(createResumeMessage(visibleDataSets, dataSets));
4845
+
4846
+ expect(parser.dataSets.main.hashTree).to.be.instanceOf(HashTree);
4847
+ expect(parser.dataSets.self.hashTree).to.be.instanceOf(HashTree);
4848
+ expect(parser.dataSets['atd-unmuted'].hashTree).to.be.undefined;
4849
+ });
4850
+
4851
+ it('should call handleMessage with the resume message', () => {
4852
+ const parser = createHashTreeParser();
4853
+ parser.stop();
4854
+
4855
+ const handleMessageStub = sinon.stub(parser, 'handleMessage');
4856
+
4857
+ const message = createResumeMessage();
4858
+ parser.resumeFromMessage(message);
4859
+
4860
+ assert.calledOnceWithExactly(handleMessageStub, message, 'on resume');
4861
+ });
4862
+
4863
+ it('should set visibleDataSets from message metadata filtered by excludedDataSets', () => {
4864
+ const parser = createHashTreeParser(exampleInitialLocus, exampleMetadata, ['atd-unmuted']);
4865
+ parser.stop();
4866
+
4867
+ const dataSets = [
4868
+ createDataSet('main', 16, 2000),
4869
+ createDataSet('self', 1, 3000),
4870
+ createDataSet('atd-unmuted', 16, 4000),
4871
+ ];
4872
+ const visibleDataSets = [
4873
+ {name: 'main', url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/main'},
4874
+ {name: 'self', url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self'},
4875
+ {name: 'atd-unmuted', url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted'},
4876
+ ];
4877
+
4878
+ parser.resumeFromMessage(createResumeMessage(visibleDataSets, dataSets));
4879
+
4880
+ expect(parser.visibleDataSets.some((vds) => vds.name === 'atd-unmuted')).to.be.false;
4881
+ expect(parser.visibleDataSets.some((vds) => vds.name === 'main')).to.be.true;
4882
+ expect(parser.visibleDataSets.some((vds) => vds.name === 'self')).to.be.true;
4883
+ });
4884
+ });
4885
+
4886
+ describe('#resumeFromApiResponse', () => {
4887
+ const exampleLocus = {
4888
+ participants: [],
4889
+ } as any;
4890
+
4891
+ it('should set state to active', async () => {
4892
+ const parser = createHashTreeParser();
4893
+ parser.stop();
4894
+
4895
+ expect(parser.state).to.equal('stopped');
4896
+
4897
+ sinon.stub(parser, 'initializeFromGetLociResponse').resolves();
4898
+
4899
+ await parser.resumeFromApiResponse(exampleLocus);
4900
+
4901
+ expect(parser.state).to.equal('active');
4902
+ });
4903
+
4904
+ it('should reset dataSets to empty', async () => {
4905
+ const parser = createHashTreeParser();
4906
+
4907
+ expect(Object.keys(parser.dataSets).length).to.be.greaterThan(0);
4908
+
4909
+ parser.stop();
4910
+
4911
+ sinon.stub(parser, 'initializeFromGetLociResponse').resolves();
4912
+
4913
+ await parser.resumeFromApiResponse(exampleLocus);
4914
+
4915
+ expect(parser.dataSets).to.deep.equal({});
4916
+ });
4917
+
4918
+ it('should call initializeFromGetLociResponse with the provided locus', async () => {
4919
+ const parser = createHashTreeParser();
4920
+ parser.stop();
4921
+
4922
+ const initStub = sinon.stub(parser, 'initializeFromGetLociResponse').resolves();
4923
+
4924
+ await parser.resumeFromApiResponse(exampleLocus);
4925
+
4926
+ assert.calledOnceWithExactly(initStub, exampleLocus);
4927
+ });
4928
+
4929
+ it('should propagate errors from initializeFromGetLociResponse', async () => {
4930
+ const parser = createHashTreeParser();
4931
+ parser.stop();
4932
+
4933
+ const error = new Error('initialization failed');
4934
+ const initStub = sinon.stub(parser, 'initializeFromGetLociResponse').rejects(error);
4935
+
4936
+ let caughtError: Error | undefined;
4937
+ try {
4938
+ await parser.resumeFromApiResponse(exampleLocus);
4939
+ } catch (e) {
4940
+ caughtError = e;
4941
+ }
4942
+
4943
+ expect(caughtError).to.equal(error);
4944
+ });
4945
+ });
4946
+
4947
+ describe('#handleLocusUpdate when stopped', () => {
4948
+ it('should return early without processing when parser is stopped', () => {
4949
+ const parser = createHashTreeParser();
4950
+ parser.stop();
4951
+
4952
+ parser.handleLocusUpdate({
4953
+ dataSets: [createDataSet('main', 16, 2000)],
4954
+ locus: {participants: []},
4955
+ });
4956
+
4957
+ assert.notCalled(callback);
4958
+ });
4959
+ });
4960
+
4961
+ describe('#handleMessage when stopped', () => {
4962
+ it('should return early without processing when parser is stopped', () => {
4963
+ const parser = createHashTreeParser();
4964
+ parser.stop();
4965
+
4966
+ parser.handleMessage({
4967
+ dataSets: [createDataSet('main', 16, 2000)],
4968
+ visibleDataSetsUrl,
4969
+ locusUrl,
4970
+ locusStateElements: [
4971
+ {
4972
+ htMeta: {elementId: {type: 'self' as const, id: 4, version: 200}, dataSetNames: ['self']},
4973
+ data: {id: 'new-self'},
4974
+ },
4975
+ ],
4976
+ });
4977
+
4978
+ assert.notCalled(callback);
4979
+ });
4980
+ });
4981
+
4982
+ describe('#syncAllDatasets', () => {
4983
+ it('should sync all datasets that have hash trees in priority order', async () => {
4984
+ const parser = createHashTreeParser();
4985
+
4986
+ // parser starts with main (leafCount=16) and self (leafCount=1) as visible datasets with hash trees
4987
+ // atd-unmuted has no hash tree (not visible)
4988
+ expect(parser.dataSets.main.hashTree).to.be.instanceOf(HashTree);
4989
+ expect(parser.dataSets.self.hashTree).to.be.instanceOf(HashTree);
4990
+
4991
+ const mainUrl = parser.dataSets.main.url;
4992
+ const selfUrl = parser.dataSets.self.url;
4993
+
4994
+ // Mock GET hashtree for main (leafCount > 1, so it does GET first)
4995
+ mockGetHashesFromLocusResponse(
4996
+ mainUrl,
4997
+ new Array(16).fill(EMPTY_HASH),
4998
+ createDataSet('main', 16, 1100)
4999
+ );
5000
+
5001
+ // Mock POST sync for main - return matching root hash so no further sync needed
5002
+ const mainSyncDataSet = createDataSet('main', 16, 1100);
5003
+ mainSyncDataSet.root = parser.dataSets.main.hashTree.getRootHash();
5004
+ mockSendSyncRequestResponse(mainUrl, {
5005
+ dataSets: [mainSyncDataSet],
5006
+ visibleDataSetsUrl,
5007
+ locusUrl,
5008
+ locusStateElements: [],
5009
+ });
5010
+
5011
+ // Mock POST sync for self (leafCount=1, skips GET hashtree)
5012
+ const selfSyncDataSet = createDataSet('self', 1, 2100);
5013
+ selfSyncDataSet.root = parser.dataSets.self.hashTree.getRootHash();
5014
+ mockSendSyncRequestResponse(selfUrl, {
5015
+ dataSets: [selfSyncDataSet],
5016
+ visibleDataSetsUrl,
5017
+ locusUrl,
5018
+ locusStateElements: [],
5019
+ });
5020
+
5021
+ await parser.syncAllDatasets();
5022
+
5023
+ // Verify GET hashtree was called for main only (not self, because leafCount=1)
5024
+ assert.calledWith(webexRequest, sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}));
5025
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${selfUrl}/hashtree`}));
5026
+
5027
+ // Verify POST sync was called for both
5028
+ assert.calledWith(webexRequest, sinon.match({method: 'POST', uri: `${mainUrl}/sync`}));
5029
+ assert.calledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
5030
+
5031
+ // Verify main was synced before self (priority order)
5032
+ const mainSyncCallIndex = webexRequest.args.findIndex(
5033
+ (args) => args[0]?.method === 'GET' && args[0]?.uri === `${mainUrl}/hashtree`
5034
+ );
5035
+ const selfSyncCallIndex = webexRequest.args.findIndex(
5036
+ (args) => args[0]?.method === 'POST' && args[0]?.uri === `${selfUrl}/sync`
5037
+ );
5038
+ expect(mainSyncCallIndex).to.be.lessThan(selfSyncCallIndex);
5039
+
5040
+ // Verify syncAllBackoffType is reset
5041
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.NONE);
5042
+ });
5043
+
5044
+ it('should return immediately when state is stopped', async () => {
5045
+ const parser = createHashTreeParser();
5046
+ parser.stop();
5047
+
5048
+ await parser.syncAllDatasets();
5049
+
5050
+ // No sync requests should have been made (only the initial sync from constructor)
5051
+ // Reset history to clear constructor calls then verify
5052
+ const callCountBefore = webexRequest.callCount;
5053
+ await parser.syncAllDatasets();
5054
+ assert.equal(webexRequest.callCount, callCountBefore);
5055
+ });
5056
+
5057
+ it('should guard against concurrent calls', async () => {
5058
+ const parser = createHashTreeParser();
5059
+
5060
+ const mainUrl = parser.dataSets.main.url;
5061
+ const selfUrl = parser.dataSets.self.url;
5062
+
5063
+ // Use a deferred promise for the main sync to control timing
5064
+ let resolveMainSync;
5065
+ webexRequest
5066
+ .withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}))
5067
+ .returns(new Promise((resolve) => { resolveMainSync = resolve; }));
5068
+
5069
+ mockSendSyncRequestResponse(mainUrl, {
5070
+ dataSets: [createDataSet('main', 16, 1100)],
5071
+ visibleDataSetsUrl,
5072
+ locusUrl,
5073
+ locusStateElements: [],
5074
+ });
5075
+
5076
+ mockSendSyncRequestResponse(selfUrl, {
5077
+ dataSets: [createDataSet('self', 1, 2100)],
5078
+ visibleDataSetsUrl,
5079
+ locusUrl,
5080
+ locusStateElements: [],
5081
+ });
5082
+
5083
+ // Start first call
5084
+ const promise1 = parser.syncAllDatasets();
5085
+ // Start second call while first is in progress
5086
+ const promise2 = parser.syncAllDatasets();
5087
+
5088
+ // Resolve the pending request
5089
+ resolveMainSync({
5090
+ body: {
5091
+ hashes: new Array(16).fill(EMPTY_HASH),
5092
+ dataSet: createDataSet('main', 16, 1100),
5093
+ },
5094
+ });
5095
+
5096
+ await promise1;
5097
+ await promise2;
5098
+
5099
+ // GET hashtree for main should only be called once (second syncAllDatasets returned immediately)
5100
+ const getHashtreeCalls = webexRequest.args.filter(
5101
+ (args) => args[0]?.method === 'GET' && args[0]?.uri === `${mainUrl}/hashtree`
5102
+ );
5103
+ expect(getHashtreeCalls).to.have.lengthOf(1);
5104
+ });
5105
+
5106
+ it('should sync only LLM datasets when onlyLLM=true', async () => {
5107
+ const parser = createHashTreeParser();
5108
+
5109
+ const mainUrl = parser.dataSets.main.url;
5110
+ const selfUrl = parser.dataSets.self.url;
5111
+
5112
+ mockGetHashesFromLocusResponse(
5113
+ mainUrl,
5114
+ new Array(16).fill(EMPTY_HASH),
5115
+ createDataSet('main', 16, 1100)
5116
+ );
5117
+
5118
+ const mainSyncDs = createDataSet('main', 16, 1100);
5119
+ mainSyncDs.root = parser.dataSets.main.hashTree.getRootHash();
5120
+ mockSendSyncRequestResponse(mainUrl, {
5121
+ dataSets: [mainSyncDs],
5122
+ visibleDataSetsUrl,
5123
+ locusUrl,
5124
+ locusStateElements: [],
5125
+ });
5126
+
5127
+ await parser.syncAllDatasets({onlyLLM: true});
5128
+
5129
+ // main is an LLM dataset, so it should have been synced
5130
+ assert.calledWith(webexRequest, sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}));
5131
+
5132
+ // self is NOT an LLM dataset, so it should NOT have been synced
5133
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
5134
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${selfUrl}/hashtree`}));
5135
+ });
5136
+
5137
+ it('uses the syncAll random backoff when reporting sync metrics', async () => {
5138
+ mathRandomStub.returns(0.5); // syncAll backoff = 0.5^2 * 1000 = 250ms
5139
+
5140
+ const syncLatencyTracker = {
5141
+ saveLatency: sinon.stub(),
5142
+ saveTimestamp: sinon.stub(),
5143
+ getLocusSyncLatency: sinon.stub(),
5144
+ clearLocusSyncLatency: sinon.stub(),
5145
+ completeLocusSyncLatency: sinon.stub(),
5146
+ };
5147
+ const parser = createHashTreeParser(
5148
+ undefined,
5149
+ undefined,
5150
+ ['atd-unmuted'],
5151
+ syncLatencyTracker
5152
+ );
5153
+ const mainUrl = parser.dataSets.main.url;
5154
+
5155
+ mockGetHashesFromLocusResponse(
5156
+ mainUrl,
5157
+ new Array(16).fill('00000000000000000000000000000000'),
5158
+ createDataSet('main', 16, 1100)
5159
+ );
5160
+ mockSendSyncRequestResponse(mainUrl, null);
5161
+
5162
+ const syncAllPromise = parser.syncAllDatasets({onlyLLM: true});
5163
+
5164
+ await clock.tickAsync(250);
5165
+ await syncAllPromise;
5166
+
5167
+ assert.calledWithExactly(
5168
+ syncLatencyTracker.saveLatency,
5169
+ 'internal.client.locus.sync.random.backoff',
5170
+ 250,
5171
+ {
5172
+ meetingId: 'meeting-1',
5173
+ dataSetName: 'main',
5174
+ }
5175
+ );
5176
+ });
5177
+
5178
+ it('should upgrade scope from onlyLLM=true to all datasets when onlyLLM=false call arrives during backoff', async () => {
5179
+ // Make Math.random return 1 so backoff = 1^2 * 1000 = 1000ms (non-zero delay for interleaving)
5180
+ mathRandomStub.returns(1);
5181
+
5182
+ const parser = createHashTreeParser();
5183
+
5184
+ const mainUrl = parser.dataSets.main.url;
5185
+ const selfUrl = parser.dataSets.self.url;
5186
+
5187
+ mockGetHashesFromLocusResponse(
5188
+ mainUrl,
5189
+ new Array(16).fill(EMPTY_HASH),
5190
+ createDataSet('main', 16, 1100)
5191
+ );
5192
+
5193
+ const mainSyncDs = createDataSet('main', 16, 1100);
5194
+ mainSyncDs.root = parser.dataSets.main.hashTree.getRootHash();
5195
+ mockSendSyncRequestResponse(mainUrl, {
5196
+ dataSets: [mainSyncDs],
5197
+ visibleDataSetsUrl,
5198
+ locusUrl,
5199
+ locusStateElements: [],
5200
+ });
5201
+
5202
+ const selfSyncDs = createDataSet('self', 1, 2100);
5203
+ selfSyncDs.root = parser.dataSets.self.hashTree.getRootHash();
5204
+ mockSendSyncRequestResponse(selfUrl, {
5205
+ dataSets: [selfSyncDs],
5206
+ visibleDataSetsUrl,
5207
+ locusUrl,
5208
+ locusStateElements: [],
5209
+ });
5210
+
5211
+ // First call with onlyLLM=true starts backoff
5212
+ const promise1 = parser.syncAllDatasets({onlyLLM: true});
5213
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.ONLY_LLM);
5214
+
5215
+ // Second call with onlyLLM=false upgrades the scope during backoff
5216
+ const promise2 = parser.syncAllDatasets({onlyLLM: false});
5217
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.ALL);
5218
+
5219
+ // Advance clock past the backoff delay (1000ms)
5220
+ await clock.tickAsync(1000);
5221
+
5222
+ await promise1;
5223
+ await promise2;
5224
+
5225
+ // Both main (LLM) and self (non-LLM) should have been synced
5226
+ assert.calledWith(webexRequest, sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}));
5227
+ assert.calledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
5228
+ });
5229
+
5230
+ it('should not downgrade scope from onlyLLM=false when onlyLLM=true call arrives during backoff', async () => {
5231
+ // Make Math.random return 1 so backoff = 1^2 * 1000 = 1000ms (non-zero delay for interleaving)
5232
+ mathRandomStub.returns(1);
5233
+
5234
+ const parser = createHashTreeParser();
5235
+
5236
+ const mainUrl = parser.dataSets.main.url;
5237
+ const selfUrl = parser.dataSets.self.url;
5238
+
5239
+ mockGetHashesFromLocusResponse(
5240
+ mainUrl,
5241
+ new Array(16).fill(EMPTY_HASH),
5242
+ createDataSet('main', 16, 1100)
5243
+ );
5244
+
5245
+ const mainSyncDs = createDataSet('main', 16, 1100);
5246
+ mainSyncDs.root = parser.dataSets.main.hashTree.getRootHash();
5247
+ mockSendSyncRequestResponse(mainUrl, {
5248
+ dataSets: [mainSyncDs],
5249
+ visibleDataSetsUrl,
5250
+ locusUrl,
5251
+ locusStateElements: [],
5252
+ });
5253
+
5254
+ const selfSyncDs = createDataSet('self', 1, 2100);
5255
+ selfSyncDs.root = parser.dataSets.self.hashTree.getRootHash();
5256
+ mockSendSyncRequestResponse(selfUrl, {
5257
+ dataSets: [selfSyncDs],
5258
+ visibleDataSetsUrl,
5259
+ locusUrl,
5260
+ locusStateElements: [],
5261
+ });
5262
+
5263
+ // First call with onlyLLM=false starts backoff with all-datasets scope
5264
+ const promise1 = parser.syncAllDatasets({onlyLLM: false});
5265
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.ALL);
5266
+
5267
+ // Second call with onlyLLM=true should NOT downgrade the scope
5268
+ const promise2 = parser.syncAllDatasets({onlyLLM: true});
5269
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.ALL);
5270
+
5271
+ // Advance clock past the backoff delay (1000ms)
5272
+ await clock.tickAsync(1000);
5273
+
5274
+ await promise1;
5275
+ await promise2;
5276
+
5277
+ // Both main (LLM) and self (non-LLM) should have been synced (scope was not downgraded)
5278
+ assert.calledWith(webexRequest, sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}));
5279
+ assert.calledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
5280
+ });
5281
+
5282
+ it('should skip datasets that received messages during the backoff sleep', async () => {
5283
+ // Make Math.random return 1 so backoff = 1^2 * 1000 = 1000ms
5284
+ mathRandomStub.returns(1);
5285
+
5286
+ const parser = createHashTreeParser();
5287
+
5288
+ const mainUrl = parser.dataSets.main.url;
5289
+ const selfUrl = parser.dataSets.self.url;
5290
+ const atdUnmutedUrl = parser.dataSets['atd-unmuted'].url;
5291
+
5292
+ // Setup mocks only for self (main and atd-unmuted should be skipped)
5293
+ mockSendSyncRequestResponse(selfUrl, {
5294
+ dataSets: [createDataSet('self', 1, 2100)],
5295
+ visibleDataSetsUrl,
5296
+ locusUrl,
5297
+ locusStateElements: [],
5298
+ });
5299
+
5300
+ // Start syncAllDatasets - begins backoff sleep
5301
+ const promise = parser.syncAllDatasets();
5302
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.ALL);
5303
+
5304
+ // Simulate a normal message arriving for "main" during the backoff sleep
5305
+ parser.handleMessage({
5306
+ dataSets: [createDataSet('main', 16, 1100)],
5307
+ visibleDataSetsUrl,
5308
+ locusUrl,
5309
+ locusStateElements: [
5310
+ {
5311
+ htMeta: {
5312
+ elementId: {type: 'locus' as const, id: 0, version: 201},
5313
+ dataSetNames: ['main'],
5314
+ },
5315
+ data: {someData: 'value'},
5316
+ },
5317
+ ],
5318
+ });
5319
+
5320
+ // Simulate a heartbeat message arriving for "atd-unmuted" during the backoff sleep
5321
+ parser.handleMessage(
5322
+ createHeartbeatMessage('atd-unmuted', 1, 1100, parser.dataSets['atd-unmuted'].root)
5323
+ );
5324
+
5325
+ // Advance clock past the backoff delay
5326
+ await clock.tickAsync(1000);
5327
+ await promise;
5328
+
5329
+ // main should NOT have been synced (it received a normal message during backoff)
5330
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}));
5331
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${mainUrl}/sync`}));
5332
+
5333
+ // atd-unmuted should NOT have been synced (it received a heartbeat during backoff)
5334
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${atdUnmutedUrl}/hashtree`}));
5335
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${atdUnmutedUrl}/sync`}));
5336
+
5337
+ // self SHOULD have been synced (no messages received for it during backoff)
5338
+ assert.calledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
5339
+ });
5340
+
5341
+ it('should skip datasets that do not have a hash tree', async () => {
5342
+ // Create parser with metadata that only has main and self as visible (not atd-unmuted)
5343
+ const metadataWithoutAtd = {
5344
+ ...exampleMetadata,
5345
+ visibleDataSets: exampleMetadata.visibleDataSets.filter((ds) => ds.name !== 'atd-unmuted'),
5346
+ };
5347
+ const parser = createHashTreeParser(exampleInitialLocus, metadataWithoutAtd);
5348
+
5349
+ // atd-unmuted is in dataSets but has no hashTree (not visible)
5350
+ expect(parser.dataSets['atd-unmuted']).to.exist;
5351
+ expect(parser.dataSets['atd-unmuted'].hashTree).to.be.undefined;
5352
+
5353
+ const atdUrl = parser.dataSets['atd-unmuted'].url;
5354
+ const mainUrl = parser.dataSets.main.url;
5355
+ const selfUrl = parser.dataSets.self.url;
5356
+
5357
+ mockGetHashesFromLocusResponse(
5358
+ mainUrl,
5359
+ new Array(16).fill(EMPTY_HASH),
5360
+ createDataSet('main', 16, 1100)
5361
+ );
5362
+
5363
+ const mainSyncDs = createDataSet('main', 16, 1100);
5364
+ mainSyncDs.root = parser.dataSets.main.hashTree.getRootHash();
5365
+ mockSendSyncRequestResponse(mainUrl, {
5366
+ dataSets: [mainSyncDs],
5367
+ visibleDataSetsUrl,
5368
+ locusUrl,
5369
+ locusStateElements: [],
5370
+ });
5371
+
5372
+ const selfSyncDs = createDataSet('self', 1, 2100);
5373
+ selfSyncDs.root = parser.dataSets.self.hashTree.getRootHash();
5374
+ mockSendSyncRequestResponse(selfUrl, {
5375
+ dataSets: [selfSyncDs],
5376
+ visibleDataSetsUrl,
5377
+ locusUrl,
5378
+ locusStateElements: [],
5379
+ });
5380
+
5381
+ await parser.syncAllDatasets();
5382
+
5383
+ // No requests should have been made for atd-unmuted
5384
+ assert.neverCalledWith(webexRequest, sinon.match({uri: sinon.match(atdUrl)}));
5385
+ });
5386
+ });
5387
+
5388
+ describe('#handleMessage sync queue', () => {
5389
+ it('should deduplicate: not sync the same dataset twice when enqueued multiple times', async () => {
5390
+ const parser = createHashTreeParser();
5391
+
5392
+ const mainUrl = parser.dataSets.main.url;
5393
+
5394
+ // Setup mocks before triggering syncs
5395
+ mockGetHashesFromLocusResponse(
5396
+ mainUrl,
5397
+ new Array(16).fill(EMPTY_HASH),
5398
+ createDataSet('main', 16, 1101)
5399
+ );
5400
+
5401
+ const mainSyncDs = createDataSet('main', 16, 1101);
5402
+ mainSyncDs.root = parser.dataSets.main.hashTree.getRootHash();
5403
+ mockSendSyncRequestResponse(mainUrl, {
5404
+ dataSets: [mainSyncDs],
5405
+ visibleDataSetsUrl,
5406
+ locusUrl,
5407
+ locusStateElements: [],
5408
+ });
5409
+
5410
+ // Send two heartbeat messages (no locusStateElements) with different root hashes for main
5411
+ parser.handleMessage(createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'), 'first');
5412
+ parser.handleMessage(createHeartbeatMessage('main', 16, 1101, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa2'), 'second');
5413
+
5414
+ // The second call resets the timer. After 1000ms, only one sync fires.
5415
+ await clock.tickAsync(1000);
5416
+
5417
+ // Only one GET hashtree call should have been made for main
5418
+ const getHashtreeCalls = webexRequest.args.filter(
5419
+ (args) => args[0]?.method === 'GET' && args[0]?.uri === `${mainUrl}/hashtree`
5420
+ );
5421
+ expect(getHashtreeCalls).to.have.lengthOf(1);
5422
+ });
5423
+
5424
+ it('should stop processing the sync queue when parser is stopped mid-queue', async () => {
5425
+ const parser = createHashTreeParser();
5426
+
5427
+ const mainUrl = parser.dataSets.main.url;
5428
+ const selfUrl = parser.dataSets.self.url;
5429
+
5430
+ // Mock main GET hashtree with a deferred promise so we can control when it resolves
5431
+ let resolveMainHashtree;
5432
+ webexRequest
5433
+ .withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}))
5434
+ .callsFake(() => new Promise((resolve) => { resolveMainHashtree = resolve; }));
5435
+
5436
+ // Send a heartbeat message that triggers sync timers for both main and self
5437
+ parser.handleMessage(
5438
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5439
+ 'trigger main sync'
5440
+ );
5441
+ parser.handleMessage(
5442
+ createHeartbeatMessage('self', 1, 2100, 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb1'),
5443
+ 'trigger self sync'
5444
+ );
5445
+
5446
+ // Fire the timers - main sync starts (calls GET hashtree, which blocks)
5447
+ await clock.tickAsync(1000);
5448
+
5449
+ // Stop the parser while main sync is in progress
5450
+ parser.stop();
5451
+
5452
+ // Resolve the pending main GET request
5453
+ resolveMainHashtree({
5454
+ body: {
5455
+ hashes: new Array(16).fill(EMPTY_HASH),
5456
+ dataSet: createDataSet('main', 16, 1100),
5457
+ },
5458
+ });
5459
+
5460
+ await clock.tickAsync(0);
5461
+
5462
+ // Self sync should NOT have been triggered because parser was stopped
5463
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
5464
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${selfUrl}/hashtree`}));
5465
+ });
5466
+ });
5467
+
5468
+ describe('#stop sync queue', () => {
5469
+ it('should clear the syncQueue when stopped so remaining queued items are not processed', async () => {
5470
+ const parser = createHashTreeParser();
5471
+
5472
+ const mainUrl = parser.dataSets.main.url;
5473
+ const selfUrl = parser.dataSets.self.url;
5474
+
5475
+ // Mock main GET hashtree with a deferred promise so we can control when it resolves
5476
+ let resolveMainHashtree;
5477
+ webexRequest
5478
+ .withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}))
5479
+ .callsFake(() => new Promise((resolve) => { resolveMainHashtree = resolve; }));
5480
+
5481
+ // Enqueue syncs for both main and self by sending heartbeat messages
5482
+ parser.handleMessage(
5483
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5484
+ 'trigger main sync'
5485
+ );
5486
+ parser.handleMessage(
5487
+ createHeartbeatMessage('self', 1, 2100, 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb1'),
5488
+ 'trigger self sync'
5489
+ );
5490
+
5491
+ // Fire the timers - main sync starts and blocks on GET hashtree
5492
+ await clock.tickAsync(1000);
5493
+
5494
+ // Verify that self is still in the queue (main is being processed, self is waiting)
5495
+ // Now stop the parser - this should clear the syncQueue
5496
+ parser.stop();
5497
+
5498
+ // Resolve the pending main GET request so the in-flight sync can finish
5499
+ resolveMainHashtree({
5500
+ body: {
5501
+ hashes: new Array(16).fill(EMPTY_HASH),
5502
+ dataSet: createDataSet('main', 16, 1100),
5503
+ },
5504
+ });
5505
+
5506
+ await clock.tickAsync(0);
5507
+
5508
+ // Self should never have been synced because stop() cleared the queue
5509
+ const selfGetCalls = webexRequest.args.filter(
5510
+ (args) => args[0]?.method === 'GET' && args[0]?.uri === `${selfUrl}/hashtree`
5511
+ );
5512
+ expect(selfGetCalls).to.have.lengthOf(0);
5513
+ });
5514
+ });
5515
+
5516
+ describe('#performSync abort controller', () => {
5517
+ it('should reuse an existing syncAbortController if one is already set on the dataset', async () => {
5518
+ const parser = createHashTreeParser();
5519
+ const mainUrl = parser.dataSets.main.url;
5520
+
5521
+ // Pre-set an AbortController on the dataset before sync starts
5522
+ const existingController = new AbortController();
5523
+ parser.dataSets.main.syncAbortController = existingController;
5524
+
5525
+ // Use a deferred promise for GET hashtree so we can inspect the controller mid-sync
5526
+ let resolveGetHashtree;
5527
+ webexRequest.withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`})).callsFake(
5528
+ () =>
5529
+ new Promise((resolve) => {
5530
+ resolveGetHashtree = resolve;
5531
+ })
5532
+ );
5533
+
5534
+ // Trigger sync for main
5535
+ parser.handleMessage(
5536
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5537
+ 'trigger main sync'
5538
+ );
5539
+
5540
+ await clock.tickAsync(1000);
5541
+
5542
+ // While sync is in-flight, verify the controller is the same one we pre-set
5543
+ expect(parser.dataSets.main.syncAbortController).to.equal(existingController);
5544
+
5545
+ // Resolve GET hashtree with matching hashes (no sync needed)
5546
+ resolveGetHashtree({body: {}});
5547
+ await testUtils.flushPromises();
5548
+
5549
+ // After sync completes, syncAbortController is cleared in finally
5550
+ expect(parser.dataSets.main.syncAbortController).to.be.undefined;
5551
+ });
5552
+
5553
+ it('should abort the sync before /sync request when the controller is aborted during getHashesFromLocus', async () => {
5554
+ const parser = createHashTreeParser();
5555
+ const mainUrl = parser.dataSets.main.url;
5556
+
5557
+ // Use a deferred promise for GET hashtree so we can abort while it's pending
5558
+ let resolveGetHashtree;
5559
+ webexRequest.withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`})).callsFake(
5560
+ () =>
5561
+ new Promise((resolve) => {
5562
+ resolveGetHashtree = resolve;
5563
+ })
5564
+ );
5565
+
5566
+ // Mock POST sync - should NOT be called if abort works
5567
+ mockSendSyncRequestResponse(mainUrl, null);
5568
+
5569
+ // Trigger sync for main via heartbeat with mismatched root hash
5570
+ parser.handleMessage(
5571
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5572
+ 'trigger main sync'
5573
+ );
5574
+
5575
+ // Fire the timer to start the sync
5576
+ await clock.tickAsync(1000);
5577
+
5578
+ // Now abort the controller while getHashesFromLocus is pending
5579
+ expect(parser.dataSets.main.syncAbortController).to.not.be.undefined;
5580
+ parser.dataSets.main.syncAbortController.abort();
5581
+
5582
+ // Resolve GET hashtree with mismatched hashes so the code would normally proceed to /sync
5583
+ resolveGetHashtree({
5584
+ body: {
5585
+ hashes: new Array(16).fill('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5586
+ dataSet: createDataSet('main', 16, 1100),
5587
+ },
5588
+ });
5589
+
5590
+ await testUtils.flushPromises();
5591
+
5592
+ // POST sync should NOT have been called because the controller was aborted
5593
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${mainUrl}/sync`}));
5594
+ });
5595
+
5596
+ it('should abort the sync before /sync request when the controller is aborted for leafCount === 1 datasets', async () => {
5597
+ const parser = createHashTreeParser();
5598
+ const selfUrl = parser.dataSets.self.url;
5599
+
5600
+ // Pre-set an already-aborted controller so performSync picks it up via ??
5601
+ const abortedController = new AbortController();
5602
+ abortedController.abort();
5603
+ parser.dataSets.self.syncAbortController = abortedController;
5604
+
5605
+ // Mock POST sync - should NOT be called
5606
+ mockSendSyncRequestResponse(selfUrl, null);
5607
+
5608
+ // Trigger sync for self via heartbeat with mismatched root hash
5609
+ parser.handleMessage(
5610
+ {
5611
+ dataSets: [
5612
+ {
5613
+ ...createDataSet('self', 1, 2100),
5614
+ url: parser.dataSets.self.url,
5615
+ root: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb1',
5616
+ },
5617
+ ],
5618
+ visibleDataSetsUrl,
5619
+ locusUrl,
5620
+ },
5621
+ 'trigger self sync'
5622
+ );
5623
+
5624
+ // Fire the timer to start the sync
5625
+ await clock.tickAsync(1000);
5626
+
5627
+ // GET hashtree should NOT have been called (leafCount === 1 skips it)
5628
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${selfUrl}/hashtree`}));
5629
+
5630
+ // POST sync should NOT have been called because the controller was already aborted
5631
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
5632
+ });
5633
+
5634
+ it('should unconditionally clear syncAbortController in the finally block', async () => {
5635
+ const parser = createHashTreeParser();
5636
+ const mainUrl = parser.dataSets.main.url;
5637
+
5638
+ // Mock GET hashtree to return matching hashes (early return, no sync needed)
5639
+ webexRequest
5640
+ .withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}))
5641
+ .resolves({body: {}});
5642
+
5643
+ // Trigger sync for main
5644
+ parser.handleMessage(
5645
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5646
+ 'trigger main sync'
5647
+ );
5648
+
5649
+ await clock.tickAsync(1000);
5650
+
5651
+ // After sync completes (even via early return), syncAbortController should be cleared
5652
+ expect(parser.dataSets.main.syncAbortController).to.be.undefined;
5653
+ });
5654
+
5655
+ it('should unconditionally clear syncAbortController even when sync throws an error', async () => {
5656
+ const parser = createHashTreeParser();
5657
+ const mainUrl = parser.dataSets.main.url;
5658
+
5659
+ // Mock GET hashtree to reject with a non-409 error
5660
+ webexRequest
5661
+ .withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}))
5662
+ .rejects({statusCode: 500, message: 'Internal Server Error'});
5663
+
5664
+ // Trigger sync for main
5665
+ parser.handleMessage(
5666
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5667
+ 'trigger main sync'
5668
+ );
5669
+
5670
+ await clock.tickAsync(1000);
5671
+
5672
+ // After sync completes with error, syncAbortController should still be cleared
5673
+ expect(parser.dataSets.main.syncAbortController).to.be.undefined;
5674
+ });
5675
+
5676
+ it('should reuse a pre-existing abort controller and respect its aborted state', async () => {
5677
+ const parser = createHashTreeParser();
5678
+ const mainUrl = parser.dataSets.main.url;
5679
+
5680
+ // Pre-set an AbortController and abort it before sync starts
5681
+ const preAbortedController = new AbortController();
5682
+ preAbortedController.abort();
5683
+ parser.dataSets.main.syncAbortController = preAbortedController;
5684
+
5685
+ // Mock GET hashtree to return mismatched hashes
5686
+ mockGetHashesFromLocusResponse(
5687
+ mainUrl,
5688
+ new Array(16).fill('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5689
+ createDataSet('main', 16, 1100)
5690
+ );
5691
+
5692
+ // Mock POST sync - should NOT be called
5693
+ mockSendSyncRequestResponse(mainUrl, null);
5694
+
5695
+ // Trigger sync for main
5696
+ parser.handleMessage(
5697
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5698
+ 'trigger main sync'
5699
+ );
5700
+
5701
+ await clock.tickAsync(1000);
5702
+
5703
+ // POST sync should NOT have been called because the reused controller was already aborted
5704
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${mainUrl}/sync`}));
5705
+
5706
+ // syncAbortController should be cleaned up
5707
+ expect(parser.dataSets.main.syncAbortController).to.be.undefined;
5708
+ });
5709
+
5710
+ it('should allow cancelPendingSyncsForDataSets to abort an in-flight sync via the shared controller', async () => {
5711
+ const parser = createHashTreeParser();
5712
+ const mainUrl = parser.dataSets.main.url;
5713
+
5714
+ // Use a deferred promise for GET hashtree
5715
+ let resolveGetHashtree;
5716
+ webexRequest.withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`})).callsFake(
5717
+ () =>
5718
+ new Promise((resolve) => {
5719
+ resolveGetHashtree = resolve;
5720
+ })
5721
+ );
5722
+
5723
+ mockSendSyncRequestResponse(mainUrl, null);
5724
+
5725
+ // Trigger sync for main
5726
+ parser.handleMessage(
5727
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5728
+ 'trigger main sync'
5729
+ );
5730
+
5731
+ // Fire the timer to start sync
5732
+ await clock.tickAsync(1000);
5733
+
5734
+ // Verify controller is set
5735
+ expect(parser.dataSets.main.syncAbortController).to.not.be.undefined;
5736
+
5737
+ // Simulate a new heartbeat arriving that cancels the in-flight sync
5738
+ // (this is what happens in production via parseMessage -> cancelPendingSyncsForDataSets)
5739
+ parser.handleMessage(
5740
+ {
5741
+ dataSets: [
5742
+ {
5743
+ ...createDataSet('main', 16, 1101),
5744
+ root: parser.dataSets.main.hashTree.getRootHash(), // matching hash so no new sync
5745
+ },
5746
+ ],
5747
+ visibleDataSetsUrl,
5748
+ locusUrl,
5749
+ },
5750
+ 'new heartbeat cancels sync'
5751
+ );
5752
+
5753
+ // Resolve the pending GET hashtree with mismatched hashes
5754
+ resolveGetHashtree({
5755
+ body: {
5756
+ hashes: new Array(16).fill('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5757
+ dataSet: createDataSet('main', 16, 1101),
5758
+ },
5759
+ });
5760
+
5761
+ await testUtils.flushPromises();
5762
+
5763
+ // POST sync should NOT have been called because cancelPendingSyncsForDataSets aborted the controller
5764
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${mainUrl}/sync`}));
5765
+ });
5766
+ });
5767
+
5768
+ describe('#cleanUp', () => {
5769
+ it('should stop the parser, clear all timers and clear all dataSets', () => {
5770
+ const parser = createHashTreeParser();
5771
+
5772
+ // Send a message to set up sync timers via runSyncAlgorithm
5773
+ const message = {
5774
+ dataSets: [
5775
+ {
5776
+ ...createDataSet('main', 16, 1100),
5777
+ root: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1',
5778
+ },
5779
+ ],
5780
+ visibleDataSetsUrl,
5781
+ locusUrl,
5782
+ locusStateElements: [
5783
+ {
5784
+ htMeta: {
5785
+ elementId: {type: 'locus' as const, id: 0, version: 201},
5786
+ dataSetNames: ['main'],
5787
+ },
5788
+ data: {someData: 'value'},
5789
+ },
5790
+ ],
5791
+ };
5792
+
5793
+ parser.handleMessage(message, 'setup timers');
5794
+
5795
+ // Verify timers were set by handleMessage
5796
+ expect(parser.dataSets.main.timer).to.not.be.undefined;
5797
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
5798
+
5799
+ parser.cleanUp();
5800
+
5801
+ expect(parser.state).to.equal('stopped');
5802
+ expect(parser.visibleDataSets).to.deep.equal([]);
5803
+ expect(parser.dataSets).to.deep.equal({});
5804
+ });
5805
+ });
5806
+
5807
+ describe('#syncMetrics', () => {
5808
+ it('records sync latency timestamps when sync response has empty body', async () => {
5809
+ const syncLatencyTracker = {
5810
+ saveLatency: sinon.stub(),
5811
+ saveTimestamp: sinon.stub(),
5812
+ getLocusSyncLatency: sinon.stub(),
5813
+ clearLocusSyncLatency: sinon.stub(),
5814
+ completeLocusSyncLatency: sinon.stub(),
5815
+ };
5816
+ const parser = createHashTreeParser(
5817
+ undefined,
5818
+ undefined,
5819
+ undefined,
5820
+ syncLatencyTracker
5821
+ );
5822
+ const mainDataSetUrl = parser.dataSets.main.url;
5823
+
5824
+ mockGetHashesFromLocusResponse(
5825
+ mainDataSetUrl,
5826
+ new Array(16).fill('00000000000000000000000000000000'),
5827
+ createDataSet('main', 16, 1101)
5828
+ );
5829
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
5830
+
5831
+ parser.handleMessage(
5832
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5833
+ 'trigger sync metrics'
5834
+ );
5835
+
5836
+ await clock.tickAsync(1000);
5837
+
5838
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5839
+ key: 'internal.client.locus.sync.start',
5840
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: undefined},
5841
+ });
5842
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5843
+ key: 'internal.client.locus.hashtree.request',
5844
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: undefined},
5845
+ });
5846
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5847
+ key: 'internal.client.locus.hashtree.response',
5848
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: undefined},
5849
+ });
5850
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5851
+ key: 'internal.client.locus.sync.request',
5852
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: undefined},
5853
+ });
5854
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5855
+ key: 'internal.client.locus.sync.response',
5856
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: undefined},
5857
+ });
5858
+ assert.notCalled(syncLatencyTracker.getLocusSyncLatency);
5859
+ });
5860
+
5861
+ it('clears only the failed sync record (by tracking id) when the /sync request errors', async () => {
5862
+ const syncLatencyTracker = {
5863
+ saveLatency: sinon.stub(),
5864
+ saveTimestamp: sinon.stub(),
5865
+ getLocusSyncLatency: sinon.stub(),
5866
+ clearLocusSyncLatency: sinon.stub(),
5867
+ completeLocusSyncLatency: sinon.stub(),
5868
+ };
5869
+ const generateTrackingId = sinon.stub().returns('our-sync-tracking-id');
5870
+ const parser = createHashTreeParser(
5871
+ undefined,
5872
+ undefined,
5873
+ undefined,
5874
+ syncLatencyTracker,
5875
+ undefined,
5876
+ generateTrackingId
5877
+ );
5878
+ const mainDataSetUrl = parser.dataSets.main.url;
5879
+
5880
+ // Mismatched hashes so the flow proceeds to POST /sync, which then fails.
5881
+ mockGetHashesFromLocusResponse(
5882
+ mainDataSetUrl,
5883
+ new Array(16).fill('00000000000000000000000000000000'),
5884
+ createDataSet('main', 16, 1101)
5885
+ );
5886
+ webexRequest
5887
+ .withArgs(sinon.match({method: 'POST', uri: `${mainDataSetUrl}/sync`}))
5888
+ .rejects(new Error('sync failed'));
5889
+
5890
+ parser.handleMessage(
5891
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5892
+ 'trigger sync metrics'
5893
+ );
5894
+
5895
+ await clock.tickAsync(1000);
5896
+
5897
+ // Because /sync failed, syncRequestSent stays false and the finally block drops the record,
5898
+ // passing the tracking id so only this in-progress record is removed (native onSyncError parity).
5899
+ assert.calledWithExactly(
5900
+ syncLatencyTracker.clearLocusSyncLatency,
5901
+ 'main',
5902
+ 'meeting-1',
5903
+ 'our-sync-tracking-id'
5904
+ );
5905
+ });
5906
+
5907
+ it('forces a pre-generated tracking id onto the sync request and records it', async () => {
5908
+ const syncLatencyTracker = {
5909
+ saveLatency: sinon.stub(),
5910
+ saveTimestamp: sinon.stub(),
5911
+ getLocusSyncLatency: sinon.stub(),
5912
+ clearLocusSyncLatency: sinon.stub(),
5913
+ completeLocusSyncLatency: sinon.stub(),
5914
+ };
5915
+ // two distinct tracking ids are generated: the first for the /hashtree request and the
5916
+ // second for the /sync request (which is also stored in metrics and used for LLM matching)
5917
+ const generateTrackingId = sinon.stub();
5918
+ generateTrackingId.onFirstCall().returns('our-hashtree-tracking-id');
5919
+ generateTrackingId.onSecondCall().returns('our-sync-tracking-id');
5920
+ const parser = createHashTreeParser(
5921
+ undefined,
5922
+ undefined,
5923
+ undefined,
5924
+ syncLatencyTracker,
5925
+ undefined,
5926
+ generateTrackingId
5927
+ );
5928
+ const mainDataSetUrl = parser.dataSets.main.url;
5929
+
5930
+ mockGetHashesFromLocusResponse(
5931
+ mainDataSetUrl,
5932
+ new Array(16).fill('00000000000000000000000000000000'),
5933
+ createDataSet('main', 16, 1102)
5934
+ );
5935
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
5936
+
5937
+ parser.handleMessage(
5938
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5939
+ 'trigger sync metrics'
5940
+ );
5941
+
5942
+ await clock.tickAsync(1000);
5943
+
5944
+ // two distinct tracking ids are generated up-front so the /hashtree and /sync requests do
5945
+ // not share a tracking id
5946
+ assert.calledTwice(generateTrackingId);
5947
+ // the /hashtree request carries its own (first) tracking id
5948
+ assert.calledWith(
5949
+ webexRequest,
5950
+ sinon.match({
5951
+ method: 'GET',
5952
+ uri: `${mainDataSetUrl}/hashtree`,
5953
+ headers: {trackingid: 'our-hashtree-tracking-id'},
5954
+ })
5955
+ );
5956
+ // the /sync request carries the second tracking id, which Locus echoes back on the resulting
5957
+ // LLM message so the Meeting object can match it to this sync
5958
+ assert.calledWith(
5959
+ webexRequest,
5960
+ sinon.match({
5961
+ method: 'POST',
5962
+ uri: `${mainDataSetUrl}/sync`,
5963
+ headers: {trackingid: 'our-sync-tracking-id'},
5964
+ })
5965
+ );
5966
+
5967
+ // the same tracking id is stamped on the sync milestones so the Meeting object can later
5968
+ // match the LLM event to this sync
5969
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5970
+ key: 'internal.client.locus.sync.start',
5971
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: 'our-sync-tracking-id'},
5972
+ });
5973
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5974
+ key: 'internal.client.locus.hashtree.request',
5975
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: 'our-sync-tracking-id'},
5976
+ });
5977
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5978
+ key: 'internal.client.locus.hashtree.response',
5979
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: 'our-sync-tracking-id'},
5980
+ });
5981
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5982
+ key: 'internal.client.locus.sync.request',
5983
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: 'our-sync-tracking-id'},
5984
+ });
5985
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5986
+ key: 'internal.client.locus.sync.response',
5987
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: 'our-sync-tracking-id'},
5988
+ });
5989
+ assert.notCalled(syncLatencyTracker.getLocusSyncLatency);
5990
+ });
5991
+
5992
+ it('does not complete or clear metrics when matching dataset message arrives', () => {
5993
+ const syncLatencyTracker = {
5994
+ saveLatency: sinon.stub(),
5995
+ saveTimestamp: sinon.stub(),
5996
+ getLocusSyncLatency: sinon.stub(),
5997
+ clearLocusSyncLatency: sinon.stub(),
5998
+ completeLocusSyncLatency: sinon.stub(),
5999
+ };
6000
+ const parser = createHashTreeParser(
6001
+ undefined,
6002
+ undefined,
6003
+ undefined,
6004
+ syncLatencyTracker
6005
+ );
6006
+
6007
+ parser.handleMessage({
6008
+ dataSets: [
6009
+ {
6010
+ ...createDataSet('main', 16, 1001),
6011
+ root: 'newroot',
6012
+ },
6013
+ ],
6014
+ visibleDataSetsUrl,
6015
+ locusUrl,
6016
+ locusStateElements: [],
6017
+ });
6018
+
6019
+ assert.notCalled(syncLatencyTracker.getLocusSyncLatency);
6020
+ assert.notCalled(syncLatencyTracker.clearLocusSyncLatency);
6021
+ assert.notCalled(syncLatencyTracker.completeLocusSyncLatency);
6022
+ });
6023
+
6024
+ it('does not complete sync metrics when sync response has body (completion is LLM-only)', async () => {
6025
+ const syncLatencyTracker = {
6026
+ saveLatency: sinon.stub(),
6027
+ saveTimestamp: sinon.stub(),
6028
+ getLocusSyncLatency: sinon.stub(),
6029
+ clearLocusSyncLatency: sinon.stub(),
6030
+ completeLocusSyncLatency: sinon.stub(),
6031
+ };
6032
+ const generateTrackingId = sinon.stub().returns('our-sync-tracking-id');
6033
+ const parser = createHashTreeParser(
6034
+ undefined,
6035
+ undefined,
6036
+ undefined,
6037
+ syncLatencyTracker,
6038
+ undefined,
6039
+ generateTrackingId
6040
+ );
6041
+ const mainDataSetUrl = parser.dataSets.main.url;
6042
+ const syncResponse = {
6043
+ dataSets: [
6044
+ {
6045
+ ...createDataSet('main', 16, 1102),
6046
+ root: 'newroot',
6047
+ },
6048
+ ],
6049
+ visibleDataSetsUrl,
6050
+ locusUrl,
6051
+ locusStateElements: [],
6052
+ };
6053
+
6054
+ mockGetHashesFromLocusResponse(
6055
+ mainDataSetUrl,
6056
+ new Array(16).fill('00000000000000000000000000000000'),
6057
+ createDataSet('main', 16, 1102)
6058
+ );
6059
+ mockSendSyncRequestResponse(mainDataSetUrl, syncResponse);
6060
+
6061
+ parser.handleMessage(
6062
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
6063
+ 'trigger sync metrics'
6064
+ );
6065
+
6066
+ await clock.tickAsync(1000);
6067
+
6068
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
6069
+ key: 'internal.client.locus.sync.response',
6070
+ options: {
6071
+ meetingId: 'meeting-1',
6072
+ dataSetName: 'main',
6073
+ trackingId: 'our-sync-tracking-id',
6074
+ },
6075
+ });
6076
+ // body-mode syncs return the state elements in the /sync HTTP response, but per the LLM-only
6077
+ // design the CA metric is completed solely from Meeting#processLocusLLMEvent once the matching
6078
+ // LLM message arrives. handleMessage must not record the message-received milestone nor
6079
+ // complete the metric here.
6080
+ assert.neverCalledWith(syncLatencyTracker.saveTimestamp, {
6081
+ key: 'internal.client.locus.sync.message.received',
6082
+ options: {
6083
+ meetingId: 'meeting-1',
6084
+ dataSetName: 'main',
6085
+ trackingId: 'our-sync-tracking-id',
6086
+ },
6087
+ });
6088
+ assert.notCalled(syncLatencyTracker.completeLocusSyncLatency);
6089
+ });
6090
+
3203
6091
  });
3204
6092
  });