@webex/plugin-meetings 3.11.0 → 3.12.0-metrics-init-fix-2.1

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 (293) hide show
  1. package/AGENTS.md +9 -0
  2. package/dist/aiEnableRequest/index.js +197 -0
  3. package/dist/aiEnableRequest/index.js.map +1 -0
  4. package/dist/aiEnableRequest/utils.js +36 -0
  5. package/dist/aiEnableRequest/utils.js.map +1 -0
  6. package/dist/annotation/index.js +14 -5
  7. package/dist/annotation/index.js.map +1 -1
  8. package/dist/breakouts/breakout.js +8 -3
  9. package/dist/breakouts/breakout.js.map +1 -1
  10. package/dist/breakouts/events.js +29 -14
  11. package/dist/breakouts/events.js.map +1 -1
  12. package/dist/breakouts/index.js +90 -3
  13. package/dist/breakouts/index.js.map +1 -1
  14. package/dist/common/errors/webex-errors.js +49 -5
  15. package/dist/common/errors/webex-errors.js.map +1 -1
  16. package/dist/config.js +8 -3
  17. package/dist/config.js.map +1 -1
  18. package/dist/constants.js +60 -11
  19. package/dist/constants.js.map +1 -1
  20. package/dist/controls-options-manager/constants.js +11 -1
  21. package/dist/controls-options-manager/constants.js.map +1 -1
  22. package/dist/controls-options-manager/index.js +67 -29
  23. package/dist/controls-options-manager/index.js.map +1 -1
  24. package/dist/controls-options-manager/util.js +91 -0
  25. package/dist/controls-options-manager/util.js.map +1 -1
  26. package/dist/hashTree/constants.js +16 -2
  27. package/dist/hashTree/constants.js.map +1 -1
  28. package/dist/hashTree/hashTree.js +18 -0
  29. package/dist/hashTree/hashTree.js.map +1 -1
  30. package/dist/hashTree/hashTreeParser.js +1655 -538
  31. package/dist/hashTree/hashTreeParser.js.map +1 -1
  32. package/dist/hashTree/types.js +4 -2
  33. package/dist/hashTree/types.js.map +1 -1
  34. package/dist/hashTree/utils.js +52 -0
  35. package/dist/hashTree/utils.js.map +1 -1
  36. package/dist/index.js +18 -2
  37. package/dist/index.js.map +1 -1
  38. package/dist/interceptors/constant.js +12 -0
  39. package/dist/interceptors/constant.js.map +1 -0
  40. package/dist/interceptors/dataChannelAuthToken.js +350 -0
  41. package/dist/interceptors/dataChannelAuthToken.js.map +1 -0
  42. package/dist/interceptors/index.js +7 -0
  43. package/dist/interceptors/index.js.map +1 -1
  44. package/dist/interceptors/locusRetry.js +23 -8
  45. package/dist/interceptors/locusRetry.js.map +1 -1
  46. package/dist/interceptors/utils.js +27 -0
  47. package/dist/interceptors/utils.js.map +1 -0
  48. package/dist/interpretation/index.js +11 -2
  49. package/dist/interpretation/index.js.map +1 -1
  50. package/dist/interpretation/interpretation.types.js +7 -0
  51. package/dist/interpretation/interpretation.types.js.map +1 -0
  52. package/dist/interpretation/siLanguage.js +1 -1
  53. package/dist/locus-info/controlsUtils.js +9 -4
  54. package/dist/locus-info/controlsUtils.js.map +1 -1
  55. package/dist/locus-info/index.js +911 -211
  56. package/dist/locus-info/index.js.map +1 -1
  57. package/dist/locus-info/infoUtils.js +36 -5
  58. package/dist/locus-info/infoUtils.js.map +1 -1
  59. package/dist/locus-info/selfUtils.js +1 -0
  60. package/dist/locus-info/selfUtils.js.map +1 -1
  61. package/dist/locus-info/types.js +19 -0
  62. package/dist/locus-info/types.js.map +1 -1
  63. package/dist/media/MediaConnectionAwaiter.js +72 -3
  64. package/dist/media/MediaConnectionAwaiter.js.map +1 -1
  65. package/dist/media/index.js +8 -2
  66. package/dist/media/index.js.map +1 -1
  67. package/dist/media/properties.js +8 -7
  68. package/dist/media/properties.js.map +1 -1
  69. package/dist/meeting/in-meeting-actions.js +11 -1
  70. package/dist/meeting/in-meeting-actions.js.map +1 -1
  71. package/dist/meeting/index.js +2276 -1067
  72. package/dist/meeting/index.js.map +1 -1
  73. package/dist/meeting/locusMediaRequest.js +229 -82
  74. package/dist/meeting/locusMediaRequest.js.map +1 -1
  75. package/dist/meeting/muteState.js +10 -1
  76. package/dist/meeting/muteState.js.map +1 -1
  77. package/dist/meeting/request.js +55 -2
  78. package/dist/meeting/request.js.map +1 -1
  79. package/dist/meeting/request.type.js.map +1 -1
  80. package/dist/meeting/util.js +168 -5
  81. package/dist/meeting/util.js.map +1 -1
  82. package/dist/meeting-info/meeting-info-v2.js +2 -2
  83. package/dist/meeting-info/meeting-info-v2.js.map +1 -1
  84. package/dist/meetings/index.js +369 -162
  85. package/dist/meetings/index.js.map +1 -1
  86. package/dist/meetings/meetings.types.js +6 -1
  87. package/dist/meetings/meetings.types.js.map +1 -1
  88. package/dist/meetings/request.js +39 -0
  89. package/dist/meetings/request.js.map +1 -1
  90. package/dist/meetings/util.js +116 -18
  91. package/dist/meetings/util.js.map +1 -1
  92. package/dist/member/index.js +20 -0
  93. package/dist/member/index.js.map +1 -1
  94. package/dist/member/types.js.map +1 -1
  95. package/dist/member/util.js +40 -0
  96. package/dist/member/util.js.map +1 -1
  97. package/dist/members/index.js +101 -43
  98. package/dist/members/index.js.map +1 -1
  99. package/dist/members/util.js +8 -1
  100. package/dist/members/util.js.map +1 -1
  101. package/dist/metrics/constants.js +12 -1
  102. package/dist/metrics/constants.js.map +1 -1
  103. package/dist/multistream/codec/constants.js +63 -0
  104. package/dist/multistream/codec/constants.js.map +1 -0
  105. package/dist/multistream/mediaRequestManager.js +64 -68
  106. package/dist/multistream/mediaRequestManager.js.map +1 -1
  107. package/dist/multistream/receiveSlot.js +9 -0
  108. package/dist/multistream/receiveSlot.js.map +1 -1
  109. package/dist/multistream/remoteMediaManager.js +11 -0
  110. package/dist/multistream/remoteMediaManager.js.map +1 -1
  111. package/dist/multistream/sendSlotManager.js +116 -2
  112. package/dist/multistream/sendSlotManager.js.map +1 -1
  113. package/dist/reachability/clusterReachability.js.map +1 -1
  114. package/dist/reachability/index.js +139 -93
  115. package/dist/reachability/index.js.map +1 -1
  116. package/dist/reachability/reachability.types.js +2 -0
  117. package/dist/reachability/reachability.types.js.map +1 -1
  118. package/dist/reachability/util.js +45 -0
  119. package/dist/reachability/util.js.map +1 -1
  120. package/dist/reactions/reactions.type.js.map +1 -1
  121. package/dist/reconnection-manager/index.js +0 -1
  122. package/dist/reconnection-manager/index.js.map +1 -1
  123. package/dist/recording-controller/index.js +1 -3
  124. package/dist/recording-controller/index.js.map +1 -1
  125. package/dist/roap/turnDiscovery.js +8 -1
  126. package/dist/roap/turnDiscovery.js.map +1 -1
  127. package/dist/types/aiEnableRequest/index.d.ts +5 -0
  128. package/dist/types/aiEnableRequest/utils.d.ts +2 -0
  129. package/dist/types/common/errors/webex-errors.d.ts +32 -2
  130. package/dist/types/config.d.ts +6 -2
  131. package/dist/types/constants.d.ts +35 -1
  132. package/dist/types/controls-options-manager/constants.d.ts +6 -1
  133. package/dist/types/controls-options-manager/index.d.ts +16 -0
  134. package/dist/types/hashTree/constants.d.ts +3 -0
  135. package/dist/types/hashTree/hashTree.d.ts +7 -0
  136. package/dist/types/hashTree/hashTreeParser.d.ts +315 -30
  137. package/dist/types/hashTree/types.d.ts +3 -0
  138. package/dist/types/hashTree/utils.d.ts +24 -0
  139. package/dist/types/index.d.ts +4 -0
  140. package/dist/types/interceptors/constant.d.ts +5 -0
  141. package/dist/types/interceptors/dataChannelAuthToken.d.ts +43 -0
  142. package/dist/types/interceptors/index.d.ts +2 -1
  143. package/dist/types/interceptors/locusRetry.d.ts +4 -4
  144. package/dist/types/interceptors/utils.d.ts +1 -0
  145. package/dist/types/interpretation/interpretation.types.d.ts +10 -0
  146. package/dist/types/locus-info/index.d.ts +126 -15
  147. package/dist/types/locus-info/infoUtils.d.ts +8 -0
  148. package/dist/types/locus-info/types.d.ts +28 -1
  149. package/dist/types/media/MediaConnectionAwaiter.d.ts +20 -2
  150. package/dist/types/media/properties.d.ts +8 -3
  151. package/dist/types/meeting/in-meeting-actions.d.ts +10 -0
  152. package/dist/types/meeting/index.d.ts +245 -16
  153. package/dist/types/meeting/locusMediaRequest.d.ts +12 -0
  154. package/dist/types/meeting/request.d.ts +17 -1
  155. package/dist/types/meeting/request.type.d.ts +5 -0
  156. package/dist/types/meeting/util.d.ts +40 -0
  157. package/dist/types/meetings/index.d.ts +42 -20
  158. package/dist/types/meetings/meetings.types.d.ts +15 -0
  159. package/dist/types/meetings/request.d.ts +14 -0
  160. package/dist/types/member/index.d.ts +2 -0
  161. package/dist/types/member/types.d.ts +1 -0
  162. package/dist/types/member/util.d.ts +14 -0
  163. package/dist/types/members/index.d.ts +15 -2
  164. package/dist/types/members/util.d.ts +1 -5
  165. package/dist/types/metrics/constants.d.ts +11 -0
  166. package/dist/types/multistream/codec/constants.d.ts +7 -0
  167. package/dist/types/multistream/mediaRequestManager.d.ts +20 -26
  168. package/dist/types/multistream/sendSlotManager.d.ts +23 -1
  169. package/dist/types/reachability/clusterReachability.d.ts +3 -3
  170. package/dist/types/reachability/index.d.ts +10 -3
  171. package/dist/types/reachability/reachability.types.d.ts +7 -0
  172. package/dist/types/reachability/util.d.ts +17 -0
  173. package/dist/types/reactions/reactions.type.d.ts +4 -0
  174. package/dist/types/webinar/utils.d.ts +6 -0
  175. package/dist/webinar/index.js +585 -164
  176. package/dist/webinar/index.js.map +1 -1
  177. package/dist/webinar/utils.js +25 -0
  178. package/dist/webinar/utils.js.map +1 -0
  179. package/package.json +24 -23
  180. package/src/aiEnableRequest/README.md +84 -0
  181. package/src/aiEnableRequest/index.ts +186 -0
  182. package/src/aiEnableRequest/utils.ts +25 -0
  183. package/src/annotation/index.ts +27 -7
  184. package/src/breakouts/breakout.ts +3 -1
  185. package/src/breakouts/events.ts +33 -11
  186. package/src/breakouts/index.ts +110 -1
  187. package/src/common/errors/webex-errors.ts +50 -3
  188. package/src/config.ts +6 -2
  189. package/src/constants.ts +49 -3
  190. package/src/controls-options-manager/constants.ts +14 -1
  191. package/src/controls-options-manager/index.ts +87 -28
  192. package/src/controls-options-manager/util.ts +81 -1
  193. package/src/hashTree/constants.ts +17 -0
  194. package/src/hashTree/hashTree.ts +17 -0
  195. package/src/hashTree/hashTreeParser.ts +1482 -361
  196. package/src/hashTree/types.ts +4 -0
  197. package/src/hashTree/utils.ts +45 -0
  198. package/src/index.ts +14 -1
  199. package/src/interceptors/constant.ts +6 -0
  200. package/src/interceptors/dataChannelAuthToken.ts +246 -0
  201. package/src/interceptors/index.ts +2 -1
  202. package/src/interceptors/locusRetry.ts +25 -4
  203. package/src/interceptors/utils.ts +16 -0
  204. package/src/interpretation/index.ts +29 -11
  205. package/src/interpretation/interpretation.types.ts +11 -0
  206. package/src/locus-info/controlsUtils.ts +14 -1
  207. package/src/locus-info/index.ts +975 -203
  208. package/src/locus-info/infoUtils.ts +41 -6
  209. package/src/locus-info/selfUtils.ts +1 -0
  210. package/src/locus-info/types.ts +33 -1
  211. package/src/media/MediaConnectionAwaiter.ts +62 -5
  212. package/src/media/index.ts +10 -1
  213. package/src/media/properties.ts +11 -4
  214. package/src/meeting/in-meeting-actions.ts +20 -0
  215. package/src/meeting/index.ts +1272 -164
  216. package/src/meeting/locusMediaRequest.ts +106 -6
  217. package/src/meeting/muteState.ts +10 -1
  218. package/src/meeting/request.ts +53 -0
  219. package/src/meeting/request.type.ts +6 -0
  220. package/src/meeting/util.ts +207 -7
  221. package/src/meeting-info/meeting-info-v2.ts +4 -2
  222. package/src/meetings/index.ts +319 -117
  223. package/src/meetings/meetings.types.ts +19 -0
  224. package/src/meetings/request.ts +43 -0
  225. package/src/meetings/util.ts +117 -4
  226. package/src/member/index.ts +20 -0
  227. package/src/member/types.ts +1 -0
  228. package/src/member/util.ts +41 -0
  229. package/src/members/index.ts +70 -7
  230. package/src/members/util.ts +12 -4
  231. package/src/metrics/constants.ts +12 -0
  232. package/src/multistream/codec/constants.ts +58 -0
  233. package/src/multistream/mediaRequestManager.ts +117 -76
  234. package/src/multistream/receiveSlot.ts +18 -0
  235. package/src/multistream/remoteMediaManager.ts +13 -0
  236. package/src/multistream/sendSlotManager.ts +97 -3
  237. package/src/reachability/clusterReachability.ts +3 -2
  238. package/src/reachability/index.ts +56 -16
  239. package/src/reachability/reachability.types.ts +11 -0
  240. package/src/reachability/util.ts +36 -0
  241. package/src/reactions/reactions.type.ts +4 -0
  242. package/src/reconnection-manager/index.ts +0 -1
  243. package/src/recording-controller/index.ts +1 -2
  244. package/src/roap/turnDiscovery.ts +9 -1
  245. package/src/webinar/index.ts +448 -11
  246. package/src/webinar/utils.ts +16 -0
  247. package/test/unit/spec/aiEnableRequest/index.ts +1067 -0
  248. package/test/unit/spec/aiEnableRequest/utils.ts +130 -0
  249. package/test/unit/spec/annotation/index.ts +69 -7
  250. package/test/unit/spec/breakouts/breakout.ts +9 -3
  251. package/test/unit/spec/breakouts/events.ts +120 -2
  252. package/test/unit/spec/breakouts/index.ts +191 -2
  253. package/test/unit/spec/common/errors/webex-errors.ts +78 -0
  254. package/test/unit/spec/controls-options-manager/index.js +244 -29
  255. package/test/unit/spec/controls-options-manager/util.js +165 -0
  256. package/test/unit/spec/hashTree/hashTree.ts +66 -0
  257. package/test/unit/spec/hashTree/hashTreeParser.ts +4528 -171
  258. package/test/unit/spec/hashTree/utils.ts +125 -1
  259. package/test/unit/spec/interceptors/dataChannelAuthToken.ts +406 -0
  260. package/test/unit/spec/interceptors/locusRetry.ts +205 -4
  261. package/test/unit/spec/interceptors/utils.ts +75 -0
  262. package/test/unit/spec/interpretation/index.ts +26 -4
  263. package/test/unit/spec/locus-info/controlsUtils.js +200 -56
  264. package/test/unit/spec/locus-info/index.js +1848 -164
  265. package/test/unit/spec/locus-info/infoUtils.js +184 -1
  266. package/test/unit/spec/media/MediaConnectionAwaiter.ts +96 -1
  267. package/test/unit/spec/media/index.ts +92 -0
  268. package/test/unit/spec/media/properties.ts +35 -26
  269. package/test/unit/spec/meeting/in-meeting-actions.ts +12 -2
  270. package/test/unit/spec/meeting/index.js +3706 -405
  271. package/test/unit/spec/meeting/locusMediaRequest.ts +406 -4
  272. package/test/unit/spec/meeting/muteState.js +81 -0
  273. package/test/unit/spec/meeting/request.js +82 -0
  274. package/test/unit/spec/meeting/utils.js +595 -27
  275. package/test/unit/spec/meeting-info/meetinginfov2.js +19 -10
  276. package/test/unit/spec/meetings/index.js +1138 -86
  277. package/test/unit/spec/meetings/request.js +141 -0
  278. package/test/unit/spec/meetings/utils.js +402 -51
  279. package/test/unit/spec/member/index.js +35 -4
  280. package/test/unit/spec/member/util.js +154 -27
  281. package/test/unit/spec/members/index.js +216 -0
  282. package/test/unit/spec/members/request.js +37 -1
  283. package/test/unit/spec/members/utils.js +63 -0
  284. package/test/unit/spec/multistream/mediaRequestManager.ts +503 -122
  285. package/test/unit/spec/multistream/remoteMediaManager.ts +30 -0
  286. package/test/unit/spec/multistream/sendSlotManager.ts +135 -36
  287. package/test/unit/spec/reachability/index.ts +151 -46
  288. package/test/unit/spec/reachability/util.ts +31 -0
  289. package/test/unit/spec/reconnection-manager/index.js +4 -8
  290. package/test/unit/spec/recording-controller/index.js +9 -8
  291. package/test/unit/spec/roap/turnDiscovery.ts +20 -0
  292. package/test/unit/spec/webinar/index.ts +837 -39
  293. package/test/unit/spec/webinar/utils.ts +39 -0
@@ -1,11 +1,20 @@
1
1
  import {cloneDeep, isEmpty, zip} from 'lodash';
2
+ import type {LocusSyncLatencyEventName} from '@webex/internal-plugin-metrics';
2
3
  import HashTree, {LeafDataItem} from './hashTree';
3
4
  import LoggerProxy from '../common/logs/logger-proxy';
5
+ import Metrics from '../metrics';
6
+ import BEHAVIORAL_METRICS from '../metrics/constants';
4
7
  import {Enum, HTTP_VERBS} from '../constants';
5
- import {DataSetNames, EMPTY_HASH} from './constants';
8
+ import {DataSetNames, DATA_SET_INIT_PRIORITY, EMPTY_HASH, LLM_DATASET_NAMES} from './constants';
6
9
  import {ObjectType, HtMeta, HashTreeObject} from './types';
7
- import {LocusDTO} from '../locus-info/types';
8
- import {deleteNestedObjectsWithHtMeta, isSelf} from './utils';
10
+ import {LocusDTO, LocusErrorCodes} from '../locus-info/types';
11
+ import {deleteNestedObjectsWithHtMeta, isMetadata, sleep, sortByInitPriority} from './utils';
12
+
13
+ export enum SyncAllBackoffType {
14
+ NONE = 'none',
15
+ ONLY_LLM = 'onlyLLM',
16
+ ALL = 'all',
17
+ }
9
18
 
10
19
  export interface DataSet {
11
20
  url: string;
@@ -18,10 +27,12 @@ export interface DataSet {
18
27
  maxMs: number;
19
28
  exponent: number;
20
29
  };
30
+ heartbeatIntervalMs?: number;
21
31
  }
22
32
 
23
33
  export interface RootHashMessage {
24
34
  dataSets: Array<DataSet>;
35
+ heartbeatIntervalMs?: number;
25
36
  }
26
37
  export interface HashTreeMessage {
27
38
  dataSets: Array<DataSet>;
@@ -29,31 +40,114 @@ export interface HashTreeMessage {
29
40
  locusStateElements?: Array<HashTreeObject>;
30
41
  locusSessionId?: string;
31
42
  locusUrl: string;
43
+ heartbeatIntervalMs?: number;
44
+ }
45
+
46
+ export interface VisibleDataSetInfo {
47
+ name: string;
48
+ url: string;
49
+ dataChannelUrl?: string;
50
+ }
51
+
52
+ export interface Metadata {
53
+ htMeta: HtMeta;
54
+ visibleDataSets: VisibleDataSetInfo[];
32
55
  }
33
56
 
34
57
  interface InternalDataSet extends DataSet {
35
58
  hashTree?: HashTree; // set only for visible data sets
36
59
  timer?: ReturnType<typeof setTimeout>;
60
+ heartbeatWatchdogTimer?: ReturnType<typeof setTimeout>;
61
+ syncAbortController?: AbortController;
37
62
  }
38
63
 
39
64
  type WebexRequestMethod = (options: Record<string, any>) => Promise<any>;
65
+ type GenerateTrackingId = () => string | undefined;
40
66
 
41
67
  export const LocusInfoUpdateType = {
42
68
  OBJECTS_UPDATED: 'OBJECTS_UPDATED',
43
69
  MEETING_ENDED: 'MEETING_ENDED',
70
+ LOCUS_NOT_FOUND: 'LOCUS_NOT_FOUND',
44
71
  } as const;
45
72
 
46
73
  export type LocusInfoUpdateType = Enum<typeof LocusInfoUpdateType>;
47
- export type LocusInfoUpdateCallback = (
48
- updateType: LocusInfoUpdateType,
49
- data?: {updatedObjects: HashTreeObject[]}
50
- ) => void;
74
+
75
+ interface LocusUpdatePayloads {
76
+ [LocusInfoUpdateType.OBJECTS_UPDATED]: {updatedObjects: HashTreeObject[]};
77
+ [LocusInfoUpdateType.MEETING_ENDED]: unknown; // No extra data
78
+ [LocusInfoUpdateType.LOCUS_NOT_FOUND]: unknown; // No extra data
79
+ }
80
+
81
+ export type LocusInfoUpdate = {
82
+ [K in keyof LocusUpdatePayloads]: {
83
+ updateType: K;
84
+ } & LocusUpdatePayloads[K];
85
+ }[keyof LocusUpdatePayloads];
86
+
87
+ export type LocusInfoUpdateCallback = (update: LocusInfoUpdate) => void;
88
+
89
+ export type SyncLatencyTracker = {
90
+ saveLatency: (
91
+ key: 'internal.client.locus.sync.random.backoff',
92
+ value: number,
93
+ options: {
94
+ meetingId: string;
95
+ dataSetName: string;
96
+ }
97
+ ) => void;
98
+ saveTimestamp: (options: {
99
+ key: LocusSyncLatencyEventName;
100
+ options: {
101
+ meetingId: string;
102
+ dataSetName: string;
103
+ trackingId?: string;
104
+ };
105
+ }) => void;
106
+ clearLocusSyncLatency: (dataSetName: string, meetingId: string, trackingId?: string) => void;
107
+ };
108
+
109
+ export type HashTreeParserCallbacks = {
110
+ locusInfoUpdateCallback: LocusInfoUpdateCallback;
111
+ syncLatencyTracker?: SyncLatencyTracker;
112
+ generateTrackingId?: GenerateTrackingId;
113
+ };
114
+
115
+ const SYNC_METRICS_DATA_SETS = [
116
+ DataSetNames.MAIN,
117
+ DataSetNames.ATD_ACTIVE,
118
+ DataSetNames.ATD_UNMUTED,
119
+ ];
120
+
121
+ interface LeafInfo {
122
+ type: ObjectType;
123
+ id: number;
124
+ version: number;
125
+ data?: any;
126
+ }
51
127
 
52
128
  /**
53
129
  * This error is thrown if we receive information that the meeting has ended while we're processing some hash messages.
54
130
  * It's handled internally by HashTreeParser and results in MEETING_ENDED being sent up.
55
131
  */
56
- class MeetingEndedError extends Error {}
132
+ export class MeetingEndedError extends Error {}
133
+
134
+ /**
135
+ * This error is thrown when a 404 is received from Locus hash tree endpoints, indicating that the locus URL
136
+ * is no longer valid (e.g. participant moved to a breakout room, or meeting ended).
137
+ * It's handled internally by HashTreeParser and results in LOCUS_NOT_FOUND being sent up.
138
+ */
139
+ export class LocusNotFoundError extends Error {}
140
+
141
+ /* Currently Locus always sends Metadata objects only in the "self" dataset.
142
+ * If this ever changes, update all the code that relies on this constant.
143
+ */
144
+ const MetadataDataSetName = DataSetNames.SELF;
145
+
146
+ const PossibleSentinelMessageDataSetNames = [
147
+ DataSetNames.MAIN,
148
+ DataSetNames.SELF,
149
+ DataSetNames.UNJOINED,
150
+ ];
57
151
 
58
152
  /**
59
153
  * Parses hash tree eventing locus data
@@ -62,10 +156,26 @@ class HashTreeParser {
62
156
  dataSets: Record<string, InternalDataSet> = {};
63
157
  visibleDataSetsUrl: string; // url from which we can get info about all data sets
64
158
  webexRequest: WebexRequestMethod;
65
- locusInfoUpdateCallback: LocusInfoUpdateCallback;
66
- visibleDataSets: string[];
159
+ private callbacks: HashTreeParserCallbacks;
160
+ private syncLatencyMeetingId: string;
161
+ visibleDataSets: VisibleDataSetInfo[];
67
162
  debugId: string;
68
-
163
+ private excludedDataSets: string[];
164
+ state: 'active' | 'stopped';
165
+ private syncQueue: Array<{
166
+ dataSetName: string;
167
+ reason: string;
168
+ isInitialization?: boolean;
169
+ }> = [];
170
+
171
+ private isSyncInProgress = false;
172
+ // tracks whether syncAllDatasets is currently in its backoff delay phase and with what scope
173
+ private syncAllBackoffType: SyncAllBackoffType = SyncAllBackoffType.NONE;
174
+ // datasets that received messages during the syncAllDatasets backoff sleep and should be skipped
175
+ private dataSetsSyncedDuringBackoff: Set<string> = new Set();
176
+ private syncQueueProcessingPromise: Promise<void> = Promise.resolve();
177
+ // top-level heartbeat interval from the most recent message, used as fallback when dataset-level value is missing
178
+ private topLevelHeartbeatIntervalMs?: number;
69
179
  /**
70
180
  * Constructor for HashTreeParser
71
181
  * @param {Object} options
@@ -76,29 +186,44 @@ class HashTreeParser {
76
186
  dataSets: Array<DataSet>;
77
187
  locus: any;
78
188
  };
189
+ metadata: Metadata | null;
79
190
  webexRequest: WebexRequestMethod;
80
- locusInfoUpdateCallback: LocusInfoUpdateCallback;
191
+ callbacks: HashTreeParserCallbacks;
81
192
  debugId: string;
193
+ excludedDataSets?: string[];
194
+ syncLatencyMeetingId: string;
82
195
  }) {
83
196
  const {dataSets, locus} = options.initialLocus; // extract dataSets from initialLocus
84
197
 
85
198
  this.debugId = options.debugId;
86
199
  this.webexRequest = options.webexRequest;
87
- this.locusInfoUpdateCallback = options.locusInfoUpdateCallback;
88
- this.visibleDataSets = locus?.self?.visibleDataSets || [];
200
+ this.callbacks = options.callbacks;
201
+ this.syncLatencyMeetingId = options.syncLatencyMeetingId;
202
+ this.excludedDataSets = options.excludedDataSets || [];
203
+ this.visibleDataSetsUrl = locus?.links?.resources?.visibleDataSets?.url;
204
+ this.setVisibleDataSets(options.metadata?.visibleDataSets || [], dataSets);
205
+
206
+ this.state = 'active';
89
207
 
90
- if (this.visibleDataSets.length === 0) {
208
+ if (options.metadata?.visibleDataSets?.length === 0) {
91
209
  LoggerProxy.logger.warn(
92
- `HashTreeParser#constructor --> ${this.debugId} No visibleDataSets found in locus.self`
210
+ `HashTreeParser#constructor --> ${this.debugId} No visibleDataSets found in Metadata`
93
211
  );
94
212
  }
95
213
  // object mapping dataset names to arrays of leaf data
96
214
  const leafData = this.analyzeLocusHtMeta(locus);
97
215
 
216
+ if (options.metadata) {
217
+ // add also the metadata that's outside of locus object itself
218
+ this.analyzeMetadata(leafData, options.metadata);
219
+ }
220
+
98
221
  LoggerProxy.logger.info(
99
- `HashTreeParser#constructor --> creating HashTreeParser for datasets: ${JSON.stringify(
222
+ `HashTreeParser#constructor --> ${
223
+ this.debugId
224
+ } creating HashTreeParser for datasets: ${JSON.stringify(
100
225
  dataSets.map((ds) => ds.name)
101
- )}`
226
+ )} with visible datasets: ${JSON.stringify(this.visibleDataSets.map((vds) => vds.name))}`
102
227
  );
103
228
 
104
229
  for (const dataSet of dataSets) {
@@ -106,102 +231,134 @@ class HashTreeParser {
106
231
 
107
232
  this.dataSets[name] = {
108
233
  ...dataSet,
109
- hashTree: this.visibleDataSets.includes(name)
234
+ hashTree: this.isVisibleDataSet(name)
110
235
  ? new HashTree(leafData[name] || [], leafCount)
111
236
  : undefined,
112
237
  };
113
238
  }
114
239
  }
115
240
 
241
+ /**
242
+ * Sets the visible data sets list for the HashTreeParser. This method should be called only at the start, to initialize
243
+ * the visible data sets, before any message processsing, so for example from the constructor or when resuming the parser.
244
+ *
245
+ * @param {Array<VisibleDataSetInfo>} visibleDataSets - The visible data sets to set
246
+ * @param {Array<DataSet>} dataSets - The "dataSets" list from Locus (yes, Locus sends visibleDataSets and dataSets as separate lists and they can differ)
247
+ * @returns {void}
248
+ */
249
+ private setVisibleDataSets(visibleDataSets: VisibleDataSetInfo[], dataSets: Array<DataSet>) {
250
+ this.visibleDataSets = cloneDeep(visibleDataSets).filter(
251
+ (vds) =>
252
+ // exclude data sets we will never care about
253
+ !this.isExcludedDataSet(vds.name) &&
254
+ // and make sure that visibleDataSets list is consistent with dataSets list
255
+ dataSets.some((ds) => ds.name === vds.name)
256
+ );
257
+ }
258
+
259
+ /**
260
+ * Checks if the given data set name is in the list of visible data sets
261
+ * @param {string} dataSetName data set name to check
262
+ * @returns {Boolean} True if the data set is visible, false otherwise
263
+ */
264
+ private isVisibleDataSet(dataSetName: string): boolean {
265
+ return this.visibleDataSets.some((vds) => vds.name === dataSetName);
266
+ }
267
+
268
+ /**
269
+ * Checks if the given data set name is in the excluded list
270
+ * @param {string} dataSetName data set name to check
271
+ * @returns {boolean} True if the data set is excluded, false otherwise
272
+ */
273
+ private isExcludedDataSet(dataSetName: string): boolean {
274
+ return this.excludedDataSets.some((name) => name === dataSetName);
275
+ }
276
+
277
+ /**
278
+ * Adds a data set to the visible data sets list, unless it is in the excluded list.
279
+ * @param {VisibleDataSetInfo} dataSetInfo data set info to add
280
+ * @returns {boolean} True if the data set was added, false if it was excluded
281
+ */
282
+ private addToVisibleDataSetsList(dataSetInfo: VisibleDataSetInfo): boolean {
283
+ if (this.isExcludedDataSet(dataSetInfo.name)) {
284
+ LoggerProxy.logger.info(
285
+ `HashTreeParser#addToVisibleDataSetsList --> ${this.debugId} Data set "${dataSetInfo.name}" is in the excluded list, ignoring`
286
+ );
287
+
288
+ return false;
289
+ }
290
+
291
+ this.visibleDataSets.push(dataSetInfo);
292
+
293
+ return true;
294
+ }
295
+
116
296
  /**
117
297
  * Initializes a new visible data set by creating a hash tree for it, adding it to all the internal structures,
118
298
  * and sending an initial sync request to Locus with empty leaf data - that will trigger Locus to gives us all the data
119
299
  * from that dataset (in the response or via messages).
120
300
  *
121
- * @param {DataSet} dataSet The new data set to be added
301
+ * @param {VisibleDataSetInfo} visibleDataSetInfo Information about the new visible data set
302
+ * @param {DataSet} dataSetInfo The new data set to be added
122
303
  * @returns {Promise}
123
304
  */
124
- private initializeNewVisibleDataSet(
125
- dataSet: DataSet
126
- ): Promise<{updateType: LocusInfoUpdateType; updatedObjects?: HashTreeObject[]}> {
127
- if (this.visibleDataSets.includes(dataSet.name)) {
305
+ private async initializeNewVisibleDataSet(
306
+ visibleDataSetInfo: VisibleDataSetInfo,
307
+ dataSetInfo: DataSet
308
+ ): Promise<void> {
309
+ if (this.isVisibleDataSet(dataSetInfo.name)) {
128
310
  LoggerProxy.logger.info(
129
- `HashTreeParser#initializeNewVisibleDataSet --> ${this.debugId} Data set "${dataSet.name}" already exists, skipping init`
311
+ `HashTreeParser#initializeNewVisibleDataSet --> ${this.debugId} Data set "${dataSetInfo.name}" already exists, skipping init`
130
312
  );
131
313
 
132
- return Promise.resolve({updateType: LocusInfoUpdateType.OBJECTS_UPDATED, updatedObjects: []});
314
+ return;
133
315
  }
134
316
 
135
317
  LoggerProxy.logger.info(
136
- `HashTreeParser#initializeNewVisibleDataSet --> ${this.debugId} Adding visible data set "${dataSet.name}"`
318
+ `HashTreeParser#initializeNewVisibleDataSet --> ${this.debugId} Adding visible data set "${dataSetInfo.name}"`
137
319
  );
138
320
 
139
- this.visibleDataSets.push(dataSet.name);
321
+ if (!this.addToVisibleDataSetsList(visibleDataSetInfo)) {
322
+ return;
323
+ }
140
324
 
141
- const hashTree = new HashTree([], dataSet.leafCount);
325
+ const hashTree = new HashTree([], dataSetInfo.leafCount);
142
326
 
143
- this.dataSets[dataSet.name] = {
144
- ...dataSet,
327
+ this.dataSets[dataSetInfo.name] = {
328
+ ...dataSetInfo,
145
329
  hashTree,
146
330
  };
147
331
 
148
- return this.sendInitializationSyncRequestToLocus(dataSet.name, 'new visible data set');
332
+ this.enqueueSyncForDataset(dataSetInfo.name, 'new visible data set initialization', true);
333
+ await this.syncQueueProcessingPromise;
149
334
  }
150
335
 
151
336
  /**
152
- * Sends a special sync request to Locus with all leaves empty - this is a way to get all the data for a given dataset.
337
+ * Queries Locus for all up-to-date information about all visible data sets
153
338
  *
154
- * @param {string} datasetName - name of the dataset for which to send the request
155
- * @param {string} debugText - text to include in logs
156
339
  * @returns {Promise}
157
340
  */
158
- private sendInitializationSyncRequestToLocus(
159
- datasetName: string,
160
- debugText: string
161
- ): Promise<{updateType: LocusInfoUpdateType; updatedObjects?: HashTreeObject[]}> {
162
- const dataset = this.dataSets[datasetName];
163
-
164
- if (!dataset) {
341
+ private getAllVisibleDataSetsFromLocus() {
342
+ if (!this.visibleDataSetsUrl) {
165
343
  LoggerProxy.logger.warn(
166
- `HashTreeParser#sendInitializationSyncRequestToLocus --> ${this.debugId} No data set found for ${datasetName}, cannot send the request for leaf data`
344
+ `HashTreeParser#getAllVisibleDataSetsFromLocus --> ${this.debugId} No visibleDataSetsUrl, cannot get data sets information`
167
345
  );
168
346
 
169
- return Promise.resolve(null);
347
+ return Promise.resolve([]);
170
348
  }
171
349
 
172
- const emptyLeavesData = new Array(dataset.leafCount).fill([]);
173
-
174
- LoggerProxy.logger.info(
175
- `HashTreeParser#sendInitializationSyncRequestToLocus --> ${this.debugId} Sending initial sync request to Locus for data set "${datasetName}" with empty leaf data`
176
- );
177
-
178
- return this.sendSyncRequestToLocus(this.dataSets[datasetName], emptyLeavesData).then(
179
- (syncResponse) => {
180
- if (syncResponse) {
181
- return this.parseMessage(
182
- syncResponse,
183
- `via empty leaves /sync API call for ${debugText}`
184
- );
185
- }
186
-
187
- return {updateType: LocusInfoUpdateType.OBJECTS_UPDATED, updatedObjects: []};
188
- }
189
- );
190
- }
191
-
192
- /**
193
- * Queries Locus for information about all the data sets
194
- *
195
- * @param {string} url - url from which we can get info about all data sets
196
- * @returns {Promise}
197
- */
198
- private getAllDataSetsMetadata(url) {
199
350
  return this.webexRequest({
200
351
  method: HTTP_VERBS.GET,
201
- uri: url,
202
- }).then((response) => {
203
- return response.body.dataSets as Array<DataSet>;
204
- });
352
+ uri: this.visibleDataSetsUrl,
353
+ })
354
+ .then((response) => {
355
+ return response.body.dataSets as Array<DataSet>;
356
+ })
357
+ .catch((error) => {
358
+ this.checkForSentinelHttpResponse(error);
359
+
360
+ throw error;
361
+ });
205
362
  }
206
363
 
207
364
  /**
@@ -211,12 +368,14 @@ class HashTreeParser {
211
368
  * @returns {Promise}
212
369
  */
213
370
  async initializeFromMessage(message: HashTreeMessage) {
371
+ this.visibleDataSetsUrl = message.visibleDataSetsUrl;
372
+
214
373
  LoggerProxy.logger.info(
215
- `HashTreeParser#initializeFromMessage --> ${this.debugId} visibleDataSetsUrl=${message.visibleDataSetsUrl}`
374
+ `HashTreeParser#initializeFromMessage --> ${this.debugId} visibleDataSetsUrl=${this.visibleDataSetsUrl}`
216
375
  );
217
- const dataSets = await this.getAllDataSetsMetadata(message.visibleDataSetsUrl);
376
+ const visibleDataSets = await this.getAllVisibleDataSetsFromLocus();
218
377
 
219
- await this.initializeDataSets(dataSets, 'initialization from message');
378
+ await this.initializeDataSets(visibleDataSets, 'initialization from message');
220
379
  }
221
380
 
222
381
  /**
@@ -236,28 +395,31 @@ class HashTreeParser {
236
395
 
237
396
  return;
238
397
  }
398
+ this.visibleDataSetsUrl = locus.links.resources.visibleDataSets.url;
239
399
 
240
400
  LoggerProxy.logger.info(
241
- `HashTreeParser#initializeFromGetLociResponse --> ${this.debugId} visibleDataSets url: ${locus.links.resources.visibleDataSets.url}`
401
+ `HashTreeParser#initializeFromGetLociResponse --> ${this.debugId} visibleDataSets url: ${this.visibleDataSetsUrl}`
242
402
  );
243
403
 
244
- const dataSets = await this.getAllDataSetsMetadata(locus.links.resources.visibleDataSets.url);
404
+ const visibleDataSets = await this.getAllVisibleDataSetsFromLocus();
245
405
 
246
- await this.initializeDataSets(dataSets, 'initialization from GET /loci response');
406
+ await this.initializeDataSets(visibleDataSets, 'initialization from GET /loci response');
247
407
  }
248
408
 
249
409
  /**
250
410
  * Initializes data sets by doing an initialization sync on each visible data set that doesn't have a hash tree yet.
251
411
  *
252
- * @param {DataSet[]} dataSets Array of DataSet objects to initialize
412
+ * @param {DataSet[]} visibleDataSets Array of visible DataSet objects to initialize
253
413
  * @param {string} debugText Text to include in logs for debugging purposes
254
414
  * @returns {Promise}
255
415
  */
256
- private async initializeDataSets(dataSets: Array<DataSet>, debugText: string) {
257
- const updatedObjects: HashTreeObject[] = [];
416
+ private async initializeDataSets(visibleDataSets: Array<DataSet>, debugText: string) {
417
+ if (this.state === 'stopped') {
418
+ return;
419
+ }
258
420
 
259
- for (const dataSet of dataSets) {
260
- const {name, leafCount} = dataSet;
421
+ for (const dataSet of sortByInitPriority(visibleDataSets, DATA_SET_INIT_PRIORITY)) {
422
+ const {name, leafCount, url} = dataSet;
261
423
 
262
424
  if (!this.dataSets[name]) {
263
425
  LoggerProxy.logger.info(
@@ -273,34 +435,31 @@ class HashTreeParser {
273
435
  );
274
436
  }
275
437
 
276
- if (this.visibleDataSets.includes(name) && !this.dataSets[name].hashTree) {
438
+ if (!this.isVisibleDataSet(name)) {
439
+ if (
440
+ !this.addToVisibleDataSetsList({
441
+ name,
442
+ url,
443
+ })
444
+ ) {
445
+ // dataset is excluded, skip it
446
+ // eslint-disable-next-line no-continue
447
+ continue;
448
+ }
449
+ }
450
+
451
+ if (!this.dataSets[name].hashTree) {
277
452
  LoggerProxy.logger.info(
278
453
  `HashTreeParser#initializeDataSets --> ${this.debugId} creating hash tree for visible dataset "${name}" (${debugText})`
279
454
  );
280
455
  this.dataSets[name].hashTree = new HashTree([], leafCount);
281
456
 
282
- // eslint-disable-next-line no-await-in-loop
283
- const data = await this.sendInitializationSyncRequestToLocus(name, debugText);
284
-
285
- if (data.updateType === LocusInfoUpdateType.MEETING_ENDED) {
286
- LoggerProxy.logger.warn(
287
- `HashTreeParser#initializeDataSets --> ${this.debugId} meeting ended while initializing new visible data set "${name}"`
288
- );
289
-
290
- // throw an error, it will be caught higher up and the meeting will be destroyed
291
- throw new MeetingEndedError();
292
- }
293
-
294
- if (data.updateType === LocusInfoUpdateType.OBJECTS_UPDATED) {
295
- updatedObjects.push(...(data.updatedObjects || []));
296
- }
457
+ this.enqueueSyncForDataset(name, `initialization sync for ${debugText}`, true);
297
458
  }
298
459
  }
299
460
 
300
- this.callLocusInfoUpdateCallback({
301
- updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
302
- updatedObjects,
303
- });
461
+ // wait for all enqueued initialization syncs to complete
462
+ await this.syncQueueProcessingPromise;
304
463
  }
305
464
 
306
465
  /**
@@ -316,12 +475,9 @@ class HashTreeParser {
316
475
  private analyzeLocusHtMeta(locus: any, options?: {copyData?: boolean}) {
317
476
  const {copyData = false} = options || {};
318
477
  // object mapping dataset names to arrays of leaf data
319
- const leafInfo: Record<
320
- string,
321
- Array<{type: ObjectType; id: number; version: number; data?: any}>
322
- > = {};
478
+ const leafInfo: Record<string, Array<LeafInfo>> = {};
323
479
 
324
- const findAndStoreMetaData = (currentLocusPart: any) => {
480
+ const findAndStoreMetaData = (currentLocusPart: any, currentLocusPartName: string) => {
325
481
  if (typeof currentLocusPart !== 'object' || currentLocusPart === null) {
326
482
  return;
327
483
  }
@@ -329,17 +485,25 @@ class HashTreeParser {
329
485
  if (currentLocusPart.htMeta && currentLocusPart.htMeta.dataSetNames) {
330
486
  const {type, id, version} = currentLocusPart.htMeta.elementId;
331
487
  const {dataSetNames} = currentLocusPart.htMeta;
332
- const newLeafInfo: {type: ObjectType; id: number; version: number; data?: any} = {
488
+ const newLeafInfo: LeafInfo = {
333
489
  type,
334
490
  id,
335
491
  version,
336
492
  };
337
493
 
338
494
  if (copyData) {
339
- newLeafInfo.data = cloneDeep(currentLocusPart);
495
+ if ((type as string).toLowerCase() === ObjectType.control) {
496
+ // control entries require special handling, because they are signalled by Locus
497
+ // differently when coming in messages vs API responses
498
+ newLeafInfo.data = {
499
+ [currentLocusPartName]: cloneDeep(currentLocusPart),
500
+ };
501
+ } else {
502
+ newLeafInfo.data = cloneDeep(currentLocusPart);
340
503
 
341
- // remove any nested other objects that have their own htMeta
342
- deleteNestedObjectsWithHtMeta(newLeafInfo.data);
504
+ // remove any nested other objects that have their own htMeta
505
+ deleteNestedObjectsWithHtMeta(newLeafInfo.data);
506
+ }
343
507
  }
344
508
 
345
509
  for (const dataSetName of dataSetNames) {
@@ -351,45 +515,80 @@ class HashTreeParser {
351
515
  }
352
516
 
353
517
  if (Array.isArray(currentLocusPart)) {
354
- for (const item of currentLocusPart) {
355
- findAndStoreMetaData(item);
518
+ for (const [index, item] of currentLocusPart.entries()) {
519
+ findAndStoreMetaData(item, index.toString());
356
520
  }
357
521
  } else {
358
522
  for (const key of Object.keys(currentLocusPart)) {
359
523
  if (Object.prototype.hasOwnProperty.call(currentLocusPart, key)) {
360
- findAndStoreMetaData(currentLocusPart[key]);
524
+ findAndStoreMetaData(currentLocusPart[key], key);
361
525
  }
362
526
  }
363
527
  }
364
528
  };
365
529
 
366
- findAndStoreMetaData(locus);
530
+ findAndStoreMetaData(locus, 'locus');
367
531
 
368
532
  return leafInfo;
369
533
  }
370
534
 
371
535
  /**
372
- * Checks if the provided hash tree message indicates the end of the meeting and that there won't be any more updates.
536
+ * Analyzes the Metadata object that is sent outside of Locus object, and appends its data to passed in leafInfo
537
+ * structure.
373
538
  *
374
- * @param {HashTreeMessage} message - The hash tree message to check
375
- * @returns {boolean} - Returns true if the message indicates the end of the meeting, false otherwise
539
+ * @param {Record<string, LeafInfo[]>} leafInfo the structure to which the Metadata info will be appended
540
+ * @param {Metadata} metadata Metadata object
541
+ * @returns {void}
376
542
  */
377
- private isEndMessage(message: HashTreeMessage) {
378
- const mainDataSet = message.dataSets.find(
379
- (dataSet) => dataSet.name.toLowerCase() === DataSetNames.MAIN
380
- );
543
+ private analyzeMetadata(leafInfo: Record<string, LeafInfo[]>, metadata: Metadata) {
544
+ const {htMeta} = metadata;
381
545
 
382
546
  if (
383
- mainDataSet &&
384
- mainDataSet.leafCount === 1 &&
385
- mainDataSet.root === EMPTY_HASH &&
386
- this.dataSets[DataSetNames.MAIN].version < mainDataSet.version
547
+ htMeta?.dataSetNames?.length === 1 &&
548
+ htMeta.dataSetNames[0].toLowerCase() === MetadataDataSetName
387
549
  ) {
388
- // this is a special way for Locus to indicate that this meeting has ended
389
- return true;
550
+ const {type, id, version} = metadata.htMeta.elementId;
551
+
552
+ const dataSetName = htMeta.dataSetNames[0];
553
+
554
+ if (!leafInfo[dataSetName]) {
555
+ leafInfo[dataSetName] = [];
556
+ }
557
+
558
+ leafInfo[dataSetName].push({
559
+ type,
560
+ id,
561
+ version,
562
+ });
563
+ } else {
564
+ throw new Error(
565
+ `${this.debugId} Metadata htMeta has unexpected dataSetNames: ${
566
+ htMeta && htMeta.dataSetNames.join(',')
567
+ }`
568
+ );
390
569
  }
570
+ }
391
571
 
392
- return false;
572
+ /**
573
+ * Checks if the provided hash tree message indicates the end of the meeting and that there won't be any more updates.
574
+ *
575
+ * @param {HashTreeMessage} message - The hash tree message to check
576
+ * @returns {boolean} - Returns true if the message indicates the end of the meeting, false otherwise
577
+ */
578
+ private isEndMessage(message: HashTreeMessage) {
579
+ return message.dataSets.some((dataSet) => {
580
+ if (
581
+ dataSet.leafCount === 1 &&
582
+ dataSet.root === EMPTY_HASH &&
583
+ (!this.dataSets[dataSet.name] || this.dataSets[dataSet.name].version < dataSet.version) &&
584
+ PossibleSentinelMessageDataSetNames.includes(dataSet.name.toLowerCase())
585
+ ) {
586
+ // this is a special way for Locus to indicate that this meeting has ended
587
+ return true;
588
+ }
589
+
590
+ return false;
591
+ });
393
592
  }
394
593
 
395
594
  /**
@@ -414,12 +613,120 @@ class HashTreeParser {
414
613
  )}`
415
614
  );
416
615
 
616
+ this.cancelPendingSyncsForDataSets(dataSets.map((ds) => ds.name));
617
+
417
618
  dataSets.forEach((dataSet) => {
418
619
  this.updateDataSetInfo(dataSet);
419
620
  this.runSyncAlgorithm(dataSet);
420
621
  });
421
622
  }
422
623
 
624
+ /**
625
+ * Handles known errors that can happen during syncs
626
+ *
627
+ * @param {any} error - The error to handle
628
+ * @returns {boolean} true if the error was recognized and handled, false otherwise
629
+ */
630
+ private handleSyncErrors(error: any) {
631
+ if (error instanceof MeetingEndedError) {
632
+ this.callLocusInfoUpdateCallback({
633
+ updateType: LocusInfoUpdateType.MEETING_ENDED,
634
+ });
635
+
636
+ return true;
637
+ }
638
+ if (error instanceof LocusNotFoundError) {
639
+ this.callLocusInfoUpdateCallback({
640
+ updateType: LocusInfoUpdateType.LOCUS_NOT_FOUND,
641
+ });
642
+ this.stop();
643
+
644
+ return true;
645
+ }
646
+
647
+ return false;
648
+ }
649
+
650
+ /**
651
+ * Asynchronously initializes new visible data sets
652
+ *
653
+ * @param {VisibleDataSetInfo[]} dataSetsRequiringInitialization list of datasets to initialize
654
+ * @returns {void}
655
+ */
656
+ private queueInitForNewVisibleDataSets(dataSetsRequiringInitialization: VisibleDataSetInfo[]) {
657
+ LoggerProxy.logger.info(
658
+ `HashTreeParser#queueInitForNewVisibleDataSets --> ${
659
+ this.debugId
660
+ } queuing initialization of new visible datasets: ${dataSetsRequiringInitialization
661
+ .map((ds) => ds.name)
662
+ .join(', ')}`
663
+ );
664
+ queueMicrotask(() => {
665
+ this.initializeNewVisibleDataSets(dataSetsRequiringInitialization).catch((error) => {
666
+ if (!this.handleSyncErrors(error)) {
667
+ LoggerProxy.logger.warn(
668
+ `HashTreeParser#queueInitForNewVisibleDataSets --> ${
669
+ this.debugId
670
+ } error while initializing new visible datasets: ${dataSetsRequiringInitialization
671
+ .map((ds) => ds.name)
672
+ .join(', ')}: `,
673
+ error
674
+ );
675
+ }
676
+ });
677
+ });
678
+ }
679
+
680
+ /**
681
+ * Handles updates to Metadata object that we receive from Locus via other means than messages. Right now
682
+ * that means only in the API response alongside locus object.
683
+ *
684
+ * @param {Metadata} metadata received in Locus update other than a message (for example in an API response)
685
+ * @param {HashTreeObject[]} updatedObjects a list of updated hash tree objects to which any updates resulting from new Metadata will be added
686
+ * @returns {void}
687
+ */
688
+ handleMetadataUpdate(metadata: Metadata, updatedObjects: HashTreeObject[]): void {
689
+ let dataSetsRequiringInitialization: VisibleDataSetInfo[] = [];
690
+
691
+ // current assumption based on Locus docs is that Metadata object lives always in "self" data set
692
+ const hashTree = this.dataSets[MetadataDataSetName]?.hashTree;
693
+
694
+ if (!hashTree) {
695
+ LoggerProxy.logger.warn(
696
+ `HashTreeParser#handleLocusUpdate --> ${this.debugId} received Metadata object but no hash tree for "${MetadataDataSetName}" data set exists`
697
+ );
698
+ } else {
699
+ const metadataUpdated = hashTree.putItem(metadata.htMeta.elementId);
700
+
701
+ if (metadataUpdated) {
702
+ // metadata in Locus API response is in a slightly different format than the objects in messages, so need to adapt it
703
+ const metadataObject: HashTreeObject = {
704
+ htMeta: metadata.htMeta,
705
+ data: metadata,
706
+ };
707
+
708
+ updatedObjects.push(metadataObject);
709
+
710
+ const {changeDetected, removedDataSets, addedDataSets} = this.checkForVisibleDataSetChanges(
711
+ [metadataObject]
712
+ );
713
+
714
+ if (changeDetected) {
715
+ dataSetsRequiringInitialization = this.processVisibleDataSetChanges(
716
+ removedDataSets,
717
+ addedDataSets,
718
+ updatedObjects
719
+ );
720
+ }
721
+
722
+ if (dataSetsRequiringInitialization.length > 0) {
723
+ // there are some data sets that we need to initialize asynchronously
724
+ this.queueInitForNewVisibleDataSets(dataSetsRequiringInitialization);
725
+ }
726
+ }
727
+ }
728
+ }
729
+
423
730
  /**
424
731
  * This method should be called when we receive a partial locus DTO that contains dataSets and htMeta information
425
732
  * It updates the hash trees with the new leaf data based on the received Locus
@@ -427,22 +734,39 @@ class HashTreeParser {
427
734
  * @param {Object} update - The locus update containing data sets and locus information
428
735
  * @returns {void}
429
736
  */
430
- handleLocusUpdate(update: {dataSets?: Array<DataSet>; locus: any}): void {
431
- const {dataSets, locus} = update;
737
+ handleLocusUpdate(update: {dataSets?: Array<DataSet>; locus: any; metadata?: Metadata}): void {
738
+ if (this.state === 'stopped') {
739
+ return;
740
+ }
741
+
742
+ const {dataSets, locus, metadata} = update;
743
+
744
+ LoggerProxy.logger.info(
745
+ `HashTreeParser#handleLocusUpdate --> ${this.debugId} received update with dataSets=${dataSets
746
+ ?.map((ds) => ds.name)
747
+ .join(',')} metadata=${metadata ? 'yes' : 'no'}`
748
+ );
432
749
 
433
750
  if (!dataSets) {
434
- LoggerProxy.logger.warn(
751
+ // this happens for example when we handle GET /loci response
752
+ LoggerProxy.logger.info(
435
753
  `HashTreeParser#handleLocusUpdate --> ${this.debugId} received hash tree update without dataSets`
436
754
  );
437
- }
438
- for (const dataSet of dataSets) {
439
- this.updateDataSetInfo(dataSet);
755
+ } else {
756
+ for (const dataSet of dataSets) {
757
+ this.updateDataSetInfo(dataSet);
758
+ }
440
759
  }
441
760
  const updatedObjects: HashTreeObject[] = [];
442
761
 
443
762
  // first, analyze the locus object to extract the hash tree objects' htMeta and data from it
444
763
  const leafInfo = this.analyzeLocusHtMeta(locus, {copyData: true});
445
764
 
765
+ // if we got metadata, process it (currently that means only potential visible data set list changes)
766
+ if (metadata) {
767
+ this.handleMetadataUpdate(metadata, updatedObjects);
768
+ }
769
+
446
770
  // then process the data in hash trees, if it is a new version, then add it to updatedObjects
447
771
  Object.keys(leafInfo).forEach((dataSetName) => {
448
772
  if (this.dataSets[dataSetName]) {
@@ -477,7 +801,7 @@ class HashTreeParser {
477
801
  );
478
802
  }
479
803
  } else {
480
- LoggerProxy.logger.warn(
804
+ LoggerProxy.logger.info(
481
805
  `HashTreeParser#handleLocusUpdate --> ${this.debugId} received leaf data for unknown data set "${dataSetName}", ignoring`
482
806
  );
483
807
  }
@@ -493,9 +817,6 @@ class HashTreeParser {
493
817
  updatedObjects,
494
818
  });
495
819
  }
496
-
497
- // todo: once Locus design on how visible data sets will be communicated in subsequent API responses is confirmed,
498
- // we'll need to check here if visible data sets have changed and update this.visibleDataSets, remove/create hash trees etc
499
820
  }
500
821
 
501
822
  /**
@@ -511,7 +832,7 @@ class HashTreeParser {
511
832
  };
512
833
 
513
834
  LoggerProxy.logger.info(
514
- `HashTreeParser#handleMessage --> ${this.debugId} created entry for "${receivedDataSet.name}" dataset: version=${receivedDataSet.version}, root=${receivedDataSet.root}`
835
+ `HashTreeParser#updateDataSetInfo --> ${this.debugId} created entry for "${receivedDataSet.name}" dataset: version=${receivedDataSet.version}, root=${receivedDataSet.root}`
515
836
  );
516
837
 
517
838
  return;
@@ -525,37 +846,55 @@ class HashTreeParser {
525
846
  maxMs: receivedDataSet.backoff.maxMs,
526
847
  exponent: receivedDataSet.backoff.exponent,
527
848
  };
849
+ this.dataSets[receivedDataSet.name].heartbeatIntervalMs = receivedDataSet.heartbeatIntervalMs;
528
850
  LoggerProxy.logger.info(
529
- `HashTreeParser#handleMessage --> ${this.debugId} updated "${receivedDataSet.name}" to version=${receivedDataSet.version}, root=${receivedDataSet.root}`
851
+ `HashTreeParser#updateDataSetInfo --> ${this.debugId} updated "${receivedDataSet.name}" dataset to version=${receivedDataSet.version}, root=${receivedDataSet.root}`
530
852
  );
531
853
  }
532
854
  }
533
855
 
856
+ /**
857
+ * Updates the leaf count for a data set, resizing its hash tree accordingly.
858
+ *
859
+ * @param {InternalDataSet} dataSet - The data set to update
860
+ * @param {number} newLeafCount - The new leaf count
861
+ * @returns {void}
862
+ */
863
+ private updateDataSetLeafCount(dataSet: InternalDataSet, newLeafCount: number): void {
864
+ dataSet.hashTree?.resize(newLeafCount);
865
+ dataSet.leafCount = newLeafCount;
866
+ }
867
+
534
868
  /**
535
869
  * Checks for changes in the visible data sets based on the updated objects.
536
870
  * @param {HashTreeObject[]} updatedObjects - The list of updated hash tree objects.
537
871
  * @returns {Object} An object containing the removed and added visible data sets.
538
872
  */
539
873
  private checkForVisibleDataSetChanges(updatedObjects: HashTreeObject[]) {
540
- let removedDataSets: string[] = [];
541
- let addedDataSets: string[] = [];
874
+ let removedDataSets: VisibleDataSetInfo[] = [];
875
+ let addedDataSets: VisibleDataSetInfo[] = [];
542
876
 
543
- // visibleDataSets can only be changed by self object updates
877
+ // visibleDataSets can only be changed by Metadata object updates
544
878
  updatedObjects.forEach((object) => {
545
- // todo: in the future visibleDataSets will be in "Metadata" object, not in "self"
546
- if (isSelf(object) && object.data?.visibleDataSets) {
547
- const newVisibleDataSets = object.data.visibleDataSets;
879
+ if (isMetadata(object) && object.data?.visibleDataSets) {
880
+ const newVisibleDataSets = object.data.visibleDataSets.filter(
881
+ (vds) => !this.isExcludedDataSet(vds.name)
882
+ );
548
883
 
549
- removedDataSets = this.visibleDataSets.filter((ds) => !newVisibleDataSets.includes(ds));
550
- addedDataSets = newVisibleDataSets.filter((ds) => !this.visibleDataSets.includes(ds));
884
+ removedDataSets = this.visibleDataSets.filter(
885
+ (ds) => !newVisibleDataSets.some((nvs) => nvs.name === ds.name)
886
+ );
887
+ addedDataSets = newVisibleDataSets.filter((nvs) =>
888
+ this.visibleDataSets.every((ds) => ds.name !== nvs.name)
889
+ );
551
890
 
552
891
  if (removedDataSets.length > 0 || addedDataSets.length > 0) {
553
892
  LoggerProxy.logger.info(
554
893
  `HashTreeParser#checkForVisibleDataSetChanges --> ${
555
894
  this.debugId
556
- } visible data sets change: removed: ${removedDataSets.join(
557
- ', '
558
- )}, added: ${addedDataSets.join(', ')}`
895
+ } visible data sets change: removed: ${removedDataSets
896
+ .map((ds) => ds.name)
897
+ .join(', ')}, added: ${addedDataSets.map((ds) => ds.name).join(', ')}`
559
898
  );
560
899
  }
561
900
  }
@@ -576,12 +915,18 @@ class HashTreeParser {
576
915
  */
577
916
  private deleteHashTree(dataSetName: string) {
578
917
  this.dataSets[dataSetName].hashTree = undefined;
918
+ this.dataSets[dataSetName].syncAbortController?.abort();
919
+ this.dataSets[dataSetName].syncAbortController = undefined;
579
920
 
580
- // we also need to stop the timer as there is no hash tree anymore to sync
921
+ // we also need to stop the timers as there is no hash tree anymore to sync
581
922
  if (this.dataSets[dataSetName].timer) {
582
923
  clearTimeout(this.dataSets[dataSetName].timer);
583
924
  this.dataSets[dataSetName].timer = undefined;
584
925
  }
926
+ if (this.dataSets[dataSetName].heartbeatWatchdogTimer) {
927
+ clearTimeout(this.dataSets[dataSetName].heartbeatWatchdogTimer);
928
+ this.dataSets[dataSetName].heartbeatWatchdogTimer = undefined;
929
+ }
585
930
  }
586
931
 
587
932
  /**
@@ -593,49 +938,51 @@ class HashTreeParser {
593
938
  * visible data sets and they require async initialization, the names of these data sets
594
939
  * are returned in an array.
595
940
  *
596
- * @param {string[]} removedDataSets - The list of removed data sets.
597
- * @param {string[]} addedDataSets - The list of added data sets.
941
+ * @param {VisibleDataSetInfo[]} removedDataSets - The list of removed data sets.
942
+ * @param {VisibleDataSetInfo[]} addedDataSets - The list of added data sets.
598
943
  * @param {HashTreeObject[]} updatedObjects - The list of updated hash tree objects to which changes will be added.
599
- * @returns {string[]} names of data sets that couldn't be initialized synchronously
944
+ * @returns {VisibleDataSetInfo[]} list of data sets that couldn't be initialized synchronously
600
945
  */
601
946
  private processVisibleDataSetChanges(
602
- removedDataSets: string[],
603
- addedDataSets: string[],
947
+ removedDataSets: VisibleDataSetInfo[],
948
+ addedDataSets: VisibleDataSetInfo[],
604
949
  updatedObjects: HashTreeObject[]
605
- ): string[] {
606
- const dataSetsRequiringInitialization = [];
950
+ ): VisibleDataSetInfo[] {
951
+ const dataSetsRequiringInitialization: VisibleDataSetInfo[] = [];
607
952
 
608
953
  // if a visible data set was removed, we need to tell our client that all objects from it are removed
609
954
  const removedObjects: HashTreeObject[] = [];
610
955
 
611
956
  removedDataSets.forEach((ds) => {
612
- if (this.dataSets[ds]?.hashTree) {
613
- for (let i = 0; i < this.dataSets[ds].hashTree.numLeaves; i += 1) {
957
+ if (this.dataSets[ds.name]?.hashTree) {
958
+ for (let i = 0; i < this.dataSets[ds.name].hashTree.numLeaves; i += 1) {
614
959
  removedObjects.push(
615
- ...this.dataSets[ds].hashTree.getLeafData(i).map((elementId) => ({
960
+ ...this.dataSets[ds.name].hashTree.getLeafData(i).map((elementId) => ({
616
961
  htMeta: {
617
962
  elementId,
618
- dataSetNames: [ds],
963
+ dataSetNames: [ds.name],
619
964
  },
620
965
  data: null,
621
966
  }))
622
967
  );
623
968
  }
624
969
 
625
- this.deleteHashTree(ds);
970
+ this.deleteHashTree(ds.name);
626
971
  }
627
972
  });
628
- this.visibleDataSets = this.visibleDataSets.filter((vds) => !removedDataSets.includes(vds));
973
+ this.visibleDataSets = this.visibleDataSets.filter(
974
+ (vds) => !removedDataSets.some((rds) => rds.name === vds.name)
975
+ );
629
976
  updatedObjects.push(...removedObjects);
630
977
 
631
978
  // now setup the new visible data sets
632
979
  for (const ds of addedDataSets) {
633
- const dataSetInfo = this.dataSets[ds];
980
+ const dataSetInfo = this.dataSets[ds.name];
634
981
 
635
982
  if (dataSetInfo) {
636
- if (this.visibleDataSets.includes(dataSetInfo.name)) {
983
+ if (this.isVisibleDataSet(dataSetInfo.name)) {
637
984
  LoggerProxy.logger.info(
638
- `HashTreeParser#processVisibleDataSetChanges --> ${this.debugId} Data set "${ds}" is already visible, skipping`
985
+ `HashTreeParser#processVisibleDataSetChanges --> ${this.debugId} Data set "${ds.name}" is already visible, skipping`
639
986
  );
640
987
 
641
988
  // eslint-disable-next-line no-continue
@@ -643,10 +990,13 @@ class HashTreeParser {
643
990
  }
644
991
 
645
992
  LoggerProxy.logger.info(
646
- `HashTreeParser#processVisibleDataSetChanges --> ${this.debugId} Adding visible data set "${ds}"`
993
+ `HashTreeParser#processVisibleDataSetChanges --> ${this.debugId} Adding visible data set "${ds.name}"`
647
994
  );
648
995
 
649
- this.visibleDataSets.push(ds);
996
+ if (!this.addToVisibleDataSetsList(ds)) {
997
+ // eslint-disable-next-line no-continue
998
+ continue;
999
+ }
650
1000
 
651
1001
  const hashTree = new HashTree([], dataSetInfo.leafCount);
652
1002
 
@@ -654,9 +1004,13 @@ class HashTreeParser {
654
1004
  ...dataSetInfo,
655
1005
  hashTree,
656
1006
  };
1007
+
1008
+ // this call is needed here for the edge case where we receive a message with new visible data sets
1009
+ // and there are no objects belonging to these data sets in the message but we already have the info about them in this.dataSets
1010
+ this.runSyncAlgorithm(this.dataSets[dataSetInfo.name]);
657
1011
  } else {
658
1012
  LoggerProxy.logger.info(
659
- `HashTreeParser#processVisibleDataSetChanges --> ${this.debugId} visible data set "${ds}" added but no info about it in our dataSets structures`
1013
+ `HashTreeParser#processVisibleDataSetChanges --> ${this.debugId} visible data set "${ds.name}" added but no info about it in our dataSets structures`
660
1014
  );
661
1015
  // todo: add a metric here
662
1016
  dataSetsRequiringInitialization.push(ds);
@@ -670,34 +1024,29 @@ class HashTreeParser {
670
1024
  * Adds entries to the passed in updateObjects array
671
1025
  * for the changes that result from adding and removing visible data sets.
672
1026
  *
673
- * @param {HashTreeMessage} message - The hash tree message that triggered the visible data set changes.
674
- * @param {string[]} addedDataSets - The list of added data sets.
1027
+ * @param {VisibleDataSetInfo[]} addedDataSets - The list of added data sets.
675
1028
  * @returns {Promise<void>}
676
1029
  */
677
- private async initializeNewVisibleDataSets(
678
- message: HashTreeMessage,
679
- addedDataSets: string[]
680
- ): Promise<void> {
681
- const allDataSets = await this.getAllDataSetsMetadata(message.visibleDataSetsUrl);
1030
+ private async initializeNewVisibleDataSets(addedDataSets: VisibleDataSetInfo[]): Promise<void> {
1031
+ if (this.state === 'stopped') {
1032
+ return;
1033
+ }
1034
+ const allDataSets = await this.getAllVisibleDataSetsFromLocus();
682
1035
 
683
- for (const ds of addedDataSets) {
684
- const dataSetInfo = allDataSets.find((d) => d.name === ds);
1036
+ for (const ds of sortByInitPriority(addedDataSets, DATA_SET_INIT_PRIORITY)) {
1037
+ const dataSetInfo = allDataSets.find((d) => d.name === ds.name);
685
1038
 
686
1039
  LoggerProxy.logger.info(
687
- `HashTreeParser#initializeNewVisibleDataSets --> ${this.debugId} initializing data set "${ds}"`
1040
+ `HashTreeParser#initializeNewVisibleDataSets --> ${this.debugId} initializing data set "${ds.name}"`
688
1041
  );
689
1042
 
690
1043
  if (!dataSetInfo) {
691
1044
  LoggerProxy.logger.warn(
692
- `HashTreeParser#handleHashTreeMessage --> ${this.debugId} missing info about data set "${ds}" in Locus response from visibleDataSetsUrl`
1045
+ `HashTreeParser#initializeNewVisibleDataSets --> ${this.debugId} missing info about data set "${ds.name}" in Locus response from visibleDataSetsUrl`
693
1046
  );
694
1047
  } else {
695
- // we're awaiting in a loop, because in practice there will be only one new data set at a time,
696
- // so no point in trying to parallelize this
697
1048
  // eslint-disable-next-line no-await-in-loop
698
- const updates = await this.initializeNewVisibleDataSet(dataSetInfo);
699
-
700
- this.callLocusInfoUpdateCallback(updates);
1049
+ await this.initializeNewVisibleDataSet(ds, dataSetInfo);
701
1050
  }
702
1051
  }
703
1052
  }
@@ -707,71 +1056,75 @@ class HashTreeParser {
707
1056
  *
708
1057
  * @param {HashTreeMessage} message - The hash tree message containing data sets and objects to be processed
709
1058
  * @param {string} [debugText] - Optional debug text to include in logs
710
- * @returns {Promise}
1059
+ * @returns {HashTreeObject[]} list of hash tree objects that were updated as a result of processing the message
711
1060
  */
712
- private async parseMessage(
713
- message: HashTreeMessage,
714
- debugText?: string
715
- ): Promise<{updateType: LocusInfoUpdateType; updatedObjects?: HashTreeObject[]}> {
1061
+ private parseMessage(message: HashTreeMessage, debugText?: string): HashTreeObject[] {
1062
+ if (this.state === 'stopped') {
1063
+ return [];
1064
+ }
1065
+
716
1066
  const {dataSets, visibleDataSetsUrl} = message;
717
1067
 
718
1068
  LoggerProxy.logger.info(
719
- `HashTreeParser#parseMessage --> ${this.debugId} received message ${debugText || ''}:`,
720
- message
1069
+ `HashTreeParser#parseMessage --> ${this.debugId} ${
1070
+ debugText || ''
1071
+ } dataSets: ${message.dataSets
1072
+ ?.map(({name, version}) => `${name}:${version}`)
1073
+ .join(',')}, elements: ${message.locusStateElements
1074
+ ?.map(
1075
+ (el) =>
1076
+ `${el.htMeta.elementId.type}:${el.htMeta.elementId.id}:${el.htMeta.elementId.version}${
1077
+ el.data ? '+' : '-'
1078
+ }`
1079
+ )
1080
+ .join(',')}`
721
1081
  );
1082
+
722
1083
  if (message.locusStateElements?.length === 0) {
723
1084
  LoggerProxy.logger.warn(
724
1085
  `HashTreeParser#parseMessage --> ${this.debugId} got empty locusStateElements!!!`
725
1086
  );
726
- // todo: send a metric
1087
+ Metrics.sendBehavioralMetric(BEHAVIORAL_METRICS.HASH_TREE_EMPTY_LOCUS_STATE_ELEMENTS, {
1088
+ debugId: this.debugId,
1089
+ });
727
1090
  }
728
1091
 
729
1092
  // first, update our metadata about the datasets with info from the message
730
1093
  this.visibleDataSetsUrl = visibleDataSetsUrl;
731
1094
  dataSets.forEach((dataSet) => this.updateDataSetInfo(dataSet));
1095
+ this.cancelPendingSyncsForDataSets(dataSets.map((ds) => ds.name));
732
1096
 
733
- if (this.isEndMessage(message)) {
734
- LoggerProxy.logger.info(
735
- `HashTreeParser#parseMessage --> ${this.debugId} received END message`
736
- );
737
- this.stopAllTimers();
738
-
739
- return {updateType: LocusInfoUpdateType.MEETING_ENDED};
740
- }
741
-
742
- let isRosterDropped = false;
743
1097
  const updatedObjects: HashTreeObject[] = [];
744
1098
 
745
1099
  // when we detect new visible datasets, it may be that the metadata about them is not
746
1100
  // available in the message, they will require separate async initialization
747
- let dataSetsRequiringInitialization = [];
1101
+ let dataSetsRequiringInitialization: VisibleDataSetInfo[] = [];
748
1102
 
749
- // first find out if there are any visible data set changes - they're signalled in SELF object updates
750
- const selfUpdates = (message.locusStateElements || []).filter((object) =>
751
- // todo: SPARK-744859 once Locus supports it, we will filter for "Metadata" type here instead of "self"
752
- isSelf(object)
1103
+ // first find out if there are any visible data set changes - they're signalled in Metadata object updates
1104
+ const metadataUpdates = (message.locusStateElements || []).filter((object) =>
1105
+ isMetadata(object)
753
1106
  );
754
1107
 
755
- if (selfUpdates.length > 0) {
756
- const updatedSelfObjects = [];
1108
+ if (metadataUpdates.length > 0) {
1109
+ const updatedMetadataObjects: HashTreeObject[] = [];
757
1110
 
758
- selfUpdates.forEach((object) => {
1111
+ metadataUpdates.forEach((object) => {
759
1112
  // todo: once Locus supports it, we will use the "view" field here instead of dataSetNames
760
1113
  for (const dataSetName of object.htMeta.dataSetNames) {
761
1114
  const hashTree = this.dataSets[dataSetName]?.hashTree;
762
1115
 
763
1116
  if (hashTree && object.data) {
764
1117
  if (hashTree.putItem(object.htMeta.elementId)) {
765
- updatedSelfObjects.push(object);
1118
+ updatedMetadataObjects.push(object);
766
1119
  }
767
1120
  }
768
1121
  }
769
1122
  });
770
1123
 
771
- updatedObjects.push(...updatedSelfObjects);
1124
+ updatedObjects.push(...updatedMetadataObjects);
772
1125
 
773
1126
  const {changeDetected, removedDataSets, addedDataSets} =
774
- this.checkForVisibleDataSetChanges(updatedSelfObjects);
1127
+ this.checkForVisibleDataSetChanges(updatedMetadataObjects);
775
1128
 
776
1129
  if (changeDetected) {
777
1130
  dataSetsRequiringInitialization = this.processVisibleDataSetChanges(
@@ -782,64 +1135,49 @@ class HashTreeParser {
782
1135
  }
783
1136
  }
784
1137
 
785
- // by this point we now have this.dataSets setup for data sets from this message
786
- // and hash trees created for the new visible data sets,
787
- // so we can now process all the updates from the message
788
- dataSets.forEach((dataSet) => {
789
- if (this.dataSets[dataSet.name]) {
790
- const {hashTree} = this.dataSets[dataSet.name];
791
-
792
- if (hashTree) {
793
- const locusStateElementsForThisSet = message.locusStateElements.filter((object) =>
794
- object.htMeta.dataSetNames.includes(dataSet.name)
795
- );
796
-
797
- const appliedChangesList = hashTree.updateItems(
798
- locusStateElementsForThisSet.map((object) =>
799
- object.data
800
- ? {operation: 'update', item: object.htMeta.elementId}
801
- : {operation: 'remove', item: object.htMeta.elementId}
802
- )
803
- );
804
-
805
- zip(appliedChangesList, locusStateElementsForThisSet).forEach(
806
- ([changeApplied, object]) => {
807
- if (changeApplied) {
808
- if (isSelf(object) && !object.data) {
809
- isRosterDropped = true;
1138
+ if (message.locusStateElements && message.locusStateElements.length > 0) {
1139
+ // by this point we now have this.dataSets setup for data sets from this message
1140
+ // and hash trees created for the new visible data sets,
1141
+ // so we can now process all the updates from the message
1142
+ dataSets.forEach((dataSet) => {
1143
+ if (this.dataSets[dataSet.name]) {
1144
+ const {hashTree} = this.dataSets[dataSet.name];
1145
+
1146
+ if (hashTree) {
1147
+ const locusStateElementsForThisSet = message.locusStateElements.filter((object) =>
1148
+ object.htMeta.dataSetNames.includes(dataSet.name)
1149
+ );
1150
+
1151
+ const appliedChangesList = hashTree.updateItems(
1152
+ locusStateElementsForThisSet.map((object) =>
1153
+ object.data
1154
+ ? {operation: 'update', item: object.htMeta.elementId}
1155
+ : {operation: 'remove', item: object.htMeta.elementId}
1156
+ )
1157
+ );
1158
+
1159
+ zip(appliedChangesList, locusStateElementsForThisSet).forEach(
1160
+ ([changeApplied, object]) => {
1161
+ if (changeApplied) {
1162
+ // add to updatedObjects so that our locus DTO will get updated with the new object
1163
+ updatedObjects.push(object);
810
1164
  }
811
- // add to updatedObjects so that our locus DTO will get updated with the new object
812
- updatedObjects.push(object);
813
1165
  }
814
- }
815
- );
816
- } else {
817
- LoggerProxy.logger.info(
818
- `Locus-info:index#parseMessage --> ${this.debugId} unexpected (not visible) dataSet ${dataSet.name} received in hash tree message`
819
- );
1166
+ );
1167
+ } else {
1168
+ LoggerProxy.logger.info(
1169
+ `Locus-info:index#parseMessage --> ${this.debugId} unexpected (not visible) dataSet ${dataSet.name} received in hash tree message`
1170
+ );
1171
+ }
820
1172
  }
821
- }
822
1173
 
823
- if (!isRosterDropped) {
824
1174
  this.runSyncAlgorithm(dataSet);
825
- }
826
- });
827
-
828
- if (isRosterDropped) {
829
- LoggerProxy.logger.info(
830
- `HashTreeParser#parseMessage --> ${this.debugId} detected roster drop`
831
- );
832
- this.stopAllTimers();
833
-
834
- // in case of roster drop we don't care about other updates
835
- return {updateType: LocusInfoUpdateType.MEETING_ENDED};
836
- }
1175
+ });
1176
+ }
837
1177
 
838
1178
  if (dataSetsRequiringInitialization.length > 0) {
839
1179
  // there are some data sets that we need to initialize asynchronously
840
- queueMicrotask(() => {
841
- this.initializeNewVisibleDataSets(message, dataSetsRequiringInitialization);
842
- });
1180
+ this.queueInitForNewVisibleDataSets(dataSetsRequiringInitialization);
843
1181
  }
844
1182
 
845
1183
  if (updatedObjects.length === 0) {
@@ -848,7 +1186,7 @@ class HashTreeParser {
848
1186
  );
849
1187
  }
850
1188
 
851
- return {updateType: LocusInfoUpdateType.OBJECTS_UPDATED, updatedObjects};
1189
+ return updatedObjects;
852
1190
  }
853
1191
 
854
1192
  /**
@@ -858,30 +1196,131 @@ class HashTreeParser {
858
1196
  * @param {string} [debugText] - Optional debug text to include in logs
859
1197
  * @returns {void}
860
1198
  */
861
- async handleMessage(message: HashTreeMessage, debugText?: string): Promise<void> {
862
- if (message.locusStateElements === undefined) {
1199
+ handleMessage(message: HashTreeMessage, debugText?: string) {
1200
+ if (this.state === 'stopped') {
1201
+ return;
1202
+ }
1203
+
1204
+ if (message.heartbeatIntervalMs !== undefined) {
1205
+ this.topLevelHeartbeatIntervalMs = message.heartbeatIntervalMs;
1206
+ }
1207
+
1208
+ if (this.isEndMessage(message)) {
1209
+ LoggerProxy.logger.info(
1210
+ `HashTreeParser#handleMessage --> ${this.debugId} received sentinel END MEETING message`
1211
+ );
1212
+ this.stopAllTimers();
1213
+
1214
+ this.callLocusInfoUpdateCallback({updateType: LocusInfoUpdateType.MEETING_ENDED});
1215
+ } else if (message.locusStateElements === undefined) {
863
1216
  this.handleRootHashHeartBeatMessage(message);
1217
+ this.resetHeartbeatWatchdogs(message.dataSets);
864
1218
  } else {
865
- const updates = await this.parseMessage(message, debugText);
1219
+ // Completion of the sync latency metric (client.locus.sync.complete) is driven solely from
1220
+ // Meeting#processLocusLLMEvent once the matching LLM message arrives. body-mode syncs return
1221
+ // the locus state elements in the /sync HTTP response body, but per design the CA metric is
1222
+ // emitted only from the LLM message path, so no completion happens here.
1223
+ const updatedObjects = this.parseMessage(message, debugText);
866
1224
 
867
- this.callLocusInfoUpdateCallback(updates);
1225
+ this.resetHeartbeatWatchdogs(message.dataSets);
1226
+ this.callLocusInfoUpdateCallback({
1227
+ updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
1228
+ updatedObjects,
1229
+ });
868
1230
  }
869
1231
  }
870
1232
 
1233
+ /**
1234
+ * Checks if Locus sync latency metrics should be collected for a dataset.
1235
+ *
1236
+ * @param {string} dataSetName dataset name
1237
+ * @param {boolean} [isInitialization=false] whether this is an initialization sync
1238
+ * @returns {boolean}
1239
+ */
1240
+ private shouldCollectSyncMetrics(dataSetName: string, isInitialization = false): boolean {
1241
+ return Boolean(
1242
+ this.callbacks.syncLatencyTracker &&
1243
+ !isInitialization &&
1244
+ SYNC_METRICS_DATA_SETS.includes(dataSetName)
1245
+ );
1246
+ }
1247
+
1248
+ private saveSyncBackoffLatency(
1249
+ dataSetName: string,
1250
+ randomBackoffTime: number,
1251
+ isInitialization = false
1252
+ ) {
1253
+ if (!this.shouldCollectSyncMetrics(dataSetName, isInitialization)) {
1254
+ return;
1255
+ }
1256
+
1257
+ this.callbacks.syncLatencyTracker?.saveLatency(
1258
+ 'internal.client.locus.sync.random.backoff',
1259
+ Math.round(randomBackoffTime),
1260
+ {
1261
+ meetingId: this.syncLatencyMeetingId,
1262
+ dataSetName,
1263
+ }
1264
+ );
1265
+ }
1266
+
871
1267
  /**
872
1268
  * Calls the updateInfo callback if there are any updates to report
873
1269
  *
874
1270
  * @param {Object} updates parsed from a Locus message
875
1271
  * @returns {void}
876
1272
  */
877
- private callLocusInfoUpdateCallback(updates: {
878
- updateType: LocusInfoUpdateType;
879
- updatedObjects?: HashTreeObject[];
880
- }) {
881
- const {updateType, updatedObjects} = updates;
1273
+ private callLocusInfoUpdateCallback(updates: LocusInfoUpdate) {
1274
+ if (this.state === 'stopped') {
1275
+ return;
1276
+ }
1277
+
1278
+ const {updateType} = updates;
1279
+
1280
+ if (updateType === LocusInfoUpdateType.OBJECTS_UPDATED && updates.updatedObjects?.length > 0) {
1281
+ // Filter out updates for objects that already have a higher version in their datasets,
1282
+ // or removals for objects that still exist in any of their datasets
1283
+ const filteredUpdates = updates.updatedObjects.filter((object) => {
1284
+ const {elementId} = object.htMeta;
1285
+ const {type, id, version} = elementId;
1286
+
1287
+ // Check all datasets
1288
+ for (const dataSetName of Object.keys(this.dataSets)) {
1289
+ const dataSet = this.dataSets[dataSetName];
1290
+
1291
+ // only visible datasets have hash trees set
1292
+ if (dataSet?.hashTree) {
1293
+ const existingVersion = dataSet.hashTree.getItemVersion(id, type);
1294
+ if (existingVersion !== undefined) {
1295
+ if (object.data) {
1296
+ // For updates: filter out if any dataset has a higher version
1297
+ if (existingVersion > version) {
1298
+ LoggerProxy.logger.info(
1299
+ `HashTreeParser#callLocusInfoUpdateCallback --> ${this.debugId} Filtering out update for ${type}:${id} v${version} because dataset "${dataSetName}" has v${existingVersion}`
1300
+ );
1301
+
1302
+ return false;
1303
+ }
1304
+ } else if (existingVersion >= version) {
1305
+ // For removals: filter out if the object still exists in any dataset
1306
+ LoggerProxy.logger.info(
1307
+ `HashTreeParser#callLocusInfoUpdateCallback --> ${this.debugId} Filtering out removal for ${type}:${id} v${version} because dataset "${dataSetName}" still has v${existingVersion}`
1308
+ );
1309
+
1310
+ return false;
1311
+ }
1312
+ }
1313
+ }
1314
+ }
1315
+
1316
+ return true;
1317
+ });
882
1318
 
883
- if (updateType !== LocusInfoUpdateType.OBJECTS_UPDATED || updatedObjects?.length > 0) {
884
- this.locusInfoUpdateCallback(updateType, {updatedObjects});
1319
+ if (filteredUpdates.length > 0) {
1320
+ this.callbacks.locusInfoUpdateCallback({updateType, updatedObjects: filteredUpdates});
1321
+ }
1322
+ } else if (updateType !== LocusInfoUpdateType.OBJECTS_UPDATED) {
1323
+ this.callbacks.locusInfoUpdateCallback({updateType});
885
1324
  }
886
1325
  }
887
1326
 
@@ -899,6 +1338,460 @@ class HashTreeParser {
899
1338
  return Math.round(randomValue ** exponent * maxMs);
900
1339
  }
901
1340
 
1341
+ /**
1342
+ * Returns a copy of a hash tree message restricted to a single dataset, keeping only the
1343
+ * requested dataset and the elements belonging to it. Used to strip out datasets that Locus
1344
+ * may include in a sync response but that we didn't request (e.g. "unjoined" sharing elements
1345
+ * with "main"), which would otherwise be applied once per dataset.
1346
+ *
1347
+ * @param {HashTreeMessage} message the sync response message
1348
+ * @param {string} dataSetName the dataset that was requested
1349
+ * @returns {HashTreeMessage} a new message containing only the requested dataset
1350
+ */
1351
+ private filterMessageToDataSet(message: HashTreeMessage, dataSetName: string): HashTreeMessage {
1352
+ const filteredOutDataSets = message.dataSets?.filter((ds) => ds.name !== dataSetName) ?? [];
1353
+ const filteredOutElements =
1354
+ message.locusStateElements?.filter((el) => !el.htMeta.dataSetNames?.includes(dataSetName)) ??
1355
+ [];
1356
+
1357
+ if (filteredOutDataSets.length > 0 || filteredOutElements.length > 0) {
1358
+ LoggerProxy.logger.info(
1359
+ `HashTreeParser#filterMessageToDataSet --> ${
1360
+ this.debugId
1361
+ } keeping only dataset "${dataSetName}", filtering out datasets: [${filteredOutDataSets
1362
+ .map((ds) => `${ds.name}:${ds.version}`)
1363
+ .join(',')}], elements: [${filteredOutElements
1364
+ .map(
1365
+ (el) =>
1366
+ `${el.htMeta?.elementId?.type}:${el.htMeta?.elementId?.id}:${el.htMeta?.elementId?.version}`
1367
+ )
1368
+ .join(',')}]`
1369
+ );
1370
+ }
1371
+
1372
+ return {
1373
+ ...message,
1374
+ dataSets: message.dataSets?.filter((ds) => ds.name === dataSetName),
1375
+ locusStateElements: message.locusStateElements?.filter((el) =>
1376
+ el.htMeta.dataSetNames?.includes(dataSetName)
1377
+ ),
1378
+ };
1379
+ }
1380
+
1381
+ /**
1382
+ * Performs a sync for the given data set.
1383
+ *
1384
+ * @param {InternalDataSet} dataSet - The data set to sync
1385
+ * @param {string} reason - The reason for the sync (used for logging)
1386
+ * @param {boolean} [isInitialization] - Whether this is an initialization sync (sends empty leaves data instead of comparing hashes)
1387
+ * @returns {Promise<void>}
1388
+ */
1389
+ private async performSync(
1390
+ dataSet: InternalDataSet,
1391
+ reason: string,
1392
+ isInitialization?: boolean
1393
+ ): Promise<void> {
1394
+ if (!dataSet.hashTree) {
1395
+ return;
1396
+ }
1397
+
1398
+ const abortController = dataSet.syncAbortController ?? new AbortController();
1399
+ dataSet.syncAbortController = abortController;
1400
+
1401
+ const {hashTree} = dataSet;
1402
+ const rootHash = hashTree.getRootHash();
1403
+ const shouldCollectMetrics = this.shouldCollectSyncMetrics(dataSet.name, isInitialization);
1404
+ // Generate two distinct tracking ids up-front. Each Locus request must carry its own unique
1405
+ // tracking id, so the /hashtree and /sync requests must not share one. hashtreeTrackingId is
1406
+ // generated first so that syncTrackingId (forced onto the /sync request, stored in metrics, and
1407
+ // used to match the LLM broadcast message) ends up with the later/higher sequence number,
1408
+ // matching the order in which Locus sees the requests. If we never call /hashtree (single-leaf
1409
+ // or initialization syncs), hashtreeTrackingId is simply unused.
1410
+ const hashtreeTrackingId = shouldCollectMetrics
1411
+ ? this.callbacks.generateTrackingId?.()
1412
+ : undefined;
1413
+ const syncTrackingId = shouldCollectMetrics ? this.callbacks.generateTrackingId?.() : undefined;
1414
+ let syncRequestSent = false;
1415
+
1416
+ if (shouldCollectMetrics) {
1417
+ this.callbacks.syncLatencyTracker?.saveTimestamp({
1418
+ key: 'internal.client.locus.sync.start',
1419
+ options: {
1420
+ meetingId: this.syncLatencyMeetingId,
1421
+ dataSetName: dataSet.name,
1422
+ trackingId: syncTrackingId,
1423
+ },
1424
+ });
1425
+ }
1426
+
1427
+ try {
1428
+ LoggerProxy.logger.info(
1429
+ `HashTreeParser#performSync --> ${this.debugId} ${reason}, syncing data set "${dataSet.name}"`
1430
+ );
1431
+
1432
+ let leavesData: Record<number, LeafDataItem[]> = {};
1433
+
1434
+ if (!isInitialization) {
1435
+ if (dataSet.leafCount !== 1) {
1436
+ let receivedHashes;
1437
+
1438
+ try {
1439
+ // request hashes from sender
1440
+ const hashesResult = await this.getHashesFromLocus(dataSet.name, rootHash, {
1441
+ requestTrackingId: hashtreeTrackingId,
1442
+ metricTrackingId: syncTrackingId,
1443
+ });
1444
+
1445
+ if (!hashesResult) {
1446
+ // hashes match, no sync needed
1447
+ return;
1448
+ }
1449
+
1450
+ receivedHashes = hashesResult.hashes;
1451
+
1452
+ this.updateDataSetLeafCount(dataSet, hashesResult.dataSet.leafCount);
1453
+ } catch (error: any) {
1454
+ if (error?.statusCode === 409) {
1455
+ // this is a leaf count mismatch, we should do nothing, just wait for another heartbeat message from Locus
1456
+ LoggerProxy.logger.info(
1457
+ `HashTreeParser#getHashesFromLocus --> ${this.debugId} Got 409 when fetching hashes for data set "${dataSet.name}": ${error.message}`
1458
+ );
1459
+
1460
+ return;
1461
+ }
1462
+ throw error;
1463
+ }
1464
+
1465
+ // identify mismatched leaves
1466
+ const mismatchedLeaveIndexes = hashTree.diffHashes(receivedHashes);
1467
+
1468
+ mismatchedLeaveIndexes.forEach((index) => {
1469
+ leavesData[index] = hashTree.getLeafData(index);
1470
+ });
1471
+ } else {
1472
+ leavesData = {0: hashTree.getLeafData(0)};
1473
+ }
1474
+ }
1475
+
1476
+ if (abortController.signal.aborted) {
1477
+ LoggerProxy.logger.info(
1478
+ `HashTreeParser#performSync --> ${this.debugId} abandoning sync for "${dataSet.name}" before /sync - message received during sync`
1479
+ );
1480
+
1481
+ return;
1482
+ }
1483
+ // request sync for mismatched leaves
1484
+ let syncResponse: HashTreeMessage | null = null;
1485
+
1486
+ if (isInitialization) {
1487
+ syncResponse = await this.sendSyncRequestToLocus(
1488
+ dataSet,
1489
+ {isInitialization: true},
1490
+ syncTrackingId
1491
+ );
1492
+
1493
+ syncRequestSent = true;
1494
+ } else if (Object.keys(leavesData).length > 0) {
1495
+ syncResponse = await this.sendSyncRequestToLocus(
1496
+ dataSet,
1497
+ {mismatchedLeavesData: leavesData},
1498
+ syncTrackingId
1499
+ );
1500
+
1501
+ syncRequestSent = true;
1502
+ }
1503
+
1504
+ // sync API may return nothing (in that case data will arrive via messages)
1505
+ // or it may return a response in the same format as messages
1506
+ // We still need to restart the sync timer as a safety net in case the messages don't arrive.
1507
+ this.runSyncAlgorithm(dataSet);
1508
+
1509
+ if (syncResponse) {
1510
+ // clear the abort controller before processing the response so that
1511
+ // parseMessage() -> cancelPendingSyncsForDataSets() doesn't log a
1512
+ // misleading "aborting sync" message for this already-completed sync
1513
+ dataSet.syncAbortController = undefined;
1514
+
1515
+ // we only requested this dataset, so restrict the response to it before processing
1516
+ // (Locus may include shared datasets like "unjoined" alongside "main")
1517
+ const filteredResponse = this.filterMessageToDataSet(syncResponse, dataSet.name);
1518
+
1519
+ // the format of sync response is the same as messages, so we can reuse the same handler
1520
+ this.handleMessage(
1521
+ filteredResponse,
1522
+ `via sync API (${
1523
+ isInitialization ? 'init' : `${Object.keys(leavesData).length} mismatched leaves`
1524
+ })`
1525
+ );
1526
+ }
1527
+ } catch (error) {
1528
+ if (!this.handleSyncErrors(error)) {
1529
+ LoggerProxy.logger.warn(
1530
+ `HashTreeParser#performSync --> ${this.debugId} error during sync for data set "${dataSet.name}":`,
1531
+ error
1532
+ );
1533
+ }
1534
+ } finally {
1535
+ if (shouldCollectMetrics && !syncRequestSent) {
1536
+ // Drop only this sync's in-progress record (matched by its tracking id) rather than the
1537
+ // whole dataset, so a still-pending record from an earlier successful sync isn't wiped.
1538
+ // This mirrors the native client's onSyncError(syncId) which discards a single record.
1539
+ this.callbacks.syncLatencyTracker?.clearLocusSyncLatency(
1540
+ dataSet.name,
1541
+ this.syncLatencyMeetingId,
1542
+ syncTrackingId
1543
+ );
1544
+ }
1545
+ dataSet.syncAbortController = undefined;
1546
+ }
1547
+ }
1548
+
1549
+ /**
1550
+ * Cancels any pending or in-flight syncs for the specified data sets.
1551
+ * This removes matching entries from the sync queue and aborts any in-flight sync HTTP requests.
1552
+ *
1553
+ * @param {string[]} dataSetNames - The names of the data sets to cancel syncs for
1554
+ * @returns {void}
1555
+ */
1556
+ private cancelPendingSyncsForDataSets(dataSetNames: string[]): void {
1557
+ const previousLength = this.syncQueue.length;
1558
+
1559
+ this.syncQueue = this.syncQueue.filter((entry) => !dataSetNames.includes(entry.dataSetName));
1560
+
1561
+ if (previousLength !== this.syncQueue.length) {
1562
+ LoggerProxy.logger.info(
1563
+ `HashTreeParser#cancelPendingSyncsForDataSets --> ${this.debugId} removed ${
1564
+ previousLength - this.syncQueue.length
1565
+ } entries from sync queue for data sets: ${dataSetNames.join(', ')}`
1566
+ );
1567
+ }
1568
+
1569
+ this.markDataSetsForSyncAllBackoffSkip(dataSetNames);
1570
+ this.abortInFlightSyncs(dataSetNames);
1571
+ }
1572
+
1573
+ /**
1574
+ * If a syncAllDatasets backoff sleep is in progress, marks the given data sets to be skipped
1575
+ * after the sleep completes.
1576
+ *
1577
+ * @param {string[]} dataSetNames - The names of the data sets to mark
1578
+ * @returns {void}
1579
+ */
1580
+ private markDataSetsForSyncAllBackoffSkip(dataSetNames: string[]): void {
1581
+ if (this.syncAllBackoffType !== SyncAllBackoffType.NONE) {
1582
+ for (const name of dataSetNames) {
1583
+ this.dataSetsSyncedDuringBackoff.add(name);
1584
+ }
1585
+ }
1586
+ }
1587
+
1588
+ /**
1589
+ * Aborts any in-flight sync HTTP requests for the specified data sets.
1590
+ *
1591
+ * @param {string[]} dataSetNames - The names of the data sets whose syncs should be aborted
1592
+ * @returns {void}
1593
+ */
1594
+ private abortInFlightSyncs(dataSetNames: string[]): void {
1595
+ for (const name of dataSetNames) {
1596
+ if (this.dataSets[name]?.syncAbortController) {
1597
+ LoggerProxy.logger.info(
1598
+ `HashTreeParser#cancelPendingSyncsForDataSets --> ${this.debugId} aborting in-flight sync for data set "${name}"`
1599
+ );
1600
+ this.dataSets[name].syncAbortController.abort();
1601
+ }
1602
+ }
1603
+ }
1604
+
1605
+ /**
1606
+ * Enqueues a sync for the given data set. If the data set is already in the queue, the request is ignored.
1607
+ * This ensures that all syncs are executed sequentially and no more than 1 sync runs at a time.
1608
+ *
1609
+ * @param {string} dataSetName - The name of the data set to sync
1610
+ * @param {string} reason - The reason for the sync (used for logging)
1611
+ * @param {boolean} [isInitialization=false] - Whether this is an initialization sync (uses empty leaves data instead of hash comparison)
1612
+ * @returns {void}
1613
+ */
1614
+ private enqueueSyncForDataset(
1615
+ dataSetName: string,
1616
+ reason: string,
1617
+ isInitialization = false
1618
+ ): void {
1619
+ if (this.state === 'stopped') return;
1620
+
1621
+ const existingEntry = this.syncQueue.find((entry) => entry.dataSetName === dataSetName);
1622
+
1623
+ if (existingEntry) {
1624
+ if (isInitialization) {
1625
+ existingEntry.isInitialization = true;
1626
+ }
1627
+ LoggerProxy.logger.info(
1628
+ `HashTreeParser#enqueueSyncForDataset --> ${this.debugId} data set "${dataSetName}" already in sync queue, skipping`
1629
+ );
1630
+
1631
+ return;
1632
+ }
1633
+
1634
+ this.syncQueue.push({dataSetName, reason, isInitialization});
1635
+
1636
+ if (!this.isSyncInProgress) {
1637
+ this.syncQueueProcessingPromise = this.processSyncQueue();
1638
+ }
1639
+ }
1640
+
1641
+ /**
1642
+ * Processes the sync queue sequentially. Only one instance of this method runs at a time.
1643
+ *
1644
+ * @returns {Promise<void>}
1645
+ */
1646
+ private async processSyncQueue(): Promise<void> {
1647
+ if (this.isSyncInProgress) return;
1648
+
1649
+ this.isSyncInProgress = true;
1650
+ try {
1651
+ while (this.syncQueue.length > 0 && this.state !== 'stopped') {
1652
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1653
+ const {dataSetName, reason, isInitialization} = this.syncQueue.shift()!;
1654
+ const dataSet = this.dataSets[dataSetName];
1655
+
1656
+ if (!dataSet?.hashTree) {
1657
+ // eslint-disable-next-line no-continue
1658
+ continue;
1659
+ }
1660
+
1661
+ // eslint-disable-next-line no-await-in-loop
1662
+ await this.performSync(dataSet, reason, isInitialization);
1663
+ }
1664
+ } finally {
1665
+ this.isSyncInProgress = false;
1666
+ }
1667
+ }
1668
+
1669
+ /**
1670
+ * sets the backoff type for syncAllDatasets calls, which determines the scope of datasets that will be synced after the backoff delay.
1671
+ *
1672
+ * @param {boolean} onlyLLM - Whether the backoff is for a syncAllDatasets call that is syncing only LLM datasets
1673
+ * @returns {void}
1674
+ */
1675
+ private setSyncAllBackoffType(onlyLLM: boolean): void {
1676
+ this.syncAllBackoffType = onlyLLM ? SyncAllBackoffType.ONLY_LLM : SyncAllBackoffType.ALL;
1677
+ }
1678
+
1679
+ /**
1680
+ * Checks if a syncAll backoff is already in progress. If so, upgrades the scope from
1681
+ * onlyLLM to all datasets when the new call has a broader scope.
1682
+ *
1683
+ * @param {boolean} onlyLLM - Whether the current call is for LLM datasets only
1684
+ * @returns {boolean} true if a backoff is already pending (caller should return early)
1685
+ */
1686
+ private tryUpgradePendingBackoff(onlyLLM: boolean): boolean {
1687
+ if (this.syncAllBackoffType !== SyncAllBackoffType.NONE) {
1688
+ if (!onlyLLM && this.syncAllBackoffType === SyncAllBackoffType.ONLY_LLM) {
1689
+ this.setSyncAllBackoffType(false);
1690
+ LoggerProxy.logger.info(
1691
+ `HashTreeParser#syncAllDatasets --> ${this.debugId} upgraded pending syncAll from onlyLLM to all datasets`
1692
+ );
1693
+ }
1694
+
1695
+ return true;
1696
+ }
1697
+
1698
+ return false;
1699
+ }
1700
+
1701
+ /**
1702
+ * Syncs all data sets that have hash trees, one by one in sequence, using the priority order
1703
+ * provided by sortByInitPriority().
1704
+ *
1705
+ * If a call is already waiting in the backoff delay phase, a new call with a broader scope
1706
+ * (onlyLLM=false) will upgrade the pending scope, and the dataset list will be computed after
1707
+ * the backoff using the upgraded scope. After the backoff, the sync queue handles deduplication
1708
+ * so no guard is needed.
1709
+ *
1710
+ * @param {Object} [options={}] - Options for syncing
1711
+ * @param {boolean} [options.onlyLLM=false] - Whether to sync only LLM based data sets
1712
+ * @returns {Promise<void>}
1713
+ */
1714
+ public async syncAllDatasets(options: {onlyLLM?: boolean} = {}): Promise<void> {
1715
+ const {onlyLLM = false} = options;
1716
+ if (this.state === 'stopped') return;
1717
+
1718
+ // if we're already in the backoff delay phase, try to upgrade the scope instead of starting a new one
1719
+ if (this.tryUpgradePendingBackoff(onlyLLM)) {
1720
+ return;
1721
+ }
1722
+
1723
+ const dataSetsToSync = this.getSortedDataSetsWithHashTrees(onlyLLM);
1724
+
1725
+ if (dataSetsToSync.length === 0) return;
1726
+
1727
+ this.setSyncAllBackoffType(onlyLLM);
1728
+
1729
+ const delay = this.getWeightedBackoffTime(dataSetsToSync[0].backoff);
1730
+
1731
+ LoggerProxy.logger.info(
1732
+ `HashTreeParser#syncAllDatasets --> ${this.debugId} starting backoff delay of ${delay}ms (onlyLLM=${onlyLLM})`
1733
+ );
1734
+
1735
+ // delay the start of the syncs - this is a Locus requirement to avoid thundering herd issues
1736
+ await sleep(delay);
1737
+
1738
+ // read the (possibly upgraded) scope and clear the backoff flag
1739
+ const effectiveBackoffType = this.syncAllBackoffType;
1740
+ const skippedDataSets = this.dataSetsSyncedDuringBackoff;
1741
+
1742
+ this.syncAllBackoffType = SyncAllBackoffType.NONE;
1743
+ this.dataSetsSyncedDuringBackoff = new Set();
1744
+
1745
+ if ((this.state as string) === 'stopped') return;
1746
+
1747
+ // re-evaluate the dataset list after the sleep, since the scope may have been upgraded
1748
+ // and exclude datasets that received messages during the backoff sleep
1749
+ const effectiveDataSetsToSync = this.getSortedDataSetsWithHashTrees(
1750
+ effectiveBackoffType === SyncAllBackoffType.ONLY_LLM
1751
+ ).filter((ds) => !skippedDataSets.has(ds.name));
1752
+
1753
+ if (skippedDataSets.size > 0) {
1754
+ LoggerProxy.logger.info(
1755
+ `HashTreeParser#syncAllDatasets --> ${
1756
+ this.debugId
1757
+ } skipping datasets that received messages during backoff: ${[...skippedDataSets].join(
1758
+ ', '
1759
+ )}`
1760
+ );
1761
+ }
1762
+
1763
+ LoggerProxy.logger.info(
1764
+ `HashTreeParser#syncAllDatasets --> ${this.debugId} syncing ${
1765
+ effectiveBackoffType === SyncAllBackoffType.ONLY_LLM ? 'only LLM' : 'all'
1766
+ } datasets: ${effectiveDataSetsToSync.map((ds) => ds.name).join(', ')}`
1767
+ );
1768
+
1769
+ for (const ds of effectiveDataSetsToSync) {
1770
+ this.saveSyncBackoffLatency(ds.name, delay);
1771
+ this.enqueueSyncForDataset(ds.name, 'syncAllDatasets');
1772
+ }
1773
+
1774
+ await this.syncQueueProcessingPromise;
1775
+ }
1776
+
1777
+ /**
1778
+ * Returns the list of data sets that have hash trees, sorted by the priority order provided by sortByInitPriority().
1779
+ *
1780
+ * @param {boolean} onlyLLM - Whether to include only LLM based data sets
1781
+ * @returns {Array<{name: string, backoff: {maxMs: number, exponent: number}}>} The sorted list of data sets with their backoff configurations
1782
+ */
1783
+ private getSortedDataSetsWithHashTrees(onlyLLM: boolean) {
1784
+ let dataSets = Object.values(this.dataSets)
1785
+ .filter((dataSet) => dataSet?.hashTree)
1786
+ .map((dataSet) => ({name: dataSet.name, backoff: dataSet.backoff}));
1787
+
1788
+ if (onlyLLM) {
1789
+ dataSets = dataSets.filter((ds) => LLM_DATASET_NAMES.includes(ds.name));
1790
+ }
1791
+
1792
+ return sortByInitPriority(dataSets, DATA_SET_INIT_PRIORITY);
1793
+ }
1794
+
902
1795
  /**
903
1796
  * Runs the sync algorithm for the given data set.
904
1797
  *
@@ -917,33 +1810,25 @@ class HashTreeParser {
917
1810
  }
918
1811
 
919
1812
  if (!dataSet.hashTree) {
920
- LoggerProxy.logger.info(
921
- `HashTreeParser#runSyncAlgorithm --> ${this.debugId} Data set "${dataSet.name}" has no hash tree, skipping sync algorithm`
922
- );
1813
+ // no hash tree, so no need to do any syncing
1814
+ // we fall into this branch often, because Locus sends dataSets in messages that are not visible to us
923
1815
 
924
1816
  return;
925
1817
  }
926
1818
 
927
1819
  dataSet.hashTree.resize(receivedDataSet.leafCount);
928
1820
 
929
- // temporary log for the workshop // todo: remove
930
- const ourCurrentRootHash = dataSet.hashTree.getRootHash();
931
- LoggerProxy.logger.info(
932
- `HashTreeParser#runSyncAlgorithm --> ${this.debugId} dataSet="${dataSet.name}" version=${dataSet.version} hashes before starting timer: ours=${ourCurrentRootHash} Locus=${dataSet.root}`
933
- );
934
-
935
- const delay = dataSet.idleMs + this.getWeightedBackoffTime(dataSet.backoff);
1821
+ const randomBackoffTime = this.getWeightedBackoffTime(dataSet.backoff);
1822
+ const delay = dataSet.idleMs + randomBackoffTime;
936
1823
 
937
1824
  if (delay > 0) {
938
1825
  if (dataSet.timer) {
939
1826
  clearTimeout(dataSet.timer);
940
1827
  }
941
1828
 
942
- LoggerProxy.logger.info(
943
- `HashTreeParser#runSyncAlgorithm --> ${this.debugId} setting "${dataSet.name}" sync timer for ${delay}`
944
- );
1829
+ this.saveSyncBackoffLatency(dataSet.name, randomBackoffTime);
945
1830
 
946
- dataSet.timer = setTimeout(async () => {
1831
+ dataSet.timer = setTimeout(() => {
947
1832
  dataSet.timer = undefined;
948
1833
 
949
1834
  if (!dataSet.hashTree) {
@@ -957,65 +1842,65 @@ class HashTreeParser {
957
1842
  const rootHash = dataSet.hashTree.getRootHash();
958
1843
 
959
1844
  if (dataSet.root !== rootHash) {
960
- LoggerProxy.logger.info(
961
- `HashTreeParser#runSyncAlgorithm --> ${this.debugId} Root hash mismatch: received=${dataSet.root}, ours=${rootHash}, syncing data set "${dataSet.name}"`
1845
+ this.enqueueSyncForDataset(
1846
+ dataSet.name,
1847
+ `Root hash mismatch: received=${dataSet.root}, ours=${rootHash}`
962
1848
  );
1849
+ }
1850
+ }, delay);
1851
+ } else {
1852
+ LoggerProxy.logger.info(
1853
+ `HashTreeParser#runSyncAlgorithm --> ${this.debugId} No delay for "${dataSet.name}" data set, skipping sync timer reset/setup`
1854
+ );
1855
+ }
1856
+ }
963
1857
 
964
- const mismatchedLeavesData: Record<number, LeafDataItem[]> = {};
1858
+ /**
1859
+ * Resets the heartbeat watchdog timers for the specified data sets. Each data set has its own
1860
+ * watchdog timer that monitors whether heartbeats are being received within the expected interval.
1861
+ * If a heartbeat is not received for a specific data set within heartbeatIntervalMs plus
1862
+ * a backoff-calculated time, the sync algorithm is initiated for that data set
1863
+ *
1864
+ * @param {Array<DataSet>} receivedDataSets - The data sets from the received message for which watchdog timers should be reset
1865
+ * @returns {void}
1866
+ */
1867
+ private resetHeartbeatWatchdogs(receivedDataSets: Array<DataSet>): void {
1868
+ for (const receivedDataSet of receivedDataSets) {
1869
+ const dataSet = this.dataSets[receivedDataSet.name];
965
1870
 
966
- if (dataSet.leafCount !== 1) {
967
- let receivedHashes;
1871
+ if (dataSet.heartbeatWatchdogTimer) {
1872
+ clearTimeout(dataSet.heartbeatWatchdogTimer);
1873
+ dataSet.heartbeatWatchdogTimer = undefined;
1874
+ }
968
1875
 
969
- try {
970
- // request hashes from sender
971
- const {hashes, dataSet: latestDataSetInfo} = await this.getHashesFromLocus(
972
- dataSet.name
973
- );
1876
+ // dataset-level heartbeatIntervalMs takes priority; fall back to top-level common value
1877
+ const heartbeatIntervalMs = dataSet?.heartbeatIntervalMs ?? this.topLevelHeartbeatIntervalMs;
974
1878
 
975
- receivedHashes = hashes;
1879
+ if (!dataSet?.hashTree || !heartbeatIntervalMs) {
1880
+ // eslint-disable-next-line no-continue
1881
+ continue;
1882
+ }
976
1883
 
977
- dataSet.hashTree.resize(latestDataSetInfo.leafCount);
978
- } catch (error) {
979
- if (error.statusCode === 409) {
980
- // this is a leaf count mismatch, we should do nothing, just wait for another heartbeat message from Locus
981
- LoggerProxy.logger.info(
982
- `HashTreeParser#getHashesFromLocus --> ${this.debugId} Got 409 when fetching hashes for data set "${dataSet.name}": ${error.message}`
983
- );
1884
+ const backoffTime = this.getWeightedBackoffTime(dataSet.backoff);
1885
+ const delay = heartbeatIntervalMs + backoffTime;
984
1886
 
985
- return;
986
- }
987
- throw error;
988
- }
1887
+ dataSet.heartbeatWatchdogTimer = setTimeout(() => {
1888
+ dataSet.heartbeatWatchdogTimer = undefined;
989
1889
 
990
- // identify mismatched leaves
991
- const mismatchedLeaveIndexes = dataSet.hashTree.diffHashes(receivedHashes);
1890
+ LoggerProxy.logger.warn(
1891
+ `HashTreeParser#resetHeartbeatWatchdogs --> ${this.debugId} Heartbeat watchdog fired for data set "${dataSet.name}" - no heartbeat received within expected interval, initiating sync`
1892
+ );
992
1893
 
993
- mismatchedLeaveIndexes.forEach((index) => {
994
- mismatchedLeavesData[index] = dataSet.hashTree.getLeafData(index);
995
- });
996
- } else {
997
- mismatchedLeavesData[0] = dataSet.hashTree.getLeafData(0);
998
- }
999
- // request sync for mismatched leaves
1000
- if (Object.keys(mismatchedLeavesData).length > 0) {
1001
- const syncResponse = await this.sendSyncRequestToLocus(dataSet, mismatchedLeavesData);
1002
-
1003
- // sync API may return nothing (in that case data will arrive via messages)
1004
- // or it may return a response in the same format as messages
1005
- if (syncResponse) {
1006
- this.handleMessage(syncResponse, 'via sync API');
1007
- }
1008
- }
1009
- } else {
1010
- LoggerProxy.logger.info(
1011
- `HashTreeParser#runSyncAlgorithm --> ${this.debugId} "${dataSet.name}" root hash matching: ${rootHash}, version=${dataSet.version}`
1012
- );
1013
- }
1894
+ Metrics.sendBehavioralMetric(BEHAVIORAL_METRICS.HASH_TREE_HEARTBEAT_WATCHDOG_EXPIRED, {
1895
+ debugId: this.debugId,
1896
+ dataSetName: dataSet.name,
1897
+ });
1898
+
1899
+ this.saveSyncBackoffLatency(dataSet.name, backoffTime);
1900
+
1901
+ this.enqueueSyncForDataset(dataSet.name, `heartbeat watchdog expired`);
1902
+ this.resetHeartbeatWatchdogs([dataSet]);
1014
1903
  }, delay);
1015
- } else {
1016
- LoggerProxy.logger.info(
1017
- `HashTreeParser#runSyncAlgorithm --> ${this.debugId} No delay for "${dataSet.name}" data set, skipping sync timer reset/setup`
1018
- );
1019
1904
  }
1020
1905
  }
1021
1906
 
@@ -1029,15 +1914,153 @@ class HashTreeParser {
1029
1914
  clearTimeout(dataSet.timer);
1030
1915
  dataSet.timer = undefined;
1031
1916
  }
1917
+ if (dataSet.heartbeatWatchdogTimer) {
1918
+ clearTimeout(dataSet.heartbeatWatchdogTimer);
1919
+ dataSet.heartbeatWatchdogTimer = undefined;
1920
+ }
1921
+ });
1922
+ }
1923
+
1924
+ /**
1925
+ * Stops the HashTreeParser, preventing it from processing any further messages and clearing all timers.
1926
+ * It also clears all the hash trees, so if the parser is resumed later, it will need to do a sync
1927
+ * to be up-to-date.
1928
+ * @returns {void}
1929
+ */
1930
+ public stop() {
1931
+ LoggerProxy.logger.info(
1932
+ `HashTreeParser#stop --> ${this.debugId} Stopping HashTreeParser, clearing timers and hash trees`
1933
+ );
1934
+ this.stopAllTimers();
1935
+ this.syncQueue = [];
1936
+ this.topLevelHeartbeatIntervalMs = undefined;
1937
+ this.syncAllBackoffType = SyncAllBackoffType.NONE;
1938
+ this.dataSetsSyncedDuringBackoff = new Set();
1939
+ Object.values(this.dataSets).forEach((dataSet) => {
1940
+ dataSet.syncAbortController?.abort();
1941
+ dataSet.syncAbortController = undefined;
1942
+ dataSet.hashTree = undefined;
1032
1943
  });
1944
+ this.visibleDataSets = [];
1945
+ this.state = 'stopped';
1946
+ }
1947
+
1948
+ /**
1949
+ * Cleans up the HashTreeParser, stopping all timers and clearing all internal state.
1950
+ * After calling this, the parser should not be used anymore.
1951
+ * @returns {void}
1952
+ */
1953
+ public cleanUp() {
1954
+ this.stop();
1955
+ this.dataSets = {};
1956
+ }
1957
+
1958
+ /**
1959
+ * Resumes the HashTreeParser that was previously stopped, using a hash tree message.
1960
+ * @param {HashTreeMessage} message - The message to resume with, it must contain metadata with visible data sets info
1961
+ * @returns {void}
1962
+ */
1963
+ public resumeFromMessage(message: HashTreeMessage) {
1964
+ const metadataObject = message.locusStateElements?.find((el) => isMetadata(el));
1965
+
1966
+ if (!metadataObject?.data?.visibleDataSets) {
1967
+ LoggerProxy.logger.warn(
1968
+ `HashTreeParser#resumeFromMessage --> ${this.debugId} Cannot resume HashTreeParser because the message is missing metadata with visible data sets info`
1969
+ );
1970
+
1971
+ return;
1972
+ }
1973
+ this.setVisibleDataSets(
1974
+ metadataObject.data.visibleDataSets as VisibleDataSetInfo[],
1975
+ message.dataSets
1976
+ );
1977
+
1978
+ this.dataSets = {};
1979
+
1980
+ for (const dataSet of message.dataSets) {
1981
+ const {name, leafCount} = dataSet;
1982
+
1983
+ this.dataSets[name] = {
1984
+ ...dataSet,
1985
+ hashTree: this.isVisibleDataSet(name) ? new HashTree([], leafCount) : undefined,
1986
+ };
1987
+ }
1988
+ LoggerProxy.logger.info(
1989
+ `HashTreeParser#resumeFromMessage --> ${
1990
+ this.debugId
1991
+ } Resuming HashTreeParser with data sets: ${Object.keys(this.dataSets).join(
1992
+ ', '
1993
+ )}, visible data sets: ${this.visibleDataSets.map((ds) => ds.name).join(', ')}`
1994
+ );
1995
+ this.state = 'active';
1996
+
1997
+ this.handleMessage(message, 'on resume');
1998
+ }
1999
+
2000
+ /**
2001
+ * Resumes the HashTreeParser that was previously stopped, using a Locus API response.
2002
+ * Unlike resumeFromMessage(), this does not require metadata/dataSets in the input,
2003
+ * as it fetches all necessary information from Locus via initializeFromGetLociResponse.
2004
+ * @param {LocusDTO} locus - locus object from an API response
2005
+ * @returns {Promise}
2006
+ */
2007
+ public async resumeFromApiResponse(locus: LocusDTO) {
2008
+ this.state = 'active';
2009
+ this.dataSets = {};
2010
+
2011
+ LoggerProxy.logger.info(
2012
+ `HashTreeParser#resumeFromApiResponse --> ${this.debugId} Resuming HashTreeParser from API response`
2013
+ );
2014
+
2015
+ await this.initializeFromGetLociResponse(locus);
2016
+ }
2017
+
2018
+ private checkForSentinelHttpResponse(error: any, dataSetName?: string) {
2019
+ // 404 for any dataset means the locus is no longer available at this URL - could be replaced or ended
2020
+ // if a dataset is just not visible, we would get a 400
2021
+ if (error.statusCode === 404) {
2022
+ LoggerProxy.logger.info(
2023
+ `HashTreeParser#checkForSentinelHttpResponse --> ${this.debugId} Received 404 for data set "${dataSetName}", locus not found`
2024
+ );
2025
+ this.stopAllTimers();
2026
+
2027
+ throw new LocusNotFoundError();
2028
+ }
2029
+
2030
+ const isValidDataSetForSentinel =
2031
+ dataSetName === undefined ||
2032
+ PossibleSentinelMessageDataSetNames.includes(dataSetName.toLowerCase());
2033
+
2034
+ if (
2035
+ error.statusCode === 409 &&
2036
+ error.body?.errorCode === LocusErrorCodes.LOCUS_INACTIVE &&
2037
+ isValidDataSetForSentinel
2038
+ ) {
2039
+ LoggerProxy.logger.info(
2040
+ `HashTreeParser#checkForSentinelHttpResponse --> ${this.debugId} Received ${error.statusCode}/${error.body?.errorCode} for data set "${dataSetName}", indicating that the meeting has ended`
2041
+ );
2042
+ this.stopAllTimers();
2043
+
2044
+ throw new MeetingEndedError();
2045
+ }
1033
2046
  }
1034
2047
 
1035
2048
  /**
1036
2049
  * Gets the current hashes from the locus for a specific data set.
1037
2050
  * @param {string} dataSetName
1038
- * @returns {string[]}
2051
+ * @param {string} currentRootHash
2052
+ * @param {Object} [trackingIds] tracking ids for the /hashtree request
2053
+ * @param {string} [trackingIds.requestTrackingId] tracking id forced onto the /hashtree HTTP request header (kept distinct from the /sync request's tracking id)
2054
+ * @param {string} [trackingIds.metricTrackingId] tracking id (the /sync request's) under which the hashtree latency milestones are recorded, so they belong to the same sync latency record
2055
+ * @returns {Object|null} An object containing the hashes and leaf count, or null if the hashes match and no sync is needed
1039
2056
  */
1040
- private getHashesFromLocus(dataSetName: string) {
2057
+ private getHashesFromLocus(
2058
+ dataSetName: string,
2059
+ currentRootHash: string,
2060
+ trackingIds?: {requestTrackingId?: string; metricTrackingId?: string}
2061
+ ) {
2062
+ const {requestTrackingId, metricTrackingId} = trackingIds ?? {};
2063
+
1041
2064
  LoggerProxy.logger.info(
1042
2065
  `HashTreeParser#getHashesFromLocus --> ${this.debugId} Requesting hashes for data set "${dataSetName}"`
1043
2066
  );
@@ -1046,11 +2069,48 @@ class HashTreeParser {
1046
2069
 
1047
2070
  const url = `${dataSet.url}/hashtree`;
1048
2071
 
2072
+ if (this.shouldCollectSyncMetrics(dataSetName)) {
2073
+ this.callbacks.syncLatencyTracker?.saveTimestamp({
2074
+ key: 'internal.client.locus.hashtree.request',
2075
+ options: {
2076
+ meetingId: this.syncLatencyMeetingId,
2077
+ dataSetName,
2078
+ trackingId: metricTrackingId,
2079
+ },
2080
+ });
2081
+ }
2082
+
1049
2083
  return this.webexRequest({
1050
2084
  method: HTTP_VERBS.GET,
1051
2085
  uri: url,
2086
+ qs: {
2087
+ rootHash: currentRootHash,
2088
+ },
2089
+ // Force a dedicated tracking id onto the /hashtree request so it does not share the /sync
2090
+ // request's tracking id; the tracking id interceptor leaves an already-set header untouched.
2091
+ ...(requestTrackingId ? {headers: {trackingid: requestTrackingId}} : {}),
1052
2092
  })
1053
2093
  .then((response) => {
2094
+ if (this.shouldCollectSyncMetrics(dataSetName)) {
2095
+ this.callbacks.syncLatencyTracker?.saveTimestamp({
2096
+ key: 'internal.client.locus.hashtree.response',
2097
+ options: {
2098
+ meetingId: this.syncLatencyMeetingId,
2099
+ dataSetName,
2100
+ trackingId: metricTrackingId,
2101
+ },
2102
+ });
2103
+ }
2104
+
2105
+ if (!response.body || isEmpty(response.body)) {
2106
+ // 204 with empty body means our hashes match Locus, no sync needed
2107
+ LoggerProxy.logger.info(
2108
+ `HashTreeParser#getHashesFromLocus --> ${this.debugId} Got ${response.statusCode} with empty body for data set "${dataSetName}", hashes match - no sync needed`
2109
+ );
2110
+
2111
+ return null;
2112
+ }
2113
+
1054
2114
  const hashes = response.body?.hashes as string[] | undefined;
1055
2115
  const dataSetFromResponse = response.body?.dataSet;
1056
2116
 
@@ -1078,6 +2138,15 @@ class HashTreeParser {
1078
2138
  `HashTreeParser#getHashesFromLocus --> ${this.debugId} Error ${error.statusCode} fetching hashes for data set "${dataSetName}":`,
1079
2139
  error
1080
2140
  );
2141
+ this.checkForSentinelHttpResponse(error, dataSet.name);
2142
+ Metrics.sendBehavioralMetric(BEHAVIORAL_METRICS.HASH_TREE_SYNC_FAILURE, {
2143
+ debugId: this.debugId,
2144
+ dataSetName,
2145
+ request: 'GET /hashtree',
2146
+ statusCode: error.statusCode,
2147
+ reason: error.message,
2148
+ });
2149
+
1081
2150
  throw error;
1082
2151
  });
1083
2152
  }
@@ -1086,39 +2155,82 @@ class HashTreeParser {
1086
2155
  * Sends a sync request to Locus for the specified data set.
1087
2156
  *
1088
2157
  * @param {InternalDataSet} dataSet The data set to sync.
1089
- * @param {Record<number, LeafDataItem[]>} mismatchedLeavesData The mismatched leaves data to include in the sync request.
1090
- * @returns {Promise<HashTreeMessage|null>}
2158
+ * @param {Object} options Either `{ isInitialization: true }` for init syncs (uses leafCount=1 with empty leaf data) or `{ mismatchedLeavesData }` for normal syncs.
2159
+ * @param {string} [trackingId] tracking id
2160
+ * @returns {Promise<HashTreeMessage | null>}
1091
2161
  */
1092
2162
  private sendSyncRequestToLocus(
1093
2163
  dataSet: InternalDataSet,
1094
- mismatchedLeavesData: Record<number, LeafDataItem[]>
2164
+ options: {isInitialization: true} | {mismatchedLeavesData: Record<number, LeafDataItem[]>},
2165
+ trackingId?: string
1095
2166
  ): Promise<HashTreeMessage | null> {
1096
2167
  LoggerProxy.logger.info(
1097
2168
  `HashTreeParser#sendSyncRequestToLocus --> ${this.debugId} Sending sync request for data set "${dataSet.name}"`
1098
2169
  );
1099
2170
 
2171
+ const isInitialization = 'isInitialization' in options;
2172
+
1100
2173
  const url = `${dataSet.url}/sync`;
1101
- const body = {
1102
- leafCount: dataSet.leafCount,
2174
+ const body: {
2175
+ leafCount: number;
2176
+ leafDataEntries: {leafIndex: number; elementIds: LeafDataItem[]}[];
2177
+ } = {
2178
+ leafCount: isInitialization ? 1 : dataSet.leafCount,
1103
2179
  leafDataEntries: [],
1104
2180
  };
1105
2181
 
1106
- Object.keys(mismatchedLeavesData).forEach((index) => {
1107
- body.leafDataEntries.push({
1108
- leafIndex: parseInt(index, 10),
1109
- elementIds: mismatchedLeavesData[index],
2182
+ if (isInitialization) {
2183
+ // initialization sync: Locus requires leafCount=1 with a single empty leaf
2184
+ body.leafDataEntries.push({leafIndex: 0, elementIds: []});
2185
+ } else {
2186
+ const {mismatchedLeavesData} = options;
2187
+
2188
+ Object.keys(mismatchedLeavesData).forEach((index) => {
2189
+ const leafIndex = parseInt(index, 10);
2190
+
2191
+ body.leafDataEntries.push({
2192
+ leafIndex,
2193
+ elementIds: mismatchedLeavesData[leafIndex],
2194
+ });
1110
2195
  });
1111
- });
2196
+ }
2197
+
2198
+ const ourCurrentRootHash = dataSet.hashTree ? dataSet.hashTree.getRootHash() : EMPTY_HASH;
2199
+ const shouldCollectMetrics = this.shouldCollectSyncMetrics(dataSet.name, isInitialization);
2200
+
2201
+ if (shouldCollectMetrics) {
2202
+ this.callbacks.syncLatencyTracker?.saveTimestamp({
2203
+ key: 'internal.client.locus.sync.request',
2204
+ options: {
2205
+ meetingId: this.syncLatencyMeetingId,
2206
+ dataSetName: dataSet.name,
2207
+ trackingId,
2208
+ },
2209
+ });
2210
+ }
1112
2211
 
1113
2212
  return this.webexRequest({
1114
2213
  method: HTTP_VERBS.POST,
1115
2214
  uri: url,
2215
+ qs: {
2216
+ rootHash: ourCurrentRootHash,
2217
+ },
2218
+ // Force the pre-generated tracking id onto the /sync request so Locus echoes it back on the
2219
+ // resulting LLM message; the tracking id interceptor leaves an already-set header untouched.
2220
+ ...(trackingId ? {headers: {trackingid: trackingId}} : {}),
1116
2221
  body,
1117
2222
  })
1118
2223
  .then((resp) => {
1119
- LoggerProxy.logger.info(
1120
- `HashTreeParser#sendSyncRequestToLocus --> ${this.debugId} Sync request succeeded for "${dataSet.name}"`
1121
- );
2224
+ if (shouldCollectMetrics) {
2225
+ this.callbacks.syncLatencyTracker?.saveTimestamp({
2226
+ key: 'internal.client.locus.sync.response',
2227
+ options: {
2228
+ meetingId: this.syncLatencyMeetingId,
2229
+ dataSetName: dataSet.name,
2230
+ trackingId,
2231
+ },
2232
+ });
2233
+ }
1122
2234
 
1123
2235
  if (!resp.body || isEmpty(resp.body)) {
1124
2236
  LoggerProxy.logger.info(
@@ -1135,6 +2247,15 @@ class HashTreeParser {
1135
2247
  `HashTreeParser#sendSyncRequestToLocus --> ${this.debugId} Error ${error.statusCode} sending sync request for data set "${dataSet.name}":`,
1136
2248
  error
1137
2249
  );
2250
+ this.checkForSentinelHttpResponse(error, dataSet.name);
2251
+ Metrics.sendBehavioralMetric(BEHAVIORAL_METRICS.HASH_TREE_SYNC_FAILURE, {
2252
+ debugId: this.debugId,
2253
+ dataSetName: dataSet.name,
2254
+ request: 'POST /sync',
2255
+ statusCode: error.statusCode,
2256
+ reason: error.message,
2257
+ });
2258
+
1138
2259
  throw error;
1139
2260
  });
1140
2261
  }