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

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 (230) hide show
  1. package/AGENTS.md +9 -0
  2. package/dist/aiEnableRequest/index.js +15 -2
  3. package/dist/aiEnableRequest/index.js.map +1 -1
  4. package/dist/breakouts/breakout.js +8 -3
  5. package/dist/breakouts/breakout.js.map +1 -1
  6. package/dist/breakouts/index.js +26 -2
  7. package/dist/breakouts/index.js.map +1 -1
  8. package/dist/common/errors/webex-errors.js +49 -5
  9. package/dist/common/errors/webex-errors.js.map +1 -1
  10. package/dist/config.js +2 -2
  11. package/dist/config.js.map +1 -1
  12. package/dist/constants.js +35 -9
  13. package/dist/constants.js.map +1 -1
  14. package/dist/controls-options-manager/constants.js +11 -1
  15. package/dist/controls-options-manager/constants.js.map +1 -1
  16. package/dist/controls-options-manager/index.js +67 -29
  17. package/dist/controls-options-manager/index.js.map +1 -1
  18. package/dist/controls-options-manager/util.js +91 -0
  19. package/dist/controls-options-manager/util.js.map +1 -1
  20. package/dist/hashTree/constants.js +4 -1
  21. package/dist/hashTree/constants.js.map +1 -1
  22. package/dist/hashTree/hashTreeParser.js +880 -382
  23. package/dist/hashTree/hashTreeParser.js.map +1 -1
  24. package/dist/hashTree/utils.js +20 -0
  25. package/dist/hashTree/utils.js.map +1 -1
  26. package/dist/index.js +7 -0
  27. package/dist/index.js.map +1 -1
  28. package/dist/interceptors/dataChannelAuthToken.js +75 -15
  29. package/dist/interceptors/dataChannelAuthToken.js.map +1 -1
  30. package/dist/interceptors/locusRetry.js +23 -8
  31. package/dist/interceptors/locusRetry.js.map +1 -1
  32. package/dist/interpretation/index.js +10 -1
  33. package/dist/interpretation/index.js.map +1 -1
  34. package/dist/interpretation/interpretation.types.js +7 -0
  35. package/dist/interpretation/interpretation.types.js.map +1 -0
  36. package/dist/interpretation/siLanguage.js +1 -1
  37. package/dist/locus-info/controlsUtils.js +4 -1
  38. package/dist/locus-info/controlsUtils.js.map +1 -1
  39. package/dist/locus-info/index.js +401 -115
  40. package/dist/locus-info/index.js.map +1 -1
  41. package/dist/locus-info/infoUtils.js +36 -5
  42. package/dist/locus-info/infoUtils.js.map +1 -1
  43. package/dist/locus-info/types.js +19 -0
  44. package/dist/locus-info/types.js.map +1 -1
  45. package/dist/media/MediaConnectionAwaiter.js +15 -2
  46. package/dist/media/MediaConnectionAwaiter.js.map +1 -1
  47. package/dist/media/index.js +8 -2
  48. package/dist/media/index.js.map +1 -1
  49. package/dist/media/properties.js +1 -0
  50. package/dist/media/properties.js.map +1 -1
  51. package/dist/meeting/in-meeting-actions.js +5 -1
  52. package/dist/meeting/in-meeting-actions.js.map +1 -1
  53. package/dist/meeting/index.js +1389 -821
  54. package/dist/meeting/index.js.map +1 -1
  55. package/dist/meeting/locusMediaRequest.js +229 -82
  56. package/dist/meeting/locusMediaRequest.js.map +1 -1
  57. package/dist/meeting/muteState.js +10 -1
  58. package/dist/meeting/muteState.js.map +1 -1
  59. package/dist/meeting/request.js +5 -2
  60. package/dist/meeting/request.js.map +1 -1
  61. package/dist/meeting/util.js +35 -2
  62. package/dist/meeting/util.js.map +1 -1
  63. package/dist/meeting-info/meeting-info-v2.js +2 -2
  64. package/dist/meeting-info/meeting-info-v2.js.map +1 -1
  65. package/dist/meetings/index.js +231 -118
  66. package/dist/meetings/index.js.map +1 -1
  67. package/dist/meetings/meetings.types.js +6 -1
  68. package/dist/meetings/meetings.types.js.map +1 -1
  69. package/dist/meetings/request.js +39 -0
  70. package/dist/meetings/request.js.map +1 -1
  71. package/dist/meetings/util.js +116 -18
  72. package/dist/meetings/util.js.map +1 -1
  73. package/dist/member/index.js +10 -0
  74. package/dist/member/index.js.map +1 -1
  75. package/dist/member/types.js.map +1 -1
  76. package/dist/member/util.js +30 -0
  77. package/dist/member/util.js.map +1 -1
  78. package/dist/members/index.js +101 -43
  79. package/dist/members/index.js.map +1 -1
  80. package/dist/members/util.js +8 -1
  81. package/dist/members/util.js.map +1 -1
  82. package/dist/metrics/constants.js +6 -1
  83. package/dist/metrics/constants.js.map +1 -1
  84. package/dist/multistream/codec/constants.js +63 -0
  85. package/dist/multistream/codec/constants.js.map +1 -0
  86. package/dist/multistream/mediaRequestManager.js +62 -15
  87. package/dist/multistream/mediaRequestManager.js.map +1 -1
  88. package/dist/multistream/receiveSlot.js +9 -0
  89. package/dist/multistream/receiveSlot.js.map +1 -1
  90. package/dist/reachability/clusterReachability.js.map +1 -1
  91. package/dist/reachability/index.js +121 -83
  92. package/dist/reachability/index.js.map +1 -1
  93. package/dist/reachability/reachability.types.js +2 -0
  94. package/dist/reachability/reachability.types.js.map +1 -1
  95. package/dist/reachability/util.js +45 -0
  96. package/dist/reachability/util.js.map +1 -1
  97. package/dist/reactions/reactions.type.js.map +1 -1
  98. package/dist/recording-controller/index.js +1 -3
  99. package/dist/recording-controller/index.js.map +1 -1
  100. package/dist/roap/turnDiscovery.js +8 -1
  101. package/dist/roap/turnDiscovery.js.map +1 -1
  102. package/dist/types/common/errors/webex-errors.d.ts +32 -2
  103. package/dist/types/config.d.ts +2 -2
  104. package/dist/types/constants.d.ts +12 -1
  105. package/dist/types/controls-options-manager/constants.d.ts +6 -1
  106. package/dist/types/controls-options-manager/index.d.ts +16 -0
  107. package/dist/types/hashTree/constants.d.ts +1 -0
  108. package/dist/types/hashTree/hashTreeParser.d.ts +146 -17
  109. package/dist/types/hashTree/utils.d.ts +7 -0
  110. package/dist/types/index.d.ts +3 -0
  111. package/dist/types/interceptors/locusRetry.d.ts +4 -4
  112. package/dist/types/interpretation/interpretation.types.d.ts +10 -0
  113. package/dist/types/locus-info/index.d.ts +59 -6
  114. package/dist/types/locus-info/infoUtils.d.ts +8 -0
  115. package/dist/types/locus-info/types.d.ts +21 -1
  116. package/dist/types/media/MediaConnectionAwaiter.d.ts +10 -1
  117. package/dist/types/media/properties.d.ts +1 -0
  118. package/dist/types/meeting/in-meeting-actions.d.ts +4 -0
  119. package/dist/types/meeting/index.d.ts +121 -10
  120. package/dist/types/meeting/locusMediaRequest.d.ts +12 -0
  121. package/dist/types/meeting/request.d.ts +1 -0
  122. package/dist/types/meeting/util.d.ts +9 -0
  123. package/dist/types/meetings/index.d.ts +30 -18
  124. package/dist/types/meetings/meetings.types.d.ts +15 -0
  125. package/dist/types/meetings/request.d.ts +14 -0
  126. package/dist/types/member/index.d.ts +1 -0
  127. package/dist/types/member/types.d.ts +1 -0
  128. package/dist/types/member/util.d.ts +9 -0
  129. package/dist/types/members/index.d.ts +15 -2
  130. package/dist/types/members/util.d.ts +1 -5
  131. package/dist/types/metrics/constants.d.ts +5 -0
  132. package/dist/types/multistream/codec/constants.d.ts +7 -0
  133. package/dist/types/multistream/mediaRequestManager.d.ts +22 -5
  134. package/dist/types/reachability/clusterReachability.d.ts +3 -3
  135. package/dist/types/reachability/index.d.ts +10 -3
  136. package/dist/types/reachability/reachability.types.d.ts +7 -0
  137. package/dist/types/reachability/util.d.ts +17 -0
  138. package/dist/types/reactions/reactions.type.d.ts +3 -0
  139. package/dist/webinar/index.js +305 -159
  140. package/dist/webinar/index.js.map +1 -1
  141. package/package.json +22 -22
  142. package/src/aiEnableRequest/index.ts +16 -0
  143. package/src/breakouts/breakout.ts +3 -1
  144. package/src/breakouts/index.ts +31 -0
  145. package/src/common/errors/webex-errors.ts +50 -3
  146. package/src/config.ts +2 -2
  147. package/src/constants.ts +20 -3
  148. package/src/controls-options-manager/constants.ts +14 -1
  149. package/src/controls-options-manager/index.ts +87 -28
  150. package/src/controls-options-manager/util.ts +81 -1
  151. package/src/hashTree/constants.ts +7 -0
  152. package/src/hashTree/hashTreeParser.ts +578 -193
  153. package/src/hashTree/utils.ts +19 -0
  154. package/src/index.ts +6 -0
  155. package/src/interceptors/dataChannelAuthToken.ts +88 -12
  156. package/src/interceptors/locusRetry.ts +25 -4
  157. package/src/interpretation/index.ts +27 -9
  158. package/src/interpretation/interpretation.types.ts +11 -0
  159. package/src/locus-info/controlsUtils.ts +3 -1
  160. package/src/locus-info/index.ts +415 -136
  161. package/src/locus-info/infoUtils.ts +41 -6
  162. package/src/locus-info/types.ts +25 -1
  163. package/src/media/MediaConnectionAwaiter.ts +21 -4
  164. package/src/media/index.ts +10 -1
  165. package/src/media/properties.ts +1 -0
  166. package/src/meeting/in-meeting-actions.ts +8 -0
  167. package/src/meeting/index.ts +644 -98
  168. package/src/meeting/locusMediaRequest.ts +106 -6
  169. package/src/meeting/muteState.ts +10 -1
  170. package/src/meeting/request.ts +11 -0
  171. package/src/meeting/util.ts +47 -5
  172. package/src/meeting-info/meeting-info-v2.ts +4 -2
  173. package/src/meetings/index.ts +133 -78
  174. package/src/meetings/meetings.types.ts +19 -0
  175. package/src/meetings/request.ts +43 -0
  176. package/src/meetings/util.ts +117 -4
  177. package/src/member/index.ts +10 -0
  178. package/src/member/types.ts +1 -0
  179. package/src/member/util.ts +29 -0
  180. package/src/members/index.ts +70 -7
  181. package/src/members/util.ts +12 -4
  182. package/src/metrics/constants.ts +5 -0
  183. package/src/multistream/codec/constants.ts +58 -0
  184. package/src/multistream/mediaRequestManager.ts +119 -28
  185. package/src/multistream/receiveSlot.ts +18 -0
  186. package/src/reachability/clusterReachability.ts +3 -2
  187. package/src/reachability/index.ts +47 -16
  188. package/src/reachability/reachability.types.ts +11 -0
  189. package/src/reachability/util.ts +36 -0
  190. package/src/reactions/reactions.type.ts +3 -0
  191. package/src/recording-controller/index.ts +1 -2
  192. package/src/roap/turnDiscovery.ts +9 -1
  193. package/src/webinar/index.ts +214 -36
  194. package/test/unit/spec/aiEnableRequest/index.ts +86 -0
  195. package/test/unit/spec/breakouts/breakout.ts +9 -3
  196. package/test/unit/spec/breakouts/index.ts +49 -0
  197. package/test/unit/spec/common/errors/webex-errors.ts +78 -0
  198. package/test/unit/spec/controls-options-manager/index.js +244 -29
  199. package/test/unit/spec/controls-options-manager/util.js +165 -0
  200. package/test/unit/spec/hashTree/hashTreeParser.ts +1848 -318
  201. package/test/unit/spec/hashTree/utils.ts +37 -0
  202. package/test/unit/spec/interceptors/dataChannelAuthToken.ts +196 -0
  203. package/test/unit/spec/interceptors/locusRetry.ts +205 -4
  204. package/test/unit/spec/interpretation/index.ts +26 -4
  205. package/test/unit/spec/locus-info/controlsUtils.js +172 -57
  206. package/test/unit/spec/locus-info/index.js +645 -80
  207. package/test/unit/spec/locus-info/infoUtils.js +184 -1
  208. package/test/unit/spec/media/MediaConnectionAwaiter.ts +55 -0
  209. package/test/unit/spec/media/index.ts +92 -0
  210. package/test/unit/spec/meeting/in-meeting-actions.ts +4 -0
  211. package/test/unit/spec/meeting/index.js +2119 -98
  212. package/test/unit/spec/meeting/locusMediaRequest.ts +406 -4
  213. package/test/unit/spec/meeting/muteState.js +81 -0
  214. package/test/unit/spec/meeting/request.js +12 -0
  215. package/test/unit/spec/meeting/utils.js +157 -1
  216. package/test/unit/spec/meeting-info/meetinginfov2.js +19 -10
  217. package/test/unit/spec/meetings/index.js +363 -36
  218. package/test/unit/spec/meetings/request.js +141 -0
  219. package/test/unit/spec/meetings/utils.js +402 -51
  220. package/test/unit/spec/member/index.js +7 -0
  221. package/test/unit/spec/member/util.js +89 -0
  222. package/test/unit/spec/members/index.js +216 -0
  223. package/test/unit/spec/members/request.js +37 -1
  224. package/test/unit/spec/members/utils.js +63 -0
  225. package/test/unit/spec/multistream/mediaRequestManager.ts +501 -37
  226. package/test/unit/spec/reachability/index.ts +128 -46
  227. package/test/unit/spec/reachability/util.ts +31 -0
  228. package/test/unit/spec/recording-controller/index.js +9 -8
  229. package/test/unit/spec/roap/turnDiscovery.ts +20 -0
  230. package/test/unit/spec/webinar/index.ts +329 -28
@@ -1,12 +1,18 @@
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';
10
16
 
11
17
  const visibleDataSetsUrl = 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/visibleDataSets';
12
18
 
@@ -111,6 +117,7 @@ function createDataSet(name: string, leafCount: number, version = 1) {
111
117
  name,
112
118
  idleMs: 1000,
113
119
  backoff: {maxMs: 1000, exponent: 2},
120
+ heartbeatIntervalMs: 5000,
114
121
  };
115
122
  }
116
123
 
@@ -151,16 +158,19 @@ describe('HashTreeParser', () => {
151
158
  let webexRequest: sinon.SinonStub;
152
159
  let callback: sinon.SinonStub;
153
160
  let mathRandomStub: sinon.SinonStub;
161
+ let metricsStub: sinon.SinonStub;
154
162
 
155
163
  beforeEach(() => {
156
164
  clock = sinon.useFakeTimers();
157
165
  webexRequest = sinon.stub();
158
166
  callback = sinon.stub();
159
167
  mathRandomStub = sinon.stub(Math, 'random').returns(0);
168
+ metricsStub = sinon.stub(Metrics, 'sendBehavioralMetric');
160
169
  });
161
170
  afterEach(() => {
162
171
  clock.restore();
163
172
  mathRandomStub.restore();
173
+ metricsStub.restore();
164
174
  });
165
175
 
166
176
  // Helper to create a HashTreeParser instance with common defaults
@@ -553,8 +563,7 @@ describe('HashTreeParser', () => {
553
563
  );
554
564
 
555
565
  // Verify callback was called with OBJECTS_UPDATED and correct updatedObjects list
556
- // Note: main is initialized before self due to sortByInitPriority
557
- assert.calledWith(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
566
+ assert.calledWith(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
558
567
  updatedObjects: [
559
568
  {
560
569
  htMeta: {
@@ -567,6 +576,11 @@ describe('HashTreeParser', () => {
567
576
  },
568
577
  data: {info: {id: 'some-fake-locus-info'}},
569
578
  },
579
+ ],
580
+ });
581
+
582
+ assert.calledWith(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
583
+ updatedObjects: [
570
584
  {
571
585
  htMeta: {
572
586
  elementId: {
@@ -632,6 +646,32 @@ describe('HashTreeParser', () => {
632
646
  expect(syncCalls[2].args[0].uri).to.equal(`${atdActiveDataSet.url}/sync`);
633
647
  });
634
648
 
649
+ it('sends leafCount=1 with a single empty leaf for initialization sync, regardless of actual dataset leafCount', async () => {
650
+ const parser = createHashTreeParser({dataSets: [], locus: null}, null);
651
+
652
+ // Use a dataset with leafCount=16 to verify the initialization sync always uses leafCount=1
653
+ const mainDataSet = createDataSet('main', 16, 1100);
654
+
655
+ mockGetAllDataSetsMetadata(webexRequest, visibleDataSetsUrl, [mainDataSet]);
656
+ mockSyncRequest(webexRequest, mainDataSet.url);
657
+
658
+ await parser.initializeFromMessage({
659
+ dataSets: [],
660
+ visibleDataSetsUrl,
661
+ locusUrl,
662
+ });
663
+
664
+ assert.calledWith(webexRequest, {
665
+ method: 'POST',
666
+ uri: `${mainDataSet.url}/sync`,
667
+ qs: {rootHash: sinon.match.string},
668
+ body: {
669
+ leafCount: 1,
670
+ leafDataEntries: [{leafIndex: 0, elementIds: []}],
671
+ },
672
+ });
673
+ });
674
+
635
675
  it('handles sync response that has locusStateElements undefined', async () => {
636
676
  const minimalInitialLocus = {
637
677
  dataSets: [],
@@ -672,8 +712,11 @@ describe('HashTreeParser', () => {
672
712
  assert.notCalled(callback);
673
713
  });
674
714
 
675
- [404, 409].forEach((errorCode) => {
676
- it(`emits MeetingEndedError if getting visible datasets returns ${errorCode}`, async () => {
715
+ [
716
+ {errorCode: 404, expectedError: LocusNotFoundError},
717
+ {errorCode: 409, expectedError: MeetingEndedError},
718
+ ].forEach(({errorCode, expectedError}) => {
719
+ it(`throws ${expectedError.name} if getting visible datasets returns ${errorCode}`, async () => {
677
720
  const minimalInitialLocus = {
678
721
  dataSets: [],
679
722
  locus: null,
@@ -696,7 +739,6 @@ describe('HashTreeParser', () => {
696
739
  )
697
740
  .rejects(error);
698
741
 
699
- // initializeFromMessage should throw MeetingEndedError
700
742
  let thrownError;
701
743
  try {
702
744
  await parser.initializeFromMessage({
@@ -708,7 +750,7 @@ describe('HashTreeParser', () => {
708
750
  thrownError = e;
709
751
  }
710
752
 
711
- expect(thrownError).to.be.instanceOf(MeetingEndedError);
753
+ expect(thrownError).to.be.instanceOf(expectedError);
712
754
  });
713
755
  });
714
756
  });
@@ -824,7 +866,7 @@ describe('HashTreeParser', () => {
824
866
  expect(parser.dataSets.self.version).to.equal(2100);
825
867
  expect(parser.dataSets['atd-unmuted'].version).to.equal(3100);
826
868
 
827
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
869
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
828
870
  updatedObjects: [
829
871
  {
830
872
  htMeta: {
@@ -955,7 +997,7 @@ describe('HashTreeParser', () => {
955
997
  {type: 'ControlEntry', id: 10101, version: 100}
956
998
  ]);
957
999
 
958
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
1000
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
959
1001
  updatedObjects: [
960
1002
  {
961
1003
  htMeta: {
@@ -1045,7 +1087,7 @@ describe('HashTreeParser', () => {
1045
1087
  assert.calledOnceWithExactly(mainPutItemsSpy, [{type: 'locus', id: 0, version: 201}]);
1046
1088
 
1047
1089
  // Verify callback was called only for known dataset
1048
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
1090
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
1049
1091
  updatedObjects: [
1050
1092
  {
1051
1093
  htMeta: {
@@ -1145,7 +1187,7 @@ describe('HashTreeParser', () => {
1145
1187
  assert.calledOnceWithExactly(selfPutItemSpy, {type: 'metadata', id: 5, version: 51});
1146
1188
 
1147
1189
  // Verify callback was called with metadata object and removed dataset objects
1148
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
1190
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
1149
1191
  updatedObjects: [
1150
1192
  // updated metadata object:
1151
1193
  {
@@ -1306,7 +1348,7 @@ describe('HashTreeParser', () => {
1306
1348
  assert.notCalled(atdUnmutedPutItemsSpy);
1307
1349
 
1308
1350
  // Verify callback was called with the updated object
1309
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
1351
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
1310
1352
  updatedObjects: [
1311
1353
  {
1312
1354
  htMeta: {
@@ -1534,7 +1576,7 @@ describe('HashTreeParser', () => {
1534
1576
  ]);
1535
1577
 
1536
1578
  // Verify callback was called with OBJECTS_UPDATED and all updated objects
1537
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
1579
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
1538
1580
  updatedObjects: [
1539
1581
  {
1540
1582
  htMeta: {
@@ -1599,9 +1641,7 @@ describe('HashTreeParser', () => {
1599
1641
  parser.handleMessage(sentinelMessage, 'sentinel message');
1600
1642
 
1601
1643
  // Verify callback was called with MEETING_ENDED
1602
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.MEETING_ENDED, {
1603
- updatedObjects: undefined,
1604
- });
1644
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.MEETING_ENDED});
1605
1645
 
1606
1646
  // Verify that all timers were stopped
1607
1647
  Object.values(parser.dataSets).forEach((ds: any) => {
@@ -1623,9 +1663,7 @@ describe('HashTreeParser', () => {
1623
1663
  parser.handleMessage(sentinelMessage, 'sentinel message');
1624
1664
 
1625
1665
  // Verify callback was called with MEETING_ENDED
1626
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.MEETING_ENDED, {
1627
- updatedObjects: undefined,
1628
- });
1666
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.MEETING_ENDED});
1629
1667
 
1630
1668
  // Verify that all timers were stopped
1631
1669
  Object.values(parser.dataSets).forEach((ds: any) => {
@@ -1721,7 +1759,7 @@ describe('HashTreeParser', () => {
1721
1759
  );
1722
1760
 
1723
1761
  // Verify that callback was called with synced objects
1724
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
1762
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
1725
1763
  updatedObjects: [
1726
1764
  {
1727
1765
  htMeta: {
@@ -1734,12 +1772,10 @@ describe('HashTreeParser', () => {
1734
1772
  });
1735
1773
  });
1736
1774
 
1737
- describe('emits MEETING_ENDED', () => {
1738
- [404, 409].forEach((statusCode) => {
1739
- it(`when /hashtree returns ${statusCode}`, async () => {
1775
+ describe('emits MEETING_ENDED when 409/2403004 is returned', () => {
1776
+ it('when /hashtree returns 409', async () => {
1740
1777
  const parser = createHashTreeParser();
1741
1778
 
1742
- // Send a message to trigger sync algorithm
1743
1779
  const message = {
1744
1780
  dataSets: [createDataSet('main', 16, 1100)],
1745
1781
  visibleDataSetsUrl,
@@ -1764,12 +1800,9 @@ describe('HashTreeParser', () => {
1764
1800
 
1765
1801
  const mainDataSetUrl = parser.dataSets.main.url;
1766
1802
 
1767
- // Mock getHashesFromLocus to reject with the sentinel error
1768
- const error: any = new Error(`Request failed with status ${statusCode}`);
1769
- error.statusCode = statusCode;
1770
- if (statusCode === 409) {
1771
- error.body = {errorCode: 2403004};
1772
- }
1803
+ const error: any = new Error('Request failed with status 409');
1804
+ error.statusCode = 409;
1805
+ error.body = {errorCode: 2403004};
1773
1806
  webexRequest
1774
1807
  .withArgs(
1775
1808
  sinon.match({
@@ -1779,13 +1812,120 @@ describe('HashTreeParser', () => {
1779
1812
  )
1780
1813
  .rejects(error);
1781
1814
 
1782
- // Trigger sync by advancing time
1783
1815
  await clock.tickAsync(1000);
1784
1816
 
1785
- // Verify callback was called with MEETING_ENDED
1786
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.MEETING_ENDED, {
1787
- updatedObjects: undefined,
1817
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.MEETING_ENDED});
1818
+
1819
+ Object.values(parser.dataSets).forEach((ds: any) => {
1820
+ assert.isUndefined(ds.timer);
1821
+ assert.isUndefined(ds.heartbeatWatchdogTimer);
1822
+ });
1823
+
1824
+ // Verify no sync failure metric was sent for end-meeting sentinel
1825
+ assert.notCalled(metricsStub);
1826
+ });
1827
+
1828
+ it('when /sync returns 409', async () => {
1829
+ const parser = createHashTreeParser();
1830
+
1831
+ const message = {
1832
+ dataSets: [createDataSet('main', 16, 1100)],
1833
+ visibleDataSetsUrl,
1834
+ locusUrl,
1835
+ locusStateElements: [
1836
+ {
1837
+ htMeta: {
1838
+ elementId: {
1839
+ type: 'locus' as const,
1840
+ id: 0,
1841
+ version: 201,
1842
+ },
1843
+ dataSetNames: ['main'],
1844
+ },
1845
+ data: {info: {id: 'initial-update'}},
1846
+ },
1847
+ ],
1848
+ };
1849
+
1850
+ parser.handleMessage(message, 'initial message');
1851
+ callback.resetHistory();
1852
+
1853
+ const mainDataSetUrl = parser.dataSets.main.url;
1854
+
1855
+ mockGetHashesFromLocusResponse(
1856
+ mainDataSetUrl,
1857
+ new Array(16).fill('00000000000000000000000000000000'),
1858
+ createDataSet('main', 16, 1101)
1859
+ );
1860
+
1861
+ const error: any = new Error('Request failed with status 409');
1862
+ error.statusCode = 409;
1863
+ error.body = {errorCode: 2403004};
1864
+ webexRequest
1865
+ .withArgs(
1866
+ sinon.match({
1867
+ method: 'POST',
1868
+ uri: `${mainDataSetUrl}/sync`,
1869
+ })
1870
+ )
1871
+ .rejects(error);
1872
+
1873
+ await clock.tickAsync(1000);
1874
+
1875
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.MEETING_ENDED});
1876
+
1877
+ Object.values(parser.dataSets).forEach((ds: any) => {
1878
+ assert.isUndefined(ds.timer);
1879
+ assert.isUndefined(ds.heartbeatWatchdogTimer);
1788
1880
  });
1881
+ });
1882
+ });
1883
+
1884
+ describe('emits LOCUS_NOT_FOUND and stops parser when 404 is returned', () => {
1885
+ it('when /hashtree returns 404', async () => {
1886
+ const parser = createHashTreeParser();
1887
+
1888
+ const message = {
1889
+ dataSets: [createDataSet('main', 16, 1100)],
1890
+ visibleDataSetsUrl,
1891
+ locusUrl,
1892
+ locusStateElements: [
1893
+ {
1894
+ htMeta: {
1895
+ elementId: {
1896
+ type: 'locus' as const,
1897
+ id: 0,
1898
+ version: 201,
1899
+ },
1900
+ dataSetNames: ['main'],
1901
+ },
1902
+ data: {info: {id: 'initial-update'}},
1903
+ },
1904
+ ],
1905
+ };
1906
+
1907
+ parser.handleMessage(message, 'initial message');
1908
+ callback.resetHistory();
1909
+
1910
+ const mainDataSetUrl = parser.dataSets.main.url;
1911
+
1912
+ const error: any = new Error('Request failed with status 404');
1913
+ error.statusCode = 404;
1914
+ webexRequest
1915
+ .withArgs(
1916
+ sinon.match({
1917
+ method: 'GET',
1918
+ uri: `${mainDataSetUrl}/hashtree`,
1919
+ })
1920
+ )
1921
+ .rejects(error);
1922
+
1923
+ await clock.tickAsync(1000);
1924
+
1925
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.LOCUS_NOT_FOUND});
1926
+
1927
+ // Verify parser is stopped
1928
+ expect(parser.state).to.equal('stopped');
1789
1929
 
1790
1930
  // Verify all timers are stopped
1791
1931
  Object.values(parser.dataSets).forEach((ds: any) => {
@@ -1794,10 +1934,9 @@ describe('HashTreeParser', () => {
1794
1934
  });
1795
1935
  });
1796
1936
 
1797
- it(`when /sync returns ${statusCode}`, async () => {
1937
+ it('when /sync returns 404', async () => {
1798
1938
  const parser = createHashTreeParser();
1799
1939
 
1800
- // Send a message to trigger sync algorithm
1801
1940
  const message = {
1802
1941
  dataSets: [createDataSet('main', 16, 1100)],
1803
1942
  visibleDataSetsUrl,
@@ -1822,19 +1961,14 @@ describe('HashTreeParser', () => {
1822
1961
 
1823
1962
  const mainDataSetUrl = parser.dataSets.main.url;
1824
1963
 
1825
- // Mock getHashesFromLocus to succeed
1826
1964
  mockGetHashesFromLocusResponse(
1827
1965
  mainDataSetUrl,
1828
1966
  new Array(16).fill('00000000000000000000000000000000'),
1829
1967
  createDataSet('main', 16, 1101)
1830
1968
  );
1831
1969
 
1832
- // Mock sendSyncRequestToLocus to reject with the sentinel error
1833
- const error: any = new Error(`Request failed with status ${statusCode}`);
1834
- error.statusCode = statusCode;
1835
- if (statusCode === 409) {
1836
- error.body = {errorCode: 2403004};
1837
- }
1970
+ const error: any = new Error('Request failed with status 404');
1971
+ error.statusCode = 404;
1838
1972
  webexRequest
1839
1973
  .withArgs(
1840
1974
  sinon.match({
@@ -1844,21 +1978,22 @@ describe('HashTreeParser', () => {
1844
1978
  )
1845
1979
  .rejects(error);
1846
1980
 
1847
- // Trigger sync by advancing time
1848
1981
  await clock.tickAsync(1000);
1849
1982
 
1850
- // Verify callback was called with MEETING_ENDED
1851
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.MEETING_ENDED, {
1852
- updatedObjects: undefined,
1853
- });
1983
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.LOCUS_NOT_FOUND});
1984
+
1985
+ // Verify parser is stopped
1986
+ expect(parser.state).to.equal('stopped');
1854
1987
 
1855
1988
  // Verify all timers are stopped
1856
1989
  Object.values(parser.dataSets).forEach((ds: any) => {
1857
1990
  assert.isUndefined(ds.timer);
1858
1991
  assert.isUndefined(ds.heartbeatWatchdogTimer);
1859
1992
  });
1993
+
1994
+ // Verify no sync failure metric was sent for end-meeting sentinel
1995
+ assert.notCalled(metricsStub);
1860
1996
  });
1861
- });
1862
1997
  });
1863
1998
 
1864
1999
  it('requests only mismatched hashes during sync', async () => {
@@ -2029,129 +2164,349 @@ describe('HashTreeParser', () => {
2029
2164
  },
2030
2165
  });
2031
2166
  });
2032
- });
2033
2167
 
2034
- describe('handles visible data sets changes correctly', () => {
2035
- it('handles addition of visible data set (one that does not require async initialization)', async () => {
2036
- // Create a parser with visible datasets
2168
+ it('restarts the sync timer when sync response is empty so that a future sync can be triggered', async () => {
2037
2169
  const parser = createHashTreeParser();
2038
2170
 
2039
- // Stub updateItems on self hash tree to return true
2040
- sinon.stub(parser.dataSets.self.hashTree, 'updateItems').returns([true]);
2041
-
2042
- // Send a message with Metadata object that has a new visibleDataSets list
2043
- const message = {
2044
- dataSets: [createDataSet('self', 1, 2100), createDataSet('attendees', 8, 4000)],
2045
- visibleDataSetsUrl,
2046
- locusUrl,
2047
- locusStateElements: [
2171
+ // Send a heartbeat with a mismatched root hash to trigger runSyncAlgorithm
2172
+ const heartbeatMessage = {
2173
+ dataSets: [
2048
2174
  {
2049
- htMeta: {
2050
- elementId: {
2051
- type: 'metadata' as const,
2052
- id: 5,
2053
- version: 51,
2054
- },
2055
- dataSetNames: ['self'],
2056
- },
2057
- data: {
2058
- visibleDataSets: [
2059
- {
2060
- name: 'main',
2061
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/main',
2062
- },
2063
- {
2064
- name: 'self',
2065
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self',
2066
- },
2067
- {
2068
- name: 'atd-unmuted',
2069
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted',
2070
- },
2071
- {
2072
- name: 'attendees',
2073
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/attendees',
2074
- },
2075
- ], // added 'attendees'
2076
- },
2175
+ ...createDataSet('main', 16, 1100),
2176
+ root: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1', // different from ours
2077
2177
  },
2078
2178
  ],
2179
+ visibleDataSetsUrl,
2180
+ locusUrl,
2079
2181
  };
2080
2182
 
2081
- parser.handleMessage(message, 'add visible dataset');
2183
+ parser.handleMessage(heartbeatMessage, 'heartbeat with mismatch');
2082
2184
 
2083
- // Verify that 'attendees' was added to visibleDataSets
2084
- expect(parser.visibleDataSets.some((vds) => vds.name === 'attendees')).to.be.true;
2185
+ // The sync timer should be set
2186
+ expect(parser.dataSets.main.timer).to.not.be.undefined;
2085
2187
 
2086
- // Verify that a hash tree was created for 'attendees'
2087
- assert.exists(parser.dataSets.attendees.hashTree);
2088
- assert.equal(parser.dataSets.attendees.hashTree.numLeaves, 8);
2188
+ // Mock responses for the first sync - return null (204/empty body)
2189
+ const mainDataSetUrl = parser.dataSets.main.url;
2190
+ mockGetHashesFromLocusResponse(
2191
+ mainDataSetUrl,
2192
+ new Array(16).fill('00000000000000000000000000000000'),
2193
+ {
2194
+ ...createDataSet('main', 16, 1101),
2195
+ root: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', // still mismatched
2196
+ }
2197
+ );
2198
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
2089
2199
 
2090
- // Verify callback was called with the metadata update (appears twice - processed once for visible dataset changes, once in main loop)
2091
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
2092
- updatedObjects: [
2093
- {
2094
- htMeta: {
2095
- elementId: {type: 'metadata', id: 5, version: 51},
2096
- dataSetNames: ['self'],
2097
- },
2098
- data: {
2099
- visibleDataSets: [
2100
- {
2101
- name: 'main',
2102
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/main',
2103
- },
2104
- {
2105
- name: 'self',
2106
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self',
2107
- },
2108
- {
2109
- name: 'atd-unmuted',
2110
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted',
2111
- },
2112
- {
2113
- name: 'attendees',
2114
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/attendees',
2115
- },
2116
- ],
2117
- },
2118
- },
2119
- {
2120
- htMeta: {
2121
- elementId: {type: 'metadata', id: 5, version: 51},
2122
- dataSetNames: ['self'],
2123
- },
2124
- data: {
2125
- visibleDataSets: [
2126
- {
2127
- name: 'main',
2128
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/main',
2129
- },
2130
- {
2131
- name: 'self',
2132
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self',
2133
- },
2134
- {
2135
- name: 'atd-unmuted',
2136
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted',
2137
- },
2138
- {
2139
- name: 'attendees',
2140
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/attendees',
2141
- },
2142
- ],
2143
- },
2144
- },
2145
- ],
2146
- });
2147
- });
2200
+ // Advance time to fire the sync timer (idleMs=1000 + backoff=0)
2201
+ await clock.tickAsync(1000);
2148
2202
 
2149
- it('handles addition of visible data set (one that requires async initialization)', async () => {
2150
- // Create a parser with visible datasets
2151
- const parser = createHashTreeParser();
2203
+ // Verify sync was triggered
2204
+ assert.calledWith(
2205
+ webexRequest,
2206
+ sinon.match({
2207
+ method: 'POST',
2208
+ uri: `${mainDataSetUrl}/sync`,
2209
+ })
2210
+ );
2152
2211
 
2153
- // Stub updateItems on self hash tree to return true
2154
- sinon.stub(parser.dataSets.self.hashTree, 'updateItems').returns([true]);
2212
+ // After empty response, runSyncAlgorithm should have been called,
2213
+ // setting a new sync timer as a safety net
2214
+ expect(parser.dataSets.main.timer).to.not.be.undefined;
2215
+
2216
+ // Reset and set up mocks for the second sync
2217
+ webexRequest.resetHistory();
2218
+ mockGetHashesFromLocusResponse(
2219
+ mainDataSetUrl,
2220
+ new Array(16).fill('00000000000000000000000000000000'),
2221
+ {
2222
+ ...createDataSet('main', 16, 1102),
2223
+ root: 'cccccccccccccccccccccccccccccccc', // still mismatched
2224
+ }
2225
+ );
2226
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
2227
+
2228
+ // Advance time again to fire the second sync timer
2229
+ await clock.tickAsync(1000);
2230
+
2231
+ // Verify a second sync was triggered
2232
+ assert.calledWith(
2233
+ webexRequest,
2234
+ sinon.match({
2235
+ method: 'POST',
2236
+ uri: `${mainDataSetUrl}/sync`,
2237
+ })
2238
+ );
2239
+ });
2240
+
2241
+ it('updates dataSet.leafCount when hash tree is resized during sync so that the sync request has the correct leafCount', async () => {
2242
+ const parser = createHashTreeParser();
2243
+
2244
+ // Send a heartbeat with a mismatched root hash to trigger runSyncAlgorithm
2245
+ const heartbeatMessage = {
2246
+ dataSets: [
2247
+ {
2248
+ ...createDataSet('main', 16, 1100),
2249
+ root: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1', // different from ours
2250
+ },
2251
+ ],
2252
+ visibleDataSetsUrl,
2253
+ locusUrl,
2254
+ };
2255
+
2256
+ parser.handleMessage(heartbeatMessage, 'heartbeat with mismatch');
2257
+
2258
+ // The sync timer should be set
2259
+ expect(parser.dataSets.main.timer).to.not.be.undefined;
2260
+
2261
+ const mainDataSetUrl = parser.dataSets.main.url;
2262
+ const newLeafCount = 32;
2263
+
2264
+ // Mock getHashesFromLocus response with a DIFFERENT leafCount (32 instead of 16)
2265
+ mockGetHashesFromLocusResponse(
2266
+ mainDataSetUrl,
2267
+ new Array(newLeafCount).fill('00000000000000000000000000000000'),
2268
+ createDataSet('main', newLeafCount, 1101)
2269
+ );
2270
+
2271
+ // Mock the sync request - use matching root hash
2272
+ const syncResponseDataSet = createDataSet('main', newLeafCount, 1102);
2273
+ syncResponseDataSet.root = parser.dataSets.main.hashTree.getRootHash();
2274
+ mockSendSyncRequestResponse(mainDataSetUrl, {
2275
+ dataSets: [syncResponseDataSet],
2276
+ visibleDataSetsUrl,
2277
+ locusUrl,
2278
+ locusStateElements: [],
2279
+ });
2280
+
2281
+ // Advance time to fire the sync timer (idleMs=1000 + backoff=0)
2282
+ await clock.tickAsync(1000);
2283
+
2284
+ // Verify the sync request was sent with the NEW leafCount (32), not the old one (16)
2285
+ assert.calledWith(
2286
+ webexRequest,
2287
+ sinon.match({
2288
+ method: 'POST',
2289
+ uri: `${mainDataSetUrl}/sync`,
2290
+ body: sinon.match({
2291
+ leafCount: newLeafCount,
2292
+ }),
2293
+ })
2294
+ );
2295
+ });
2296
+
2297
+ it('sends HASH_TREE_SYNC_FAILURE metric when GET /hashtree request fails', async () => {
2298
+ const parser = createHashTreeParser();
2299
+
2300
+ // Send a heartbeat with a mismatched root hash to trigger runSyncAlgorithm
2301
+ const heartbeatMessage = {
2302
+ dataSets: [
2303
+ {
2304
+ ...createDataSet('main', 16, 1100),
2305
+ root: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1',
2306
+ },
2307
+ ],
2308
+ visibleDataSetsUrl,
2309
+ locusUrl,
2310
+ };
2311
+
2312
+ parser.handleMessage(heartbeatMessage, 'heartbeat with mismatch');
2313
+
2314
+ const mainDataSetUrl = parser.dataSets.main.url;
2315
+ const hashTreeError = new Error('server error') as any;
2316
+ hashTreeError.statusCode = 500;
2317
+
2318
+ webexRequest
2319
+ .withArgs(
2320
+ sinon.match({
2321
+ method: 'GET',
2322
+ uri: `${mainDataSetUrl}/hashtree`,
2323
+ })
2324
+ )
2325
+ .rejects(hashTreeError);
2326
+
2327
+ await clock.tickAsync(1000);
2328
+
2329
+ assert.calledOnceWithExactly(metricsStub, BEHAVIORAL_METRICS.HASH_TREE_SYNC_FAILURE, {
2330
+ debugId: 'test',
2331
+ dataSetName: 'main',
2332
+ request: 'GET /hashtree',
2333
+ statusCode: 500,
2334
+ reason: 'server error',
2335
+ });
2336
+ });
2337
+
2338
+ it('sends HASH_TREE_SYNC_FAILURE metric when POST /sync request fails', async () => {
2339
+ const parser = createHashTreeParser();
2340
+
2341
+ // Send a heartbeat with a mismatched root hash to trigger runSyncAlgorithm
2342
+ const heartbeatMessage = {
2343
+ dataSets: [
2344
+ {
2345
+ ...createDataSet('main', 16, 1100),
2346
+ root: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1',
2347
+ },
2348
+ ],
2349
+ visibleDataSetsUrl,
2350
+ locusUrl,
2351
+ };
2352
+
2353
+ parser.handleMessage(heartbeatMessage, 'heartbeat with mismatch');
2354
+
2355
+ const mainDataSetUrl = parser.dataSets.main.url;
2356
+
2357
+ // Mock getHashesFromLocus to succeed
2358
+ mockGetHashesFromLocusResponse(
2359
+ mainDataSetUrl,
2360
+ new Array(16).fill('00000000000000000000000000000000'),
2361
+ createDataSet('main', 16, 1101)
2362
+ );
2363
+
2364
+ // Mock sendSyncRequestToLocus to fail
2365
+ const syncError = new Error('sync failed') as any;
2366
+ syncError.statusCode = 500;
2367
+
2368
+ webexRequest
2369
+ .withArgs(
2370
+ sinon.match({
2371
+ method: 'POST',
2372
+ uri: `${mainDataSetUrl}/sync`,
2373
+ })
2374
+ )
2375
+ .rejects(syncError);
2376
+
2377
+ await clock.tickAsync(1000);
2378
+
2379
+ assert.calledOnceWithExactly(metricsStub, BEHAVIORAL_METRICS.HASH_TREE_SYNC_FAILURE, {
2380
+ debugId: 'test',
2381
+ dataSetName: 'main',
2382
+ request: 'POST /sync',
2383
+ statusCode: 500,
2384
+ reason: 'sync failed',
2385
+ });
2386
+ });
2387
+ });
2388
+
2389
+ describe('handles visible data sets changes correctly', () => {
2390
+ it('handles addition of visible data set (one that does not require async initialization)', async () => {
2391
+ // Create a parser with visible datasets
2392
+ const parser = createHashTreeParser();
2393
+
2394
+ // Stub updateItems on self hash tree to return true
2395
+ sinon.stub(parser.dataSets.self.hashTree, 'updateItems').returns([true]);
2396
+
2397
+ // Send a message with Metadata object that has a new visibleDataSets list
2398
+ const message = {
2399
+ dataSets: [createDataSet('self', 1, 2100), createDataSet('attendees', 8, 4000)],
2400
+ visibleDataSetsUrl,
2401
+ locusUrl,
2402
+ locusStateElements: [
2403
+ {
2404
+ htMeta: {
2405
+ elementId: {
2406
+ type: 'metadata' as const,
2407
+ id: 5,
2408
+ version: 51,
2409
+ },
2410
+ dataSetNames: ['self'],
2411
+ },
2412
+ data: {
2413
+ visibleDataSets: [
2414
+ {
2415
+ name: 'main',
2416
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/main',
2417
+ },
2418
+ {
2419
+ name: 'self',
2420
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self',
2421
+ },
2422
+ {
2423
+ name: 'atd-unmuted',
2424
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted',
2425
+ },
2426
+ {
2427
+ name: 'attendees',
2428
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/attendees',
2429
+ },
2430
+ ], // added 'attendees'
2431
+ },
2432
+ },
2433
+ ],
2434
+ };
2435
+
2436
+ parser.handleMessage(message, 'add visible dataset');
2437
+
2438
+ // Verify that 'attendees' was added to visibleDataSets
2439
+ expect(parser.visibleDataSets.some((vds) => vds.name === 'attendees')).to.be.true;
2440
+
2441
+ // Verify that a hash tree was created for 'attendees'
2442
+ assert.exists(parser.dataSets.attendees.hashTree);
2443
+ assert.equal(parser.dataSets.attendees.hashTree.numLeaves, 8);
2444
+
2445
+ // Verify callback was called with the metadata update (appears twice - processed once for visible dataset changes, once in main loop)
2446
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
2447
+ updatedObjects: [
2448
+ {
2449
+ htMeta: {
2450
+ elementId: {type: 'metadata', id: 5, version: 51},
2451
+ dataSetNames: ['self'],
2452
+ },
2453
+ data: {
2454
+ visibleDataSets: [
2455
+ {
2456
+ name: 'main',
2457
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/main',
2458
+ },
2459
+ {
2460
+ name: 'self',
2461
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self',
2462
+ },
2463
+ {
2464
+ name: 'atd-unmuted',
2465
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted',
2466
+ },
2467
+ {
2468
+ name: 'attendees',
2469
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/attendees',
2470
+ },
2471
+ ],
2472
+ },
2473
+ },
2474
+ {
2475
+ htMeta: {
2476
+ elementId: {type: 'metadata', id: 5, version: 51},
2477
+ dataSetNames: ['self'],
2478
+ },
2479
+ data: {
2480
+ visibleDataSets: [
2481
+ {
2482
+ name: 'main',
2483
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/main',
2484
+ },
2485
+ {
2486
+ name: 'self',
2487
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self',
2488
+ },
2489
+ {
2490
+ name: 'atd-unmuted',
2491
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted',
2492
+ },
2493
+ {
2494
+ name: 'attendees',
2495
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/attendees',
2496
+ },
2497
+ ],
2498
+ },
2499
+ },
2500
+ ],
2501
+ });
2502
+ });
2503
+
2504
+ it('handles addition of visible data set (one that requires async initialization)', async () => {
2505
+ // Create a parser with visible datasets
2506
+ const parser = createHashTreeParser();
2507
+
2508
+ // Stub updateItems on self hash tree to return true
2509
+ sinon.stub(parser.dataSets.self.hashTree, 'updateItems').returns([true]);
2155
2510
 
2156
2511
  // Send a message with Metadata object that has a new visibleDataSets list (adding 'new-dataset')
2157
2512
  // but WITHOUT providing info about the new dataset in dataSets array
@@ -2300,7 +2655,7 @@ describe('HashTreeParser', () => {
2300
2655
  expect(syncCalls[1].args[0].uri).to.equal(`${newAtdActiveDataSet.url}/sync`);
2301
2656
  });
2302
2657
 
2303
- it('emits MEETING_ENDED if async init of a new visible dataset fails with 404', async () => {
2658
+ it('emits LOCUS_NOT_FOUND if async init of a new visible dataset fails with 404', async () => {
2304
2659
  const parser = createHashTreeParser();
2305
2660
 
2306
2661
  // Stub updateItems on self hash tree to return true
@@ -2365,10 +2720,8 @@ describe('HashTreeParser', () => {
2365
2720
  // Wait for the async initialization (queueMicrotask) to complete
2366
2721
  await clock.tickAsync(0);
2367
2722
 
2368
- // Verify callback was called with MEETING_ENDED
2369
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.MEETING_ENDED, {
2370
- updatedObjects: undefined,
2371
- });
2723
+ // Verify callback was called with LOCUS_NOT_FOUND (404 means locus URL is stale, not necessarily meeting ended)
2724
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.LOCUS_NOT_FOUND});
2372
2725
  });
2373
2726
 
2374
2727
  it('handles removal of visible data set', async () => {
@@ -2431,7 +2784,7 @@ describe('HashTreeParser', () => {
2431
2784
  assert.isUndefined(parser.dataSets['atd-unmuted'].timer);
2432
2785
 
2433
2786
  // Verify callback was called with the metadata update and the removed objects (metadata appears twice - processed once for dataset changes, once in main loop)
2434
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
2787
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
2435
2788
  updatedObjects: [
2436
2789
  {
2437
2790
  htMeta: {
@@ -2528,24 +2881,168 @@ describe('HashTreeParser', () => {
2528
2881
  // Verify callback was NOT called (no updates for non-visible datasets)
2529
2882
  assert.notCalled(callback);
2530
2883
  });
2531
- });
2532
-
2533
- describe('heartbeat watchdog', () => {
2534
- it('initiates sync immediately only for the specific data set whose heartbeat watchdog fires', async () => {
2535
- const parser = createHashTreeParser();
2536
- const heartbeatIntervalMs = 5000;
2537
2884
 
2538
- // Send initial heartbeat message for 'main' only
2539
- const heartbeatMessage = {
2540
- dataSets: [
2541
- {
2542
- ...createDataSet('main', 16, 1100),
2543
- root: parser.dataSets.main.hashTree.getRootHash(),
2544
- },
2545
- ],
2546
- visibleDataSetsUrl,
2885
+ it('reports update for object that moves from removed visible dataset to new visible dataset even if version is unchanged', async () => {
2886
+ // The purpose of this test is to verify that when an object
2887
+ // moves from one visible dataset to another without version change,
2888
+ // the parser still reports it as an update.
2889
+ // Locus has some additional signalling for this - the "view" property in htMeta.elementId.
2890
+ // When a view changes, the contents of the object may change even if version doesn't.
2891
+ // HashTreeParser doesn't use the "view" property, because it doesn't need to -
2892
+ // the same functionality is achieved thanks to the fact that a new visible data set means
2893
+ // a new hash tree is created, so HashTreeParser still detects the change as new
2894
+ // object is added to the new hash tree.
2895
+
2896
+ // Setup: parser with visible datasets "self" and "unjoined"
2897
+ const unjoinedDataSet = createDataSet('unjoined', 4, 3000);
2898
+ const selfDataSet = createDataSet('self', 1, 2000);
2899
+
2900
+ // start with Locus that has "info" in both "unjoined" and "main" datasets,
2901
+ // but only "unjoined" is visible.
2902
+ const initialLocus = {
2903
+ dataSets: [selfDataSet, unjoinedDataSet],
2904
+ locus: {
2905
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f',
2906
+ links: {resources: {visibleDataSets: {url: visibleDataSetsUrl}}},
2907
+ // info object in "unjoined" dataset with version 500
2908
+ info: {
2909
+ htMeta: {
2910
+ elementId: {
2911
+ type: 'info',
2912
+ id: 42,
2913
+ version: 500,
2914
+ view: ['unjoined'], // not used by our code, but here for completeness - that's what real Locus would send
2915
+ },
2916
+ dataSetNames: ['main', 'unjoined'],
2917
+ },
2918
+ someField: 'some-initial-value',
2919
+ },
2920
+ self: {
2921
+ htMeta: {
2922
+ elementId: {
2923
+ type: 'self',
2924
+ id: 4,
2925
+ version: 100,
2926
+ },
2927
+ dataSetNames: ['self'],
2928
+ },
2929
+ },
2930
+ },
2931
+ };
2932
+
2933
+ const metadata = {
2934
+ htMeta: {
2935
+ elementId: {
2936
+ type: 'metadata',
2937
+ id: 5,
2938
+ version: 50,
2939
+ },
2940
+ dataSetNames: ['self'],
2941
+ },
2942
+ visibleDataSets: [
2943
+ {name: 'self', url: selfDataSet.url},
2944
+ {name: 'unjoined', url: unjoinedDataSet.url},
2945
+ ],
2946
+ };
2947
+
2948
+ const parser = createHashTreeParser(initialLocus, metadata);
2949
+
2950
+ // Verify initial state: unjoined is visible and has the info object
2951
+ expect(parser.visibleDataSets.some((vds) => vds.name === 'unjoined')).to.be.true;
2952
+ assert.exists(parser.dataSets.unjoined.hashTree);
2953
+ assert.equal(parser.dataSets.unjoined.hashTree?.getItemVersion(42, 'info'), 500);
2954
+
2955
+ // Stub updateItems on self hash tree to return true for metadata update
2956
+ sinon.stub(parser.dataSets.self.hashTree, 'updateItems').returns([true]);
2957
+
2958
+ // Now send a message that:
2959
+ // 1. Changes visible datasets: removes "unjoined", adds "main"
2960
+ // 2. Contains the same info object (same id=42, same version=500) but we see the view from "main" dataset
2961
+ const mainDataSet = createDataSet('main', 16, 1000);
2962
+
2963
+ const message = {
2964
+ dataSets: [selfDataSet, mainDataSet],
2965
+ visibleDataSetsUrl,
2966
+ locusUrl,
2967
+ locusStateElements: [
2968
+ {
2969
+ htMeta: {
2970
+ elementId: {
2971
+ type: 'metadata' as const,
2972
+ id: 5,
2973
+ version: 51,
2974
+ },
2975
+ dataSetNames: ['self'],
2976
+ },
2977
+ data: {
2978
+ visibleDataSets: [
2979
+ {name: 'self', url: selfDataSet.url},
2980
+ {name: 'main', url: mainDataSet.url},
2981
+ // "unjoined" is no longer here
2982
+ ],
2983
+ },
2984
+ },
2985
+ {
2986
+ htMeta: {
2987
+ elementId: {
2988
+ type: 'info' as const,
2989
+ id: 42,
2990
+ version: 500, // same version as before
2991
+ view: ['main'], // now points to "main" instead of "unjoined"
2992
+ },
2993
+ dataSetNames: ['main', 'unjoined'], // still in both datasets, but only "main" is visible now
2994
+ },
2995
+ data: {someNewField: 'some-value'},
2996
+ },
2997
+ ],
2998
+ };
2999
+
3000
+ parser.handleMessage(message, 'visible dataset swap with same-version object');
3001
+
3002
+ // Verify "unjoined" is no longer visible and "main" is now visible
3003
+ expect(parser.visibleDataSets.some((vds) => vds.name === 'unjoined')).to.be.false;
3004
+ expect(parser.visibleDataSets.some((vds) => vds.name === 'main')).to.be.true;
3005
+
3006
+ // Verify the info object is now in the "main" hash tree
3007
+ assert.exists(parser.dataSets.main.hashTree);
3008
+ assert.equal(parser.dataSets.main.hashTree?.getItemVersion(42, 'info'), 500);
3009
+
3010
+ // The key assertion: callback should be called with the info object update even though
3011
+ // its version hasn't changed - because visible datasets changed (moved from unjoined to main)
3012
+ assert.calledOnce(callback);
3013
+ const callbackArgs = callback.firstCall.args[0];
3014
+ assert.equal(callbackArgs.updateType, LocusInfoUpdateType.OBJECTS_UPDATED);
3015
+
3016
+ // Should contain the info object update (with data)
3017
+ const infoUpdate = callbackArgs.updatedObjects.find(
3018
+ (obj) => obj.htMeta.elementId.type === 'info' && obj.htMeta.elementId.id === 42
3019
+ );
3020
+ assert.exists(infoUpdate);
3021
+ assert.deepEqual(infoUpdate.htMeta.elementId, {
3022
+ type: 'info',
3023
+ id: 42,
3024
+ version: 500,
3025
+ view: ['main'],
3026
+ });
3027
+ assert.deepEqual(infoUpdate.data, {someNewField: 'some-value'});
3028
+ });
3029
+ });
3030
+
3031
+ describe('heartbeat watchdog', () => {
3032
+ it('initiates sync immediately only for the specific data set whose heartbeat watchdog fires', async () => {
3033
+ const parser = createHashTreeParser();
3034
+ const heartbeatIntervalMs = 5000;
3035
+
3036
+ // Send initial heartbeat message for 'main' only
3037
+ const heartbeatMessage = {
3038
+ dataSets: [
3039
+ {
3040
+ ...createDataSet('main', 16, 1100),
3041
+ root: parser.dataSets.main.hashTree.getRootHash(),
3042
+ },
3043
+ ],
3044
+ visibleDataSetsUrl,
2547
3045
  locusUrl,
2548
- heartbeatIntervalMs,
2549
3046
  };
2550
3047
 
2551
3048
  parser.handleMessage(heartbeatMessage, 'initial heartbeat');
@@ -2577,6 +3074,12 @@ describe('HashTreeParser', () => {
2577
3074
  })
2578
3075
  );
2579
3076
 
3077
+ // Verify behavioral metric was sent for the watchdog expiration
3078
+ assert.calledWith(metricsStub, BEHAVIORAL_METRICS.HASH_TREE_HEARTBEAT_WATCHDOG_EXPIRED, {
3079
+ debugId: 'test',
3080
+ dataSetName: 'main',
3081
+ });
3082
+
2580
3083
  // Verify no sync requests were sent for other datasets
2581
3084
  assert.neverCalledWith(
2582
3085
  webexRequest,
@@ -2609,7 +3112,6 @@ describe('HashTreeParser', () => {
2609
3112
  ],
2610
3113
  visibleDataSetsUrl,
2611
3114
  locusUrl,
2612
- heartbeatIntervalMs,
2613
3115
  };
2614
3116
 
2615
3117
  parser.handleMessage(heartbeatMessage, 'self heartbeat');
@@ -2620,6 +3122,12 @@ describe('HashTreeParser', () => {
2620
3122
  // Advance time past watchdog delay
2621
3123
  await clock.tickAsync(heartbeatIntervalMs);
2622
3124
 
3125
+ // Verify behavioral metric was sent for the watchdog expiration
3126
+ assert.calledWith(metricsStub, BEHAVIORAL_METRICS.HASH_TREE_HEARTBEAT_WATCHDOG_EXPIRED, {
3127
+ debugId: 'test',
3128
+ dataSetName: 'self',
3129
+ });
3130
+
2623
3131
  // For leafCount === 1, performSync skips GET hashtree and goes straight to POST sync
2624
3132
  assert.neverCalledWith(
2625
3133
  webexRequest,
@@ -2639,7 +3147,6 @@ describe('HashTreeParser', () => {
2639
3147
 
2640
3148
  it('sets watchdog timers for each data set in the message', async () => {
2641
3149
  const parser = createHashTreeParser();
2642
- const heartbeatIntervalMs = 5000;
2643
3150
 
2644
3151
  // Send heartbeat with multiple datasets
2645
3152
  const heartbeatMessage = {
@@ -2656,7 +3163,6 @@ describe('HashTreeParser', () => {
2656
3163
  ],
2657
3164
  visibleDataSetsUrl,
2658
3165
  locusUrl,
2659
- heartbeatIntervalMs,
2660
3166
  };
2661
3167
 
2662
3168
  parser.handleMessage(heartbeatMessage, 'multi-dataset heartbeat');
@@ -2670,7 +3176,6 @@ describe('HashTreeParser', () => {
2670
3176
 
2671
3177
  it('resets the watchdog timer for a specific data set when a new heartbeat for it is received', async () => {
2672
3178
  const parser = createHashTreeParser();
2673
- const heartbeatIntervalMs = 5000;
2674
3179
 
2675
3180
  // Send first heartbeat for 'main'
2676
3181
  const heartbeat1 = {
@@ -2682,7 +3187,6 @@ describe('HashTreeParser', () => {
2682
3187
  ],
2683
3188
  visibleDataSetsUrl,
2684
3189
  locusUrl,
2685
- heartbeatIntervalMs,
2686
3190
  };
2687
3191
 
2688
3192
  parser.handleMessage(heartbeat1, 'first heartbeat');
@@ -2703,7 +3207,6 @@ describe('HashTreeParser', () => {
2703
3207
  ],
2704
3208
  visibleDataSetsUrl,
2705
3209
  locusUrl,
2706
- heartbeatIntervalMs,
2707
3210
  };
2708
3211
 
2709
3212
  parser.handleMessage(heartbeat2, 'second heartbeat');
@@ -2722,7 +3225,6 @@ describe('HashTreeParser', () => {
2722
3225
 
2723
3226
  it('resets the watchdog timer when a normal message (with locusStateElements) is received', async () => {
2724
3227
  const parser = createHashTreeParser();
2725
- const heartbeatIntervalMs = 5000;
2726
3228
 
2727
3229
  // Send initial heartbeat to start the watchdog for 'main'
2728
3230
  const heartbeat = {
@@ -2734,7 +3236,6 @@ describe('HashTreeParser', () => {
2734
3236
  ],
2735
3237
  visibleDataSetsUrl,
2736
3238
  locusUrl,
2737
- heartbeatIntervalMs,
2738
3239
  };
2739
3240
 
2740
3241
  parser.handleMessage(heartbeat, 'initial heartbeat');
@@ -2762,7 +3263,6 @@ describe('HashTreeParser', () => {
2762
3263
  data: {someData: 'value'},
2763
3264
  },
2764
3265
  ],
2765
- heartbeatIntervalMs,
2766
3266
  };
2767
3267
 
2768
3268
  parser.handleMessage(normalMessage, 'normal message');
@@ -2776,12 +3276,17 @@ describe('HashTreeParser', () => {
2776
3276
  const parser = createHashTreeParser();
2777
3277
 
2778
3278
  // Send a heartbeat message without heartbeatIntervalMs
2779
- const heartbeatMessage = createHeartbeatMessage(
2780
- 'main',
2781
- 16,
2782
- 1100,
2783
- parser.dataSets.main.hashTree.getRootHash()
2784
- );
3279
+ const heartbeatMessage = {
3280
+ dataSets: [
3281
+ {
3282
+ ...createDataSet('main', 16, 1100),
3283
+ root: parser.dataSets.main.hashTree.getRootHash(),
3284
+ heartbeatIntervalMs: undefined,
3285
+ },
3286
+ ],
3287
+ visibleDataSetsUrl,
3288
+ locusUrl,
3289
+ };
2785
3290
 
2786
3291
  parser.handleMessage(heartbeatMessage, 'heartbeat without interval');
2787
3292
 
@@ -2790,7 +3295,6 @@ describe('HashTreeParser', () => {
2790
3295
 
2791
3296
  it('stops all watchdog timers when meeting ends via sentinel message', async () => {
2792
3297
  const parser = createHashTreeParser();
2793
- const heartbeatIntervalMs = 5000;
2794
3298
 
2795
3299
  // Send heartbeat for multiple datasets
2796
3300
  const heartbeat = {
@@ -2807,7 +3311,6 @@ describe('HashTreeParser', () => {
2807
3311
  ],
2808
3312
  visibleDataSetsUrl,
2809
3313
  locusUrl,
2810
- heartbeatIntervalMs,
2811
3314
  };
2812
3315
 
2813
3316
  parser.handleMessage(heartbeat, 'initial heartbeat');
@@ -2858,7 +3361,6 @@ describe('HashTreeParser', () => {
2858
3361
  };
2859
3362
 
2860
3363
  const parser = createHashTreeParser(initialLocus, metadata);
2861
- const heartbeatIntervalMs = 5000;
2862
3364
 
2863
3365
  // Set Math.random to return 1 so that backoff = 1^exponent * maxMs = maxMs
2864
3366
  mathRandomStub.returns(1);
@@ -2880,7 +3382,6 @@ describe('HashTreeParser', () => {
2880
3382
  ],
2881
3383
  visibleDataSetsUrl,
2882
3384
  locusUrl,
2883
- heartbeatIntervalMs,
2884
3385
  };
2885
3386
 
2886
3387
  parser.handleMessage(heartbeat, 'heartbeat');
@@ -2930,7 +3431,6 @@ describe('HashTreeParser', () => {
2930
3431
 
2931
3432
  it('does not set watchdog for data sets without a hash tree', async () => {
2932
3433
  const parser = createHashTreeParser();
2933
- const heartbeatIntervalMs = 5000;
2934
3434
 
2935
3435
  // 'atd-active' is in the initial locus but is not visible (no hash tree)
2936
3436
  // Send heartbeat mentioning a non-visible dataset
@@ -2944,7 +3444,6 @@ describe('HashTreeParser', () => {
2944
3444
  ],
2945
3445
  visibleDataSetsUrl,
2946
3446
  locusUrl,
2947
- heartbeatIntervalMs,
2948
3447
  };
2949
3448
 
2950
3449
  parser.handleMessage(heartbeatMessage, 'heartbeat with non-visible dataset');
@@ -2953,128 +3452,313 @@ describe('HashTreeParser', () => {
2953
3452
  expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
2954
3453
  expect(parser.dataSets['atd-active']?.heartbeatWatchdogTimer).to.be.undefined;
2955
3454
  });
2956
- });
2957
- });
2958
-
2959
- describe('#callLocusInfoUpdateCallback filtering', () => {
2960
- // Helper to setup parser with initial objects and reset callback history
2961
- function setupParserWithObjects(locusStateElements: any[]) {
2962
- const parser = createHashTreeParser();
2963
-
2964
- if (locusStateElements.length > 0) {
2965
- // Determine which datasets to include based on the objects' dataSetNames
2966
- const dataSetNames = new Set<string>();
2967
- locusStateElements.forEach((element) => {
2968
- element.htMeta?.dataSetNames?.forEach((name) => dataSetNames.add(name));
2969
- });
2970
3455
 
2971
- const dataSets = [];
2972
- if (dataSetNames.has('main')) dataSets.push(createDataSet('main', 16, 1100));
2973
- if (dataSetNames.has('self')) dataSets.push(createDataSet('self', 1, 2100));
2974
- if (dataSetNames.has('atd-unmuted')) dataSets.push(createDataSet('atd-unmuted', 16, 3100));
3456
+ it('restarts the watchdog timer after it fires so that future missed heartbeats still trigger syncs', async () => {
3457
+ const parser = createHashTreeParser();
3458
+ const heartbeatIntervalMs = 5000;
2975
3459
 
2976
- const setupMessage = {
2977
- dataSets,
3460
+ // Send initial heartbeat for 'main'
3461
+ const heartbeatMessage = {
3462
+ dataSets: [
3463
+ {
3464
+ ...createDataSet('main', 16, 1100),
3465
+ root: parser.dataSets.main.hashTree.getRootHash(),
3466
+ },
3467
+ ],
2978
3468
  visibleDataSetsUrl,
2979
3469
  locusUrl,
2980
- locusStateElements,
2981
3470
  };
2982
3471
 
2983
- parser.handleMessage(setupMessage, 'setup');
2984
- }
2985
-
2986
- callback.resetHistory();
2987
- return parser;
2988
- }
3472
+ parser.handleMessage(heartbeatMessage, 'initial heartbeat');
3473
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
2989
3474
 
2990
- it('filters out updates when a dataset has a higher version', () => {
2991
- const parser = setupParserWithObjects([
2992
- {
2993
- htMeta: {
2994
- elementId: {type: 'locus' as const, id: 5, version: 100},
2995
- dataSetNames: ['main'],
2996
- },
2997
- data: {existingField: 'existing'},
2998
- },
2999
- ]);
3475
+ // Mock responses for performSync - return null (204/empty body)
3476
+ const mainDataSetUrl = parser.dataSets.main.url;
3477
+ mockGetHashesFromLocusResponse(
3478
+ mainDataSetUrl,
3479
+ new Array(16).fill('00000000000000000000000000000000'),
3480
+ createDataSet('main', 16, 1101)
3481
+ );
3482
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
3000
3483
 
3001
- // Try to update with an older version (90)
3002
- const updateMessage = {
3003
- dataSets: [createDataSet('main', 16, 1101)],
3004
- visibleDataSetsUrl,
3005
- locusUrl,
3006
- locusStateElements: [
3007
- {
3008
- htMeta: {
3009
- elementId: {type: 'locus' as const, id: 5, version: 90},
3010
- dataSetNames: ['main'],
3011
- },
3012
- data: {someField: 'value'},
3013
- },
3014
- ],
3015
- };
3484
+ // Advance time past heartbeatIntervalMs to fire the watchdog
3485
+ await clock.tickAsync(heartbeatIntervalMs);
3016
3486
 
3017
- parser.handleMessage(updateMessage, 'update with older version');
3487
+ // Verify sync was triggered
3488
+ assert.calledWith(
3489
+ webexRequest,
3490
+ sinon.match({
3491
+ method: 'GET',
3492
+ uri: `${mainDataSetUrl}/hashtree`,
3493
+ })
3494
+ );
3018
3495
 
3019
- // Callback should not be called because the update was filtered out
3020
- assert.notCalled(callback);
3021
- });
3496
+ // The watchdog timer should have been restarted after firing
3497
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3022
3498
 
3023
- it('allows updates when version is newer than existing', () => {
3024
- const parser = setupParserWithObjects([
3025
- {
3026
- htMeta: {
3027
- elementId: {type: 'locus' as const, id: 5, version: 100},
3028
- dataSetNames: ['main'],
3029
- },
3030
- data: {existingField: 'existing'},
3031
- },
3032
- ]);
3499
+ // Reset call history and set up new mock responses for the second sync
3500
+ webexRequest.resetHistory();
3501
+ mockGetHashesFromLocusResponse(
3502
+ mainDataSetUrl,
3503
+ new Array(16).fill('00000000000000000000000000000000'),
3504
+ createDataSet('main', 16, 1102)
3505
+ );
3506
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
3033
3507
 
3034
- // Try to update with a newer version (110)
3035
- const updateMessage = {
3036
- dataSets: [createDataSet('main', 16, 1101)],
3037
- visibleDataSetsUrl,
3038
- locusUrl,
3039
- locusStateElements: [
3040
- {
3041
- htMeta: {
3042
- elementId: {type: 'locus' as const, id: 5, version: 110},
3043
- dataSetNames: ['main'],
3044
- },
3045
- data: {someField: 'new value'},
3046
- },
3047
- ],
3048
- };
3508
+ // Advance time again to fire the watchdog a second time
3509
+ await clock.tickAsync(heartbeatIntervalMs);
3049
3510
 
3050
- parser.handleMessage(updateMessage, 'update with newer version');
3511
+ // Verify a second sync was triggered
3512
+ assert.calledWith(
3513
+ webexRequest,
3514
+ sinon.match({
3515
+ method: 'GET',
3516
+ uri: `${mainDataSetUrl}/hashtree`,
3517
+ })
3518
+ );
3051
3519
 
3052
- // Callback should be called with the update
3053
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
3054
- updatedObjects: [
3055
- {
3056
- htMeta: {
3057
- elementId: {type: 'locus', id: 5, version: 110},
3058
- dataSetNames: ['main'],
3059
- },
3060
- data: {someField: 'new value'},
3061
- },
3062
- ],
3520
+ // And the watchdog should still be running
3521
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3063
3522
  });
3064
- });
3065
3523
 
3066
- it('filters out removal when object still exists in any dataset', () => {
3067
- const parser = setupParserWithObjects([
3068
- {
3069
- htMeta: {
3070
- elementId: {type: 'participant' as const, id: 10, version: 50},
3071
- dataSetNames: ['main', 'atd-unmuted'],
3072
- },
3073
- data: {name: 'participant'},
3074
- },
3075
- ]);
3524
+ it('uses dataset-level heartbeatIntervalMs over top-level value', async () => {
3525
+ const parser = createHashTreeParser();
3526
+ const datasetLevelInterval = 3000;
3527
+ const topLevelInterval = 8000;
3076
3528
 
3077
- // Try to remove the object from main only (it still exists in atd-unmuted)
3529
+ // Send heartbeat with both top-level and dataset-level heartbeatIntervalMs
3530
+ const heartbeatMessage = {
3531
+ dataSets: [
3532
+ {
3533
+ ...createDataSet('main', 16, 1100),
3534
+ root: parser.dataSets.main.hashTree.getRootHash(),
3535
+ heartbeatIntervalMs: datasetLevelInterval,
3536
+ },
3537
+ ],
3538
+ visibleDataSetsUrl,
3539
+ locusUrl,
3540
+ heartbeatIntervalMs: topLevelInterval,
3541
+ };
3542
+
3543
+ parser.handleMessage(heartbeatMessage, 'heartbeat with both levels');
3544
+
3545
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3546
+
3547
+ // Mock sync responses
3548
+ const mainDataSetUrl = parser.dataSets.main.url;
3549
+ mockGetHashesFromLocusResponse(
3550
+ mainDataSetUrl,
3551
+ new Array(16).fill('00000000000000000000000000000000'),
3552
+ createDataSet('main', 16, 1101)
3553
+ );
3554
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
3555
+
3556
+ // Watchdog should NOT fire at the top-level interval (8000ms)
3557
+ // It should fire at the dataset-level interval (3000ms)
3558
+ await clock.tickAsync(datasetLevelInterval - 1);
3559
+ assert.notCalled(webexRequest);
3560
+
3561
+ await clock.tickAsync(1);
3562
+ // Now at datasetLevelInterval, watchdog should have fired
3563
+ assert.calledWith(
3564
+ webexRequest,
3565
+ sinon.match({
3566
+ method: 'GET',
3567
+ uri: `${mainDataSetUrl}/hashtree`,
3568
+ })
3569
+ );
3570
+ });
3571
+
3572
+ it('falls back to top-level heartbeatIntervalMs when dataset-level is missing', async () => {
3573
+ const parser = createHashTreeParser();
3574
+ const topLevelInterval = 7000;
3575
+
3576
+ // Send heartbeat with top-level heartbeatIntervalMs but no dataset-level
3577
+ const heartbeatMessage = {
3578
+ dataSets: [
3579
+ {
3580
+ ...createDataSet('main', 16, 1100),
3581
+ root: parser.dataSets.main.hashTree.getRootHash(),
3582
+ heartbeatIntervalMs: undefined,
3583
+ },
3584
+ ],
3585
+ visibleDataSetsUrl,
3586
+ locusUrl,
3587
+ heartbeatIntervalMs: topLevelInterval,
3588
+ };
3589
+
3590
+ parser.handleMessage(heartbeatMessage, 'heartbeat with top-level only');
3591
+
3592
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3593
+
3594
+ // Mock sync responses
3595
+ const mainDataSetUrl = parser.dataSets.main.url;
3596
+ mockGetHashesFromLocusResponse(
3597
+ mainDataSetUrl,
3598
+ new Array(16).fill('00000000000000000000000000000000'),
3599
+ createDataSet('main', 16, 1101)
3600
+ );
3601
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
3602
+
3603
+ // Should fire at the top-level interval
3604
+ await clock.tickAsync(topLevelInterval - 1);
3605
+ assert.notCalled(webexRequest);
3606
+
3607
+ await clock.tickAsync(1);
3608
+ assert.calledWith(
3609
+ webexRequest,
3610
+ sinon.match({
3611
+ method: 'GET',
3612
+ uri: `${mainDataSetUrl}/hashtree`,
3613
+ })
3614
+ );
3615
+ });
3616
+
3617
+ it('does not start watchdog when dataset-level heartbeatIntervalMs is 0 even if top-level is set', async () => {
3618
+ const parser = createHashTreeParser();
3619
+
3620
+ // Send heartbeat with dataset-level 0 and a top-level value
3621
+ const heartbeatMessage = {
3622
+ dataSets: [
3623
+ {
3624
+ ...createDataSet('main', 16, 1100),
3625
+ root: parser.dataSets.main.hashTree.getRootHash(),
3626
+ heartbeatIntervalMs: 0,
3627
+ },
3628
+ ],
3629
+ visibleDataSetsUrl,
3630
+ locusUrl,
3631
+ heartbeatIntervalMs: 5000,
3632
+ };
3633
+
3634
+ parser.handleMessage(heartbeatMessage, 'heartbeat with dataset-level 0');
3635
+
3636
+ // Dataset-level 0 means no watchdog, should NOT fall back to top-level
3637
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.be.undefined;
3638
+ });
3639
+ });
3640
+
3641
+ });
3642
+
3643
+ describe('#callLocusInfoUpdateCallback filtering', () => {
3644
+ // Helper to setup parser with initial objects and reset callback history
3645
+ function setupParserWithObjects(locusStateElements: any[]) {
3646
+ const parser = createHashTreeParser();
3647
+
3648
+ if (locusStateElements.length > 0) {
3649
+ // Determine which datasets to include based on the objects' dataSetNames
3650
+ const dataSetNames = new Set<string>();
3651
+ locusStateElements.forEach((element) => {
3652
+ element.htMeta?.dataSetNames?.forEach((name) => dataSetNames.add(name));
3653
+ });
3654
+
3655
+ const dataSets = [];
3656
+ if (dataSetNames.has('main')) dataSets.push(createDataSet('main', 16, 1100));
3657
+ if (dataSetNames.has('self')) dataSets.push(createDataSet('self', 1, 2100));
3658
+ if (dataSetNames.has('atd-unmuted')) dataSets.push(createDataSet('atd-unmuted', 16, 3100));
3659
+
3660
+ const setupMessage = {
3661
+ dataSets,
3662
+ visibleDataSetsUrl,
3663
+ locusUrl,
3664
+ locusStateElements,
3665
+ };
3666
+
3667
+ parser.handleMessage(setupMessage, 'setup');
3668
+ }
3669
+
3670
+ callback.resetHistory();
3671
+ return parser;
3672
+ }
3673
+
3674
+ it('filters out updates when a dataset has a higher version', () => {
3675
+ const parser = setupParserWithObjects([
3676
+ {
3677
+ htMeta: {
3678
+ elementId: {type: 'locus' as const, id: 5, version: 100},
3679
+ dataSetNames: ['main'],
3680
+ },
3681
+ data: {existingField: 'existing'},
3682
+ },
3683
+ ]);
3684
+
3685
+ // Try to update with an older version (90)
3686
+ const updateMessage = {
3687
+ dataSets: [createDataSet('main', 16, 1101)],
3688
+ visibleDataSetsUrl,
3689
+ locusUrl,
3690
+ locusStateElements: [
3691
+ {
3692
+ htMeta: {
3693
+ elementId: {type: 'locus' as const, id: 5, version: 90},
3694
+ dataSetNames: ['main'],
3695
+ },
3696
+ data: {someField: 'value'},
3697
+ },
3698
+ ],
3699
+ };
3700
+
3701
+ parser.handleMessage(updateMessage, 'update with older version');
3702
+
3703
+ // Callback should not be called because the update was filtered out
3704
+ assert.notCalled(callback);
3705
+ });
3706
+
3707
+ it('allows updates when version is newer than existing', () => {
3708
+ const parser = setupParserWithObjects([
3709
+ {
3710
+ htMeta: {
3711
+ elementId: {type: 'locus' as const, id: 5, version: 100},
3712
+ dataSetNames: ['main'],
3713
+ },
3714
+ data: {existingField: 'existing'},
3715
+ },
3716
+ ]);
3717
+
3718
+ // Try to update with a newer version (110)
3719
+ const updateMessage = {
3720
+ dataSets: [createDataSet('main', 16, 1101)],
3721
+ visibleDataSetsUrl,
3722
+ locusUrl,
3723
+ locusStateElements: [
3724
+ {
3725
+ htMeta: {
3726
+ elementId: {type: 'locus' as const, id: 5, version: 110},
3727
+ dataSetNames: ['main'],
3728
+ },
3729
+ data: {someField: 'new value'},
3730
+ },
3731
+ ],
3732
+ };
3733
+
3734
+ parser.handleMessage(updateMessage, 'update with newer version');
3735
+
3736
+ // Callback should be called with the update
3737
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
3738
+ updatedObjects: [
3739
+ {
3740
+ htMeta: {
3741
+ elementId: {type: 'locus', id: 5, version: 110},
3742
+ dataSetNames: ['main'],
3743
+ },
3744
+ data: {someField: 'new value'},
3745
+ },
3746
+ ],
3747
+ });
3748
+ });
3749
+
3750
+ it('filters out removal when object still exists in any dataset', () => {
3751
+ const parser = setupParserWithObjects([
3752
+ {
3753
+ htMeta: {
3754
+ elementId: {type: 'participant' as const, id: 10, version: 50},
3755
+ dataSetNames: ['main', 'atd-unmuted'],
3756
+ },
3757
+ data: {name: 'participant'},
3758
+ },
3759
+ ]);
3760
+
3761
+ // Try to remove the object from main only (it still exists in atd-unmuted)
3078
3762
  const removalMessage = {
3079
3763
  dataSets: [createDataSet('main', 16, 1101)],
3080
3764
  visibleDataSetsUrl,
@@ -3121,7 +3805,7 @@ describe('HashTreeParser', () => {
3121
3805
  parser.handleMessage(removalMessage, 'removal of non-existent object');
3122
3806
 
3123
3807
  // Callback should be called with the removal
3124
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
3808
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
3125
3809
  updatedObjects: [
3126
3810
  {
3127
3811
  htMeta: {
@@ -3256,7 +3940,7 @@ describe('HashTreeParser', () => {
3256
3940
  parser.handleMessage(mixedMessage, 'mixed updates');
3257
3941
 
3258
3942
  // Callback should be called with only the valid updates (participant 1 v110 and participant 3 v10)
3259
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.OBJECTS_UPDATED, {
3943
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
3260
3944
  updatedObjects: [
3261
3945
  {
3262
3946
  htMeta: {
@@ -3410,6 +4094,9 @@ describe('HashTreeParser', () => {
3410
4094
  parser.handleMessage(emptyMessage, 'empty elements');
3411
4095
 
3412
4096
  assert.notCalled(callback);
4097
+ assert.calledWith(metricsStub, BEHAVIORAL_METRICS.HASH_TREE_EMPTY_LOCUS_STATE_ELEMENTS, {
4098
+ debugId: 'test',
4099
+ });
3413
4100
  });
3414
4101
 
3415
4102
  it('always calls callback for MEETING_ENDED regardless of filtering', () => {
@@ -3434,9 +4121,7 @@ describe('HashTreeParser', () => {
3434
4121
  parser.handleMessage(sentinelMessage as any, 'sentinel message');
3435
4122
 
3436
4123
  // Callback should be called with MEETING_ENDED
3437
- assert.calledOnceWithExactly(callback, LocusInfoUpdateType.MEETING_ENDED, {
3438
- updatedObjects: undefined,
3439
- });
4124
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.MEETING_ENDED});
3440
4125
  });
3441
4126
  });
3442
4127
 
@@ -3642,7 +4327,7 @@ describe('HashTreeParser', () => {
3642
4327
  });
3643
4328
  });
3644
4329
 
3645
- describe('#resume', () => {
4330
+ describe('#resumeFromMessage', () => {
3646
4331
  const createResumeMessage = (visibleDataSets?, dataSets?) => ({
3647
4332
  locusUrl,
3648
4333
  visibleDataSetsUrl,
@@ -3669,7 +4354,7 @@ describe('HashTreeParser', () => {
3669
4354
 
3670
4355
  expect(parser.state).to.equal('stopped');
3671
4356
 
3672
- parser.resume(createResumeMessage());
4357
+ parser.resumeFromMessage(createResumeMessage());
3673
4358
 
3674
4359
  expect(parser.state).to.equal('active');
3675
4360
  });
@@ -3678,7 +4363,7 @@ describe('HashTreeParser', () => {
3678
4363
  const parser = createHashTreeParser();
3679
4364
  parser.stop();
3680
4365
 
3681
- parser.resume({
4366
+ parser.resumeFromMessage({
3682
4367
  locusUrl,
3683
4368
  visibleDataSetsUrl,
3684
4369
  dataSets: [createDataSet('main', 16, 2000)],
@@ -3697,7 +4382,7 @@ describe('HashTreeParser', () => {
3697
4382
  createDataSet('self', 2, 6000),
3698
4383
  ];
3699
4384
 
3700
- parser.resume(createResumeMessage(undefined, newDataSets));
4385
+ parser.resumeFromMessage(createResumeMessage(undefined, newDataSets));
3701
4386
 
3702
4387
  expect(Object.keys(parser.dataSets)).to.have.lengthOf(2);
3703
4388
  expect(parser.dataSets.main.leafCount).to.equal(8);
@@ -3719,7 +4404,7 @@ describe('HashTreeParser', () => {
3719
4404
  {name: 'self', url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self'},
3720
4405
  ];
3721
4406
 
3722
- parser.resume(createResumeMessage(visibleDataSets, dataSets));
4407
+ parser.resumeFromMessage(createResumeMessage(visibleDataSets, dataSets));
3723
4408
 
3724
4409
  expect(parser.dataSets.main.hashTree).to.be.instanceOf(HashTree);
3725
4410
  expect(parser.dataSets.self.hashTree).to.be.instanceOf(HashTree);
@@ -3733,7 +4418,7 @@ describe('HashTreeParser', () => {
3733
4418
  const handleMessageStub = sinon.stub(parser, 'handleMessage');
3734
4419
 
3735
4420
  const message = createResumeMessage();
3736
- parser.resume(message);
4421
+ parser.resumeFromMessage(message);
3737
4422
 
3738
4423
  assert.calledOnceWithExactly(handleMessageStub, message, 'on resume');
3739
4424
  });
@@ -3753,7 +4438,7 @@ describe('HashTreeParser', () => {
3753
4438
  {name: 'atd-unmuted', url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted'},
3754
4439
  ];
3755
4440
 
3756
- parser.resume(createResumeMessage(visibleDataSets, dataSets));
4441
+ parser.resumeFromMessage(createResumeMessage(visibleDataSets, dataSets));
3757
4442
 
3758
4443
  expect(parser.visibleDataSets.some((vds) => vds.name === 'atd-unmuted')).to.be.false;
3759
4444
  expect(parser.visibleDataSets.some((vds) => vds.name === 'main')).to.be.true;
@@ -3761,6 +4446,67 @@ describe('HashTreeParser', () => {
3761
4446
  });
3762
4447
  });
3763
4448
 
4449
+ describe('#resumeFromApiResponse', () => {
4450
+ const exampleLocus = {
4451
+ participants: [],
4452
+ } as any;
4453
+
4454
+ it('should set state to active', async () => {
4455
+ const parser = createHashTreeParser();
4456
+ parser.stop();
4457
+
4458
+ expect(parser.state).to.equal('stopped');
4459
+
4460
+ sinon.stub(parser, 'initializeFromGetLociResponse').resolves();
4461
+
4462
+ await parser.resumeFromApiResponse(exampleLocus);
4463
+
4464
+ expect(parser.state).to.equal('active');
4465
+ });
4466
+
4467
+ it('should reset dataSets to empty', async () => {
4468
+ const parser = createHashTreeParser();
4469
+
4470
+ expect(Object.keys(parser.dataSets).length).to.be.greaterThan(0);
4471
+
4472
+ parser.stop();
4473
+
4474
+ sinon.stub(parser, 'initializeFromGetLociResponse').resolves();
4475
+
4476
+ await parser.resumeFromApiResponse(exampleLocus);
4477
+
4478
+ expect(parser.dataSets).to.deep.equal({});
4479
+ });
4480
+
4481
+ it('should call initializeFromGetLociResponse with the provided locus', async () => {
4482
+ const parser = createHashTreeParser();
4483
+ parser.stop();
4484
+
4485
+ const initStub = sinon.stub(parser, 'initializeFromGetLociResponse').resolves();
4486
+
4487
+ await parser.resumeFromApiResponse(exampleLocus);
4488
+
4489
+ assert.calledOnceWithExactly(initStub, exampleLocus);
4490
+ });
4491
+
4492
+ it('should propagate errors from initializeFromGetLociResponse', async () => {
4493
+ const parser = createHashTreeParser();
4494
+ parser.stop();
4495
+
4496
+ const error = new Error('initialization failed');
4497
+ const initStub = sinon.stub(parser, 'initializeFromGetLociResponse').rejects(error);
4498
+
4499
+ let caughtError: Error | undefined;
4500
+ try {
4501
+ await parser.resumeFromApiResponse(exampleLocus);
4502
+ } catch (e) {
4503
+ caughtError = e;
4504
+ }
4505
+
4506
+ expect(caughtError).to.equal(error);
4507
+ });
4508
+ });
4509
+
3764
4510
  describe('#handleLocusUpdate when stopped', () => {
3765
4511
  it('should return early without processing when parser is stopped', () => {
3766
4512
  const parser = createHashTreeParser();
@@ -3795,4 +4541,788 @@ describe('HashTreeParser', () => {
3795
4541
  assert.notCalled(callback);
3796
4542
  });
3797
4543
  });
4544
+
4545
+ describe('#syncAllDatasets', () => {
4546
+ it('should sync all datasets that have hash trees in priority order', async () => {
4547
+ const parser = createHashTreeParser();
4548
+
4549
+ // parser starts with main (leafCount=16) and self (leafCount=1) as visible datasets with hash trees
4550
+ // atd-unmuted has no hash tree (not visible)
4551
+ expect(parser.dataSets.main.hashTree).to.be.instanceOf(HashTree);
4552
+ expect(parser.dataSets.self.hashTree).to.be.instanceOf(HashTree);
4553
+
4554
+ const mainUrl = parser.dataSets.main.url;
4555
+ const selfUrl = parser.dataSets.self.url;
4556
+
4557
+ // Mock GET hashtree for main (leafCount > 1, so it does GET first)
4558
+ mockGetHashesFromLocusResponse(
4559
+ mainUrl,
4560
+ new Array(16).fill(EMPTY_HASH),
4561
+ createDataSet('main', 16, 1100)
4562
+ );
4563
+
4564
+ // Mock POST sync for main - return matching root hash so no further sync needed
4565
+ const mainSyncDataSet = createDataSet('main', 16, 1100);
4566
+ mainSyncDataSet.root = parser.dataSets.main.hashTree.getRootHash();
4567
+ mockSendSyncRequestResponse(mainUrl, {
4568
+ dataSets: [mainSyncDataSet],
4569
+ visibleDataSetsUrl,
4570
+ locusUrl,
4571
+ locusStateElements: [],
4572
+ });
4573
+
4574
+ // Mock POST sync for self (leafCount=1, skips GET hashtree)
4575
+ const selfSyncDataSet = createDataSet('self', 1, 2100);
4576
+ selfSyncDataSet.root = parser.dataSets.self.hashTree.getRootHash();
4577
+ mockSendSyncRequestResponse(selfUrl, {
4578
+ dataSets: [selfSyncDataSet],
4579
+ visibleDataSetsUrl,
4580
+ locusUrl,
4581
+ locusStateElements: [],
4582
+ });
4583
+
4584
+ await parser.syncAllDatasets();
4585
+
4586
+ // Verify GET hashtree was called for main only (not self, because leafCount=1)
4587
+ assert.calledWith(webexRequest, sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}));
4588
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${selfUrl}/hashtree`}));
4589
+
4590
+ // Verify POST sync was called for both
4591
+ assert.calledWith(webexRequest, sinon.match({method: 'POST', uri: `${mainUrl}/sync`}));
4592
+ assert.calledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
4593
+
4594
+ // Verify main was synced before self (priority order)
4595
+ const mainSyncCallIndex = webexRequest.args.findIndex(
4596
+ (args) => args[0]?.method === 'GET' && args[0]?.uri === `${mainUrl}/hashtree`
4597
+ );
4598
+ const selfSyncCallIndex = webexRequest.args.findIndex(
4599
+ (args) => args[0]?.method === 'POST' && args[0]?.uri === `${selfUrl}/sync`
4600
+ );
4601
+ expect(mainSyncCallIndex).to.be.lessThan(selfSyncCallIndex);
4602
+
4603
+ // Verify syncAllBackoffType is reset
4604
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.NONE);
4605
+ });
4606
+
4607
+ it('should return immediately when state is stopped', async () => {
4608
+ const parser = createHashTreeParser();
4609
+ parser.stop();
4610
+
4611
+ await parser.syncAllDatasets();
4612
+
4613
+ // No sync requests should have been made (only the initial sync from constructor)
4614
+ // Reset history to clear constructor calls then verify
4615
+ const callCountBefore = webexRequest.callCount;
4616
+ await parser.syncAllDatasets();
4617
+ assert.equal(webexRequest.callCount, callCountBefore);
4618
+ });
4619
+
4620
+ it('should guard against concurrent calls', async () => {
4621
+ const parser = createHashTreeParser();
4622
+
4623
+ const mainUrl = parser.dataSets.main.url;
4624
+ const selfUrl = parser.dataSets.self.url;
4625
+
4626
+ // Use a deferred promise for the main sync to control timing
4627
+ let resolveMainSync;
4628
+ webexRequest
4629
+ .withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}))
4630
+ .returns(new Promise((resolve) => { resolveMainSync = resolve; }));
4631
+
4632
+ mockSendSyncRequestResponse(mainUrl, {
4633
+ dataSets: [createDataSet('main', 16, 1100)],
4634
+ visibleDataSetsUrl,
4635
+ locusUrl,
4636
+ locusStateElements: [],
4637
+ });
4638
+
4639
+ mockSendSyncRequestResponse(selfUrl, {
4640
+ dataSets: [createDataSet('self', 1, 2100)],
4641
+ visibleDataSetsUrl,
4642
+ locusUrl,
4643
+ locusStateElements: [],
4644
+ });
4645
+
4646
+ // Start first call
4647
+ const promise1 = parser.syncAllDatasets();
4648
+ // Start second call while first is in progress
4649
+ const promise2 = parser.syncAllDatasets();
4650
+
4651
+ // Resolve the pending request
4652
+ resolveMainSync({
4653
+ body: {
4654
+ hashes: new Array(16).fill(EMPTY_HASH),
4655
+ dataSet: createDataSet('main', 16, 1100),
4656
+ },
4657
+ });
4658
+
4659
+ await promise1;
4660
+ await promise2;
4661
+
4662
+ // GET hashtree for main should only be called once (second syncAllDatasets returned immediately)
4663
+ const getHashtreeCalls = webexRequest.args.filter(
4664
+ (args) => args[0]?.method === 'GET' && args[0]?.uri === `${mainUrl}/hashtree`
4665
+ );
4666
+ expect(getHashtreeCalls).to.have.lengthOf(1);
4667
+ });
4668
+
4669
+ it('should sync only LLM datasets when onlyLLM=true', async () => {
4670
+ const parser = createHashTreeParser();
4671
+
4672
+ const mainUrl = parser.dataSets.main.url;
4673
+ const selfUrl = parser.dataSets.self.url;
4674
+
4675
+ mockGetHashesFromLocusResponse(
4676
+ mainUrl,
4677
+ new Array(16).fill(EMPTY_HASH),
4678
+ createDataSet('main', 16, 1100)
4679
+ );
4680
+
4681
+ const mainSyncDs = createDataSet('main', 16, 1100);
4682
+ mainSyncDs.root = parser.dataSets.main.hashTree.getRootHash();
4683
+ mockSendSyncRequestResponse(mainUrl, {
4684
+ dataSets: [mainSyncDs],
4685
+ visibleDataSetsUrl,
4686
+ locusUrl,
4687
+ locusStateElements: [],
4688
+ });
4689
+
4690
+ await parser.syncAllDatasets({onlyLLM: true});
4691
+
4692
+ // main is an LLM dataset, so it should have been synced
4693
+ assert.calledWith(webexRequest, sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}));
4694
+
4695
+ // self is NOT an LLM dataset, so it should NOT have been synced
4696
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
4697
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${selfUrl}/hashtree`}));
4698
+ });
4699
+
4700
+ it('should upgrade scope from onlyLLM=true to all datasets when onlyLLM=false call arrives during backoff', async () => {
4701
+ // Make Math.random return 1 so backoff = 1^2 * 1000 = 1000ms (non-zero delay for interleaving)
4702
+ mathRandomStub.returns(1);
4703
+
4704
+ const parser = createHashTreeParser();
4705
+
4706
+ const mainUrl = parser.dataSets.main.url;
4707
+ const selfUrl = parser.dataSets.self.url;
4708
+
4709
+ mockGetHashesFromLocusResponse(
4710
+ mainUrl,
4711
+ new Array(16).fill(EMPTY_HASH),
4712
+ createDataSet('main', 16, 1100)
4713
+ );
4714
+
4715
+ const mainSyncDs = createDataSet('main', 16, 1100);
4716
+ mainSyncDs.root = parser.dataSets.main.hashTree.getRootHash();
4717
+ mockSendSyncRequestResponse(mainUrl, {
4718
+ dataSets: [mainSyncDs],
4719
+ visibleDataSetsUrl,
4720
+ locusUrl,
4721
+ locusStateElements: [],
4722
+ });
4723
+
4724
+ const selfSyncDs = createDataSet('self', 1, 2100);
4725
+ selfSyncDs.root = parser.dataSets.self.hashTree.getRootHash();
4726
+ mockSendSyncRequestResponse(selfUrl, {
4727
+ dataSets: [selfSyncDs],
4728
+ visibleDataSetsUrl,
4729
+ locusUrl,
4730
+ locusStateElements: [],
4731
+ });
4732
+
4733
+ // First call with onlyLLM=true starts backoff
4734
+ const promise1 = parser.syncAllDatasets({onlyLLM: true});
4735
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.ONLY_LLM);
4736
+
4737
+ // Second call with onlyLLM=false upgrades the scope during backoff
4738
+ const promise2 = parser.syncAllDatasets({onlyLLM: false});
4739
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.ALL);
4740
+
4741
+ // Advance clock past the backoff delay (1000ms)
4742
+ await clock.tickAsync(1000);
4743
+
4744
+ await promise1;
4745
+ await promise2;
4746
+
4747
+ // Both main (LLM) and self (non-LLM) should have been synced
4748
+ assert.calledWith(webexRequest, sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}));
4749
+ assert.calledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
4750
+ });
4751
+
4752
+ it('should not downgrade scope from onlyLLM=false when onlyLLM=true call arrives during backoff', async () => {
4753
+ // Make Math.random return 1 so backoff = 1^2 * 1000 = 1000ms (non-zero delay for interleaving)
4754
+ mathRandomStub.returns(1);
4755
+
4756
+ const parser = createHashTreeParser();
4757
+
4758
+ const mainUrl = parser.dataSets.main.url;
4759
+ const selfUrl = parser.dataSets.self.url;
4760
+
4761
+ mockGetHashesFromLocusResponse(
4762
+ mainUrl,
4763
+ new Array(16).fill(EMPTY_HASH),
4764
+ createDataSet('main', 16, 1100)
4765
+ );
4766
+
4767
+ const mainSyncDs = createDataSet('main', 16, 1100);
4768
+ mainSyncDs.root = parser.dataSets.main.hashTree.getRootHash();
4769
+ mockSendSyncRequestResponse(mainUrl, {
4770
+ dataSets: [mainSyncDs],
4771
+ visibleDataSetsUrl,
4772
+ locusUrl,
4773
+ locusStateElements: [],
4774
+ });
4775
+
4776
+ const selfSyncDs = createDataSet('self', 1, 2100);
4777
+ selfSyncDs.root = parser.dataSets.self.hashTree.getRootHash();
4778
+ mockSendSyncRequestResponse(selfUrl, {
4779
+ dataSets: [selfSyncDs],
4780
+ visibleDataSetsUrl,
4781
+ locusUrl,
4782
+ locusStateElements: [],
4783
+ });
4784
+
4785
+ // First call with onlyLLM=false starts backoff with all-datasets scope
4786
+ const promise1 = parser.syncAllDatasets({onlyLLM: false});
4787
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.ALL);
4788
+
4789
+ // Second call with onlyLLM=true should NOT downgrade the scope
4790
+ const promise2 = parser.syncAllDatasets({onlyLLM: true});
4791
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.ALL);
4792
+
4793
+ // Advance clock past the backoff delay (1000ms)
4794
+ await clock.tickAsync(1000);
4795
+
4796
+ await promise1;
4797
+ await promise2;
4798
+
4799
+ // Both main (LLM) and self (non-LLM) should have been synced (scope was not downgraded)
4800
+ assert.calledWith(webexRequest, sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}));
4801
+ assert.calledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
4802
+ });
4803
+
4804
+ it('should skip datasets that received messages during the backoff sleep', async () => {
4805
+ // Make Math.random return 1 so backoff = 1^2 * 1000 = 1000ms
4806
+ mathRandomStub.returns(1);
4807
+
4808
+ const parser = createHashTreeParser();
4809
+
4810
+ const mainUrl = parser.dataSets.main.url;
4811
+ const selfUrl = parser.dataSets.self.url;
4812
+ const atdUnmutedUrl = parser.dataSets['atd-unmuted'].url;
4813
+
4814
+ // Setup mocks only for self (main and atd-unmuted should be skipped)
4815
+ mockSendSyncRequestResponse(selfUrl, {
4816
+ dataSets: [createDataSet('self', 1, 2100)],
4817
+ visibleDataSetsUrl,
4818
+ locusUrl,
4819
+ locusStateElements: [],
4820
+ });
4821
+
4822
+ // Start syncAllDatasets - begins backoff sleep
4823
+ const promise = parser.syncAllDatasets();
4824
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.ALL);
4825
+
4826
+ // Simulate a normal message arriving for "main" during the backoff sleep
4827
+ parser.handleMessage({
4828
+ dataSets: [createDataSet('main', 16, 1100)],
4829
+ visibleDataSetsUrl,
4830
+ locusUrl,
4831
+ locusStateElements: [
4832
+ {
4833
+ htMeta: {
4834
+ elementId: {type: 'locus' as const, id: 0, version: 201},
4835
+ dataSetNames: ['main'],
4836
+ },
4837
+ data: {someData: 'value'},
4838
+ },
4839
+ ],
4840
+ });
4841
+
4842
+ // Simulate a heartbeat message arriving for "atd-unmuted" during the backoff sleep
4843
+ parser.handleMessage(
4844
+ createHeartbeatMessage('atd-unmuted', 1, 1100, parser.dataSets['atd-unmuted'].root)
4845
+ );
4846
+
4847
+ // Advance clock past the backoff delay
4848
+ await clock.tickAsync(1000);
4849
+ await promise;
4850
+
4851
+ // main should NOT have been synced (it received a normal message during backoff)
4852
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}));
4853
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${mainUrl}/sync`}));
4854
+
4855
+ // atd-unmuted should NOT have been synced (it received a heartbeat during backoff)
4856
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${atdUnmutedUrl}/hashtree`}));
4857
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${atdUnmutedUrl}/sync`}));
4858
+
4859
+ // self SHOULD have been synced (no messages received for it during backoff)
4860
+ assert.calledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
4861
+ });
4862
+
4863
+ it('should skip datasets that do not have a hash tree', async () => {
4864
+ // Create parser with metadata that only has main and self as visible (not atd-unmuted)
4865
+ const metadataWithoutAtd = {
4866
+ ...exampleMetadata,
4867
+ visibleDataSets: exampleMetadata.visibleDataSets.filter((ds) => ds.name !== 'atd-unmuted'),
4868
+ };
4869
+ const parser = createHashTreeParser(exampleInitialLocus, metadataWithoutAtd);
4870
+
4871
+ // atd-unmuted is in dataSets but has no hashTree (not visible)
4872
+ expect(parser.dataSets['atd-unmuted']).to.exist;
4873
+ expect(parser.dataSets['atd-unmuted'].hashTree).to.be.undefined;
4874
+
4875
+ const atdUrl = parser.dataSets['atd-unmuted'].url;
4876
+ const mainUrl = parser.dataSets.main.url;
4877
+ const selfUrl = parser.dataSets.self.url;
4878
+
4879
+ mockGetHashesFromLocusResponse(
4880
+ mainUrl,
4881
+ new Array(16).fill(EMPTY_HASH),
4882
+ createDataSet('main', 16, 1100)
4883
+ );
4884
+
4885
+ const mainSyncDs = createDataSet('main', 16, 1100);
4886
+ mainSyncDs.root = parser.dataSets.main.hashTree.getRootHash();
4887
+ mockSendSyncRequestResponse(mainUrl, {
4888
+ dataSets: [mainSyncDs],
4889
+ visibleDataSetsUrl,
4890
+ locusUrl,
4891
+ locusStateElements: [],
4892
+ });
4893
+
4894
+ const selfSyncDs = createDataSet('self', 1, 2100);
4895
+ selfSyncDs.root = parser.dataSets.self.hashTree.getRootHash();
4896
+ mockSendSyncRequestResponse(selfUrl, {
4897
+ dataSets: [selfSyncDs],
4898
+ visibleDataSetsUrl,
4899
+ locusUrl,
4900
+ locusStateElements: [],
4901
+ });
4902
+
4903
+ await parser.syncAllDatasets();
4904
+
4905
+ // No requests should have been made for atd-unmuted
4906
+ assert.neverCalledWith(webexRequest, sinon.match({uri: sinon.match(atdUrl)}));
4907
+ });
4908
+ });
4909
+
4910
+ describe('#handleMessage sync queue', () => {
4911
+ it('should deduplicate: not sync the same dataset twice when enqueued multiple times', async () => {
4912
+ const parser = createHashTreeParser();
4913
+
4914
+ const mainUrl = parser.dataSets.main.url;
4915
+
4916
+ // Setup mocks before triggering syncs
4917
+ mockGetHashesFromLocusResponse(
4918
+ mainUrl,
4919
+ new Array(16).fill(EMPTY_HASH),
4920
+ createDataSet('main', 16, 1101)
4921
+ );
4922
+
4923
+ const mainSyncDs = createDataSet('main', 16, 1101);
4924
+ mainSyncDs.root = parser.dataSets.main.hashTree.getRootHash();
4925
+ mockSendSyncRequestResponse(mainUrl, {
4926
+ dataSets: [mainSyncDs],
4927
+ visibleDataSetsUrl,
4928
+ locusUrl,
4929
+ locusStateElements: [],
4930
+ });
4931
+
4932
+ // Send two heartbeat messages (no locusStateElements) with different root hashes for main
4933
+ parser.handleMessage(createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'), 'first');
4934
+ parser.handleMessage(createHeartbeatMessage('main', 16, 1101, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa2'), 'second');
4935
+
4936
+ // The second call resets the timer. After 1000ms, only one sync fires.
4937
+ await clock.tickAsync(1000);
4938
+
4939
+ // Only one GET hashtree call should have been made for main
4940
+ const getHashtreeCalls = webexRequest.args.filter(
4941
+ (args) => args[0]?.method === 'GET' && args[0]?.uri === `${mainUrl}/hashtree`
4942
+ );
4943
+ expect(getHashtreeCalls).to.have.lengthOf(1);
4944
+ });
4945
+
4946
+ it('should stop processing the sync queue when parser is stopped mid-queue', async () => {
4947
+ const parser = createHashTreeParser();
4948
+
4949
+ const mainUrl = parser.dataSets.main.url;
4950
+ const selfUrl = parser.dataSets.self.url;
4951
+
4952
+ // Mock main GET hashtree with a deferred promise so we can control when it resolves
4953
+ let resolveMainHashtree;
4954
+ webexRequest
4955
+ .withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}))
4956
+ .callsFake(() => new Promise((resolve) => { resolveMainHashtree = resolve; }));
4957
+
4958
+ // Send a heartbeat message that triggers sync timers for both main and self
4959
+ parser.handleMessage(
4960
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
4961
+ 'trigger main sync'
4962
+ );
4963
+ parser.handleMessage(
4964
+ createHeartbeatMessage('self', 1, 2100, 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb1'),
4965
+ 'trigger self sync'
4966
+ );
4967
+
4968
+ // Fire the timers - main sync starts (calls GET hashtree, which blocks)
4969
+ await clock.tickAsync(1000);
4970
+
4971
+ // Stop the parser while main sync is in progress
4972
+ parser.stop();
4973
+
4974
+ // Resolve the pending main GET request
4975
+ resolveMainHashtree({
4976
+ body: {
4977
+ hashes: new Array(16).fill(EMPTY_HASH),
4978
+ dataSet: createDataSet('main', 16, 1100),
4979
+ },
4980
+ });
4981
+
4982
+ await clock.tickAsync(0);
4983
+
4984
+ // Self sync should NOT have been triggered because parser was stopped
4985
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
4986
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${selfUrl}/hashtree`}));
4987
+ });
4988
+ });
4989
+
4990
+ describe('#stop sync queue', () => {
4991
+ it('should clear the syncQueue when stopped so remaining queued items are not processed', async () => {
4992
+ const parser = createHashTreeParser();
4993
+
4994
+ const mainUrl = parser.dataSets.main.url;
4995
+ const selfUrl = parser.dataSets.self.url;
4996
+
4997
+ // Mock main GET hashtree with a deferred promise so we can control when it resolves
4998
+ let resolveMainHashtree;
4999
+ webexRequest
5000
+ .withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}))
5001
+ .callsFake(() => new Promise((resolve) => { resolveMainHashtree = resolve; }));
5002
+
5003
+ // Enqueue syncs for both main and self by sending heartbeat messages
5004
+ parser.handleMessage(
5005
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5006
+ 'trigger main sync'
5007
+ );
5008
+ parser.handleMessage(
5009
+ createHeartbeatMessage('self', 1, 2100, 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb1'),
5010
+ 'trigger self sync'
5011
+ );
5012
+
5013
+ // Fire the timers - main sync starts and blocks on GET hashtree
5014
+ await clock.tickAsync(1000);
5015
+
5016
+ // Verify that self is still in the queue (main is being processed, self is waiting)
5017
+ // Now stop the parser - this should clear the syncQueue
5018
+ parser.stop();
5019
+
5020
+ // Resolve the pending main GET request so the in-flight sync can finish
5021
+ resolveMainHashtree({
5022
+ body: {
5023
+ hashes: new Array(16).fill(EMPTY_HASH),
5024
+ dataSet: createDataSet('main', 16, 1100),
5025
+ },
5026
+ });
5027
+
5028
+ await clock.tickAsync(0);
5029
+
5030
+ // Self should never have been synced because stop() cleared the queue
5031
+ const selfGetCalls = webexRequest.args.filter(
5032
+ (args) => args[0]?.method === 'GET' && args[0]?.uri === `${selfUrl}/hashtree`
5033
+ );
5034
+ expect(selfGetCalls).to.have.lengthOf(0);
5035
+ });
5036
+ });
5037
+
5038
+ describe('#performSync abort controller', () => {
5039
+ it('should reuse an existing syncAbortController if one is already set on the dataset', async () => {
5040
+ const parser = createHashTreeParser();
5041
+ const mainUrl = parser.dataSets.main.url;
5042
+
5043
+ // Pre-set an AbortController on the dataset before sync starts
5044
+ const existingController = new AbortController();
5045
+ parser.dataSets.main.syncAbortController = existingController;
5046
+
5047
+ // Use a deferred promise for GET hashtree so we can inspect the controller mid-sync
5048
+ let resolveGetHashtree;
5049
+ webexRequest.withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`})).callsFake(
5050
+ () =>
5051
+ new Promise((resolve) => {
5052
+ resolveGetHashtree = resolve;
5053
+ })
5054
+ );
5055
+
5056
+ // Trigger sync for main
5057
+ parser.handleMessage(
5058
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5059
+ 'trigger main sync'
5060
+ );
5061
+
5062
+ await clock.tickAsync(1000);
5063
+
5064
+ // While sync is in-flight, verify the controller is the same one we pre-set
5065
+ expect(parser.dataSets.main.syncAbortController).to.equal(existingController);
5066
+
5067
+ // Resolve GET hashtree with matching hashes (no sync needed)
5068
+ resolveGetHashtree({body: {}});
5069
+ await testUtils.flushPromises();
5070
+
5071
+ // After sync completes, syncAbortController is cleared in finally
5072
+ expect(parser.dataSets.main.syncAbortController).to.be.undefined;
5073
+ });
5074
+
5075
+ it('should abort the sync before /sync request when the controller is aborted during getHashesFromLocus', async () => {
5076
+ const parser = createHashTreeParser();
5077
+ const mainUrl = parser.dataSets.main.url;
5078
+
5079
+ // Use a deferred promise for GET hashtree so we can abort while it's pending
5080
+ let resolveGetHashtree;
5081
+ webexRequest.withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`})).callsFake(
5082
+ () =>
5083
+ new Promise((resolve) => {
5084
+ resolveGetHashtree = resolve;
5085
+ })
5086
+ );
5087
+
5088
+ // Mock POST sync - should NOT be called if abort works
5089
+ mockSendSyncRequestResponse(mainUrl, null);
5090
+
5091
+ // Trigger sync for main via heartbeat with mismatched root hash
5092
+ parser.handleMessage(
5093
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5094
+ 'trigger main sync'
5095
+ );
5096
+
5097
+ // Fire the timer to start the sync
5098
+ await clock.tickAsync(1000);
5099
+
5100
+ // Now abort the controller while getHashesFromLocus is pending
5101
+ expect(parser.dataSets.main.syncAbortController).to.not.be.undefined;
5102
+ parser.dataSets.main.syncAbortController.abort();
5103
+
5104
+ // Resolve GET hashtree with mismatched hashes so the code would normally proceed to /sync
5105
+ resolveGetHashtree({
5106
+ body: {
5107
+ hashes: new Array(16).fill('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5108
+ dataSet: createDataSet('main', 16, 1100),
5109
+ },
5110
+ });
5111
+
5112
+ await testUtils.flushPromises();
5113
+
5114
+ // POST sync should NOT have been called because the controller was aborted
5115
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${mainUrl}/sync`}));
5116
+ });
5117
+
5118
+ it('should abort the sync before /sync request when the controller is aborted for leafCount === 1 datasets', async () => {
5119
+ const parser = createHashTreeParser();
5120
+ const selfUrl = parser.dataSets.self.url;
5121
+
5122
+ // Pre-set an already-aborted controller so performSync picks it up via ??
5123
+ const abortedController = new AbortController();
5124
+ abortedController.abort();
5125
+ parser.dataSets.self.syncAbortController = abortedController;
5126
+
5127
+ // Mock POST sync - should NOT be called
5128
+ mockSendSyncRequestResponse(selfUrl, null);
5129
+
5130
+ // Trigger sync for self via heartbeat with mismatched root hash
5131
+ parser.handleMessage(
5132
+ {
5133
+ dataSets: [
5134
+ {
5135
+ ...createDataSet('self', 1, 2100),
5136
+ url: parser.dataSets.self.url,
5137
+ root: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb1',
5138
+ },
5139
+ ],
5140
+ visibleDataSetsUrl,
5141
+ locusUrl,
5142
+ },
5143
+ 'trigger self sync'
5144
+ );
5145
+
5146
+ // Fire the timer to start the sync
5147
+ await clock.tickAsync(1000);
5148
+
5149
+ // GET hashtree should NOT have been called (leafCount === 1 skips it)
5150
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${selfUrl}/hashtree`}));
5151
+
5152
+ // POST sync should NOT have been called because the controller was already aborted
5153
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
5154
+ });
5155
+
5156
+ it('should unconditionally clear syncAbortController in the finally block', async () => {
5157
+ const parser = createHashTreeParser();
5158
+ const mainUrl = parser.dataSets.main.url;
5159
+
5160
+ // Mock GET hashtree to return matching hashes (early return, no sync needed)
5161
+ webexRequest
5162
+ .withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}))
5163
+ .resolves({body: {}});
5164
+
5165
+ // Trigger sync for main
5166
+ parser.handleMessage(
5167
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5168
+ 'trigger main sync'
5169
+ );
5170
+
5171
+ await clock.tickAsync(1000);
5172
+
5173
+ // After sync completes (even via early return), syncAbortController should be cleared
5174
+ expect(parser.dataSets.main.syncAbortController).to.be.undefined;
5175
+ });
5176
+
5177
+ it('should unconditionally clear syncAbortController even when sync throws an error', async () => {
5178
+ const parser = createHashTreeParser();
5179
+ const mainUrl = parser.dataSets.main.url;
5180
+
5181
+ // Mock GET hashtree to reject with a non-409 error
5182
+ webexRequest
5183
+ .withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}))
5184
+ .rejects({statusCode: 500, message: 'Internal Server Error'});
5185
+
5186
+ // Trigger sync for main
5187
+ parser.handleMessage(
5188
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5189
+ 'trigger main sync'
5190
+ );
5191
+
5192
+ await clock.tickAsync(1000);
5193
+
5194
+ // After sync completes with error, syncAbortController should still be cleared
5195
+ expect(parser.dataSets.main.syncAbortController).to.be.undefined;
5196
+ });
5197
+
5198
+ it('should reuse a pre-existing abort controller and respect its aborted state', async () => {
5199
+ const parser = createHashTreeParser();
5200
+ const mainUrl = parser.dataSets.main.url;
5201
+
5202
+ // Pre-set an AbortController and abort it before sync starts
5203
+ const preAbortedController = new AbortController();
5204
+ preAbortedController.abort();
5205
+ parser.dataSets.main.syncAbortController = preAbortedController;
5206
+
5207
+ // Mock GET hashtree to return mismatched hashes
5208
+ mockGetHashesFromLocusResponse(
5209
+ mainUrl,
5210
+ new Array(16).fill('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5211
+ createDataSet('main', 16, 1100)
5212
+ );
5213
+
5214
+ // Mock POST sync - should NOT be called
5215
+ mockSendSyncRequestResponse(mainUrl, null);
5216
+
5217
+ // Trigger sync for main
5218
+ parser.handleMessage(
5219
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5220
+ 'trigger main sync'
5221
+ );
5222
+
5223
+ await clock.tickAsync(1000);
5224
+
5225
+ // POST sync should NOT have been called because the reused controller was already aborted
5226
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${mainUrl}/sync`}));
5227
+
5228
+ // syncAbortController should be cleaned up
5229
+ expect(parser.dataSets.main.syncAbortController).to.be.undefined;
5230
+ });
5231
+
5232
+ it('should allow cancelPendingSyncsForDataSets to abort an in-flight sync via the shared controller', async () => {
5233
+ const parser = createHashTreeParser();
5234
+ const mainUrl = parser.dataSets.main.url;
5235
+
5236
+ // Use a deferred promise for GET hashtree
5237
+ let resolveGetHashtree;
5238
+ webexRequest.withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`})).callsFake(
5239
+ () =>
5240
+ new Promise((resolve) => {
5241
+ resolveGetHashtree = resolve;
5242
+ })
5243
+ );
5244
+
5245
+ mockSendSyncRequestResponse(mainUrl, null);
5246
+
5247
+ // Trigger sync for main
5248
+ parser.handleMessage(
5249
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5250
+ 'trigger main sync'
5251
+ );
5252
+
5253
+ // Fire the timer to start sync
5254
+ await clock.tickAsync(1000);
5255
+
5256
+ // Verify controller is set
5257
+ expect(parser.dataSets.main.syncAbortController).to.not.be.undefined;
5258
+
5259
+ // Simulate a new heartbeat arriving that cancels the in-flight sync
5260
+ // (this is what happens in production via parseMessage -> cancelPendingSyncsForDataSets)
5261
+ parser.handleMessage(
5262
+ {
5263
+ dataSets: [
5264
+ {
5265
+ ...createDataSet('main', 16, 1101),
5266
+ root: parser.dataSets.main.hashTree.getRootHash(), // matching hash so no new sync
5267
+ },
5268
+ ],
5269
+ visibleDataSetsUrl,
5270
+ locusUrl,
5271
+ },
5272
+ 'new heartbeat cancels sync'
5273
+ );
5274
+
5275
+ // Resolve the pending GET hashtree with mismatched hashes
5276
+ resolveGetHashtree({
5277
+ body: {
5278
+ hashes: new Array(16).fill('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5279
+ dataSet: createDataSet('main', 16, 1101),
5280
+ },
5281
+ });
5282
+
5283
+ await testUtils.flushPromises();
5284
+
5285
+ // POST sync should NOT have been called because cancelPendingSyncsForDataSets aborted the controller
5286
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${mainUrl}/sync`}));
5287
+ });
5288
+ });
5289
+
5290
+ describe('#cleanUp', () => {
5291
+ it('should stop the parser, clear all timers and clear all dataSets', () => {
5292
+ const parser = createHashTreeParser();
5293
+
5294
+ // Send a message to set up sync timers via runSyncAlgorithm
5295
+ const message = {
5296
+ dataSets: [
5297
+ {
5298
+ ...createDataSet('main', 16, 1100),
5299
+ root: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1',
5300
+ },
5301
+ ],
5302
+ visibleDataSetsUrl,
5303
+ locusUrl,
5304
+ locusStateElements: [
5305
+ {
5306
+ htMeta: {
5307
+ elementId: {type: 'locus' as const, id: 0, version: 201},
5308
+ dataSetNames: ['main'],
5309
+ },
5310
+ data: {someData: 'value'},
5311
+ },
5312
+ ],
5313
+ };
5314
+
5315
+ parser.handleMessage(message, 'setup timers');
5316
+
5317
+ // Verify timers were set by handleMessage
5318
+ expect(parser.dataSets.main.timer).to.not.be.undefined;
5319
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
5320
+
5321
+ parser.cleanUp();
5322
+
5323
+ expect(parser.state).to.equal('stopped');
5324
+ expect(parser.visibleDataSets).to.deep.equal([]);
5325
+ expect(parser.dataSets).to.deep.equal({});
5326
+ });
5327
+ });
3798
5328
  });