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