@webex/plugin-meetings 3.12.0-next.11 → 3.12.0-next.111

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 (235) 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/events.js +29 -14
  7. package/dist/breakouts/events.js.map +1 -1
  8. package/dist/breakouts/index.js +90 -3
  9. package/dist/breakouts/index.js.map +1 -1
  10. package/dist/common/errors/webex-errors.js +49 -5
  11. package/dist/common/errors/webex-errors.js.map +1 -1
  12. package/dist/config.js +2 -2
  13. package/dist/config.js.map +1 -1
  14. package/dist/constants.js +37 -10
  15. package/dist/constants.js.map +1 -1
  16. package/dist/controls-options-manager/constants.js +11 -1
  17. package/dist/controls-options-manager/constants.js.map +1 -1
  18. package/dist/controls-options-manager/index.js +67 -29
  19. package/dist/controls-options-manager/index.js.map +1 -1
  20. package/dist/controls-options-manager/util.js +91 -0
  21. package/dist/controls-options-manager/util.js.map +1 -1
  22. package/dist/hashTree/constants.js +4 -1
  23. package/dist/hashTree/constants.js.map +1 -1
  24. package/dist/hashTree/hashTreeParser.js +1003 -393
  25. package/dist/hashTree/hashTreeParser.js.map +1 -1
  26. package/dist/hashTree/utils.js +20 -0
  27. package/dist/hashTree/utils.js.map +1 -1
  28. package/dist/index.js +7 -0
  29. package/dist/index.js.map +1 -1
  30. package/dist/interceptors/dataChannelAuthToken.js +75 -15
  31. package/dist/interceptors/dataChannelAuthToken.js.map +1 -1
  32. package/dist/interceptors/locusRetry.js +23 -8
  33. package/dist/interceptors/locusRetry.js.map +1 -1
  34. package/dist/interpretation/index.js +10 -1
  35. package/dist/interpretation/index.js.map +1 -1
  36. package/dist/interpretation/interpretation.types.js +7 -0
  37. package/dist/interpretation/interpretation.types.js.map +1 -0
  38. package/dist/interpretation/siLanguage.js +1 -1
  39. package/dist/locus-info/controlsUtils.js +4 -1
  40. package/dist/locus-info/controlsUtils.js.map +1 -1
  41. package/dist/locus-info/index.js +406 -121
  42. package/dist/locus-info/index.js.map +1 -1
  43. package/dist/locus-info/infoUtils.js +36 -5
  44. package/dist/locus-info/infoUtils.js.map +1 -1
  45. package/dist/locus-info/types.js +19 -0
  46. package/dist/locus-info/types.js.map +1 -1
  47. package/dist/media/MediaConnectionAwaiter.js +15 -2
  48. package/dist/media/MediaConnectionAwaiter.js.map +1 -1
  49. package/dist/media/index.js +8 -2
  50. package/dist/media/index.js.map +1 -1
  51. package/dist/media/properties.js +4 -5
  52. package/dist/media/properties.js.map +1 -1
  53. package/dist/meeting/in-meeting-actions.js +5 -1
  54. package/dist/meeting/in-meeting-actions.js.map +1 -1
  55. package/dist/meeting/index.js +1662 -829
  56. package/dist/meeting/index.js.map +1 -1
  57. package/dist/meeting/locusMediaRequest.js +229 -82
  58. package/dist/meeting/locusMediaRequest.js.map +1 -1
  59. package/dist/meeting/muteState.js +10 -1
  60. package/dist/meeting/muteState.js.map +1 -1
  61. package/dist/meeting/request.js +5 -2
  62. package/dist/meeting/request.js.map +1 -1
  63. package/dist/meeting/util.js +34 -2
  64. package/dist/meeting/util.js.map +1 -1
  65. package/dist/meeting-info/meeting-info-v2.js +2 -2
  66. package/dist/meeting-info/meeting-info-v2.js.map +1 -1
  67. package/dist/meetings/index.js +256 -118
  68. package/dist/meetings/index.js.map +1 -1
  69. package/dist/meetings/meetings.types.js +6 -1
  70. package/dist/meetings/meetings.types.js.map +1 -1
  71. package/dist/meetings/request.js +39 -0
  72. package/dist/meetings/request.js.map +1 -1
  73. package/dist/meetings/util.js +116 -18
  74. package/dist/meetings/util.js.map +1 -1
  75. package/dist/member/index.js +10 -0
  76. package/dist/member/index.js.map +1 -1
  77. package/dist/member/types.js.map +1 -1
  78. package/dist/member/util.js +30 -0
  79. package/dist/member/util.js.map +1 -1
  80. package/dist/members/index.js +101 -43
  81. package/dist/members/index.js.map +1 -1
  82. package/dist/members/util.js +8 -1
  83. package/dist/members/util.js.map +1 -1
  84. package/dist/metrics/constants.js +7 -1
  85. package/dist/metrics/constants.js.map +1 -1
  86. package/dist/multistream/codec/constants.js +63 -0
  87. package/dist/multistream/codec/constants.js.map +1 -0
  88. package/dist/multistream/mediaRequestManager.js +62 -15
  89. package/dist/multistream/mediaRequestManager.js.map +1 -1
  90. package/dist/multistream/receiveSlot.js +9 -0
  91. package/dist/multistream/receiveSlot.js.map +1 -1
  92. package/dist/reachability/clusterReachability.js.map +1 -1
  93. package/dist/reachability/index.js +121 -83
  94. package/dist/reachability/index.js.map +1 -1
  95. package/dist/reachability/reachability.types.js +2 -0
  96. package/dist/reachability/reachability.types.js.map +1 -1
  97. package/dist/reachability/util.js +45 -0
  98. package/dist/reachability/util.js.map +1 -1
  99. package/dist/reactions/reactions.type.js.map +1 -1
  100. package/dist/recording-controller/index.js +1 -3
  101. package/dist/recording-controller/index.js.map +1 -1
  102. package/dist/roap/turnDiscovery.js +8 -1
  103. package/dist/roap/turnDiscovery.js.map +1 -1
  104. package/dist/types/common/errors/webex-errors.d.ts +32 -2
  105. package/dist/types/config.d.ts +2 -2
  106. package/dist/types/constants.d.ts +13 -1
  107. package/dist/types/controls-options-manager/constants.d.ts +6 -1
  108. package/dist/types/controls-options-manager/index.d.ts +16 -0
  109. package/dist/types/hashTree/constants.d.ts +1 -0
  110. package/dist/types/hashTree/hashTreeParser.d.ts +178 -22
  111. package/dist/types/hashTree/utils.d.ts +7 -0
  112. package/dist/types/index.d.ts +3 -0
  113. package/dist/types/interceptors/locusRetry.d.ts +4 -4
  114. package/dist/types/interpretation/interpretation.types.d.ts +10 -0
  115. package/dist/types/locus-info/index.d.ts +61 -7
  116. package/dist/types/locus-info/infoUtils.d.ts +8 -0
  117. package/dist/types/locus-info/types.d.ts +21 -1
  118. package/dist/types/media/MediaConnectionAwaiter.d.ts +10 -1
  119. package/dist/types/media/properties.d.ts +6 -2
  120. package/dist/types/meeting/in-meeting-actions.d.ts +4 -0
  121. package/dist/types/meeting/index.d.ts +175 -11
  122. package/dist/types/meeting/locusMediaRequest.d.ts +12 -0
  123. package/dist/types/meeting/request.d.ts +1 -0
  124. package/dist/types/meeting/util.d.ts +9 -0
  125. package/dist/types/meetings/index.d.ts +38 -18
  126. package/dist/types/meetings/meetings.types.d.ts +15 -0
  127. package/dist/types/meetings/request.d.ts +14 -0
  128. package/dist/types/member/index.d.ts +1 -0
  129. package/dist/types/member/types.d.ts +1 -0
  130. package/dist/types/member/util.d.ts +9 -0
  131. package/dist/types/members/index.d.ts +15 -2
  132. package/dist/types/members/util.d.ts +1 -5
  133. package/dist/types/metrics/constants.d.ts +6 -0
  134. package/dist/types/multistream/codec/constants.d.ts +7 -0
  135. package/dist/types/multistream/mediaRequestManager.d.ts +22 -5
  136. package/dist/types/reachability/clusterReachability.d.ts +3 -3
  137. package/dist/types/reachability/index.d.ts +10 -3
  138. package/dist/types/reachability/reachability.types.d.ts +7 -0
  139. package/dist/types/reachability/util.d.ts +17 -0
  140. package/dist/types/reactions/reactions.type.d.ts +3 -0
  141. package/dist/webinar/index.js +307 -161
  142. package/dist/webinar/index.js.map +1 -1
  143. package/package.json +23 -23
  144. package/src/aiEnableRequest/index.ts +16 -0
  145. package/src/breakouts/breakout.ts +3 -1
  146. package/src/breakouts/events.ts +33 -11
  147. package/src/breakouts/index.ts +110 -1
  148. package/src/common/errors/webex-errors.ts +50 -3
  149. package/src/config.ts +2 -2
  150. package/src/constants.ts +21 -3
  151. package/src/controls-options-manager/constants.ts +14 -1
  152. package/src/controls-options-manager/index.ts +87 -28
  153. package/src/controls-options-manager/util.ts +81 -1
  154. package/src/hashTree/constants.ts +7 -0
  155. package/src/hashTree/hashTreeParser.ts +752 -192
  156. package/src/hashTree/utils.ts +19 -0
  157. package/src/index.ts +6 -0
  158. package/src/interceptors/dataChannelAuthToken.ts +88 -12
  159. package/src/interceptors/locusRetry.ts +25 -4
  160. package/src/interpretation/index.ts +27 -9
  161. package/src/interpretation/interpretation.types.ts +11 -0
  162. package/src/locus-info/controlsUtils.ts +3 -1
  163. package/src/locus-info/index.ts +412 -130
  164. package/src/locus-info/infoUtils.ts +41 -6
  165. package/src/locus-info/types.ts +25 -1
  166. package/src/media/MediaConnectionAwaiter.ts +21 -4
  167. package/src/media/index.ts +10 -1
  168. package/src/media/properties.ts +8 -3
  169. package/src/meeting/in-meeting-actions.ts +8 -0
  170. package/src/meeting/index.ts +913 -111
  171. package/src/meeting/locusMediaRequest.ts +106 -6
  172. package/src/meeting/muteState.ts +10 -1
  173. package/src/meeting/request.ts +11 -0
  174. package/src/meeting/util.ts +46 -5
  175. package/src/meeting-info/meeting-info-v2.ts +4 -2
  176. package/src/meetings/index.ts +168 -79
  177. package/src/meetings/meetings.types.ts +19 -0
  178. package/src/meetings/request.ts +43 -0
  179. package/src/meetings/util.ts +117 -4
  180. package/src/member/index.ts +10 -0
  181. package/src/member/types.ts +1 -0
  182. package/src/member/util.ts +29 -0
  183. package/src/members/index.ts +70 -7
  184. package/src/members/util.ts +12 -4
  185. package/src/metrics/constants.ts +6 -0
  186. package/src/multistream/codec/constants.ts +58 -0
  187. package/src/multistream/mediaRequestManager.ts +119 -28
  188. package/src/multistream/receiveSlot.ts +18 -0
  189. package/src/reachability/clusterReachability.ts +3 -2
  190. package/src/reachability/index.ts +47 -16
  191. package/src/reachability/reachability.types.ts +11 -0
  192. package/src/reachability/util.ts +36 -0
  193. package/src/reactions/reactions.type.ts +3 -0
  194. package/src/recording-controller/index.ts +1 -2
  195. package/src/roap/turnDiscovery.ts +9 -1
  196. package/src/webinar/index.ts +216 -38
  197. package/test/unit/spec/aiEnableRequest/index.ts +86 -0
  198. package/test/unit/spec/breakouts/breakout.ts +9 -3
  199. package/test/unit/spec/breakouts/events.ts +120 -2
  200. package/test/unit/spec/breakouts/index.ts +191 -2
  201. package/test/unit/spec/common/errors/webex-errors.ts +78 -0
  202. package/test/unit/spec/controls-options-manager/index.js +244 -29
  203. package/test/unit/spec/controls-options-manager/util.js +165 -0
  204. package/test/unit/spec/hashTree/hashTreeParser.ts +2110 -170
  205. package/test/unit/spec/hashTree/utils.ts +37 -0
  206. package/test/unit/spec/interceptors/dataChannelAuthToken.ts +196 -0
  207. package/test/unit/spec/interceptors/locusRetry.ts +205 -4
  208. package/test/unit/spec/interpretation/index.ts +26 -4
  209. package/test/unit/spec/locus-info/controlsUtils.js +172 -57
  210. package/test/unit/spec/locus-info/index.js +643 -63
  211. package/test/unit/spec/locus-info/infoUtils.js +184 -1
  212. package/test/unit/spec/media/MediaConnectionAwaiter.ts +55 -0
  213. package/test/unit/spec/media/index.ts +92 -0
  214. package/test/unit/spec/media/properties.ts +23 -23
  215. package/test/unit/spec/meeting/in-meeting-actions.ts +4 -0
  216. package/test/unit/spec/meeting/index.js +2711 -183
  217. package/test/unit/spec/meeting/locusMediaRequest.ts +406 -4
  218. package/test/unit/spec/meeting/muteState.js +81 -0
  219. package/test/unit/spec/meeting/request.js +12 -0
  220. package/test/unit/spec/meeting/utils.js +153 -1
  221. package/test/unit/spec/meeting-info/meetinginfov2.js +19 -10
  222. package/test/unit/spec/meetings/index.js +467 -36
  223. package/test/unit/spec/meetings/request.js +141 -0
  224. package/test/unit/spec/meetings/utils.js +402 -51
  225. package/test/unit/spec/member/index.js +7 -0
  226. package/test/unit/spec/member/util.js +89 -0
  227. package/test/unit/spec/members/index.js +216 -0
  228. package/test/unit/spec/members/request.js +37 -1
  229. package/test/unit/spec/members/utils.js +63 -0
  230. package/test/unit/spec/multistream/mediaRequestManager.ts +501 -37
  231. package/test/unit/spec/reachability/index.ts +128 -46
  232. package/test/unit/spec/reachability/util.ts +31 -0
  233. package/test/unit/spec/recording-controller/index.js +9 -8
  234. package/test/unit/spec/roap/turnDiscovery.ts +20 -0
  235. package/test/unit/spec/webinar/index.ts +332 -31
@@ -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,31 +158,42 @@ 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
167
177
  function createHashTreeParser(
168
178
  initialLocus: any = exampleInitialLocus,
169
179
  metadata: any = exampleMetadata,
170
- excludedDataSets?: string[]
180
+ excludedDataSets?: string[],
181
+ syncLatencyTracker?: any,
182
+ syncLatencyMeetingId = 'meeting-1',
183
+ generateTrackingId?: any
171
184
  ) {
172
185
  return new HashTreeParser({
173
186
  initialLocus,
174
187
  metadata,
175
188
  webexRequest,
176
- locusInfoUpdateCallback: callback,
189
+ callbacks: {
190
+ locusInfoUpdateCallback: callback,
191
+ syncLatencyTracker,
192
+ generateTrackingId,
193
+ },
177
194
  debugId: 'test',
178
195
  excludedDataSets,
196
+ syncLatencyMeetingId,
179
197
  });
180
198
  }
181
199
 
@@ -216,7 +234,7 @@ describe('HashTreeParser', () => {
216
234
  }
217
235
 
218
236
  // Helper to mock sendSyncRequestToLocus response
219
- function mockSendSyncRequestResponse(dataSetUrl: string, response: any) {
237
+ function mockSendSyncRequestResponse(dataSetUrl: string, response: any, headers?: any) {
220
238
  webexRequest
221
239
  .withArgs(
222
240
  sinon.match({
@@ -226,6 +244,7 @@ describe('HashTreeParser', () => {
226
244
  )
227
245
  .resolves({
228
246
  body: response,
247
+ headers,
229
248
  });
230
249
  }
231
250
 
@@ -566,6 +585,11 @@ describe('HashTreeParser', () => {
566
585
  },
567
586
  data: {info: {id: 'some-fake-locus-info'}},
568
587
  },
588
+ ],
589
+ });
590
+
591
+ assert.calledWith(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
592
+ updatedObjects: [
569
593
  {
570
594
  htMeta: {
571
595
  elementId: {
@@ -631,6 +655,32 @@ describe('HashTreeParser', () => {
631
655
  expect(syncCalls[2].args[0].uri).to.equal(`${atdActiveDataSet.url}/sync`);
632
656
  });
633
657
 
658
+ it('sends leafCount=1 with a single empty leaf for initialization sync, regardless of actual dataset leafCount', async () => {
659
+ const parser = createHashTreeParser({dataSets: [], locus: null}, null);
660
+
661
+ // Use a dataset with leafCount=16 to verify the initialization sync always uses leafCount=1
662
+ const mainDataSet = createDataSet('main', 16, 1100);
663
+
664
+ mockGetAllDataSetsMetadata(webexRequest, visibleDataSetsUrl, [mainDataSet]);
665
+ mockSyncRequest(webexRequest, mainDataSet.url);
666
+
667
+ await parser.initializeFromMessage({
668
+ dataSets: [],
669
+ visibleDataSetsUrl,
670
+ locusUrl,
671
+ });
672
+
673
+ assert.calledWith(webexRequest, {
674
+ method: 'POST',
675
+ uri: `${mainDataSet.url}/sync`,
676
+ qs: {rootHash: sinon.match.string},
677
+ body: {
678
+ leafCount: 1,
679
+ leafDataEntries: [{leafIndex: 0, elementIds: []}],
680
+ },
681
+ });
682
+ });
683
+
634
684
  it('handles sync response that has locusStateElements undefined', async () => {
635
685
  const minimalInitialLocus = {
636
686
  dataSets: [],
@@ -671,8 +721,11 @@ describe('HashTreeParser', () => {
671
721
  assert.notCalled(callback);
672
722
  });
673
723
 
674
- [404, 409].forEach((errorCode) => {
675
- it(`emits MeetingEndedError if getting visible datasets returns ${errorCode}`, async () => {
724
+ [
725
+ {errorCode: 404, expectedError: LocusNotFoundError},
726
+ {errorCode: 409, expectedError: MeetingEndedError},
727
+ ].forEach(({errorCode, expectedError}) => {
728
+ it(`throws ${expectedError.name} if getting visible datasets returns ${errorCode}`, async () => {
676
729
  const minimalInitialLocus = {
677
730
  dataSets: [],
678
731
  locus: null,
@@ -695,7 +748,6 @@ describe('HashTreeParser', () => {
695
748
  )
696
749
  .rejects(error);
697
750
 
698
- // initializeFromMessage should throw MeetingEndedError
699
751
  let thrownError;
700
752
  try {
701
753
  await parser.initializeFromMessage({
@@ -707,7 +759,7 @@ describe('HashTreeParser', () => {
707
759
  thrownError = e;
708
760
  }
709
761
 
710
- expect(thrownError).to.be.instanceOf(MeetingEndedError);
762
+ expect(thrownError).to.be.instanceOf(expectedError);
711
763
  });
712
764
  });
713
765
  });
@@ -1729,12 +1781,10 @@ describe('HashTreeParser', () => {
1729
1781
  });
1730
1782
  });
1731
1783
 
1732
- describe('emits MEETING_ENDED', () => {
1733
- [404, 409].forEach((statusCode) => {
1734
- it(`when /hashtree returns ${statusCode}`, async () => {
1784
+ describe('emits MEETING_ENDED when 409/2403004 is returned', () => {
1785
+ it('when /hashtree returns 409', async () => {
1735
1786
  const parser = createHashTreeParser();
1736
1787
 
1737
- // Send a message to trigger sync algorithm
1738
1788
  const message = {
1739
1789
  dataSets: [createDataSet('main', 16, 1100)],
1740
1790
  visibleDataSetsUrl,
@@ -1759,12 +1809,9 @@ describe('HashTreeParser', () => {
1759
1809
 
1760
1810
  const mainDataSetUrl = parser.dataSets.main.url;
1761
1811
 
1762
- // Mock getHashesFromLocus to reject with the sentinel error
1763
- const error: any = new Error(`Request failed with status ${statusCode}`);
1764
- error.statusCode = statusCode;
1765
- if (statusCode === 409) {
1766
- error.body = {errorCode: 2403004};
1767
- }
1812
+ const error: any = new Error('Request failed with status 409');
1813
+ error.statusCode = 409;
1814
+ error.body = {errorCode: 2403004};
1768
1815
  webexRequest
1769
1816
  .withArgs(
1770
1817
  sinon.match({
@@ -1774,23 +1821,22 @@ describe('HashTreeParser', () => {
1774
1821
  )
1775
1822
  .rejects(error);
1776
1823
 
1777
- // Trigger sync by advancing time
1778
1824
  await clock.tickAsync(1000);
1779
1825
 
1780
- // Verify callback was called with MEETING_ENDED
1781
1826
  assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.MEETING_ENDED});
1782
1827
 
1783
- // Verify all timers are stopped
1784
1828
  Object.values(parser.dataSets).forEach((ds: any) => {
1785
1829
  assert.isUndefined(ds.timer);
1786
1830
  assert.isUndefined(ds.heartbeatWatchdogTimer);
1787
1831
  });
1832
+
1833
+ // Verify no sync failure metric was sent for end-meeting sentinel
1834
+ assert.notCalled(metricsStub);
1788
1835
  });
1789
1836
 
1790
- it(`when /sync returns ${statusCode}`, async () => {
1837
+ it('when /sync returns 409', async () => {
1791
1838
  const parser = createHashTreeParser();
1792
1839
 
1793
- // Send a message to trigger sync algorithm
1794
1840
  const message = {
1795
1841
  dataSets: [createDataSet('main', 16, 1100)],
1796
1842
  visibleDataSetsUrl,
@@ -1815,19 +1861,15 @@ describe('HashTreeParser', () => {
1815
1861
 
1816
1862
  const mainDataSetUrl = parser.dataSets.main.url;
1817
1863
 
1818
- // Mock getHashesFromLocus to succeed
1819
1864
  mockGetHashesFromLocusResponse(
1820
1865
  mainDataSetUrl,
1821
1866
  new Array(16).fill('00000000000000000000000000000000'),
1822
1867
  createDataSet('main', 16, 1101)
1823
1868
  );
1824
1869
 
1825
- // Mock sendSyncRequestToLocus to reject with the sentinel error
1826
- const error: any = new Error(`Request failed with status ${statusCode}`);
1827
- error.statusCode = statusCode;
1828
- if (statusCode === 409) {
1829
- error.body = {errorCode: 2403004};
1830
- }
1870
+ const error: any = new Error('Request failed with status 409');
1871
+ error.statusCode = 409;
1872
+ error.body = {errorCode: 2403004};
1831
1873
  webexRequest
1832
1874
  .withArgs(
1833
1875
  sinon.match({
@@ -1837,19 +1879,130 @@ describe('HashTreeParser', () => {
1837
1879
  )
1838
1880
  .rejects(error);
1839
1881
 
1840
- // Trigger sync by advancing time
1841
1882
  await clock.tickAsync(1000);
1842
1883
 
1843
- // Verify callback was called with MEETING_ENDED
1844
1884
  assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.MEETING_ENDED});
1845
1885
 
1886
+ Object.values(parser.dataSets).forEach((ds: any) => {
1887
+ assert.isUndefined(ds.timer);
1888
+ assert.isUndefined(ds.heartbeatWatchdogTimer);
1889
+ });
1890
+ });
1891
+ });
1892
+
1893
+ describe('emits LOCUS_NOT_FOUND and stops parser when 404 is returned', () => {
1894
+ it('when /hashtree returns 404', async () => {
1895
+ const parser = createHashTreeParser();
1896
+
1897
+ const message = {
1898
+ dataSets: [createDataSet('main', 16, 1100)],
1899
+ visibleDataSetsUrl,
1900
+ locusUrl,
1901
+ locusStateElements: [
1902
+ {
1903
+ htMeta: {
1904
+ elementId: {
1905
+ type: 'locus' as const,
1906
+ id: 0,
1907
+ version: 201,
1908
+ },
1909
+ dataSetNames: ['main'],
1910
+ },
1911
+ data: {info: {id: 'initial-update'}},
1912
+ },
1913
+ ],
1914
+ };
1915
+
1916
+ parser.handleMessage(message, 'initial message');
1917
+ callback.resetHistory();
1918
+
1919
+ const mainDataSetUrl = parser.dataSets.main.url;
1920
+
1921
+ const error: any = new Error('Request failed with status 404');
1922
+ error.statusCode = 404;
1923
+ webexRequest
1924
+ .withArgs(
1925
+ sinon.match({
1926
+ method: 'GET',
1927
+ uri: `${mainDataSetUrl}/hashtree`,
1928
+ })
1929
+ )
1930
+ .rejects(error);
1931
+
1932
+ await clock.tickAsync(1000);
1933
+
1934
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.LOCUS_NOT_FOUND});
1935
+
1936
+ // Verify parser is stopped
1937
+ expect(parser.state).to.equal('stopped');
1938
+
1846
1939
  // Verify all timers are stopped
1847
1940
  Object.values(parser.dataSets).forEach((ds: any) => {
1848
1941
  assert.isUndefined(ds.timer);
1849
1942
  assert.isUndefined(ds.heartbeatWatchdogTimer);
1850
1943
  });
1851
1944
  });
1852
- });
1945
+
1946
+ it('when /sync returns 404', async () => {
1947
+ const parser = createHashTreeParser();
1948
+
1949
+ const message = {
1950
+ dataSets: [createDataSet('main', 16, 1100)],
1951
+ visibleDataSetsUrl,
1952
+ locusUrl,
1953
+ locusStateElements: [
1954
+ {
1955
+ htMeta: {
1956
+ elementId: {
1957
+ type: 'locus' as const,
1958
+ id: 0,
1959
+ version: 201,
1960
+ },
1961
+ dataSetNames: ['main'],
1962
+ },
1963
+ data: {info: {id: 'initial-update'}},
1964
+ },
1965
+ ],
1966
+ };
1967
+
1968
+ parser.handleMessage(message, 'initial message');
1969
+ callback.resetHistory();
1970
+
1971
+ const mainDataSetUrl = parser.dataSets.main.url;
1972
+
1973
+ mockGetHashesFromLocusResponse(
1974
+ mainDataSetUrl,
1975
+ new Array(16).fill('00000000000000000000000000000000'),
1976
+ createDataSet('main', 16, 1101)
1977
+ );
1978
+
1979
+ const error: any = new Error('Request failed with status 404');
1980
+ error.statusCode = 404;
1981
+ webexRequest
1982
+ .withArgs(
1983
+ sinon.match({
1984
+ method: 'POST',
1985
+ uri: `${mainDataSetUrl}/sync`,
1986
+ })
1987
+ )
1988
+ .rejects(error);
1989
+
1990
+ await clock.tickAsync(1000);
1991
+
1992
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.LOCUS_NOT_FOUND});
1993
+
1994
+ // Verify parser is stopped
1995
+ expect(parser.state).to.equal('stopped');
1996
+
1997
+ // Verify all timers are stopped
1998
+ Object.values(parser.dataSets).forEach((ds: any) => {
1999
+ assert.isUndefined(ds.timer);
2000
+ assert.isUndefined(ds.heartbeatWatchdogTimer);
2001
+ });
2002
+
2003
+ // Verify no sync failure metric was sent for end-meeting sentinel
2004
+ assert.notCalled(metricsStub);
2005
+ });
1853
2006
  });
1854
2007
 
1855
2008
  it('requests only mismatched hashes during sync', async () => {
@@ -2020,98 +2173,319 @@ describe('HashTreeParser', () => {
2020
2173
  },
2021
2174
  });
2022
2175
  });
2023
- });
2024
2176
 
2025
- describe('handles visible data sets changes correctly', () => {
2026
- it('handles addition of visible data set (one that does not require async initialization)', async () => {
2027
- // Create a parser with visible datasets
2177
+ it('restarts the sync timer when sync response is empty so that a future sync can be triggered', async () => {
2028
2178
  const parser = createHashTreeParser();
2029
2179
 
2030
- // Stub updateItems on self hash tree to return true
2031
- sinon.stub(parser.dataSets.self.hashTree, 'updateItems').returns([true]);
2032
-
2033
- // Send a message with Metadata object that has a new visibleDataSets list
2034
- const message = {
2035
- dataSets: [createDataSet('self', 1, 2100), createDataSet('attendees', 8, 4000)],
2036
- visibleDataSetsUrl,
2037
- locusUrl,
2038
- locusStateElements: [
2180
+ // Send a heartbeat with a mismatched root hash to trigger runSyncAlgorithm
2181
+ const heartbeatMessage = {
2182
+ dataSets: [
2039
2183
  {
2040
- htMeta: {
2041
- elementId: {
2042
- type: 'metadata' as const,
2043
- id: 5,
2044
- version: 51,
2045
- },
2046
- dataSetNames: ['self'],
2047
- },
2048
- data: {
2049
- visibleDataSets: [
2050
- {
2051
- name: 'main',
2052
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/main',
2053
- },
2054
- {
2055
- name: 'self',
2056
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self',
2057
- },
2058
- {
2059
- name: 'atd-unmuted',
2060
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted',
2061
- },
2062
- {
2063
- name: 'attendees',
2064
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/attendees',
2065
- },
2066
- ], // added 'attendees'
2067
- },
2184
+ ...createDataSet('main', 16, 1100),
2185
+ root: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1', // different from ours
2068
2186
  },
2069
2187
  ],
2188
+ visibleDataSetsUrl,
2189
+ locusUrl,
2070
2190
  };
2071
2191
 
2072
- parser.handleMessage(message, 'add visible dataset');
2192
+ parser.handleMessage(heartbeatMessage, 'heartbeat with mismatch');
2073
2193
 
2074
- // Verify that 'attendees' was added to visibleDataSets
2075
- expect(parser.visibleDataSets.some((vds) => vds.name === 'attendees')).to.be.true;
2194
+ // The sync timer should be set
2195
+ expect(parser.dataSets.main.timer).to.not.be.undefined;
2076
2196
 
2077
- // Verify that a hash tree was created for 'attendees'
2078
- assert.exists(parser.dataSets.attendees.hashTree);
2079
- assert.equal(parser.dataSets.attendees.hashTree.numLeaves, 8);
2197
+ // Mock responses for the first sync - return null (204/empty body)
2198
+ const mainDataSetUrl = parser.dataSets.main.url;
2199
+ mockGetHashesFromLocusResponse(
2200
+ mainDataSetUrl,
2201
+ new Array(16).fill('00000000000000000000000000000000'),
2202
+ {
2203
+ ...createDataSet('main', 16, 1101),
2204
+ root: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', // still mismatched
2205
+ }
2206
+ );
2207
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
2080
2208
 
2081
- // Verify callback was called with the metadata update (appears twice - processed once for visible dataset changes, once in main loop)
2082
- assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
2083
- updatedObjects: [
2209
+ // Advance time to fire the sync timer (idleMs=1000 + backoff=0)
2210
+ await clock.tickAsync(1000);
2211
+
2212
+ // Verify sync was triggered
2213
+ assert.calledWith(
2214
+ webexRequest,
2215
+ sinon.match({
2216
+ method: 'POST',
2217
+ uri: `${mainDataSetUrl}/sync`,
2218
+ })
2219
+ );
2220
+
2221
+ // After empty response, runSyncAlgorithm should have been called,
2222
+ // setting a new sync timer as a safety net
2223
+ expect(parser.dataSets.main.timer).to.not.be.undefined;
2224
+
2225
+ // Reset and set up mocks for the second sync
2226
+ webexRequest.resetHistory();
2227
+ mockGetHashesFromLocusResponse(
2228
+ mainDataSetUrl,
2229
+ new Array(16).fill('00000000000000000000000000000000'),
2230
+ {
2231
+ ...createDataSet('main', 16, 1102),
2232
+ root: 'cccccccccccccccccccccccccccccccc', // still mismatched
2233
+ }
2234
+ );
2235
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
2236
+
2237
+ // Advance time again to fire the second sync timer
2238
+ await clock.tickAsync(1000);
2239
+
2240
+ // Verify a second sync was triggered
2241
+ assert.calledWith(
2242
+ webexRequest,
2243
+ sinon.match({
2244
+ method: 'POST',
2245
+ uri: `${mainDataSetUrl}/sync`,
2246
+ })
2247
+ );
2248
+ });
2249
+
2250
+ it('updates dataSet.leafCount when hash tree is resized during sync so that the sync request has the correct leafCount', async () => {
2251
+ const parser = createHashTreeParser();
2252
+
2253
+ // Send a heartbeat with a mismatched root hash to trigger runSyncAlgorithm
2254
+ const heartbeatMessage = {
2255
+ dataSets: [
2084
2256
  {
2085
- htMeta: {
2086
- elementId: {type: 'metadata', id: 5, version: 51},
2087
- dataSetNames: ['self'],
2088
- },
2089
- data: {
2090
- visibleDataSets: [
2091
- {
2092
- name: 'main',
2093
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/main',
2094
- },
2095
- {
2096
- name: 'self',
2097
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self',
2098
- },
2099
- {
2100
- name: 'atd-unmuted',
2101
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted',
2102
- },
2103
- {
2104
- name: 'attendees',
2105
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/attendees',
2106
- },
2107
- ],
2108
- },
2257
+ ...createDataSet('main', 16, 1100),
2258
+ root: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1', // different from ours
2109
2259
  },
2110
- {
2111
- htMeta: {
2112
- elementId: {type: 'metadata', id: 5, version: 51},
2113
- dataSetNames: ['self'],
2114
- },
2260
+ ],
2261
+ visibleDataSetsUrl,
2262
+ locusUrl,
2263
+ };
2264
+
2265
+ parser.handleMessage(heartbeatMessage, 'heartbeat with mismatch');
2266
+
2267
+ // The sync timer should be set
2268
+ expect(parser.dataSets.main.timer).to.not.be.undefined;
2269
+
2270
+ const mainDataSetUrl = parser.dataSets.main.url;
2271
+ const newLeafCount = 32;
2272
+
2273
+ // Mock getHashesFromLocus response with a DIFFERENT leafCount (32 instead of 16)
2274
+ mockGetHashesFromLocusResponse(
2275
+ mainDataSetUrl,
2276
+ new Array(newLeafCount).fill('00000000000000000000000000000000'),
2277
+ createDataSet('main', newLeafCount, 1101)
2278
+ );
2279
+
2280
+ // Mock the sync request - use matching root hash
2281
+ const syncResponseDataSet = createDataSet('main', newLeafCount, 1102);
2282
+ syncResponseDataSet.root = parser.dataSets.main.hashTree.getRootHash();
2283
+ mockSendSyncRequestResponse(mainDataSetUrl, {
2284
+ dataSets: [syncResponseDataSet],
2285
+ visibleDataSetsUrl,
2286
+ locusUrl,
2287
+ locusStateElements: [],
2288
+ });
2289
+
2290
+ // Advance time to fire the sync timer (idleMs=1000 + backoff=0)
2291
+ await clock.tickAsync(1000);
2292
+
2293
+ // Verify the sync request was sent with the NEW leafCount (32), not the old one (16)
2294
+ assert.calledWith(
2295
+ webexRequest,
2296
+ sinon.match({
2297
+ method: 'POST',
2298
+ uri: `${mainDataSetUrl}/sync`,
2299
+ body: sinon.match({
2300
+ leafCount: newLeafCount,
2301
+ }),
2302
+ })
2303
+ );
2304
+ });
2305
+
2306
+ it('sends HASH_TREE_SYNC_FAILURE metric when GET /hashtree request fails', async () => {
2307
+ const parser = createHashTreeParser();
2308
+
2309
+ // Send a heartbeat with a mismatched root hash to trigger runSyncAlgorithm
2310
+ const heartbeatMessage = {
2311
+ dataSets: [
2312
+ {
2313
+ ...createDataSet('main', 16, 1100),
2314
+ root: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1',
2315
+ },
2316
+ ],
2317
+ visibleDataSetsUrl,
2318
+ locusUrl,
2319
+ };
2320
+
2321
+ parser.handleMessage(heartbeatMessage, 'heartbeat with mismatch');
2322
+
2323
+ const mainDataSetUrl = parser.dataSets.main.url;
2324
+ const hashTreeError = new Error('server error') as any;
2325
+ hashTreeError.statusCode = 500;
2326
+
2327
+ webexRequest
2328
+ .withArgs(
2329
+ sinon.match({
2330
+ method: 'GET',
2331
+ uri: `${mainDataSetUrl}/hashtree`,
2332
+ })
2333
+ )
2334
+ .rejects(hashTreeError);
2335
+
2336
+ await clock.tickAsync(1000);
2337
+
2338
+ assert.calledOnceWithExactly(metricsStub, BEHAVIORAL_METRICS.HASH_TREE_SYNC_FAILURE, {
2339
+ debugId: 'test',
2340
+ dataSetName: 'main',
2341
+ request: 'GET /hashtree',
2342
+ statusCode: 500,
2343
+ reason: 'server error',
2344
+ });
2345
+ });
2346
+
2347
+ it('sends HASH_TREE_SYNC_FAILURE metric when POST /sync request fails', async () => {
2348
+ const parser = createHashTreeParser();
2349
+
2350
+ // Send a heartbeat with a mismatched root hash to trigger runSyncAlgorithm
2351
+ const heartbeatMessage = {
2352
+ dataSets: [
2353
+ {
2354
+ ...createDataSet('main', 16, 1100),
2355
+ root: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1',
2356
+ },
2357
+ ],
2358
+ visibleDataSetsUrl,
2359
+ locusUrl,
2360
+ };
2361
+
2362
+ parser.handleMessage(heartbeatMessage, 'heartbeat with mismatch');
2363
+
2364
+ const mainDataSetUrl = parser.dataSets.main.url;
2365
+
2366
+ // Mock getHashesFromLocus to succeed
2367
+ mockGetHashesFromLocusResponse(
2368
+ mainDataSetUrl,
2369
+ new Array(16).fill('00000000000000000000000000000000'),
2370
+ createDataSet('main', 16, 1101)
2371
+ );
2372
+
2373
+ // Mock sendSyncRequestToLocus to fail
2374
+ const syncError = new Error('sync failed') as any;
2375
+ syncError.statusCode = 500;
2376
+
2377
+ webexRequest
2378
+ .withArgs(
2379
+ sinon.match({
2380
+ method: 'POST',
2381
+ uri: `${mainDataSetUrl}/sync`,
2382
+ })
2383
+ )
2384
+ .rejects(syncError);
2385
+
2386
+ await clock.tickAsync(1000);
2387
+
2388
+ assert.calledOnceWithExactly(metricsStub, BEHAVIORAL_METRICS.HASH_TREE_SYNC_FAILURE, {
2389
+ debugId: 'test',
2390
+ dataSetName: 'main',
2391
+ request: 'POST /sync',
2392
+ statusCode: 500,
2393
+ reason: 'sync failed',
2394
+ });
2395
+ });
2396
+
2397
+ });
2398
+
2399
+ describe('handles visible data sets changes correctly', () => {
2400
+ it('handles addition of visible data set (one that does not require async initialization)', async () => {
2401
+ // Create a parser with visible datasets
2402
+ const parser = createHashTreeParser();
2403
+
2404
+ // Stub updateItems on self hash tree to return true
2405
+ sinon.stub(parser.dataSets.self.hashTree, 'updateItems').returns([true]);
2406
+
2407
+ // Send a message with Metadata object that has a new visibleDataSets list
2408
+ const message = {
2409
+ dataSets: [createDataSet('self', 1, 2100), createDataSet('attendees', 8, 4000)],
2410
+ visibleDataSetsUrl,
2411
+ locusUrl,
2412
+ locusStateElements: [
2413
+ {
2414
+ htMeta: {
2415
+ elementId: {
2416
+ type: 'metadata' as const,
2417
+ id: 5,
2418
+ version: 51,
2419
+ },
2420
+ dataSetNames: ['self'],
2421
+ },
2422
+ data: {
2423
+ visibleDataSets: [
2424
+ {
2425
+ name: 'main',
2426
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/main',
2427
+ },
2428
+ {
2429
+ name: 'self',
2430
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self',
2431
+ },
2432
+ {
2433
+ name: 'atd-unmuted',
2434
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted',
2435
+ },
2436
+ {
2437
+ name: 'attendees',
2438
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/attendees',
2439
+ },
2440
+ ], // added 'attendees'
2441
+ },
2442
+ },
2443
+ ],
2444
+ };
2445
+
2446
+ parser.handleMessage(message, 'add visible dataset');
2447
+
2448
+ // Verify that 'attendees' was added to visibleDataSets
2449
+ expect(parser.visibleDataSets.some((vds) => vds.name === 'attendees')).to.be.true;
2450
+
2451
+ // Verify that a hash tree was created for 'attendees'
2452
+ assert.exists(parser.dataSets.attendees.hashTree);
2453
+ assert.equal(parser.dataSets.attendees.hashTree.numLeaves, 8);
2454
+
2455
+ // Verify callback was called with the metadata update (appears twice - processed once for visible dataset changes, once in main loop)
2456
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
2457
+ updatedObjects: [
2458
+ {
2459
+ htMeta: {
2460
+ elementId: {type: 'metadata', id: 5, version: 51},
2461
+ dataSetNames: ['self'],
2462
+ },
2463
+ data: {
2464
+ visibleDataSets: [
2465
+ {
2466
+ name: 'main',
2467
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/main',
2468
+ },
2469
+ {
2470
+ name: 'self',
2471
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self',
2472
+ },
2473
+ {
2474
+ name: 'atd-unmuted',
2475
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted',
2476
+ },
2477
+ {
2478
+ name: 'attendees',
2479
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/attendees',
2480
+ },
2481
+ ],
2482
+ },
2483
+ },
2484
+ {
2485
+ htMeta: {
2486
+ elementId: {type: 'metadata', id: 5, version: 51},
2487
+ dataSetNames: ['self'],
2488
+ },
2115
2489
  data: {
2116
2490
  visibleDataSets: [
2117
2491
  {
@@ -2291,7 +2665,7 @@ describe('HashTreeParser', () => {
2291
2665
  expect(syncCalls[1].args[0].uri).to.equal(`${newAtdActiveDataSet.url}/sync`);
2292
2666
  });
2293
2667
 
2294
- it('emits MEETING_ENDED if async init of a new visible dataset fails with 404', async () => {
2668
+ it('emits LOCUS_NOT_FOUND if async init of a new visible dataset fails with 404', async () => {
2295
2669
  const parser = createHashTreeParser();
2296
2670
 
2297
2671
  // Stub updateItems on self hash tree to return true
@@ -2356,8 +2730,8 @@ describe('HashTreeParser', () => {
2356
2730
  // Wait for the async initialization (queueMicrotask) to complete
2357
2731
  await clock.tickAsync(0);
2358
2732
 
2359
- // Verify callback was called with MEETING_ENDED
2360
- assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.MEETING_ENDED});
2733
+ // Verify callback was called with LOCUS_NOT_FOUND (404 means locus URL is stale, not necessarily meeting ended)
2734
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.LOCUS_NOT_FOUND});
2361
2735
  });
2362
2736
 
2363
2737
  it('handles removal of visible data set', async () => {
@@ -2517,6 +2891,151 @@ describe('HashTreeParser', () => {
2517
2891
  // Verify callback was NOT called (no updates for non-visible datasets)
2518
2892
  assert.notCalled(callback);
2519
2893
  });
2894
+
2895
+ it('reports update for object that moves from removed visible dataset to new visible dataset even if version is unchanged', async () => {
2896
+ // The purpose of this test is to verify that when an object
2897
+ // moves from one visible dataset to another without version change,
2898
+ // the parser still reports it as an update.
2899
+ // Locus has some additional signalling for this - the "view" property in htMeta.elementId.
2900
+ // When a view changes, the contents of the object may change even if version doesn't.
2901
+ // HashTreeParser doesn't use the "view" property, because it doesn't need to -
2902
+ // the same functionality is achieved thanks to the fact that a new visible data set means
2903
+ // a new hash tree is created, so HashTreeParser still detects the change as new
2904
+ // object is added to the new hash tree.
2905
+
2906
+ // Setup: parser with visible datasets "self" and "unjoined"
2907
+ const unjoinedDataSet = createDataSet('unjoined', 4, 3000);
2908
+ const selfDataSet = createDataSet('self', 1, 2000);
2909
+
2910
+ // start with Locus that has "info" in both "unjoined" and "main" datasets,
2911
+ // but only "unjoined" is visible.
2912
+ const initialLocus = {
2913
+ dataSets: [selfDataSet, unjoinedDataSet],
2914
+ locus: {
2915
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f',
2916
+ links: {resources: {visibleDataSets: {url: visibleDataSetsUrl}}},
2917
+ // info object in "unjoined" dataset with version 500
2918
+ info: {
2919
+ htMeta: {
2920
+ elementId: {
2921
+ type: 'info',
2922
+ id: 42,
2923
+ version: 500,
2924
+ view: ['unjoined'], // not used by our code, but here for completeness - that's what real Locus would send
2925
+ },
2926
+ dataSetNames: ['main', 'unjoined'],
2927
+ },
2928
+ someField: 'some-initial-value',
2929
+ },
2930
+ self: {
2931
+ htMeta: {
2932
+ elementId: {
2933
+ type: 'self',
2934
+ id: 4,
2935
+ version: 100,
2936
+ },
2937
+ dataSetNames: ['self'],
2938
+ },
2939
+ },
2940
+ },
2941
+ };
2942
+
2943
+ const metadata = {
2944
+ htMeta: {
2945
+ elementId: {
2946
+ type: 'metadata',
2947
+ id: 5,
2948
+ version: 50,
2949
+ },
2950
+ dataSetNames: ['self'],
2951
+ },
2952
+ visibleDataSets: [
2953
+ {name: 'self', url: selfDataSet.url},
2954
+ {name: 'unjoined', url: unjoinedDataSet.url},
2955
+ ],
2956
+ };
2957
+
2958
+ const parser = createHashTreeParser(initialLocus, metadata);
2959
+
2960
+ // Verify initial state: unjoined is visible and has the info object
2961
+ expect(parser.visibleDataSets.some((vds) => vds.name === 'unjoined')).to.be.true;
2962
+ assert.exists(parser.dataSets.unjoined.hashTree);
2963
+ assert.equal(parser.dataSets.unjoined.hashTree?.getItemVersion(42, 'info'), 500);
2964
+
2965
+ // Stub updateItems on self hash tree to return true for metadata update
2966
+ sinon.stub(parser.dataSets.self.hashTree, 'updateItems').returns([true]);
2967
+
2968
+ // Now send a message that:
2969
+ // 1. Changes visible datasets: removes "unjoined", adds "main"
2970
+ // 2. Contains the same info object (same id=42, same version=500) but we see the view from "main" dataset
2971
+ const mainDataSet = createDataSet('main', 16, 1000);
2972
+
2973
+ const message = {
2974
+ dataSets: [selfDataSet, mainDataSet],
2975
+ visibleDataSetsUrl,
2976
+ locusUrl,
2977
+ locusStateElements: [
2978
+ {
2979
+ htMeta: {
2980
+ elementId: {
2981
+ type: 'metadata' as const,
2982
+ id: 5,
2983
+ version: 51,
2984
+ },
2985
+ dataSetNames: ['self'],
2986
+ },
2987
+ data: {
2988
+ visibleDataSets: [
2989
+ {name: 'self', url: selfDataSet.url},
2990
+ {name: 'main', url: mainDataSet.url},
2991
+ // "unjoined" is no longer here
2992
+ ],
2993
+ },
2994
+ },
2995
+ {
2996
+ htMeta: {
2997
+ elementId: {
2998
+ type: 'info' as const,
2999
+ id: 42,
3000
+ version: 500, // same version as before
3001
+ view: ['main'], // now points to "main" instead of "unjoined"
3002
+ },
3003
+ dataSetNames: ['main', 'unjoined'], // still in both datasets, but only "main" is visible now
3004
+ },
3005
+ data: {someNewField: 'some-value'},
3006
+ },
3007
+ ],
3008
+ };
3009
+
3010
+ parser.handleMessage(message, 'visible dataset swap with same-version object');
3011
+
3012
+ // Verify "unjoined" is no longer visible and "main" is now visible
3013
+ expect(parser.visibleDataSets.some((vds) => vds.name === 'unjoined')).to.be.false;
3014
+ expect(parser.visibleDataSets.some((vds) => vds.name === 'main')).to.be.true;
3015
+
3016
+ // Verify the info object is now in the "main" hash tree
3017
+ assert.exists(parser.dataSets.main.hashTree);
3018
+ assert.equal(parser.dataSets.main.hashTree?.getItemVersion(42, 'info'), 500);
3019
+
3020
+ // The key assertion: callback should be called with the info object update even though
3021
+ // its version hasn't changed - because visible datasets changed (moved from unjoined to main)
3022
+ assert.calledOnce(callback);
3023
+ const callbackArgs = callback.firstCall.args[0];
3024
+ assert.equal(callbackArgs.updateType, LocusInfoUpdateType.OBJECTS_UPDATED);
3025
+
3026
+ // Should contain the info object update (with data)
3027
+ const infoUpdate = callbackArgs.updatedObjects.find(
3028
+ (obj) => obj.htMeta.elementId.type === 'info' && obj.htMeta.elementId.id === 42
3029
+ );
3030
+ assert.exists(infoUpdate);
3031
+ assert.deepEqual(infoUpdate.htMeta.elementId, {
3032
+ type: 'info',
3033
+ id: 42,
3034
+ version: 500,
3035
+ view: ['main'],
3036
+ });
3037
+ assert.deepEqual(infoUpdate.data, {someNewField: 'some-value'});
3038
+ });
2520
3039
  });
2521
3040
 
2522
3041
  describe('heartbeat watchdog', () => {
@@ -2534,7 +3053,6 @@ describe('HashTreeParser', () => {
2534
3053
  ],
2535
3054
  visibleDataSetsUrl,
2536
3055
  locusUrl,
2537
- heartbeatIntervalMs,
2538
3056
  };
2539
3057
 
2540
3058
  parser.handleMessage(heartbeatMessage, 'initial heartbeat');
@@ -2566,6 +3084,12 @@ describe('HashTreeParser', () => {
2566
3084
  })
2567
3085
  );
2568
3086
 
3087
+ // Verify behavioral metric was sent for the watchdog expiration
3088
+ assert.calledWith(metricsStub, BEHAVIORAL_METRICS.HASH_TREE_HEARTBEAT_WATCHDOG_EXPIRED, {
3089
+ debugId: 'test',
3090
+ dataSetName: 'main',
3091
+ });
3092
+
2569
3093
  // Verify no sync requests were sent for other datasets
2570
3094
  assert.neverCalledWith(
2571
3095
  webexRequest,
@@ -2583,6 +3107,106 @@ describe('HashTreeParser', () => {
2583
3107
  );
2584
3108
  });
2585
3109
 
3110
+ it('uses the watchdog random backoff when reporting sync metrics', async () => {
3111
+ const syncLatencyTracker = {
3112
+ saveLatency: sinon.stub(),
3113
+ saveTimestamp: sinon.stub(),
3114
+ getLocusSyncLatency: sinon.stub(),
3115
+ clearLocusSyncLatency: sinon.stub(),
3116
+ completeLocusSyncLatency: sinon.stub(),
3117
+ };
3118
+ const parser = createHashTreeParser(
3119
+ undefined,
3120
+ undefined,
3121
+ undefined,
3122
+ syncLatencyTracker
3123
+ );
3124
+ const heartbeatIntervalMs = 5000;
3125
+ const mainDataSetUrl = parser.dataSets.main.url;
3126
+
3127
+ mathRandomStub.onFirstCall().returns(0.1); // root-hash timer backoff = 10ms
3128
+ mathRandomStub.onSecondCall().returns(0.5); // watchdog backoff = 250ms
3129
+ mathRandomStub.returns(0);
3130
+
3131
+ parser.handleMessage(
3132
+ {
3133
+ dataSets: [
3134
+ {
3135
+ ...createDataSet('main', 16, 1100),
3136
+ root: parser.dataSets.main.hashTree.getRootHash(),
3137
+ },
3138
+ ],
3139
+ visibleDataSetsUrl,
3140
+ locusUrl,
3141
+ },
3142
+ 'initial heartbeat'
3143
+ );
3144
+
3145
+ mockGetHashesFromLocusResponse(
3146
+ mainDataSetUrl,
3147
+ new Array(16).fill('00000000000000000000000000000000'),
3148
+ createDataSet('main', 16, 1101)
3149
+ );
3150
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
3151
+
3152
+ await clock.tickAsync(heartbeatIntervalMs + 250);
3153
+
3154
+ assert.calledWithExactly(
3155
+ syncLatencyTracker.saveLatency,
3156
+ 'internal.client.locus.sync.random.backoff',
3157
+ 250,
3158
+ {
3159
+ meetingId: 'meeting-1',
3160
+ dataSetName: 'main',
3161
+ }
3162
+ );
3163
+ });
3164
+
3165
+ it('uses the root sync random backoff when root timer fires before watchdog', async () => {
3166
+ const syncLatencyTracker = {
3167
+ saveLatency: sinon.stub(),
3168
+ saveTimestamp: sinon.stub(),
3169
+ getLocusSyncLatency: sinon.stub(),
3170
+ clearLocusSyncLatency: sinon.stub(),
3171
+ completeLocusSyncLatency: sinon.stub(),
3172
+ };
3173
+ const parser = createHashTreeParser(
3174
+ undefined,
3175
+ undefined,
3176
+ undefined,
3177
+ syncLatencyTracker
3178
+ );
3179
+ const mainDataSetUrl = parser.dataSets.main.url;
3180
+
3181
+ mathRandomStub.onFirstCall().returns(0.1); // root-hash timer backoff = 10ms
3182
+ mathRandomStub.onSecondCall().returns(0.5); // watchdog backoff = 250ms
3183
+ mathRandomStub.returns(0);
3184
+
3185
+ parser.handleMessage(
3186
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
3187
+ 'root mismatch heartbeat'
3188
+ );
3189
+
3190
+ mockGetHashesFromLocusResponse(
3191
+ mainDataSetUrl,
3192
+ new Array(16).fill('00000000000000000000000000000000'),
3193
+ createDataSet('main', 16, 1101)
3194
+ );
3195
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
3196
+
3197
+ await clock.tickAsync(1010);
3198
+
3199
+ assert.calledWithExactly(
3200
+ syncLatencyTracker.saveLatency,
3201
+ 'internal.client.locus.sync.random.backoff',
3202
+ 10,
3203
+ {
3204
+ meetingId: 'meeting-1',
3205
+ dataSetName: 'main',
3206
+ }
3207
+ );
3208
+ });
3209
+
2586
3210
  it('calls POST sync directly for leafCount === 1 data sets', async () => {
2587
3211
  const parser = createHashTreeParser();
2588
3212
  const heartbeatIntervalMs = 5000;
@@ -2598,7 +3222,6 @@ describe('HashTreeParser', () => {
2598
3222
  ],
2599
3223
  visibleDataSetsUrl,
2600
3224
  locusUrl,
2601
- heartbeatIntervalMs,
2602
3225
  };
2603
3226
 
2604
3227
  parser.handleMessage(heartbeatMessage, 'self heartbeat');
@@ -2609,6 +3232,12 @@ describe('HashTreeParser', () => {
2609
3232
  // Advance time past watchdog delay
2610
3233
  await clock.tickAsync(heartbeatIntervalMs);
2611
3234
 
3235
+ // Verify behavioral metric was sent for the watchdog expiration
3236
+ assert.calledWith(metricsStub, BEHAVIORAL_METRICS.HASH_TREE_HEARTBEAT_WATCHDOG_EXPIRED, {
3237
+ debugId: 'test',
3238
+ dataSetName: 'self',
3239
+ });
3240
+
2612
3241
  // For leafCount === 1, performSync skips GET hashtree and goes straight to POST sync
2613
3242
  assert.neverCalledWith(
2614
3243
  webexRequest,
@@ -2628,7 +3257,6 @@ describe('HashTreeParser', () => {
2628
3257
 
2629
3258
  it('sets watchdog timers for each data set in the message', async () => {
2630
3259
  const parser = createHashTreeParser();
2631
- const heartbeatIntervalMs = 5000;
2632
3260
 
2633
3261
  // Send heartbeat with multiple datasets
2634
3262
  const heartbeatMessage = {
@@ -2645,7 +3273,6 @@ describe('HashTreeParser', () => {
2645
3273
  ],
2646
3274
  visibleDataSetsUrl,
2647
3275
  locusUrl,
2648
- heartbeatIntervalMs,
2649
3276
  };
2650
3277
 
2651
3278
  parser.handleMessage(heartbeatMessage, 'multi-dataset heartbeat');
@@ -2659,7 +3286,6 @@ describe('HashTreeParser', () => {
2659
3286
 
2660
3287
  it('resets the watchdog timer for a specific data set when a new heartbeat for it is received', async () => {
2661
3288
  const parser = createHashTreeParser();
2662
- const heartbeatIntervalMs = 5000;
2663
3289
 
2664
3290
  // Send first heartbeat for 'main'
2665
3291
  const heartbeat1 = {
@@ -2671,7 +3297,6 @@ describe('HashTreeParser', () => {
2671
3297
  ],
2672
3298
  visibleDataSetsUrl,
2673
3299
  locusUrl,
2674
- heartbeatIntervalMs,
2675
3300
  };
2676
3301
 
2677
3302
  parser.handleMessage(heartbeat1, 'first heartbeat');
@@ -2692,7 +3317,6 @@ describe('HashTreeParser', () => {
2692
3317
  ],
2693
3318
  visibleDataSetsUrl,
2694
3319
  locusUrl,
2695
- heartbeatIntervalMs,
2696
3320
  };
2697
3321
 
2698
3322
  parser.handleMessage(heartbeat2, 'second heartbeat');
@@ -2711,7 +3335,6 @@ describe('HashTreeParser', () => {
2711
3335
 
2712
3336
  it('resets the watchdog timer when a normal message (with locusStateElements) is received', async () => {
2713
3337
  const parser = createHashTreeParser();
2714
- const heartbeatIntervalMs = 5000;
2715
3338
 
2716
3339
  // Send initial heartbeat to start the watchdog for 'main'
2717
3340
  const heartbeat = {
@@ -2723,7 +3346,6 @@ describe('HashTreeParser', () => {
2723
3346
  ],
2724
3347
  visibleDataSetsUrl,
2725
3348
  locusUrl,
2726
- heartbeatIntervalMs,
2727
3349
  };
2728
3350
 
2729
3351
  parser.handleMessage(heartbeat, 'initial heartbeat');
@@ -2751,7 +3373,6 @@ describe('HashTreeParser', () => {
2751
3373
  data: {someData: 'value'},
2752
3374
  },
2753
3375
  ],
2754
- heartbeatIntervalMs,
2755
3376
  };
2756
3377
 
2757
3378
  parser.handleMessage(normalMessage, 'normal message');
@@ -2765,12 +3386,17 @@ describe('HashTreeParser', () => {
2765
3386
  const parser = createHashTreeParser();
2766
3387
 
2767
3388
  // Send a heartbeat message without heartbeatIntervalMs
2768
- const heartbeatMessage = createHeartbeatMessage(
2769
- 'main',
2770
- 16,
2771
- 1100,
2772
- parser.dataSets.main.hashTree.getRootHash()
2773
- );
3389
+ const heartbeatMessage = {
3390
+ dataSets: [
3391
+ {
3392
+ ...createDataSet('main', 16, 1100),
3393
+ root: parser.dataSets.main.hashTree.getRootHash(),
3394
+ heartbeatIntervalMs: undefined,
3395
+ },
3396
+ ],
3397
+ visibleDataSetsUrl,
3398
+ locusUrl,
3399
+ };
2774
3400
 
2775
3401
  parser.handleMessage(heartbeatMessage, 'heartbeat without interval');
2776
3402
 
@@ -2779,7 +3405,6 @@ describe('HashTreeParser', () => {
2779
3405
 
2780
3406
  it('stops all watchdog timers when meeting ends via sentinel message', async () => {
2781
3407
  const parser = createHashTreeParser();
2782
- const heartbeatIntervalMs = 5000;
2783
3408
 
2784
3409
  // Send heartbeat for multiple datasets
2785
3410
  const heartbeat = {
@@ -2796,7 +3421,6 @@ describe('HashTreeParser', () => {
2796
3421
  ],
2797
3422
  visibleDataSetsUrl,
2798
3423
  locusUrl,
2799
- heartbeatIntervalMs,
2800
3424
  };
2801
3425
 
2802
3426
  parser.handleMessage(heartbeat, 'initial heartbeat');
@@ -2847,7 +3471,6 @@ describe('HashTreeParser', () => {
2847
3471
  };
2848
3472
 
2849
3473
  const parser = createHashTreeParser(initialLocus, metadata);
2850
- const heartbeatIntervalMs = 5000;
2851
3474
 
2852
3475
  // Set Math.random to return 1 so that backoff = 1^exponent * maxMs = maxMs
2853
3476
  mathRandomStub.returns(1);
@@ -2869,7 +3492,6 @@ describe('HashTreeParser', () => {
2869
3492
  ],
2870
3493
  visibleDataSetsUrl,
2871
3494
  locusUrl,
2872
- heartbeatIntervalMs,
2873
3495
  };
2874
3496
 
2875
3497
  parser.handleMessage(heartbeat, 'heartbeat');
@@ -2919,7 +3541,6 @@ describe('HashTreeParser', () => {
2919
3541
 
2920
3542
  it('does not set watchdog for data sets without a hash tree', async () => {
2921
3543
  const parser = createHashTreeParser();
2922
- const heartbeatIntervalMs = 5000;
2923
3544
 
2924
3545
  // 'atd-active' is in the initial locus but is not visible (no hash tree)
2925
3546
  // Send heartbeat mentioning a non-visible dataset
@@ -2933,7 +3554,6 @@ describe('HashTreeParser', () => {
2933
3554
  ],
2934
3555
  visibleDataSetsUrl,
2935
3556
  locusUrl,
2936
- heartbeatIntervalMs,
2937
3557
  };
2938
3558
 
2939
3559
  parser.handleMessage(heartbeatMessage, 'heartbeat with non-visible dataset');
@@ -2942,7 +3562,192 @@ describe('HashTreeParser', () => {
2942
3562
  expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
2943
3563
  expect(parser.dataSets['atd-active']?.heartbeatWatchdogTimer).to.be.undefined;
2944
3564
  });
3565
+
3566
+ it('restarts the watchdog timer after it fires so that future missed heartbeats still trigger syncs', async () => {
3567
+ const parser = createHashTreeParser();
3568
+ const heartbeatIntervalMs = 5000;
3569
+
3570
+ // Send initial heartbeat for 'main'
3571
+ const heartbeatMessage = {
3572
+ dataSets: [
3573
+ {
3574
+ ...createDataSet('main', 16, 1100),
3575
+ root: parser.dataSets.main.hashTree.getRootHash(),
3576
+ },
3577
+ ],
3578
+ visibleDataSetsUrl,
3579
+ locusUrl,
3580
+ };
3581
+
3582
+ parser.handleMessage(heartbeatMessage, 'initial heartbeat');
3583
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3584
+
3585
+ // Mock responses for performSync - return null (204/empty body)
3586
+ const mainDataSetUrl = parser.dataSets.main.url;
3587
+ mockGetHashesFromLocusResponse(
3588
+ mainDataSetUrl,
3589
+ new Array(16).fill('00000000000000000000000000000000'),
3590
+ createDataSet('main', 16, 1101)
3591
+ );
3592
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
3593
+
3594
+ // Advance time past heartbeatIntervalMs to fire the watchdog
3595
+ await clock.tickAsync(heartbeatIntervalMs);
3596
+
3597
+ // Verify sync was triggered
3598
+ assert.calledWith(
3599
+ webexRequest,
3600
+ sinon.match({
3601
+ method: 'GET',
3602
+ uri: `${mainDataSetUrl}/hashtree`,
3603
+ })
3604
+ );
3605
+
3606
+ // The watchdog timer should have been restarted after firing
3607
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3608
+
3609
+ // Reset call history and set up new mock responses for the second sync
3610
+ webexRequest.resetHistory();
3611
+ mockGetHashesFromLocusResponse(
3612
+ mainDataSetUrl,
3613
+ new Array(16).fill('00000000000000000000000000000000'),
3614
+ createDataSet('main', 16, 1102)
3615
+ );
3616
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
3617
+
3618
+ // Advance time again to fire the watchdog a second time
3619
+ await clock.tickAsync(heartbeatIntervalMs);
3620
+
3621
+ // Verify a second sync was triggered
3622
+ assert.calledWith(
3623
+ webexRequest,
3624
+ sinon.match({
3625
+ method: 'GET',
3626
+ uri: `${mainDataSetUrl}/hashtree`,
3627
+ })
3628
+ );
3629
+
3630
+ // And the watchdog should still be running
3631
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3632
+ });
3633
+
3634
+ it('uses dataset-level heartbeatIntervalMs over top-level value', async () => {
3635
+ const parser = createHashTreeParser();
3636
+ const datasetLevelInterval = 3000;
3637
+ const topLevelInterval = 8000;
3638
+
3639
+ // Send heartbeat with both top-level and dataset-level heartbeatIntervalMs
3640
+ const heartbeatMessage = {
3641
+ dataSets: [
3642
+ {
3643
+ ...createDataSet('main', 16, 1100),
3644
+ root: parser.dataSets.main.hashTree.getRootHash(),
3645
+ heartbeatIntervalMs: datasetLevelInterval,
3646
+ },
3647
+ ],
3648
+ visibleDataSetsUrl,
3649
+ locusUrl,
3650
+ heartbeatIntervalMs: topLevelInterval,
3651
+ };
3652
+
3653
+ parser.handleMessage(heartbeatMessage, 'heartbeat with both levels');
3654
+
3655
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3656
+
3657
+ // Mock sync responses
3658
+ const mainDataSetUrl = parser.dataSets.main.url;
3659
+ mockGetHashesFromLocusResponse(
3660
+ mainDataSetUrl,
3661
+ new Array(16).fill('00000000000000000000000000000000'),
3662
+ createDataSet('main', 16, 1101)
3663
+ );
3664
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
3665
+
3666
+ // Watchdog should NOT fire at the top-level interval (8000ms)
3667
+ // It should fire at the dataset-level interval (3000ms)
3668
+ await clock.tickAsync(datasetLevelInterval - 1);
3669
+ assert.notCalled(webexRequest);
3670
+
3671
+ await clock.tickAsync(1);
3672
+ // Now at datasetLevelInterval, watchdog should have fired
3673
+ assert.calledWith(
3674
+ webexRequest,
3675
+ sinon.match({
3676
+ method: 'GET',
3677
+ uri: `${mainDataSetUrl}/hashtree`,
3678
+ })
3679
+ );
3680
+ });
3681
+
3682
+ it('falls back to top-level heartbeatIntervalMs when dataset-level is missing', async () => {
3683
+ const parser = createHashTreeParser();
3684
+ const topLevelInterval = 7000;
3685
+
3686
+ // Send heartbeat with top-level heartbeatIntervalMs but no dataset-level
3687
+ const heartbeatMessage = {
3688
+ dataSets: [
3689
+ {
3690
+ ...createDataSet('main', 16, 1100),
3691
+ root: parser.dataSets.main.hashTree.getRootHash(),
3692
+ heartbeatIntervalMs: undefined,
3693
+ },
3694
+ ],
3695
+ visibleDataSetsUrl,
3696
+ locusUrl,
3697
+ heartbeatIntervalMs: topLevelInterval,
3698
+ };
3699
+
3700
+ parser.handleMessage(heartbeatMessage, 'heartbeat with top-level only');
3701
+
3702
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3703
+
3704
+ // Mock sync responses
3705
+ const mainDataSetUrl = parser.dataSets.main.url;
3706
+ mockGetHashesFromLocusResponse(
3707
+ mainDataSetUrl,
3708
+ new Array(16).fill('00000000000000000000000000000000'),
3709
+ createDataSet('main', 16, 1101)
3710
+ );
3711
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
3712
+
3713
+ // Should fire at the top-level interval
3714
+ await clock.tickAsync(topLevelInterval - 1);
3715
+ assert.notCalled(webexRequest);
3716
+
3717
+ await clock.tickAsync(1);
3718
+ assert.calledWith(
3719
+ webexRequest,
3720
+ sinon.match({
3721
+ method: 'GET',
3722
+ uri: `${mainDataSetUrl}/hashtree`,
3723
+ })
3724
+ );
3725
+ });
3726
+
3727
+ it('does not start watchdog when dataset-level heartbeatIntervalMs is 0 even if top-level is set', async () => {
3728
+ const parser = createHashTreeParser();
3729
+
3730
+ // Send heartbeat with dataset-level 0 and a top-level value
3731
+ const heartbeatMessage = {
3732
+ dataSets: [
3733
+ {
3734
+ ...createDataSet('main', 16, 1100),
3735
+ root: parser.dataSets.main.hashTree.getRootHash(),
3736
+ heartbeatIntervalMs: 0,
3737
+ },
3738
+ ],
3739
+ visibleDataSetsUrl,
3740
+ locusUrl,
3741
+ heartbeatIntervalMs: 5000,
3742
+ };
3743
+
3744
+ parser.handleMessage(heartbeatMessage, 'heartbeat with dataset-level 0');
3745
+
3746
+ // Dataset-level 0 means no watchdog, should NOT fall back to top-level
3747
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.be.undefined;
3748
+ });
2945
3749
  });
3750
+
2946
3751
  });
2947
3752
 
2948
3753
  describe('#callLocusInfoUpdateCallback filtering', () => {
@@ -3399,6 +4204,9 @@ describe('HashTreeParser', () => {
3399
4204
  parser.handleMessage(emptyMessage, 'empty elements');
3400
4205
 
3401
4206
  assert.notCalled(callback);
4207
+ assert.calledWith(metricsStub, BEHAVIORAL_METRICS.HASH_TREE_EMPTY_LOCUS_STATE_ELEMENTS, {
4208
+ debugId: 'test',
4209
+ });
3402
4210
  });
3403
4211
 
3404
4212
  it('always calls callback for MEETING_ENDED regardless of filtering', () => {
@@ -3629,7 +4437,7 @@ describe('HashTreeParser', () => {
3629
4437
  });
3630
4438
  });
3631
4439
 
3632
- describe('#resume', () => {
4440
+ describe('#resumeFromMessage', () => {
3633
4441
  const createResumeMessage = (visibleDataSets?, dataSets?) => ({
3634
4442
  locusUrl,
3635
4443
  visibleDataSetsUrl,
@@ -3656,7 +4464,7 @@ describe('HashTreeParser', () => {
3656
4464
 
3657
4465
  expect(parser.state).to.equal('stopped');
3658
4466
 
3659
- parser.resume(createResumeMessage());
4467
+ parser.resumeFromMessage(createResumeMessage());
3660
4468
 
3661
4469
  expect(parser.state).to.equal('active');
3662
4470
  });
@@ -3665,7 +4473,7 @@ describe('HashTreeParser', () => {
3665
4473
  const parser = createHashTreeParser();
3666
4474
  parser.stop();
3667
4475
 
3668
- parser.resume({
4476
+ parser.resumeFromMessage({
3669
4477
  locusUrl,
3670
4478
  visibleDataSetsUrl,
3671
4479
  dataSets: [createDataSet('main', 16, 2000)],
@@ -3684,7 +4492,7 @@ describe('HashTreeParser', () => {
3684
4492
  createDataSet('self', 2, 6000),
3685
4493
  ];
3686
4494
 
3687
- parser.resume(createResumeMessage(undefined, newDataSets));
4495
+ parser.resumeFromMessage(createResumeMessage(undefined, newDataSets));
3688
4496
 
3689
4497
  expect(Object.keys(parser.dataSets)).to.have.lengthOf(2);
3690
4498
  expect(parser.dataSets.main.leafCount).to.equal(8);
@@ -3706,7 +4514,7 @@ describe('HashTreeParser', () => {
3706
4514
  {name: 'self', url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self'},
3707
4515
  ];
3708
4516
 
3709
- parser.resume(createResumeMessage(visibleDataSets, dataSets));
4517
+ parser.resumeFromMessage(createResumeMessage(visibleDataSets, dataSets));
3710
4518
 
3711
4519
  expect(parser.dataSets.main.hashTree).to.be.instanceOf(HashTree);
3712
4520
  expect(parser.dataSets.self.hashTree).to.be.instanceOf(HashTree);
@@ -3720,7 +4528,7 @@ describe('HashTreeParser', () => {
3720
4528
  const handleMessageStub = sinon.stub(parser, 'handleMessage');
3721
4529
 
3722
4530
  const message = createResumeMessage();
3723
- parser.resume(message);
4531
+ parser.resumeFromMessage(message);
3724
4532
 
3725
4533
  assert.calledOnceWithExactly(handleMessageStub, message, 'on resume');
3726
4534
  });
@@ -3740,7 +4548,7 @@ describe('HashTreeParser', () => {
3740
4548
  {name: 'atd-unmuted', url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted'},
3741
4549
  ];
3742
4550
 
3743
- parser.resume(createResumeMessage(visibleDataSets, dataSets));
4551
+ parser.resumeFromMessage(createResumeMessage(visibleDataSets, dataSets));
3744
4552
 
3745
4553
  expect(parser.visibleDataSets.some((vds) => vds.name === 'atd-unmuted')).to.be.false;
3746
4554
  expect(parser.visibleDataSets.some((vds) => vds.name === 'main')).to.be.true;
@@ -3748,46 +4556,893 @@ describe('HashTreeParser', () => {
3748
4556
  });
3749
4557
  });
3750
4558
 
3751
- describe('#handleLocusUpdate when stopped', () => {
3752
- it('should return early without processing when parser is stopped', () => {
4559
+ describe('#resumeFromApiResponse', () => {
4560
+ const exampleLocus = {
4561
+ participants: [],
4562
+ } as any;
4563
+
4564
+ it('should set state to active', async () => {
3753
4565
  const parser = createHashTreeParser();
3754
4566
  parser.stop();
3755
4567
 
3756
- parser.handleLocusUpdate({
3757
- dataSets: [createDataSet('main', 16, 2000)],
3758
- locus: {participants: []},
3759
- });
4568
+ expect(parser.state).to.equal('stopped');
3760
4569
 
3761
- assert.notCalled(callback);
4570
+ sinon.stub(parser, 'initializeFromGetLociResponse').resolves();
4571
+
4572
+ await parser.resumeFromApiResponse(exampleLocus);
4573
+
4574
+ expect(parser.state).to.equal('active');
3762
4575
  });
3763
- });
3764
4576
 
3765
- describe('#handleMessage when stopped', () => {
3766
- it('should return early without processing when parser is stopped', () => {
4577
+ it('should reset dataSets to empty', async () => {
3767
4578
  const parser = createHashTreeParser();
4579
+
4580
+ expect(Object.keys(parser.dataSets).length).to.be.greaterThan(0);
4581
+
3768
4582
  parser.stop();
3769
4583
 
3770
- parser.handleMessage({
3771
- dataSets: [createDataSet('main', 16, 2000)],
3772
- visibleDataSetsUrl,
3773
- locusUrl,
3774
- locusStateElements: [
3775
- {
3776
- htMeta: {elementId: {type: 'self' as const, id: 4, version: 200}, dataSetNames: ['self']},
3777
- data: {id: 'new-self'},
3778
- },
3779
- ],
3780
- });
4584
+ sinon.stub(parser, 'initializeFromGetLociResponse').resolves();
3781
4585
 
3782
- assert.notCalled(callback);
4586
+ await parser.resumeFromApiResponse(exampleLocus);
4587
+
4588
+ expect(parser.dataSets).to.deep.equal({});
3783
4589
  });
3784
- });
3785
4590
 
3786
- describe('#cleanUp', () => {
3787
- it('should stop the parser, clear all timers and clear all dataSets', () => {
4591
+ it('should call initializeFromGetLociResponse with the provided locus', async () => {
3788
4592
  const parser = createHashTreeParser();
4593
+ parser.stop();
3789
4594
 
3790
- // Send a message to set up sync timers via runSyncAlgorithm
4595
+ const initStub = sinon.stub(parser, 'initializeFromGetLociResponse').resolves();
4596
+
4597
+ await parser.resumeFromApiResponse(exampleLocus);
4598
+
4599
+ assert.calledOnceWithExactly(initStub, exampleLocus);
4600
+ });
4601
+
4602
+ it('should propagate errors from initializeFromGetLociResponse', async () => {
4603
+ const parser = createHashTreeParser();
4604
+ parser.stop();
4605
+
4606
+ const error = new Error('initialization failed');
4607
+ const initStub = sinon.stub(parser, 'initializeFromGetLociResponse').rejects(error);
4608
+
4609
+ let caughtError: Error | undefined;
4610
+ try {
4611
+ await parser.resumeFromApiResponse(exampleLocus);
4612
+ } catch (e) {
4613
+ caughtError = e;
4614
+ }
4615
+
4616
+ expect(caughtError).to.equal(error);
4617
+ });
4618
+ });
4619
+
4620
+ describe('#handleLocusUpdate when stopped', () => {
4621
+ it('should return early without processing when parser is stopped', () => {
4622
+ const parser = createHashTreeParser();
4623
+ parser.stop();
4624
+
4625
+ parser.handleLocusUpdate({
4626
+ dataSets: [createDataSet('main', 16, 2000)],
4627
+ locus: {participants: []},
4628
+ });
4629
+
4630
+ assert.notCalled(callback);
4631
+ });
4632
+ });
4633
+
4634
+ describe('#handleMessage when stopped', () => {
4635
+ it('should return early without processing when parser is stopped', () => {
4636
+ const parser = createHashTreeParser();
4637
+ parser.stop();
4638
+
4639
+ parser.handleMessage({
4640
+ dataSets: [createDataSet('main', 16, 2000)],
4641
+ visibleDataSetsUrl,
4642
+ locusUrl,
4643
+ locusStateElements: [
4644
+ {
4645
+ htMeta: {elementId: {type: 'self' as const, id: 4, version: 200}, dataSetNames: ['self']},
4646
+ data: {id: 'new-self'},
4647
+ },
4648
+ ],
4649
+ });
4650
+
4651
+ assert.notCalled(callback);
4652
+ });
4653
+ });
4654
+
4655
+ describe('#syncAllDatasets', () => {
4656
+ it('should sync all datasets that have hash trees in priority order', async () => {
4657
+ const parser = createHashTreeParser();
4658
+
4659
+ // parser starts with main (leafCount=16) and self (leafCount=1) as visible datasets with hash trees
4660
+ // atd-unmuted has no hash tree (not visible)
4661
+ expect(parser.dataSets.main.hashTree).to.be.instanceOf(HashTree);
4662
+ expect(parser.dataSets.self.hashTree).to.be.instanceOf(HashTree);
4663
+
4664
+ const mainUrl = parser.dataSets.main.url;
4665
+ const selfUrl = parser.dataSets.self.url;
4666
+
4667
+ // Mock GET hashtree for main (leafCount > 1, so it does GET first)
4668
+ mockGetHashesFromLocusResponse(
4669
+ mainUrl,
4670
+ new Array(16).fill(EMPTY_HASH),
4671
+ createDataSet('main', 16, 1100)
4672
+ );
4673
+
4674
+ // Mock POST sync for main - return matching root hash so no further sync needed
4675
+ const mainSyncDataSet = createDataSet('main', 16, 1100);
4676
+ mainSyncDataSet.root = parser.dataSets.main.hashTree.getRootHash();
4677
+ mockSendSyncRequestResponse(mainUrl, {
4678
+ dataSets: [mainSyncDataSet],
4679
+ visibleDataSetsUrl,
4680
+ locusUrl,
4681
+ locusStateElements: [],
4682
+ });
4683
+
4684
+ // Mock POST sync for self (leafCount=1, skips GET hashtree)
4685
+ const selfSyncDataSet = createDataSet('self', 1, 2100);
4686
+ selfSyncDataSet.root = parser.dataSets.self.hashTree.getRootHash();
4687
+ mockSendSyncRequestResponse(selfUrl, {
4688
+ dataSets: [selfSyncDataSet],
4689
+ visibleDataSetsUrl,
4690
+ locusUrl,
4691
+ locusStateElements: [],
4692
+ });
4693
+
4694
+ await parser.syncAllDatasets();
4695
+
4696
+ // Verify GET hashtree was called for main only (not self, because leafCount=1)
4697
+ assert.calledWith(webexRequest, sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}));
4698
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${selfUrl}/hashtree`}));
4699
+
4700
+ // Verify POST sync was called for both
4701
+ assert.calledWith(webexRequest, sinon.match({method: 'POST', uri: `${mainUrl}/sync`}));
4702
+ assert.calledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
4703
+
4704
+ // Verify main was synced before self (priority order)
4705
+ const mainSyncCallIndex = webexRequest.args.findIndex(
4706
+ (args) => args[0]?.method === 'GET' && args[0]?.uri === `${mainUrl}/hashtree`
4707
+ );
4708
+ const selfSyncCallIndex = webexRequest.args.findIndex(
4709
+ (args) => args[0]?.method === 'POST' && args[0]?.uri === `${selfUrl}/sync`
4710
+ );
4711
+ expect(mainSyncCallIndex).to.be.lessThan(selfSyncCallIndex);
4712
+
4713
+ // Verify syncAllBackoffType is reset
4714
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.NONE);
4715
+ });
4716
+
4717
+ it('should return immediately when state is stopped', async () => {
4718
+ const parser = createHashTreeParser();
4719
+ parser.stop();
4720
+
4721
+ await parser.syncAllDatasets();
4722
+
4723
+ // No sync requests should have been made (only the initial sync from constructor)
4724
+ // Reset history to clear constructor calls then verify
4725
+ const callCountBefore = webexRequest.callCount;
4726
+ await parser.syncAllDatasets();
4727
+ assert.equal(webexRequest.callCount, callCountBefore);
4728
+ });
4729
+
4730
+ it('should guard against concurrent calls', async () => {
4731
+ const parser = createHashTreeParser();
4732
+
4733
+ const mainUrl = parser.dataSets.main.url;
4734
+ const selfUrl = parser.dataSets.self.url;
4735
+
4736
+ // Use a deferred promise for the main sync to control timing
4737
+ let resolveMainSync;
4738
+ webexRequest
4739
+ .withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}))
4740
+ .returns(new Promise((resolve) => { resolveMainSync = resolve; }));
4741
+
4742
+ mockSendSyncRequestResponse(mainUrl, {
4743
+ dataSets: [createDataSet('main', 16, 1100)],
4744
+ visibleDataSetsUrl,
4745
+ locusUrl,
4746
+ locusStateElements: [],
4747
+ });
4748
+
4749
+ mockSendSyncRequestResponse(selfUrl, {
4750
+ dataSets: [createDataSet('self', 1, 2100)],
4751
+ visibleDataSetsUrl,
4752
+ locusUrl,
4753
+ locusStateElements: [],
4754
+ });
4755
+
4756
+ // Start first call
4757
+ const promise1 = parser.syncAllDatasets();
4758
+ // Start second call while first is in progress
4759
+ const promise2 = parser.syncAllDatasets();
4760
+
4761
+ // Resolve the pending request
4762
+ resolveMainSync({
4763
+ body: {
4764
+ hashes: new Array(16).fill(EMPTY_HASH),
4765
+ dataSet: createDataSet('main', 16, 1100),
4766
+ },
4767
+ });
4768
+
4769
+ await promise1;
4770
+ await promise2;
4771
+
4772
+ // GET hashtree for main should only be called once (second syncAllDatasets returned immediately)
4773
+ const getHashtreeCalls = webexRequest.args.filter(
4774
+ (args) => args[0]?.method === 'GET' && args[0]?.uri === `${mainUrl}/hashtree`
4775
+ );
4776
+ expect(getHashtreeCalls).to.have.lengthOf(1);
4777
+ });
4778
+
4779
+ it('should sync only LLM datasets when onlyLLM=true', async () => {
4780
+ const parser = createHashTreeParser();
4781
+
4782
+ const mainUrl = parser.dataSets.main.url;
4783
+ const selfUrl = parser.dataSets.self.url;
4784
+
4785
+ mockGetHashesFromLocusResponse(
4786
+ mainUrl,
4787
+ new Array(16).fill(EMPTY_HASH),
4788
+ createDataSet('main', 16, 1100)
4789
+ );
4790
+
4791
+ const mainSyncDs = createDataSet('main', 16, 1100);
4792
+ mainSyncDs.root = parser.dataSets.main.hashTree.getRootHash();
4793
+ mockSendSyncRequestResponse(mainUrl, {
4794
+ dataSets: [mainSyncDs],
4795
+ visibleDataSetsUrl,
4796
+ locusUrl,
4797
+ locusStateElements: [],
4798
+ });
4799
+
4800
+ await parser.syncAllDatasets({onlyLLM: true});
4801
+
4802
+ // main is an LLM dataset, so it should have been synced
4803
+ assert.calledWith(webexRequest, sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}));
4804
+
4805
+ // self is NOT an LLM dataset, so it should NOT have been synced
4806
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
4807
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${selfUrl}/hashtree`}));
4808
+ });
4809
+
4810
+ it('uses the syncAll random backoff when reporting sync metrics', async () => {
4811
+ mathRandomStub.returns(0.5); // syncAll backoff = 0.5^2 * 1000 = 250ms
4812
+
4813
+ const syncLatencyTracker = {
4814
+ saveLatency: sinon.stub(),
4815
+ saveTimestamp: sinon.stub(),
4816
+ getLocusSyncLatency: sinon.stub(),
4817
+ clearLocusSyncLatency: sinon.stub(),
4818
+ completeLocusSyncLatency: sinon.stub(),
4819
+ };
4820
+ const parser = createHashTreeParser(
4821
+ undefined,
4822
+ undefined,
4823
+ ['atd-unmuted'],
4824
+ syncLatencyTracker
4825
+ );
4826
+ const mainUrl = parser.dataSets.main.url;
4827
+
4828
+ mockGetHashesFromLocusResponse(
4829
+ mainUrl,
4830
+ new Array(16).fill('00000000000000000000000000000000'),
4831
+ createDataSet('main', 16, 1100)
4832
+ );
4833
+ mockSendSyncRequestResponse(mainUrl, null);
4834
+
4835
+ const syncAllPromise = parser.syncAllDatasets({onlyLLM: true});
4836
+
4837
+ await clock.tickAsync(250);
4838
+ await syncAllPromise;
4839
+
4840
+ assert.calledWithExactly(
4841
+ syncLatencyTracker.saveLatency,
4842
+ 'internal.client.locus.sync.random.backoff',
4843
+ 250,
4844
+ {
4845
+ meetingId: 'meeting-1',
4846
+ dataSetName: 'main',
4847
+ }
4848
+ );
4849
+ });
4850
+
4851
+ it('should upgrade scope from onlyLLM=true to all datasets when onlyLLM=false call arrives during backoff', async () => {
4852
+ // Make Math.random return 1 so backoff = 1^2 * 1000 = 1000ms (non-zero delay for interleaving)
4853
+ mathRandomStub.returns(1);
4854
+
4855
+ const parser = createHashTreeParser();
4856
+
4857
+ const mainUrl = parser.dataSets.main.url;
4858
+ const selfUrl = parser.dataSets.self.url;
4859
+
4860
+ mockGetHashesFromLocusResponse(
4861
+ mainUrl,
4862
+ new Array(16).fill(EMPTY_HASH),
4863
+ createDataSet('main', 16, 1100)
4864
+ );
4865
+
4866
+ const mainSyncDs = createDataSet('main', 16, 1100);
4867
+ mainSyncDs.root = parser.dataSets.main.hashTree.getRootHash();
4868
+ mockSendSyncRequestResponse(mainUrl, {
4869
+ dataSets: [mainSyncDs],
4870
+ visibleDataSetsUrl,
4871
+ locusUrl,
4872
+ locusStateElements: [],
4873
+ });
4874
+
4875
+ const selfSyncDs = createDataSet('self', 1, 2100);
4876
+ selfSyncDs.root = parser.dataSets.self.hashTree.getRootHash();
4877
+ mockSendSyncRequestResponse(selfUrl, {
4878
+ dataSets: [selfSyncDs],
4879
+ visibleDataSetsUrl,
4880
+ locusUrl,
4881
+ locusStateElements: [],
4882
+ });
4883
+
4884
+ // First call with onlyLLM=true starts backoff
4885
+ const promise1 = parser.syncAllDatasets({onlyLLM: true});
4886
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.ONLY_LLM);
4887
+
4888
+ // Second call with onlyLLM=false upgrades the scope during backoff
4889
+ const promise2 = parser.syncAllDatasets({onlyLLM: false});
4890
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.ALL);
4891
+
4892
+ // Advance clock past the backoff delay (1000ms)
4893
+ await clock.tickAsync(1000);
4894
+
4895
+ await promise1;
4896
+ await promise2;
4897
+
4898
+ // Both main (LLM) and self (non-LLM) should have been synced
4899
+ assert.calledWith(webexRequest, sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}));
4900
+ assert.calledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
4901
+ });
4902
+
4903
+ it('should not downgrade scope from onlyLLM=false when onlyLLM=true call arrives during backoff', async () => {
4904
+ // Make Math.random return 1 so backoff = 1^2 * 1000 = 1000ms (non-zero delay for interleaving)
4905
+ mathRandomStub.returns(1);
4906
+
4907
+ const parser = createHashTreeParser();
4908
+
4909
+ const mainUrl = parser.dataSets.main.url;
4910
+ const selfUrl = parser.dataSets.self.url;
4911
+
4912
+ mockGetHashesFromLocusResponse(
4913
+ mainUrl,
4914
+ new Array(16).fill(EMPTY_HASH),
4915
+ createDataSet('main', 16, 1100)
4916
+ );
4917
+
4918
+ const mainSyncDs = createDataSet('main', 16, 1100);
4919
+ mainSyncDs.root = parser.dataSets.main.hashTree.getRootHash();
4920
+ mockSendSyncRequestResponse(mainUrl, {
4921
+ dataSets: [mainSyncDs],
4922
+ visibleDataSetsUrl,
4923
+ locusUrl,
4924
+ locusStateElements: [],
4925
+ });
4926
+
4927
+ const selfSyncDs = createDataSet('self', 1, 2100);
4928
+ selfSyncDs.root = parser.dataSets.self.hashTree.getRootHash();
4929
+ mockSendSyncRequestResponse(selfUrl, {
4930
+ dataSets: [selfSyncDs],
4931
+ visibleDataSetsUrl,
4932
+ locusUrl,
4933
+ locusStateElements: [],
4934
+ });
4935
+
4936
+ // First call with onlyLLM=false starts backoff with all-datasets scope
4937
+ const promise1 = parser.syncAllDatasets({onlyLLM: false});
4938
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.ALL);
4939
+
4940
+ // Second call with onlyLLM=true should NOT downgrade the scope
4941
+ const promise2 = parser.syncAllDatasets({onlyLLM: true});
4942
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.ALL);
4943
+
4944
+ // Advance clock past the backoff delay (1000ms)
4945
+ await clock.tickAsync(1000);
4946
+
4947
+ await promise1;
4948
+ await promise2;
4949
+
4950
+ // Both main (LLM) and self (non-LLM) should have been synced (scope was not downgraded)
4951
+ assert.calledWith(webexRequest, sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}));
4952
+ assert.calledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
4953
+ });
4954
+
4955
+ it('should skip datasets that received messages during the backoff sleep', async () => {
4956
+ // Make Math.random return 1 so backoff = 1^2 * 1000 = 1000ms
4957
+ mathRandomStub.returns(1);
4958
+
4959
+ const parser = createHashTreeParser();
4960
+
4961
+ const mainUrl = parser.dataSets.main.url;
4962
+ const selfUrl = parser.dataSets.self.url;
4963
+ const atdUnmutedUrl = parser.dataSets['atd-unmuted'].url;
4964
+
4965
+ // Setup mocks only for self (main and atd-unmuted should be skipped)
4966
+ mockSendSyncRequestResponse(selfUrl, {
4967
+ dataSets: [createDataSet('self', 1, 2100)],
4968
+ visibleDataSetsUrl,
4969
+ locusUrl,
4970
+ locusStateElements: [],
4971
+ });
4972
+
4973
+ // Start syncAllDatasets - begins backoff sleep
4974
+ const promise = parser.syncAllDatasets();
4975
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.ALL);
4976
+
4977
+ // Simulate a normal message arriving for "main" during the backoff sleep
4978
+ parser.handleMessage({
4979
+ dataSets: [createDataSet('main', 16, 1100)],
4980
+ visibleDataSetsUrl,
4981
+ locusUrl,
4982
+ locusStateElements: [
4983
+ {
4984
+ htMeta: {
4985
+ elementId: {type: 'locus' as const, id: 0, version: 201},
4986
+ dataSetNames: ['main'],
4987
+ },
4988
+ data: {someData: 'value'},
4989
+ },
4990
+ ],
4991
+ });
4992
+
4993
+ // Simulate a heartbeat message arriving for "atd-unmuted" during the backoff sleep
4994
+ parser.handleMessage(
4995
+ createHeartbeatMessage('atd-unmuted', 1, 1100, parser.dataSets['atd-unmuted'].root)
4996
+ );
4997
+
4998
+ // Advance clock past the backoff delay
4999
+ await clock.tickAsync(1000);
5000
+ await promise;
5001
+
5002
+ // main should NOT have been synced (it received a normal message during backoff)
5003
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}));
5004
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${mainUrl}/sync`}));
5005
+
5006
+ // atd-unmuted should NOT have been synced (it received a heartbeat during backoff)
5007
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${atdUnmutedUrl}/hashtree`}));
5008
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${atdUnmutedUrl}/sync`}));
5009
+
5010
+ // self SHOULD have been synced (no messages received for it during backoff)
5011
+ assert.calledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
5012
+ });
5013
+
5014
+ it('should skip datasets that do not have a hash tree', async () => {
5015
+ // Create parser with metadata that only has main and self as visible (not atd-unmuted)
5016
+ const metadataWithoutAtd = {
5017
+ ...exampleMetadata,
5018
+ visibleDataSets: exampleMetadata.visibleDataSets.filter((ds) => ds.name !== 'atd-unmuted'),
5019
+ };
5020
+ const parser = createHashTreeParser(exampleInitialLocus, metadataWithoutAtd);
5021
+
5022
+ // atd-unmuted is in dataSets but has no hashTree (not visible)
5023
+ expect(parser.dataSets['atd-unmuted']).to.exist;
5024
+ expect(parser.dataSets['atd-unmuted'].hashTree).to.be.undefined;
5025
+
5026
+ const atdUrl = parser.dataSets['atd-unmuted'].url;
5027
+ const mainUrl = parser.dataSets.main.url;
5028
+ const selfUrl = parser.dataSets.self.url;
5029
+
5030
+ mockGetHashesFromLocusResponse(
5031
+ mainUrl,
5032
+ new Array(16).fill(EMPTY_HASH),
5033
+ createDataSet('main', 16, 1100)
5034
+ );
5035
+
5036
+ const mainSyncDs = createDataSet('main', 16, 1100);
5037
+ mainSyncDs.root = parser.dataSets.main.hashTree.getRootHash();
5038
+ mockSendSyncRequestResponse(mainUrl, {
5039
+ dataSets: [mainSyncDs],
5040
+ visibleDataSetsUrl,
5041
+ locusUrl,
5042
+ locusStateElements: [],
5043
+ });
5044
+
5045
+ const selfSyncDs = createDataSet('self', 1, 2100);
5046
+ selfSyncDs.root = parser.dataSets.self.hashTree.getRootHash();
5047
+ mockSendSyncRequestResponse(selfUrl, {
5048
+ dataSets: [selfSyncDs],
5049
+ visibleDataSetsUrl,
5050
+ locusUrl,
5051
+ locusStateElements: [],
5052
+ });
5053
+
5054
+ await parser.syncAllDatasets();
5055
+
5056
+ // No requests should have been made for atd-unmuted
5057
+ assert.neverCalledWith(webexRequest, sinon.match({uri: sinon.match(atdUrl)}));
5058
+ });
5059
+ });
5060
+
5061
+ describe('#handleMessage sync queue', () => {
5062
+ it('should deduplicate: not sync the same dataset twice when enqueued multiple times', async () => {
5063
+ const parser = createHashTreeParser();
5064
+
5065
+ const mainUrl = parser.dataSets.main.url;
5066
+
5067
+ // Setup mocks before triggering syncs
5068
+ mockGetHashesFromLocusResponse(
5069
+ mainUrl,
5070
+ new Array(16).fill(EMPTY_HASH),
5071
+ createDataSet('main', 16, 1101)
5072
+ );
5073
+
5074
+ const mainSyncDs = createDataSet('main', 16, 1101);
5075
+ mainSyncDs.root = parser.dataSets.main.hashTree.getRootHash();
5076
+ mockSendSyncRequestResponse(mainUrl, {
5077
+ dataSets: [mainSyncDs],
5078
+ visibleDataSetsUrl,
5079
+ locusUrl,
5080
+ locusStateElements: [],
5081
+ });
5082
+
5083
+ // Send two heartbeat messages (no locusStateElements) with different root hashes for main
5084
+ parser.handleMessage(createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'), 'first');
5085
+ parser.handleMessage(createHeartbeatMessage('main', 16, 1101, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa2'), 'second');
5086
+
5087
+ // The second call resets the timer. After 1000ms, only one sync fires.
5088
+ await clock.tickAsync(1000);
5089
+
5090
+ // Only one GET hashtree call should have been made for main
5091
+ const getHashtreeCalls = webexRequest.args.filter(
5092
+ (args) => args[0]?.method === 'GET' && args[0]?.uri === `${mainUrl}/hashtree`
5093
+ );
5094
+ expect(getHashtreeCalls).to.have.lengthOf(1);
5095
+ });
5096
+
5097
+ it('should stop processing the sync queue when parser is stopped mid-queue', async () => {
5098
+ const parser = createHashTreeParser();
5099
+
5100
+ const mainUrl = parser.dataSets.main.url;
5101
+ const selfUrl = parser.dataSets.self.url;
5102
+
5103
+ // Mock main GET hashtree with a deferred promise so we can control when it resolves
5104
+ let resolveMainHashtree;
5105
+ webexRequest
5106
+ .withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}))
5107
+ .callsFake(() => new Promise((resolve) => { resolveMainHashtree = resolve; }));
5108
+
5109
+ // Send a heartbeat message that triggers sync timers for both main and self
5110
+ parser.handleMessage(
5111
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5112
+ 'trigger main sync'
5113
+ );
5114
+ parser.handleMessage(
5115
+ createHeartbeatMessage('self', 1, 2100, 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb1'),
5116
+ 'trigger self sync'
5117
+ );
5118
+
5119
+ // Fire the timers - main sync starts (calls GET hashtree, which blocks)
5120
+ await clock.tickAsync(1000);
5121
+
5122
+ // Stop the parser while main sync is in progress
5123
+ parser.stop();
5124
+
5125
+ // Resolve the pending main GET request
5126
+ resolveMainHashtree({
5127
+ body: {
5128
+ hashes: new Array(16).fill(EMPTY_HASH),
5129
+ dataSet: createDataSet('main', 16, 1100),
5130
+ },
5131
+ });
5132
+
5133
+ await clock.tickAsync(0);
5134
+
5135
+ // Self sync should NOT have been triggered because parser was stopped
5136
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
5137
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${selfUrl}/hashtree`}));
5138
+ });
5139
+ });
5140
+
5141
+ describe('#stop sync queue', () => {
5142
+ it('should clear the syncQueue when stopped so remaining queued items are not processed', async () => {
5143
+ const parser = createHashTreeParser();
5144
+
5145
+ const mainUrl = parser.dataSets.main.url;
5146
+ const selfUrl = parser.dataSets.self.url;
5147
+
5148
+ // Mock main GET hashtree with a deferred promise so we can control when it resolves
5149
+ let resolveMainHashtree;
5150
+ webexRequest
5151
+ .withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}))
5152
+ .callsFake(() => new Promise((resolve) => { resolveMainHashtree = resolve; }));
5153
+
5154
+ // Enqueue syncs for both main and self by sending heartbeat messages
5155
+ parser.handleMessage(
5156
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5157
+ 'trigger main sync'
5158
+ );
5159
+ parser.handleMessage(
5160
+ createHeartbeatMessage('self', 1, 2100, 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb1'),
5161
+ 'trigger self sync'
5162
+ );
5163
+
5164
+ // Fire the timers - main sync starts and blocks on GET hashtree
5165
+ await clock.tickAsync(1000);
5166
+
5167
+ // Verify that self is still in the queue (main is being processed, self is waiting)
5168
+ // Now stop the parser - this should clear the syncQueue
5169
+ parser.stop();
5170
+
5171
+ // Resolve the pending main GET request so the in-flight sync can finish
5172
+ resolveMainHashtree({
5173
+ body: {
5174
+ hashes: new Array(16).fill(EMPTY_HASH),
5175
+ dataSet: createDataSet('main', 16, 1100),
5176
+ },
5177
+ });
5178
+
5179
+ await clock.tickAsync(0);
5180
+
5181
+ // Self should never have been synced because stop() cleared the queue
5182
+ const selfGetCalls = webexRequest.args.filter(
5183
+ (args) => args[0]?.method === 'GET' && args[0]?.uri === `${selfUrl}/hashtree`
5184
+ );
5185
+ expect(selfGetCalls).to.have.lengthOf(0);
5186
+ });
5187
+ });
5188
+
5189
+ describe('#performSync abort controller', () => {
5190
+ it('should reuse an existing syncAbortController if one is already set on the dataset', async () => {
5191
+ const parser = createHashTreeParser();
5192
+ const mainUrl = parser.dataSets.main.url;
5193
+
5194
+ // Pre-set an AbortController on the dataset before sync starts
5195
+ const existingController = new AbortController();
5196
+ parser.dataSets.main.syncAbortController = existingController;
5197
+
5198
+ // Use a deferred promise for GET hashtree so we can inspect the controller mid-sync
5199
+ let resolveGetHashtree;
5200
+ webexRequest.withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`})).callsFake(
5201
+ () =>
5202
+ new Promise((resolve) => {
5203
+ resolveGetHashtree = resolve;
5204
+ })
5205
+ );
5206
+
5207
+ // Trigger sync for main
5208
+ parser.handleMessage(
5209
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5210
+ 'trigger main sync'
5211
+ );
5212
+
5213
+ await clock.tickAsync(1000);
5214
+
5215
+ // While sync is in-flight, verify the controller is the same one we pre-set
5216
+ expect(parser.dataSets.main.syncAbortController).to.equal(existingController);
5217
+
5218
+ // Resolve GET hashtree with matching hashes (no sync needed)
5219
+ resolveGetHashtree({body: {}});
5220
+ await testUtils.flushPromises();
5221
+
5222
+ // After sync completes, syncAbortController is cleared in finally
5223
+ expect(parser.dataSets.main.syncAbortController).to.be.undefined;
5224
+ });
5225
+
5226
+ it('should abort the sync before /sync request when the controller is aborted during getHashesFromLocus', async () => {
5227
+ const parser = createHashTreeParser();
5228
+ const mainUrl = parser.dataSets.main.url;
5229
+
5230
+ // Use a deferred promise for GET hashtree so we can abort while it's pending
5231
+ let resolveGetHashtree;
5232
+ webexRequest.withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`})).callsFake(
5233
+ () =>
5234
+ new Promise((resolve) => {
5235
+ resolveGetHashtree = resolve;
5236
+ })
5237
+ );
5238
+
5239
+ // Mock POST sync - should NOT be called if abort works
5240
+ mockSendSyncRequestResponse(mainUrl, null);
5241
+
5242
+ // Trigger sync for main via heartbeat with mismatched root hash
5243
+ parser.handleMessage(
5244
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5245
+ 'trigger main sync'
5246
+ );
5247
+
5248
+ // Fire the timer to start the sync
5249
+ await clock.tickAsync(1000);
5250
+
5251
+ // Now abort the controller while getHashesFromLocus is pending
5252
+ expect(parser.dataSets.main.syncAbortController).to.not.be.undefined;
5253
+ parser.dataSets.main.syncAbortController.abort();
5254
+
5255
+ // Resolve GET hashtree with mismatched hashes so the code would normally proceed to /sync
5256
+ resolveGetHashtree({
5257
+ body: {
5258
+ hashes: new Array(16).fill('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5259
+ dataSet: createDataSet('main', 16, 1100),
5260
+ },
5261
+ });
5262
+
5263
+ await testUtils.flushPromises();
5264
+
5265
+ // POST sync should NOT have been called because the controller was aborted
5266
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${mainUrl}/sync`}));
5267
+ });
5268
+
5269
+ it('should abort the sync before /sync request when the controller is aborted for leafCount === 1 datasets', async () => {
5270
+ const parser = createHashTreeParser();
5271
+ const selfUrl = parser.dataSets.self.url;
5272
+
5273
+ // Pre-set an already-aborted controller so performSync picks it up via ??
5274
+ const abortedController = new AbortController();
5275
+ abortedController.abort();
5276
+ parser.dataSets.self.syncAbortController = abortedController;
5277
+
5278
+ // Mock POST sync - should NOT be called
5279
+ mockSendSyncRequestResponse(selfUrl, null);
5280
+
5281
+ // Trigger sync for self via heartbeat with mismatched root hash
5282
+ parser.handleMessage(
5283
+ {
5284
+ dataSets: [
5285
+ {
5286
+ ...createDataSet('self', 1, 2100),
5287
+ url: parser.dataSets.self.url,
5288
+ root: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb1',
5289
+ },
5290
+ ],
5291
+ visibleDataSetsUrl,
5292
+ locusUrl,
5293
+ },
5294
+ 'trigger self sync'
5295
+ );
5296
+
5297
+ // Fire the timer to start the sync
5298
+ await clock.tickAsync(1000);
5299
+
5300
+ // GET hashtree should NOT have been called (leafCount === 1 skips it)
5301
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${selfUrl}/hashtree`}));
5302
+
5303
+ // POST sync should NOT have been called because the controller was already aborted
5304
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
5305
+ });
5306
+
5307
+ it('should unconditionally clear syncAbortController in the finally block', async () => {
5308
+ const parser = createHashTreeParser();
5309
+ const mainUrl = parser.dataSets.main.url;
5310
+
5311
+ // Mock GET hashtree to return matching hashes (early return, no sync needed)
5312
+ webexRequest
5313
+ .withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}))
5314
+ .resolves({body: {}});
5315
+
5316
+ // Trigger sync for main
5317
+ parser.handleMessage(
5318
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5319
+ 'trigger main sync'
5320
+ );
5321
+
5322
+ await clock.tickAsync(1000);
5323
+
5324
+ // After sync completes (even via early return), syncAbortController should be cleared
5325
+ expect(parser.dataSets.main.syncAbortController).to.be.undefined;
5326
+ });
5327
+
5328
+ it('should unconditionally clear syncAbortController even when sync throws an error', async () => {
5329
+ const parser = createHashTreeParser();
5330
+ const mainUrl = parser.dataSets.main.url;
5331
+
5332
+ // Mock GET hashtree to reject with a non-409 error
5333
+ webexRequest
5334
+ .withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}))
5335
+ .rejects({statusCode: 500, message: 'Internal Server Error'});
5336
+
5337
+ // Trigger sync for main
5338
+ parser.handleMessage(
5339
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5340
+ 'trigger main sync'
5341
+ );
5342
+
5343
+ await clock.tickAsync(1000);
5344
+
5345
+ // After sync completes with error, syncAbortController should still be cleared
5346
+ expect(parser.dataSets.main.syncAbortController).to.be.undefined;
5347
+ });
5348
+
5349
+ it('should reuse a pre-existing abort controller and respect its aborted state', async () => {
5350
+ const parser = createHashTreeParser();
5351
+ const mainUrl = parser.dataSets.main.url;
5352
+
5353
+ // Pre-set an AbortController and abort it before sync starts
5354
+ const preAbortedController = new AbortController();
5355
+ preAbortedController.abort();
5356
+ parser.dataSets.main.syncAbortController = preAbortedController;
5357
+
5358
+ // Mock GET hashtree to return mismatched hashes
5359
+ mockGetHashesFromLocusResponse(
5360
+ mainUrl,
5361
+ new Array(16).fill('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5362
+ createDataSet('main', 16, 1100)
5363
+ );
5364
+
5365
+ // Mock POST sync - should NOT be called
5366
+ mockSendSyncRequestResponse(mainUrl, null);
5367
+
5368
+ // Trigger sync for main
5369
+ parser.handleMessage(
5370
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5371
+ 'trigger main sync'
5372
+ );
5373
+
5374
+ await clock.tickAsync(1000);
5375
+
5376
+ // POST sync should NOT have been called because the reused controller was already aborted
5377
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${mainUrl}/sync`}));
5378
+
5379
+ // syncAbortController should be cleaned up
5380
+ expect(parser.dataSets.main.syncAbortController).to.be.undefined;
5381
+ });
5382
+
5383
+ it('should allow cancelPendingSyncsForDataSets to abort an in-flight sync via the shared controller', async () => {
5384
+ const parser = createHashTreeParser();
5385
+ const mainUrl = parser.dataSets.main.url;
5386
+
5387
+ // Use a deferred promise for GET hashtree
5388
+ let resolveGetHashtree;
5389
+ webexRequest.withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`})).callsFake(
5390
+ () =>
5391
+ new Promise((resolve) => {
5392
+ resolveGetHashtree = resolve;
5393
+ })
5394
+ );
5395
+
5396
+ mockSendSyncRequestResponse(mainUrl, null);
5397
+
5398
+ // Trigger sync for main
5399
+ parser.handleMessage(
5400
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5401
+ 'trigger main sync'
5402
+ );
5403
+
5404
+ // Fire the timer to start sync
5405
+ await clock.tickAsync(1000);
5406
+
5407
+ // Verify controller is set
5408
+ expect(parser.dataSets.main.syncAbortController).to.not.be.undefined;
5409
+
5410
+ // Simulate a new heartbeat arriving that cancels the in-flight sync
5411
+ // (this is what happens in production via parseMessage -> cancelPendingSyncsForDataSets)
5412
+ parser.handleMessage(
5413
+ {
5414
+ dataSets: [
5415
+ {
5416
+ ...createDataSet('main', 16, 1101),
5417
+ root: parser.dataSets.main.hashTree.getRootHash(), // matching hash so no new sync
5418
+ },
5419
+ ],
5420
+ visibleDataSetsUrl,
5421
+ locusUrl,
5422
+ },
5423
+ 'new heartbeat cancels sync'
5424
+ );
5425
+
5426
+ // Resolve the pending GET hashtree with mismatched hashes
5427
+ resolveGetHashtree({
5428
+ body: {
5429
+ hashes: new Array(16).fill('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5430
+ dataSet: createDataSet('main', 16, 1101),
5431
+ },
5432
+ });
5433
+
5434
+ await testUtils.flushPromises();
5435
+
5436
+ // POST sync should NOT have been called because cancelPendingSyncsForDataSets aborted the controller
5437
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${mainUrl}/sync`}));
5438
+ });
5439
+ });
5440
+
5441
+ describe('#cleanUp', () => {
5442
+ it('should stop the parser, clear all timers and clear all dataSets', () => {
5443
+ const parser = createHashTreeParser();
5444
+
5445
+ // Send a message to set up sync timers via runSyncAlgorithm
3791
5446
  const message = {
3792
5447
  dataSets: [
3793
5448
  {
@@ -3797,7 +5452,6 @@ describe('HashTreeParser', () => {
3797
5452
  ],
3798
5453
  visibleDataSetsUrl,
3799
5454
  locusUrl,
3800
- heartbeatIntervalMs: 5000,
3801
5455
  locusStateElements: [
3802
5456
  {
3803
5457
  htMeta: {
@@ -3822,4 +5476,290 @@ describe('HashTreeParser', () => {
3822
5476
  expect(parser.dataSets).to.deep.equal({});
3823
5477
  });
3824
5478
  });
5479
+
5480
+ describe('#syncMetrics', () => {
5481
+ it('records sync latency timestamps when sync response has empty body', async () => {
5482
+ const syncLatencyTracker = {
5483
+ saveLatency: sinon.stub(),
5484
+ saveTimestamp: sinon.stub(),
5485
+ getLocusSyncLatency: sinon.stub(),
5486
+ clearLocusSyncLatency: sinon.stub(),
5487
+ completeLocusSyncLatency: sinon.stub(),
5488
+ };
5489
+ const parser = createHashTreeParser(
5490
+ undefined,
5491
+ undefined,
5492
+ undefined,
5493
+ syncLatencyTracker
5494
+ );
5495
+ const mainDataSetUrl = parser.dataSets.main.url;
5496
+
5497
+ mockGetHashesFromLocusResponse(
5498
+ mainDataSetUrl,
5499
+ new Array(16).fill('00000000000000000000000000000000'),
5500
+ createDataSet('main', 16, 1101)
5501
+ );
5502
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
5503
+
5504
+ parser.handleMessage(
5505
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5506
+ 'trigger sync metrics'
5507
+ );
5508
+
5509
+ await clock.tickAsync(1000);
5510
+
5511
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5512
+ key: 'internal.client.locus.sync.start',
5513
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: undefined},
5514
+ });
5515
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5516
+ key: 'internal.client.locus.hashtree.request',
5517
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: undefined},
5518
+ });
5519
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5520
+ key: 'internal.client.locus.hashtree.response',
5521
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: undefined},
5522
+ });
5523
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5524
+ key: 'internal.client.locus.sync.request',
5525
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: undefined},
5526
+ });
5527
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5528
+ key: 'internal.client.locus.sync.response',
5529
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: undefined},
5530
+ });
5531
+ assert.notCalled(syncLatencyTracker.getLocusSyncLatency);
5532
+ });
5533
+
5534
+ it('clears only the failed sync record (by tracking id) when the /sync request errors', async () => {
5535
+ const syncLatencyTracker = {
5536
+ saveLatency: sinon.stub(),
5537
+ saveTimestamp: sinon.stub(),
5538
+ getLocusSyncLatency: sinon.stub(),
5539
+ clearLocusSyncLatency: sinon.stub(),
5540
+ completeLocusSyncLatency: sinon.stub(),
5541
+ };
5542
+ const generateTrackingId = sinon.stub().returns('our-sync-tracking-id');
5543
+ const parser = createHashTreeParser(
5544
+ undefined,
5545
+ undefined,
5546
+ undefined,
5547
+ syncLatencyTracker,
5548
+ undefined,
5549
+ generateTrackingId
5550
+ );
5551
+ const mainDataSetUrl = parser.dataSets.main.url;
5552
+
5553
+ // Mismatched hashes so the flow proceeds to POST /sync, which then fails.
5554
+ mockGetHashesFromLocusResponse(
5555
+ mainDataSetUrl,
5556
+ new Array(16).fill('00000000000000000000000000000000'),
5557
+ createDataSet('main', 16, 1101)
5558
+ );
5559
+ webexRequest
5560
+ .withArgs(sinon.match({method: 'POST', uri: `${mainDataSetUrl}/sync`}))
5561
+ .rejects(new Error('sync failed'));
5562
+
5563
+ parser.handleMessage(
5564
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5565
+ 'trigger sync metrics'
5566
+ );
5567
+
5568
+ await clock.tickAsync(1000);
5569
+
5570
+ // Because /sync failed, syncRequestSent stays false and the finally block drops the record,
5571
+ // passing the tracking id so only this in-progress record is removed (native onSyncError parity).
5572
+ assert.calledWithExactly(
5573
+ syncLatencyTracker.clearLocusSyncLatency,
5574
+ 'main',
5575
+ 'meeting-1',
5576
+ 'our-sync-tracking-id'
5577
+ );
5578
+ });
5579
+
5580
+ it('forces a pre-generated tracking id onto the sync request and records it', async () => {
5581
+ const syncLatencyTracker = {
5582
+ saveLatency: sinon.stub(),
5583
+ saveTimestamp: sinon.stub(),
5584
+ getLocusSyncLatency: sinon.stub(),
5585
+ clearLocusSyncLatency: sinon.stub(),
5586
+ completeLocusSyncLatency: sinon.stub(),
5587
+ };
5588
+ // two distinct tracking ids are generated: the first for the /hashtree request and the
5589
+ // second for the /sync request (which is also stored in metrics and used for LLM matching)
5590
+ const generateTrackingId = sinon.stub();
5591
+ generateTrackingId.onFirstCall().returns('our-hashtree-tracking-id');
5592
+ generateTrackingId.onSecondCall().returns('our-sync-tracking-id');
5593
+ const parser = createHashTreeParser(
5594
+ undefined,
5595
+ undefined,
5596
+ undefined,
5597
+ syncLatencyTracker,
5598
+ undefined,
5599
+ generateTrackingId
5600
+ );
5601
+ const mainDataSetUrl = parser.dataSets.main.url;
5602
+
5603
+ mockGetHashesFromLocusResponse(
5604
+ mainDataSetUrl,
5605
+ new Array(16).fill('00000000000000000000000000000000'),
5606
+ createDataSet('main', 16, 1102)
5607
+ );
5608
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
5609
+
5610
+ parser.handleMessage(
5611
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5612
+ 'trigger sync metrics'
5613
+ );
5614
+
5615
+ await clock.tickAsync(1000);
5616
+
5617
+ // two distinct tracking ids are generated up-front so the /hashtree and /sync requests do
5618
+ // not share a tracking id
5619
+ assert.calledTwice(generateTrackingId);
5620
+ // the /hashtree request carries its own (first) tracking id
5621
+ assert.calledWith(
5622
+ webexRequest,
5623
+ sinon.match({
5624
+ method: 'GET',
5625
+ uri: `${mainDataSetUrl}/hashtree`,
5626
+ headers: {trackingid: 'our-hashtree-tracking-id'},
5627
+ })
5628
+ );
5629
+ // the /sync request carries the second tracking id, which Locus echoes back on the resulting
5630
+ // LLM message so the Meeting object can match it to this sync
5631
+ assert.calledWith(
5632
+ webexRequest,
5633
+ sinon.match({
5634
+ method: 'POST',
5635
+ uri: `${mainDataSetUrl}/sync`,
5636
+ headers: {trackingid: 'our-sync-tracking-id'},
5637
+ })
5638
+ );
5639
+
5640
+ // the same tracking id is stamped on the sync milestones so the Meeting object can later
5641
+ // match the LLM event to this sync
5642
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5643
+ key: 'internal.client.locus.sync.start',
5644
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: 'our-sync-tracking-id'},
5645
+ });
5646
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5647
+ key: 'internal.client.locus.hashtree.request',
5648
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: 'our-sync-tracking-id'},
5649
+ });
5650
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5651
+ key: 'internal.client.locus.hashtree.response',
5652
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: 'our-sync-tracking-id'},
5653
+ });
5654
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5655
+ key: 'internal.client.locus.sync.request',
5656
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: 'our-sync-tracking-id'},
5657
+ });
5658
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5659
+ key: 'internal.client.locus.sync.response',
5660
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: 'our-sync-tracking-id'},
5661
+ });
5662
+ assert.notCalled(syncLatencyTracker.getLocusSyncLatency);
5663
+ });
5664
+
5665
+ it('does not complete or clear metrics when matching dataset message arrives', () => {
5666
+ const syncLatencyTracker = {
5667
+ saveLatency: sinon.stub(),
5668
+ saveTimestamp: sinon.stub(),
5669
+ getLocusSyncLatency: sinon.stub(),
5670
+ clearLocusSyncLatency: sinon.stub(),
5671
+ completeLocusSyncLatency: sinon.stub(),
5672
+ };
5673
+ const parser = createHashTreeParser(
5674
+ undefined,
5675
+ undefined,
5676
+ undefined,
5677
+ syncLatencyTracker
5678
+ );
5679
+
5680
+ parser.handleMessage({
5681
+ dataSets: [
5682
+ {
5683
+ ...createDataSet('main', 16, 1001),
5684
+ root: 'newroot',
5685
+ },
5686
+ ],
5687
+ visibleDataSetsUrl,
5688
+ locusUrl,
5689
+ locusStateElements: [],
5690
+ });
5691
+
5692
+ assert.notCalled(syncLatencyTracker.getLocusSyncLatency);
5693
+ assert.notCalled(syncLatencyTracker.clearLocusSyncLatency);
5694
+ assert.notCalled(syncLatencyTracker.completeLocusSyncLatency);
5695
+ });
5696
+
5697
+ it('does not complete sync metrics when sync response has body (completion is LLM-only)', async () => {
5698
+ const syncLatencyTracker = {
5699
+ saveLatency: sinon.stub(),
5700
+ saveTimestamp: sinon.stub(),
5701
+ getLocusSyncLatency: sinon.stub(),
5702
+ clearLocusSyncLatency: sinon.stub(),
5703
+ completeLocusSyncLatency: sinon.stub(),
5704
+ };
5705
+ const generateTrackingId = sinon.stub().returns('our-sync-tracking-id');
5706
+ const parser = createHashTreeParser(
5707
+ undefined,
5708
+ undefined,
5709
+ undefined,
5710
+ syncLatencyTracker,
5711
+ undefined,
5712
+ generateTrackingId
5713
+ );
5714
+ const mainDataSetUrl = parser.dataSets.main.url;
5715
+ const syncResponse = {
5716
+ dataSets: [
5717
+ {
5718
+ ...createDataSet('main', 16, 1102),
5719
+ root: 'newroot',
5720
+ },
5721
+ ],
5722
+ visibleDataSetsUrl,
5723
+ locusUrl,
5724
+ locusStateElements: [],
5725
+ };
5726
+
5727
+ mockGetHashesFromLocusResponse(
5728
+ mainDataSetUrl,
5729
+ new Array(16).fill('00000000000000000000000000000000'),
5730
+ createDataSet('main', 16, 1102)
5731
+ );
5732
+ mockSendSyncRequestResponse(mainDataSetUrl, syncResponse);
5733
+
5734
+ parser.handleMessage(
5735
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5736
+ 'trigger sync metrics'
5737
+ );
5738
+
5739
+ await clock.tickAsync(1000);
5740
+
5741
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5742
+ key: 'internal.client.locus.sync.response',
5743
+ options: {
5744
+ meetingId: 'meeting-1',
5745
+ dataSetName: 'main',
5746
+ trackingId: 'our-sync-tracking-id',
5747
+ },
5748
+ });
5749
+ // body-mode syncs return the state elements in the /sync HTTP response, but per the LLM-only
5750
+ // design the CA metric is completed solely from Meeting#processLocusLLMEvent once the matching
5751
+ // LLM message arrives. handleMessage must not record the message-received milestone nor
5752
+ // complete the metric here.
5753
+ assert.neverCalledWith(syncLatencyTracker.saveTimestamp, {
5754
+ key: 'internal.client.locus.sync.message.received',
5755
+ options: {
5756
+ meetingId: 'meeting-1',
5757
+ dataSetName: 'main',
5758
+ trackingId: 'our-sync-tracking-id',
5759
+ },
5760
+ });
5761
+ assert.notCalled(syncLatencyTracker.completeLocusSyncLatency);
5762
+ });
5763
+
5764
+ });
3825
5765
  });