@fluidframework/container-runtime 2.0.0-dev.5.2.0.169897 → 2.0.0-dev.6.4.0.191258

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 (561) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +4 -3
  3. package/dist/batchTracker.d.ts +3 -2
  4. package/dist/batchTracker.d.ts.map +1 -1
  5. package/dist/batchTracker.js +6 -5
  6. package/dist/batchTracker.js.map +1 -1
  7. package/dist/blobManager.d.ts +15 -18
  8. package/dist/blobManager.d.ts.map +1 -1
  9. package/dist/blobManager.js +212 -171
  10. package/dist/blobManager.js.map +1 -1
  11. package/dist/connectionTelemetry.d.ts.map +1 -1
  12. package/dist/connectionTelemetry.js +33 -17
  13. package/dist/connectionTelemetry.js.map +1 -1
  14. package/dist/containerRuntime.d.ts +172 -35
  15. package/dist/containerRuntime.d.ts.map +1 -1
  16. package/dist/containerRuntime.js +722 -425
  17. package/dist/containerRuntime.js.map +1 -1
  18. package/dist/dataStore.d.ts.map +1 -1
  19. package/dist/dataStore.js +15 -7
  20. package/dist/dataStore.js.map +1 -1
  21. package/dist/dataStoreContext.d.ts +4 -4
  22. package/dist/dataStoreContext.d.ts.map +1 -1
  23. package/dist/dataStoreContext.js +87 -90
  24. package/dist/dataStoreContext.js.map +1 -1
  25. package/dist/dataStoreContexts.d.ts +1 -1
  26. package/dist/dataStoreContexts.d.ts.map +1 -1
  27. package/dist/dataStoreContexts.js +10 -10
  28. package/dist/dataStoreContexts.js.map +1 -1
  29. package/dist/dataStoreRegistry.js +2 -2
  30. package/dist/dataStoreRegistry.js.map +1 -1
  31. package/dist/dataStores.d.ts +23 -7
  32. package/dist/dataStores.d.ts.map +1 -1
  33. package/dist/dataStores.js +125 -82
  34. package/dist/dataStores.js.map +1 -1
  35. package/dist/deltaManagerProxyBase.d.ts +35 -0
  36. package/dist/deltaManagerProxyBase.d.ts.map +1 -0
  37. package/dist/deltaManagerProxyBase.js +77 -0
  38. package/dist/deltaManagerProxyBase.js.map +1 -0
  39. package/dist/deltaManagerSummarizerProxy.d.ts +1 -1
  40. package/dist/deltaManagerSummarizerProxy.d.ts.map +1 -1
  41. package/dist/deltaManagerSummarizerProxy.js +4 -2
  42. package/dist/deltaManagerSummarizerProxy.js.map +1 -1
  43. package/dist/deltaScheduler.d.ts.map +1 -1
  44. package/dist/deltaScheduler.js +10 -10
  45. package/dist/deltaScheduler.js.map +1 -1
  46. package/dist/error.d.ts +14 -0
  47. package/dist/error.d.ts.map +1 -0
  48. package/dist/error.js +21 -0
  49. package/dist/error.js.map +1 -0
  50. package/dist/gc/garbageCollection.d.ts +10 -9
  51. package/dist/gc/garbageCollection.d.ts.map +1 -1
  52. package/dist/gc/garbageCollection.js +65 -56
  53. package/dist/gc/garbageCollection.js.map +1 -1
  54. package/dist/gc/gcConfigs.d.ts.map +1 -1
  55. package/dist/gc/gcConfigs.js +18 -14
  56. package/dist/gc/gcConfigs.js.map +1 -1
  57. package/dist/gc/gcDefinitions.d.ts +17 -5
  58. package/dist/gc/gcDefinitions.d.ts.map +1 -1
  59. package/dist/gc/gcDefinitions.js +14 -15
  60. package/dist/gc/gcDefinitions.js.map +1 -1
  61. package/dist/gc/gcHelpers.d.ts +0 -8
  62. package/dist/gc/gcHelpers.d.ts.map +1 -1
  63. package/dist/gc/gcHelpers.js +11 -24
  64. package/dist/gc/gcHelpers.js.map +1 -1
  65. package/dist/gc/gcSummaryStateTracker.d.ts +4 -7
  66. package/dist/gc/gcSummaryStateTracker.d.ts.map +1 -1
  67. package/dist/gc/gcSummaryStateTracker.js +19 -58
  68. package/dist/gc/gcSummaryStateTracker.js.map +1 -1
  69. package/dist/gc/gcTelemetry.d.ts +1 -1
  70. package/dist/gc/gcTelemetry.d.ts.map +1 -1
  71. package/dist/gc/gcTelemetry.js +45 -35
  72. package/dist/gc/gcTelemetry.js.map +1 -1
  73. package/dist/gc/gcUnreferencedStateTracker.js +4 -4
  74. package/dist/gc/gcUnreferencedStateTracker.js.map +1 -1
  75. package/dist/gc/index.d.ts +2 -2
  76. package/dist/gc/index.d.ts.map +1 -1
  77. package/dist/gc/index.js +3 -5
  78. package/dist/gc/index.js.map +1 -1
  79. package/dist/id-compressor/appendOnlySortedMap.d.ts +8 -30
  80. package/dist/id-compressor/appendOnlySortedMap.d.ts.map +1 -1
  81. package/dist/id-compressor/appendOnlySortedMap.js +26 -68
  82. package/dist/id-compressor/appendOnlySortedMap.js.map +1 -1
  83. package/dist/id-compressor/finalSpace.d.ts +29 -0
  84. package/dist/id-compressor/finalSpace.d.ts.map +1 -0
  85. package/dist/id-compressor/finalSpace.js +62 -0
  86. package/dist/id-compressor/finalSpace.js.map +1 -0
  87. package/dist/id-compressor/idCompressor.d.ts +25 -250
  88. package/dist/id-compressor/idCompressor.d.ts.map +1 -1
  89. package/dist/id-compressor/idCompressor.js +390 -1153
  90. package/dist/id-compressor/idCompressor.js.map +1 -1
  91. package/dist/id-compressor/identifiers.d.ts +32 -0
  92. package/dist/id-compressor/identifiers.d.ts.map +1 -0
  93. package/dist/id-compressor/identifiers.js +15 -0
  94. package/dist/id-compressor/identifiers.js.map +1 -0
  95. package/dist/id-compressor/index.d.ts +5 -6
  96. package/dist/id-compressor/index.d.ts.map +1 -1
  97. package/dist/id-compressor/index.js +20 -26
  98. package/dist/id-compressor/index.js.map +1 -1
  99. package/dist/id-compressor/persistanceUtilities.d.ts +22 -0
  100. package/dist/id-compressor/persistanceUtilities.d.ts.map +1 -0
  101. package/dist/id-compressor/persistanceUtilities.js +43 -0
  102. package/dist/id-compressor/persistanceUtilities.js.map +1 -0
  103. package/dist/id-compressor/sessionSpaceNormalizer.d.ts +46 -0
  104. package/dist/id-compressor/sessionSpaceNormalizer.d.ts.map +1 -0
  105. package/dist/id-compressor/sessionSpaceNormalizer.js +80 -0
  106. package/dist/id-compressor/sessionSpaceNormalizer.js.map +1 -0
  107. package/dist/id-compressor/sessions.d.ts +115 -0
  108. package/dist/id-compressor/sessions.d.ts.map +1 -0
  109. package/dist/id-compressor/sessions.js +305 -0
  110. package/dist/id-compressor/sessions.js.map +1 -0
  111. package/dist/id-compressor/utilities.d.ts +49 -0
  112. package/dist/id-compressor/utilities.d.ts.map +1 -0
  113. package/dist/id-compressor/utilities.js +166 -0
  114. package/dist/id-compressor/utilities.js.map +1 -0
  115. package/dist/index.d.ts +3 -3
  116. package/dist/index.d.ts.map +1 -1
  117. package/dist/index.js +6 -4
  118. package/dist/index.js.map +1 -1
  119. package/dist/metadata.d.ts +18 -0
  120. package/dist/metadata.d.ts.map +1 -0
  121. package/dist/metadata.js +7 -0
  122. package/dist/metadata.js.map +1 -0
  123. package/dist/opLifecycle/batchManager.d.ts +2 -1
  124. package/dist/opLifecycle/batchManager.d.ts.map +1 -1
  125. package/dist/opLifecycle/batchManager.js +15 -7
  126. package/dist/opLifecycle/batchManager.js.map +1 -1
  127. package/dist/opLifecycle/definitions.d.ts +11 -0
  128. package/dist/opLifecycle/definitions.d.ts.map +1 -1
  129. package/dist/opLifecycle/definitions.js.map +1 -1
  130. package/dist/opLifecycle/index.d.ts +1 -1
  131. package/dist/opLifecycle/index.d.ts.map +1 -1
  132. package/dist/opLifecycle/index.js +2 -1
  133. package/dist/opLifecycle/index.js.map +1 -1
  134. package/dist/opLifecycle/opCompressor.d.ts +2 -2
  135. package/dist/opLifecycle/opCompressor.d.ts.map +1 -1
  136. package/dist/opLifecycle/opCompressor.js +12 -7
  137. package/dist/opLifecycle/opCompressor.js.map +1 -1
  138. package/dist/opLifecycle/opDecompressor.d.ts +2 -2
  139. package/dist/opLifecycle/opDecompressor.d.ts.map +1 -1
  140. package/dist/opLifecycle/opDecompressor.js +30 -21
  141. package/dist/opLifecycle/opDecompressor.js.map +1 -1
  142. package/dist/opLifecycle/opGroupingManager.d.ts +1 -1
  143. package/dist/opLifecycle/opGroupingManager.d.ts.map +1 -1
  144. package/dist/opLifecycle/opGroupingManager.js +19 -13
  145. package/dist/opLifecycle/opGroupingManager.js.map +1 -1
  146. package/dist/opLifecycle/opSplitter.d.ts +2 -2
  147. package/dist/opLifecycle/opSplitter.d.ts.map +1 -1
  148. package/dist/opLifecycle/opSplitter.js +24 -19
  149. package/dist/opLifecycle/opSplitter.js.map +1 -1
  150. package/dist/opLifecycle/outbox.d.ts +39 -6
  151. package/dist/opLifecycle/outbox.d.ts.map +1 -1
  152. package/dist/opLifecycle/outbox.js +138 -61
  153. package/dist/opLifecycle/outbox.js.map +1 -1
  154. package/dist/opLifecycle/remoteMessageProcessor.d.ts +6 -1
  155. package/dist/opLifecycle/remoteMessageProcessor.d.ts.map +1 -1
  156. package/dist/opLifecycle/remoteMessageProcessor.js +22 -8
  157. package/dist/opLifecycle/remoteMessageProcessor.js.map +1 -1
  158. package/dist/opProperties.js +1 -2
  159. package/dist/opProperties.js.map +1 -1
  160. package/dist/packageVersion.d.ts +1 -1
  161. package/dist/packageVersion.js +1 -1
  162. package/dist/packageVersion.js.map +1 -1
  163. package/dist/pendingStateManager.d.ts +25 -10
  164. package/dist/pendingStateManager.d.ts.map +1 -1
  165. package/dist/pendingStateManager.js +101 -64
  166. package/dist/pendingStateManager.js.map +1 -1
  167. package/dist/scheduleManager.d.ts.map +1 -1
  168. package/dist/scheduleManager.js +43 -33
  169. package/dist/scheduleManager.js.map +1 -1
  170. package/dist/summary/index.d.ts +4 -4
  171. package/dist/summary/index.d.ts.map +1 -1
  172. package/dist/summary/index.js +3 -1
  173. package/dist/summary/index.js.map +1 -1
  174. package/dist/summary/orderedClientElection.d.ts +3 -3
  175. package/dist/summary/orderedClientElection.d.ts.map +1 -1
  176. package/dist/summary/orderedClientElection.js +26 -27
  177. package/dist/summary/orderedClientElection.js.map +1 -1
  178. package/dist/summary/runWhileConnectedCoordinator.js +3 -3
  179. package/dist/summary/runWhileConnectedCoordinator.js.map +1 -1
  180. package/dist/summary/runningSummarizer.d.ts +31 -10
  181. package/dist/summary/runningSummarizer.d.ts.map +1 -1
  182. package/dist/summary/runningSummarizer.js +271 -139
  183. package/dist/summary/runningSummarizer.js.map +1 -1
  184. package/dist/summary/summarizer.d.ts +8 -7
  185. package/dist/summary/summarizer.d.ts.map +1 -1
  186. package/dist/summary/summarizer.js +79 -78
  187. package/dist/summary/summarizer.js.map +1 -1
  188. package/dist/summary/summarizerClientElection.d.ts +2 -2
  189. package/dist/summary/summarizerClientElection.d.ts.map +1 -1
  190. package/dist/summary/summarizerClientElection.js +7 -11
  191. package/dist/summary/summarizerClientElection.js.map +1 -1
  192. package/dist/summary/summarizerHeuristics.js +10 -14
  193. package/dist/summary/summarizerHeuristics.js.map +1 -1
  194. package/dist/summary/summarizerNode/index.d.ts +1 -1
  195. package/dist/summary/summarizerNode/index.d.ts.map +1 -1
  196. package/dist/summary/summarizerNode/index.js.map +1 -1
  197. package/dist/summary/summarizerNode/summarizerNode.d.ts +40 -23
  198. package/dist/summary/summarizerNode/summarizerNode.d.ts.map +1 -1
  199. package/dist/summary/summarizerNode/summarizerNode.js +144 -149
  200. package/dist/summary/summarizerNode/summarizerNode.js.map +1 -1
  201. package/dist/summary/summarizerNode/summarizerNodeUtils.d.ts +25 -29
  202. package/dist/summary/summarizerNode/summarizerNodeUtils.d.ts.map +1 -1
  203. package/dist/summary/summarizerNode/summarizerNodeUtils.js +2 -4
  204. package/dist/summary/summarizerNode/summarizerNodeUtils.js.map +1 -1
  205. package/dist/summary/summarizerNode/summarizerNodeWithGc.d.ts +21 -16
  206. package/dist/summary/summarizerNode/summarizerNodeWithGc.d.ts.map +1 -1
  207. package/dist/summary/summarizerNode/summarizerNodeWithGc.js +74 -123
  208. package/dist/summary/summarizerNode/summarizerNodeWithGc.js.map +1 -1
  209. package/dist/summary/summarizerTypes.d.ts +44 -24
  210. package/dist/summary/summarizerTypes.d.ts.map +1 -1
  211. package/dist/summary/summarizerTypes.js.map +1 -1
  212. package/dist/summary/summaryCollection.d.ts +2 -2
  213. package/dist/summary/summaryCollection.d.ts.map +1 -1
  214. package/dist/summary/summaryCollection.js +16 -13
  215. package/dist/summary/summaryCollection.js.map +1 -1
  216. package/dist/summary/summaryFormat.d.ts +4 -0
  217. package/dist/summary/summaryFormat.d.ts.map +1 -1
  218. package/dist/summary/summaryFormat.js +8 -5
  219. package/dist/summary/summaryFormat.js.map +1 -1
  220. package/dist/summary/summaryGenerator.d.ts +21 -6
  221. package/dist/summary/summaryGenerator.d.ts.map +1 -1
  222. package/dist/summary/summaryGenerator.js +117 -54
  223. package/dist/summary/summaryGenerator.js.map +1 -1
  224. package/dist/summary/summaryManager.d.ts +8 -7
  225. package/dist/summary/summaryManager.d.ts.map +1 -1
  226. package/dist/summary/summaryManager.js +38 -28
  227. package/dist/summary/summaryManager.js.map +1 -1
  228. package/lib/batchTracker.d.ts +3 -2
  229. package/lib/batchTracker.d.ts.map +1 -1
  230. package/lib/batchTracker.js +5 -4
  231. package/lib/batchTracker.js.map +1 -1
  232. package/lib/blobManager.d.ts +15 -18
  233. package/lib/blobManager.d.ts.map +1 -1
  234. package/lib/blobManager.js +187 -146
  235. package/lib/blobManager.js.map +1 -1
  236. package/lib/connectionTelemetry.d.ts.map +1 -1
  237. package/lib/connectionTelemetry.js +23 -7
  238. package/lib/connectionTelemetry.js.map +1 -1
  239. package/lib/containerRuntime.d.ts +172 -35
  240. package/lib/containerRuntime.d.ts.map +1 -1
  241. package/lib/containerRuntime.js +678 -380
  242. package/lib/containerRuntime.js.map +1 -1
  243. package/lib/dataStore.d.ts.map +1 -1
  244. package/lib/dataStore.js +13 -5
  245. package/lib/dataStore.js.map +1 -1
  246. package/lib/dataStoreContext.d.ts +4 -4
  247. package/lib/dataStoreContext.d.ts.map +1 -1
  248. package/lib/dataStoreContext.js +49 -52
  249. package/lib/dataStoreContext.js.map +1 -1
  250. package/lib/dataStoreContexts.d.ts +1 -1
  251. package/lib/dataStoreContexts.d.ts.map +1 -1
  252. package/lib/dataStoreContexts.js +3 -3
  253. package/lib/dataStoreContexts.js.map +1 -1
  254. package/lib/dataStoreRegistry.js +1 -1
  255. package/lib/dataStoreRegistry.js.map +1 -1
  256. package/lib/dataStores.d.ts +23 -7
  257. package/lib/dataStores.d.ts.map +1 -1
  258. package/lib/dataStores.js +107 -64
  259. package/lib/dataStores.js.map +1 -1
  260. package/lib/deltaManagerProxyBase.d.ts +35 -0
  261. package/lib/deltaManagerProxyBase.d.ts.map +1 -0
  262. package/lib/deltaManagerProxyBase.js +73 -0
  263. package/lib/deltaManagerProxyBase.js.map +1 -0
  264. package/lib/deltaManagerSummarizerProxy.d.ts +1 -1
  265. package/lib/deltaManagerSummarizerProxy.d.ts.map +1 -1
  266. package/lib/deltaManagerSummarizerProxy.js +3 -1
  267. package/lib/deltaManagerSummarizerProxy.js.map +1 -1
  268. package/lib/deltaScheduler.d.ts.map +1 -1
  269. package/lib/deltaScheduler.js +7 -7
  270. package/lib/deltaScheduler.js.map +1 -1
  271. package/lib/error.d.ts +14 -0
  272. package/lib/error.d.ts.map +1 -0
  273. package/lib/error.js +17 -0
  274. package/lib/error.js.map +1 -0
  275. package/lib/gc/garbageCollection.d.ts +10 -9
  276. package/lib/gc/garbageCollection.d.ts.map +1 -1
  277. package/lib/gc/garbageCollection.js +61 -52
  278. package/lib/gc/garbageCollection.js.map +1 -1
  279. package/lib/gc/gcConfigs.d.ts.map +1 -1
  280. package/lib/gc/gcConfigs.js +16 -12
  281. package/lib/gc/gcConfigs.js.map +1 -1
  282. package/lib/gc/gcDefinitions.d.ts +17 -5
  283. package/lib/gc/gcDefinitions.d.ts.map +1 -1
  284. package/lib/gc/gcDefinitions.js +13 -14
  285. package/lib/gc/gcDefinitions.js.map +1 -1
  286. package/lib/gc/gcHelpers.d.ts +0 -8
  287. package/lib/gc/gcHelpers.d.ts.map +1 -1
  288. package/lib/gc/gcHelpers.js +5 -17
  289. package/lib/gc/gcHelpers.js.map +1 -1
  290. package/lib/gc/gcSummaryStateTracker.d.ts +4 -7
  291. package/lib/gc/gcSummaryStateTracker.d.ts.map +1 -1
  292. package/lib/gc/gcSummaryStateTracker.js +20 -59
  293. package/lib/gc/gcSummaryStateTracker.js.map +1 -1
  294. package/lib/gc/gcTelemetry.d.ts +1 -1
  295. package/lib/gc/gcTelemetry.d.ts.map +1 -1
  296. package/lib/gc/gcTelemetry.js +46 -36
  297. package/lib/gc/gcTelemetry.js.map +1 -1
  298. package/lib/gc/gcUnreferencedStateTracker.js +1 -1
  299. package/lib/gc/gcUnreferencedStateTracker.js.map +1 -1
  300. package/lib/gc/index.d.ts +2 -2
  301. package/lib/gc/index.d.ts.map +1 -1
  302. package/lib/gc/index.js +2 -2
  303. package/lib/gc/index.js.map +1 -1
  304. package/lib/id-compressor/appendOnlySortedMap.d.ts +8 -30
  305. package/lib/id-compressor/appendOnlySortedMap.d.ts.map +1 -1
  306. package/lib/id-compressor/appendOnlySortedMap.js +25 -66
  307. package/lib/id-compressor/appendOnlySortedMap.js.map +1 -1
  308. package/lib/id-compressor/finalSpace.d.ts +29 -0
  309. package/lib/id-compressor/finalSpace.d.ts.map +1 -0
  310. package/lib/id-compressor/finalSpace.js +58 -0
  311. package/lib/id-compressor/finalSpace.js.map +1 -0
  312. package/lib/id-compressor/idCompressor.d.ts +25 -250
  313. package/lib/id-compressor/idCompressor.d.ts.map +1 -1
  314. package/lib/id-compressor/idCompressor.js +385 -1142
  315. package/lib/id-compressor/idCompressor.js.map +1 -1
  316. package/lib/id-compressor/identifiers.d.ts +32 -0
  317. package/lib/id-compressor/identifiers.d.ts.map +1 -0
  318. package/lib/id-compressor/identifiers.js +11 -0
  319. package/lib/id-compressor/identifiers.js.map +1 -0
  320. package/lib/id-compressor/index.d.ts +5 -6
  321. package/lib/id-compressor/index.d.ts.map +1 -1
  322. package/lib/id-compressor/index.js +5 -6
  323. package/lib/id-compressor/index.js.map +1 -1
  324. package/lib/id-compressor/persistanceUtilities.d.ts +22 -0
  325. package/lib/id-compressor/persistanceUtilities.d.ts.map +1 -0
  326. package/lib/id-compressor/persistanceUtilities.js +34 -0
  327. package/lib/id-compressor/persistanceUtilities.js.map +1 -0
  328. package/lib/id-compressor/sessionSpaceNormalizer.d.ts +46 -0
  329. package/lib/id-compressor/sessionSpaceNormalizer.d.ts.map +1 -0
  330. package/lib/id-compressor/sessionSpaceNormalizer.js +76 -0
  331. package/lib/id-compressor/sessionSpaceNormalizer.js.map +1 -0
  332. package/lib/id-compressor/sessions.d.ts +115 -0
  333. package/lib/id-compressor/sessions.d.ts.map +1 -0
  334. package/lib/id-compressor/sessions.js +290 -0
  335. package/lib/id-compressor/sessions.js.map +1 -0
  336. package/lib/id-compressor/utilities.d.ts +49 -0
  337. package/lib/id-compressor/utilities.d.ts.map +1 -0
  338. package/lib/id-compressor/utilities.js +148 -0
  339. package/lib/id-compressor/utilities.js.map +1 -0
  340. package/lib/index.d.ts +3 -3
  341. package/lib/index.d.ts.map +1 -1
  342. package/lib/index.js +2 -2
  343. package/lib/index.js.map +1 -1
  344. package/lib/metadata.d.ts +18 -0
  345. package/lib/metadata.d.ts.map +1 -0
  346. package/lib/metadata.js +6 -0
  347. package/lib/metadata.js.map +1 -0
  348. package/lib/opLifecycle/batchManager.d.ts +2 -1
  349. package/lib/opLifecycle/batchManager.d.ts.map +1 -1
  350. package/lib/opLifecycle/batchManager.js +15 -7
  351. package/lib/opLifecycle/batchManager.js.map +1 -1
  352. package/lib/opLifecycle/definitions.d.ts +11 -0
  353. package/lib/opLifecycle/definitions.d.ts.map +1 -1
  354. package/lib/opLifecycle/definitions.js.map +1 -1
  355. package/lib/opLifecycle/index.d.ts +1 -1
  356. package/lib/opLifecycle/index.d.ts.map +1 -1
  357. package/lib/opLifecycle/index.js +1 -1
  358. package/lib/opLifecycle/index.js.map +1 -1
  359. package/lib/opLifecycle/opCompressor.d.ts +2 -2
  360. package/lib/opLifecycle/opCompressor.d.ts.map +1 -1
  361. package/lib/opLifecycle/opCompressor.js +10 -5
  362. package/lib/opLifecycle/opCompressor.js.map +1 -1
  363. package/lib/opLifecycle/opDecompressor.d.ts +2 -2
  364. package/lib/opLifecycle/opDecompressor.d.ts.map +1 -1
  365. package/lib/opLifecycle/opDecompressor.js +22 -13
  366. package/lib/opLifecycle/opDecompressor.js.map +1 -1
  367. package/lib/opLifecycle/opGroupingManager.d.ts +1 -1
  368. package/lib/opLifecycle/opGroupingManager.d.ts.map +1 -1
  369. package/lib/opLifecycle/opGroupingManager.js +17 -11
  370. package/lib/opLifecycle/opGroupingManager.js.map +1 -1
  371. package/lib/opLifecycle/opSplitter.d.ts +2 -2
  372. package/lib/opLifecycle/opSplitter.d.ts.map +1 -1
  373. package/lib/opLifecycle/opSplitter.js +15 -10
  374. package/lib/opLifecycle/opSplitter.js.map +1 -1
  375. package/lib/opLifecycle/outbox.d.ts +39 -6
  376. package/lib/opLifecycle/outbox.d.ts.map +1 -1
  377. package/lib/opLifecycle/outbox.js +132 -56
  378. package/lib/opLifecycle/outbox.js.map +1 -1
  379. package/lib/opLifecycle/remoteMessageProcessor.d.ts +6 -1
  380. package/lib/opLifecycle/remoteMessageProcessor.d.ts.map +1 -1
  381. package/lib/opLifecycle/remoteMessageProcessor.js +23 -9
  382. package/lib/opLifecycle/remoteMessageProcessor.js.map +1 -1
  383. package/lib/opProperties.js +1 -2
  384. package/lib/opProperties.js.map +1 -1
  385. package/lib/packageVersion.d.ts +1 -1
  386. package/lib/packageVersion.js +1 -1
  387. package/lib/packageVersion.js.map +1 -1
  388. package/lib/pendingStateManager.d.ts +25 -10
  389. package/lib/pendingStateManager.d.ts.map +1 -1
  390. package/lib/pendingStateManager.js +90 -53
  391. package/lib/pendingStateManager.js.map +1 -1
  392. package/lib/scheduleManager.d.ts.map +1 -1
  393. package/lib/scheduleManager.js +25 -15
  394. package/lib/scheduleManager.js.map +1 -1
  395. package/lib/summary/index.d.ts +4 -4
  396. package/lib/summary/index.d.ts.map +1 -1
  397. package/lib/summary/index.js +2 -2
  398. package/lib/summary/index.js.map +1 -1
  399. package/lib/summary/orderedClientElection.d.ts +3 -3
  400. package/lib/summary/orderedClientElection.d.ts.map +1 -1
  401. package/lib/summary/orderedClientElection.js +21 -22
  402. package/lib/summary/orderedClientElection.js.map +1 -1
  403. package/lib/summary/runWhileConnectedCoordinator.js +1 -1
  404. package/lib/summary/runWhileConnectedCoordinator.js.map +1 -1
  405. package/lib/summary/runningSummarizer.d.ts +31 -10
  406. package/lib/summary/runningSummarizer.d.ts.map +1 -1
  407. package/lib/summary/runningSummarizer.js +265 -133
  408. package/lib/summary/runningSummarizer.js.map +1 -1
  409. package/lib/summary/summarizer.d.ts +8 -7
  410. package/lib/summary/summarizer.d.ts.map +1 -1
  411. package/lib/summary/summarizer.js +75 -74
  412. package/lib/summary/summarizer.js.map +1 -1
  413. package/lib/summary/summarizerClientElection.d.ts +2 -2
  414. package/lib/summary/summarizerClientElection.d.ts.map +1 -1
  415. package/lib/summary/summarizerClientElection.js +6 -10
  416. package/lib/summary/summarizerClientElection.js.map +1 -1
  417. package/lib/summary/summarizerHeuristics.js +9 -13
  418. package/lib/summary/summarizerHeuristics.js.map +1 -1
  419. package/lib/summary/summarizerNode/index.d.ts +1 -1
  420. package/lib/summary/summarizerNode/index.d.ts.map +1 -1
  421. package/lib/summary/summarizerNode/index.js.map +1 -1
  422. package/lib/summary/summarizerNode/summarizerNode.d.ts +40 -23
  423. package/lib/summary/summarizerNode/summarizerNode.d.ts.map +1 -1
  424. package/lib/summary/summarizerNode/summarizerNode.js +132 -137
  425. package/lib/summary/summarizerNode/summarizerNode.js.map +1 -1
  426. package/lib/summary/summarizerNode/summarizerNodeUtils.d.ts +25 -29
  427. package/lib/summary/summarizerNode/summarizerNodeUtils.d.ts.map +1 -1
  428. package/lib/summary/summarizerNode/summarizerNodeUtils.js +2 -4
  429. package/lib/summary/summarizerNode/summarizerNodeUtils.js.map +1 -1
  430. package/lib/summary/summarizerNode/summarizerNodeWithGc.d.ts +21 -16
  431. package/lib/summary/summarizerNode/summarizerNodeWithGc.d.ts.map +1 -1
  432. package/lib/summary/summarizerNode/summarizerNodeWithGc.js +70 -119
  433. package/lib/summary/summarizerNode/summarizerNodeWithGc.js.map +1 -1
  434. package/lib/summary/summarizerTypes.d.ts +44 -24
  435. package/lib/summary/summarizerTypes.d.ts.map +1 -1
  436. package/lib/summary/summarizerTypes.js.map +1 -1
  437. package/lib/summary/summaryCollection.d.ts +2 -2
  438. package/lib/summary/summaryCollection.d.ts.map +1 -1
  439. package/lib/summary/summaryCollection.js +9 -6
  440. package/lib/summary/summaryCollection.js.map +1 -1
  441. package/lib/summary/summaryFormat.d.ts +4 -0
  442. package/lib/summary/summaryFormat.d.ts.map +1 -1
  443. package/lib/summary/summaryFormat.js +7 -4
  444. package/lib/summary/summaryFormat.js.map +1 -1
  445. package/lib/summary/summaryGenerator.d.ts +21 -6
  446. package/lib/summary/summaryGenerator.d.ts.map +1 -1
  447. package/lib/summary/summaryGenerator.js +109 -47
  448. package/lib/summary/summaryGenerator.js.map +1 -1
  449. package/lib/summary/summaryManager.d.ts +8 -7
  450. package/lib/summary/summaryManager.d.ts.map +1 -1
  451. package/lib/summary/summaryManager.js +35 -25
  452. package/lib/summary/summaryManager.js.map +1 -1
  453. package/package.json +30 -32
  454. package/src/batchTracker.ts +7 -5
  455. package/src/blobManager.ts +235 -172
  456. package/src/connectionTelemetry.ts +19 -5
  457. package/src/containerRuntime.ts +853 -431
  458. package/src/dataStore.ts +12 -4
  459. package/src/dataStoreContext.ts +49 -46
  460. package/src/dataStoreContexts.ts +4 -4
  461. package/src/dataStoreRegistry.ts +1 -1
  462. package/src/dataStores.ts +119 -80
  463. package/src/deltaManagerProxyBase.ts +111 -0
  464. package/src/deltaManagerSummarizerProxy.ts +4 -1
  465. package/src/deltaScheduler.ts +7 -11
  466. package/src/error.ts +18 -0
  467. package/src/gc/garbageCollection.md +53 -5
  468. package/src/gc/garbageCollection.ts +58 -51
  469. package/src/gc/gcConfigs.ts +4 -2
  470. package/src/gc/gcDefinitions.ts +17 -21
  471. package/src/gc/gcEarlyAdoption.md +145 -0
  472. package/src/gc/gcHelpers.ts +1 -12
  473. package/src/gc/gcSummaryStateTracker.ts +19 -65
  474. package/src/gc/gcTelemetry.ts +15 -13
  475. package/src/gc/gcUnreferencedStateTracker.ts +1 -1
  476. package/src/gc/index.ts +2 -4
  477. package/src/id-compressor/appendOnlySortedMap.ts +26 -87
  478. package/src/id-compressor/finalSpace.ts +67 -0
  479. package/src/id-compressor/idCompressor.ts +458 -1682
  480. package/src/id-compressor/identifiers.ts +42 -0
  481. package/src/id-compressor/index.ts +11 -20
  482. package/src/id-compressor/persistanceUtilities.ts +58 -0
  483. package/src/id-compressor/sessionSpaceNormalizer.ts +83 -0
  484. package/src/id-compressor/sessions.ts +405 -0
  485. package/src/id-compressor/utilities.ts +187 -0
  486. package/src/index.ts +9 -2
  487. package/src/metadata.ts +19 -0
  488. package/src/opLifecycle/README.md +20 -0
  489. package/src/opLifecycle/batchManager.ts +9 -1
  490. package/src/opLifecycle/definitions.ts +11 -0
  491. package/src/opLifecycle/index.ts +1 -1
  492. package/src/opLifecycle/opCompressor.ts +6 -5
  493. package/src/opLifecycle/opDecompressor.ts +47 -17
  494. package/src/opLifecycle/opGroupingManager.ts +18 -8
  495. package/src/opLifecycle/opSplitter.ts +10 -7
  496. package/src/opLifecycle/outbox.ts +177 -72
  497. package/src/opLifecycle/remoteMessageProcessor.ts +32 -9
  498. package/src/packageVersion.ts +1 -1
  499. package/src/pendingStateManager.ts +123 -78
  500. package/src/scheduleManager.ts +22 -11
  501. package/src/summary/index.ts +7 -4
  502. package/src/summary/orderedClientElection.ts +10 -6
  503. package/src/summary/runWhileConnectedCoordinator.ts +1 -1
  504. package/src/summary/runningSummarizer.ts +291 -163
  505. package/src/summary/summarizer.ts +27 -16
  506. package/src/summary/summarizerClientElection.ts +2 -2
  507. package/src/summary/summarizerHeuristics.ts +1 -1
  508. package/src/summary/summarizerNode/index.ts +2 -2
  509. package/src/summary/summarizerNode/summarizerNode.ts +142 -184
  510. package/src/summary/summarizerNode/summarizerNodeUtils.ts +27 -35
  511. package/src/summary/summarizerNode/summarizerNodeWithGc.ts +72 -148
  512. package/src/summary/summarizerTypes.ts +49 -24
  513. package/src/summary/summaryCollection.ts +9 -4
  514. package/src/summary/summaryFormat.ts +9 -2
  515. package/src/summary/summaryGenerator.ts +72 -49
  516. package/src/summary/summaryManager.ts +44 -16
  517. package/dist/id-compressor/idRange.d.ts +0 -11
  518. package/dist/id-compressor/idRange.d.ts.map +0 -1
  519. package/dist/id-compressor/idRange.js +0 -29
  520. package/dist/id-compressor/idRange.js.map +0 -1
  521. package/dist/id-compressor/numericUuid.d.ts +0 -59
  522. package/dist/id-compressor/numericUuid.d.ts.map +0 -1
  523. package/dist/id-compressor/numericUuid.js +0 -325
  524. package/dist/id-compressor/numericUuid.js.map +0 -1
  525. package/dist/id-compressor/sessionIdNormalizer.d.ts +0 -138
  526. package/dist/id-compressor/sessionIdNormalizer.d.ts.map +0 -1
  527. package/dist/id-compressor/sessionIdNormalizer.js +0 -488
  528. package/dist/id-compressor/sessionIdNormalizer.js.map +0 -1
  529. package/dist/id-compressor/utils.d.ts +0 -57
  530. package/dist/id-compressor/utils.d.ts.map +0 -1
  531. package/dist/id-compressor/utils.js +0 -90
  532. package/dist/id-compressor/utils.js.map +0 -1
  533. package/dist/id-compressor/uuidUtilities.d.ts +0 -30
  534. package/dist/id-compressor/uuidUtilities.d.ts.map +0 -1
  535. package/dist/id-compressor/uuidUtilities.js +0 -106
  536. package/dist/id-compressor/uuidUtilities.js.map +0 -1
  537. package/lib/id-compressor/idRange.d.ts +0 -11
  538. package/lib/id-compressor/idRange.d.ts.map +0 -1
  539. package/lib/id-compressor/idRange.js +0 -25
  540. package/lib/id-compressor/idRange.js.map +0 -1
  541. package/lib/id-compressor/numericUuid.d.ts +0 -59
  542. package/lib/id-compressor/numericUuid.d.ts.map +0 -1
  543. package/lib/id-compressor/numericUuid.js +0 -315
  544. package/lib/id-compressor/numericUuid.js.map +0 -1
  545. package/lib/id-compressor/sessionIdNormalizer.d.ts +0 -138
  546. package/lib/id-compressor/sessionIdNormalizer.d.ts.map +0 -1
  547. package/lib/id-compressor/sessionIdNormalizer.js +0 -484
  548. package/lib/id-compressor/sessionIdNormalizer.js.map +0 -1
  549. package/lib/id-compressor/utils.d.ts +0 -57
  550. package/lib/id-compressor/utils.d.ts.map +0 -1
  551. package/lib/id-compressor/utils.js +0 -79
  552. package/lib/id-compressor/utils.js.map +0 -1
  553. package/lib/id-compressor/uuidUtilities.d.ts +0 -30
  554. package/lib/id-compressor/uuidUtilities.d.ts.map +0 -1
  555. package/lib/id-compressor/uuidUtilities.js +0 -98
  556. package/lib/id-compressor/uuidUtilities.js.map +0 -1
  557. package/src/id-compressor/idRange.ts +0 -35
  558. package/src/id-compressor/numericUuid.ts +0 -383
  559. package/src/id-compressor/sessionIdNormalizer.ts +0 -609
  560. package/src/id-compressor/utils.ts +0 -114
  561. package/src/id-compressor/uuidUtilities.ts +0 -123
@@ -3,217 +3,145 @@
3
3
  * Licensed under the MIT License.
4
4
  */
5
5
 
6
- /* eslint-disable @typescript-eslint/restrict-plus-operands */
7
-
8
- import { ITelemetryLoggerExt } from "@fluidframework/telemetry-utils";
9
- import { assert } from "@fluidframework/common-utils";
6
+ import { assert } from "@fluidframework/core-utils";
7
+ import { bufferToString, stringToBuffer } from "@fluid-internal/client-utils";
10
8
  import {
9
+ IdCreationRange,
11
10
  IIdCompressor,
12
11
  IIdCompressorCore,
13
- LocalCompressedId,
14
- FinalCompressedId,
15
- SessionSpaceCompressedId,
16
- StableId,
17
12
  OpSpaceCompressedId,
18
- SessionId,
19
- CompressedId,
20
- } from "@fluidframework/runtime-definitions";
21
- import type {
22
- IdCreationRange,
23
- SerializedCluster,
24
- SerializedClusterOverrides,
25
13
  SerializedIdCompressor,
26
14
  SerializedIdCompressorWithNoSession,
27
15
  SerializedIdCompressorWithOngoingSession,
28
- SerializedLocalState,
29
- SerializedSessionData,
30
- UnackedLocalId,
31
- VersionedSerializedIdCompressor,
16
+ SessionId,
17
+ SessionSpaceCompressedId,
18
+ StableId,
19
+ initialClusterCapacity,
32
20
  } from "@fluidframework/runtime-definitions";
33
- import BTree from "sorted-btree";
21
+ import { ITelemetryBaseLogger } from "@fluidframework/core-interfaces";
22
+ import { ITelemetryLoggerExt, createChildLogger } from "@fluidframework/telemetry-utils";
23
+ import { FinalCompressedId, isFinalId, LocalCompressedId, NumericUuid } from "./identifiers";
34
24
  import {
35
- hasAtLeastLength,
36
- compareFiniteNumbers,
37
- compareFiniteNumbersReversed,
38
- compareMaps,
39
- compareStrings,
40
- fail,
41
- Mutable,
42
- setPropertyIfDefined,
43
- } from "./utils";
44
- import { assertIsStableId, isStableId } from "./uuidUtilities";
45
- import { AppendOnlySortedMap } from "./appendOnlySortedMap";
46
- import { getIds } from "./idRange";
47
- import {
48
- numericUuidEquals,
49
- getPositiveDelta,
50
- incrementUuid,
25
+ createSessionId,
26
+ localIdFromGenCount,
27
+ genCountFromLocalId,
51
28
  numericUuidFromStableId,
52
- NumericUuid,
29
+ offsetNumericUuid,
53
30
  stableIdFromNumericUuid,
54
- ensureSessionUuid,
55
- } from "./numericUuid";
56
- import { SessionIdNormalizer } from "./sessionIdNormalizer";
31
+ subtractNumericUuids,
32
+ } from "./utilities";
33
+ import {
34
+ Index,
35
+ readBoolean,
36
+ readNumber,
37
+ readNumericUuid,
38
+ writeBoolean,
39
+ writeNumber,
40
+ writeNumericUuid,
41
+ } from "./persistanceUtilities";
42
+ import {
43
+ getAlignedLocal,
44
+ getAlignedFinal,
45
+ IdCluster,
46
+ lastFinalizedLocal,
47
+ Session,
48
+ Sessions,
49
+ } from "./sessions";
50
+ import { SessionSpaceNormalizer } from "./sessionSpaceNormalizer";
51
+ import { FinalSpace } from "./finalSpace";
57
52
 
58
53
  /**
59
- * A cluster of final (sequenced via consensus), sequentially allocated compressed IDs.
60
- * A final ID in a cluster decompresses to a UUID that is one of the following:
61
- * 1. A sequentially allocated UUID that is the result of adding its offset within the cluster to `baseUuid`.
62
- * 2. An override string (stored in `overrides`) specified at allocation time.
54
+ * The version of IdCompressor that is currently persisted.
55
+ * This should not be changed without careful consideration to compatibility.
63
56
  */
64
- interface IdCluster {
65
- /**
66
- * The UUID corresponding to the first final ID in the cluster.
67
- */
68
- readonly baseUuid: NumericUuid;
69
-
70
- /**
71
- * The total number of final IDs reserved for allocation in the cluster.
72
- * Clusters are reserved in blocks as a performance optimization.
73
- */
74
- capacity: number;
75
-
76
- /**
77
- * The number of final IDs currently allocated in the cluster.
78
- */
79
- count: number;
80
-
81
- /**
82
- * The session in which this cluster was created
83
- */
84
- readonly session: Session;
85
-
86
- /**
87
- * Final IDs assigned override strings within this cluster.
88
- * These are one of the following:
89
- *
90
- * 1. The override string
91
- *
92
- * 2. The override string and external override details. This occurs when local IDs corresponding to the same
93
- * override string are created by different sessions before any have been finalized. This can occur due to
94
- * concurrency or offline. In this case, the string is stored for the final ID that got sequenced first, and that
95
- * final ID is stored associated with all subsequent final IDs with the same override.
96
- *
97
- * When a final ID which is safely reserved via consensus as part of a cluster (but is not yet sequenced) is
98
- * allocated with an override, this collection will be temporarily inaccurate as it will not contain an entry for
99
- * that final ID. This absence indicates the uncertainty about what the final ID associated with that override will
100
- * be after finalizing the range (which could change due to unification of a concurrent duplicate override).
101
- * This table will be adjusted to reflect the override when that final ID is finalized via consensus, and
102
- * decompression will use `clustersAndOverridesInversion` until that point.
103
- */
104
- overrides?: Map<FinalCompressedId, string | UnifiedOverride>;
105
- }
106
-
107
- type UnifiedOverride = OverrideCompressionDetails & {
108
- override: string;
109
- };
57
+ const currentWrittenVersion = 1;
110
58
 
111
59
  /**
112
- * Data about a SharedTree session.
113
- * Used to track and allocate identity clusters associated with a particular session ID.
60
+ * See {@link IIdCompressor} and {@link IIdCompressorCore}
114
61
  */
115
- interface Session {
116
- readonly sessionUuid: NumericUuid;
117
-
118
- /**
119
- * `cluster` is undefined if a new cluster must be allocated when the session requests the next final ID allocation.
120
- */
121
- currentClusterDetails:
122
- | { readonly clusterBase: FinalCompressedId; readonly cluster: IdCluster }
123
- | undefined;
124
-
62
+ export class IdCompressor implements IIdCompressor, IIdCompressorCore {
125
63
  /**
126
- * The last local ID known to be finalized for this session.
64
+ * Max allowed initial cluster size.
127
65
  */
128
- lastFinalizedLocalId: LocalCompressedId | undefined;
129
- }
130
-
131
- /**
132
- * Roughly equates to a minimum of 1M sessions before we start allocating 64 bit IDs.
133
- * This value must *NOT* change without careful consideration to compatibility.
134
- */
135
- export const defaultClusterCapacity = 512;
136
-
137
- /**
138
- * The base UUID for the reserved id cluster.
139
- * This should not be changed without consideration to compatibility.
140
- */
141
- const reservedSessionId = ensureSessionUuid(
142
- assertIsStableId("decaf40b-3c1a-47f8-a7a1-e8461ddb69ce"),
143
- );
144
-
145
- /**
146
- * @returns true if the supplied ID is a final ID.
147
- */
148
- export function isFinalId(id: CompressedId): id is FinalCompressedId {
149
- return id >= 0;
150
- }
66
+ public static readonly maxClusterSize = 2 ** 20;
151
67
 
152
- /**
153
- * @returns true if the supplied ID is a local ID.
154
- */
155
- export function isLocalId(id: CompressedId): id is LocalCompressedId {
156
- return id < 0;
157
- }
68
+ // ----- Local state -----
158
69
 
159
- /**
160
- * A cluster in `clustersAndOverridesInversion`, which is mapped from the first stable ID in a cluster.
161
- */
162
- interface ClusterInfo {
163
- readonly clusterBase: FinalCompressedId;
164
- readonly cluster: IdCluster;
165
- }
70
+ public readonly localSessionId: SessionId;
71
+ private readonly localSession: Session;
72
+ private readonly normalizer = new SessionSpaceNormalizer();
73
+ // The number of IDs generated by the local session
74
+ private localGenCount = 0;
166
75
 
167
- interface OverrideCompressionDetails {
168
- readonly originalOverridingFinal: FinalCompressedId;
169
- readonly associatedLocalId?: LocalCompressedId;
170
- }
76
+ // -----------------------
171
77
 
172
- /**
173
- * An override with a final ID associated with it.
174
- *
175
- * `associatedLocalId` is present on this type when a local ID in this session is associated with the override.
176
- *
177
- * It may be present even when `overriddenFinalId` was created by another session. This occurs when local IDs corresponding to the
178
- * same override string are created by different sessions before any have been finalized. `overriddenFinalId` will be set to
179
- * the *first* finalized ID with that string, but `associatedLocal` will be set to the local session's local ID for that string. This is
180
- * done to preserve the invariant that an override will always compress into the same session-space ID for the lifetime of the session.
181
- */
182
- interface FinalizedOverride extends OverrideCompressionDetails {
183
- readonly cluster: IdCluster;
184
- }
78
+ // ----- Final state -----
185
79
 
186
- /**
187
- * The value of a mapping in `clustersAndOverridesInversion`, which maps an override to the cluster containing it (if finalized) or the
188
- * local ID corresponding to it (if unfinalized).
189
- *
190
- * Override strings associated with local IDs stored in `clustersAndOverridesInversion` are *always* replaced immediately upon finalizing,
191
- * and thus it is typed as op-space (unacked local).
192
- */
193
- type Override = UnackedLocalId | FinalizedOverride;
80
+ // The gen count to be annotated on the range returned by the next call to `takeNextCreationRange`.
81
+ // This is updated to be equal to `generatedIdCount` + 1 each time it is called.
82
+ private nextRangeBaseGenCount = 1;
83
+ // The capacity of the next cluster to be created
84
+ private newClusterCapacity = initialClusterCapacity;
85
+ private readonly sessions = new Sessions();
86
+ private readonly finalSpace = new FinalSpace();
194
87
 
195
- type CompressionMapping = ClusterInfo | Override;
88
+ // -----------------------
196
89
 
197
- /** Prepended to all keys in {@link IdCompressor.clustersAndOverridesInversion} that are override strings and not valid `StableIds` */
198
- const nonStableOverridePrefix = "\ue15e"; // A character in the Private Use Area of the BMP (https://en.wikipedia.org/wiki/Private_Use_Areas)
90
+ // ----- Telemetry state -----
199
91
 
200
- /** Keys of {@link IdCompressor.clustersAndOverridesInversion} */
201
- type InversionKey = `${typeof nonStableOverridePrefix}${string}` | StableId;
92
+ // The number of local IDs generated since the last telemetry was sent.
93
+ private telemetryLocalIdCount = 0;
94
+ // The number of eager final IDs generated since the last telemetry was sent.
95
+ private telemetryEagerFinalIdCount = 0;
202
96
 
203
- /**
204
- * See {@link IIdCompressor}
205
- */
206
- export class IdCompressor implements IIdCompressorCore, IIdCompressor {
207
- /**
208
- * Max allowed cluster size
209
- */
210
- public static maxClusterSize = 2 ** 20;
97
+ // -----------------------
211
98
 
212
- /**
213
- * Trivially reach consensus on default cluster size and reserved IDs.
214
- * These initial values must *NOT* change without careful consideration to compatibility.
215
- */
216
- private newClusterCapacity = defaultClusterCapacity;
99
+ private constructor(
100
+ localSessionIdOrDeserialized: SessionId | Sessions,
101
+ private readonly logger?: ITelemetryLoggerExt,
102
+ ) {
103
+ if (typeof localSessionIdOrDeserialized === "string") {
104
+ this.localSessionId = localSessionIdOrDeserialized;
105
+ this.localSession = this.sessions.getOrCreate(localSessionIdOrDeserialized);
106
+ } else {
107
+ // Deserialize case
108
+ this.sessions = localSessionIdOrDeserialized;
109
+ // As policy, the first session is always the local session. Preserve this invariant
110
+ // during deserialization.
111
+ const firstSession = localSessionIdOrDeserialized.sessions().next();
112
+ assert(!firstSession.done, 0x754 /* First session must be present. */);
113
+ this.localSession = firstSession.value;
114
+ this.localSessionId = stableIdFromNumericUuid(
115
+ this.localSession.sessionUuid,
116
+ ) as SessionId;
117
+ }
118
+ }
119
+
120
+ public static create(logger?: ITelemetryBaseLogger): IdCompressor;
121
+ public static create(sessionId: SessionId, logger?: ITelemetryBaseLogger): IdCompressor;
122
+ public static create(
123
+ sessionIdOrLogger?: SessionId | ITelemetryBaseLogger,
124
+ loggerOrUndefined?: ITelemetryBaseLogger,
125
+ ): IdCompressor {
126
+ let localSessionId: SessionId;
127
+ let logger: ITelemetryBaseLogger | undefined;
128
+ if (sessionIdOrLogger === undefined) {
129
+ localSessionId = createSessionId();
130
+ } else {
131
+ if (typeof sessionIdOrLogger === "string") {
132
+ localSessionId = sessionIdOrLogger;
133
+ logger = loggerOrUndefined;
134
+ } else {
135
+ localSessionId = createSessionId();
136
+ logger = loggerOrUndefined;
137
+ }
138
+ }
139
+ const compressor = new IdCompressor(
140
+ localSessionId,
141
+ logger === undefined ? undefined : createChildLogger({ logger }),
142
+ );
143
+ return compressor;
144
+ }
217
145
 
218
146
  /**
219
147
  * The size of each newly created ID cluster.
@@ -227,315 +155,83 @@ export class IdCompressor implements IIdCompressorCore, IIdCompressor {
227
155
  * `IdCompressor.maxClusterSize`.
228
156
  */
229
157
  public set clusterCapacity(value: number) {
230
- assert(value > 0, 0x481 /* Clusters must have a positive capacity */);
231
- assert(
232
- value <= IdCompressor.maxClusterSize,
233
- 0x482 /* Clusters must not exceed max cluster size */,
234
- );
158
+ if (value <= 0) {
159
+ throw new Error("Clusters must have a positive capacity.");
160
+ }
161
+ if (value > IdCompressor.maxClusterSize) {
162
+ throw new Error("Clusters must not exceed max cluster size.");
163
+ }
235
164
  this.newClusterCapacity = value;
236
165
  }
237
166
 
238
- /**
239
- * Session ID -\> data about the session's current cluster.
240
- * Sessions are mutable, and thus should only be created via `createSession`.
241
- */
242
- private readonly sessions = new Map<SessionId, Session>();
243
-
244
- /**
245
- * The `IdCompressor`'s current local session.
246
- */
247
- private readonly localSession: Session;
248
-
249
- /**
250
- * The base final ID of the next cluster to be created.
251
- */
252
- private nextClusterBaseFinalId: FinalCompressedId = 0 as FinalCompressedId;
253
-
254
- /**
255
- * Total number of IDs created locally during the current session.
256
- */
257
- private localIdCount = 0;
258
-
259
- /**
260
- * The most recent (i.e. smallest, due to being negative) local ID in a range returned by `takeNextCreationRange`.
261
- * Undefined if no non-empty ranges have ever been returned by this compressor.
262
- */
263
- private lastTakenLocalId: LocalCompressedId | undefined;
264
-
265
- /**
266
- * Maps local IDs to override strings. This will contain an entry for every override assigned to a local ID generated during
267
- * the current session, and retains entries for the lifetime of this compressor.
268
- */
269
- private readonly localOverrides = new AppendOnlySortedMap<LocalCompressedId, string>(
270
- compareFiniteNumbersReversed,
271
- );
272
-
273
- /**
274
- * Maps local IDs to the final ID they are associated with (if any), and maps final IDs to the corresponding local ID (if any).
275
- * This is used to efficiently compute normalization. This map can be thought of as mapping ranges of "optimistic uncertainty"
276
- * (local IDs) to the result of consensus (reserved ranges of final IDs, a.k.a. clusters). Any given range of local IDs
277
- * does not necessarily span an entire cluster, as some session-space IDs may be allocated *after* a cluster has been allocated
278
- * but before it is full. In this case, there is no uncertainty, as the range of final IDs was reserved when the cluster was created.
279
- * However, there is always a range of local IDs with size \>= 1 associated with the beginning of every cluster, as clusters are only
280
- * created *after* they are needed and thus there is some period of uncertainty after local IDs have been handed out but before the
281
- * range containing them has been finalized. There may also be ranges of local IDs that do not start at the beginning of a
282
- * cluster; this happens when a cluster is expanded instead of allocating a new one.
283
- * Additionally, session space IDs associated with an override string will also always be local IDs, because there is uncertainty as
284
- * to whether another client simultaneously allocated the same override and could get sequenced first (a.k.a. unification) and its
285
- * final ID would be associated with that override.
286
- * See `SessionIdNormalizer` for more.
287
- */
288
- private sessionIdNormalizer = new SessionIdNormalizer<IdCluster>();
289
-
290
- /**
291
- * Contains entries for cluster base UUIDs and override strings (both local and final).
292
- * As a performance optimization, entries for finalized strings also include the containing cluster object.
293
- * This can be viewed as three separate tables: the inverse table for `localOverrides`, the inverse table for the union of all
294
- * the overrides of the clusters in `finalIdToCluster`, and the inverse lookup of cluster base UUIDs to their clusters.
295
- * This is unified as a performance optimization, as the common case does not have overridden IDs. It is a btree due to the need
296
- * to make range queries.
297
- */
298
- private readonly clustersAndOverridesInversion: BTree<InversionKey, CompressionMapping> =
299
- new BTree(undefined, compareStrings);
300
-
301
- /**
302
- * Maps the first final ID in a cluster to its owning cluster.
303
- * Can be searched in O(log n) to determine clusters for any final ID.
304
- */
305
- private readonly finalIdToCluster: AppendOnlySortedMap<FinalCompressedId, IdCluster> =
306
- new AppendOnlySortedMap(compareFiniteNumbers);
167
+ public generateCompressedId(): SessionSpaceCompressedId {
168
+ this.localGenCount++;
169
+ const lastCluster = this.localSession.getLastCluster();
170
+ if (lastCluster === undefined) {
171
+ this.telemetryLocalIdCount++;
172
+ return this.generateNextLocalId();
173
+ }
307
174
 
308
- /**
309
- * @param localSessionId - the `IdCompressor`'s current local session ID.
310
- * {@link generateStableId}.
311
- */
312
- public constructor(
313
- public readonly localSessionId: SessionId,
314
- private readonly logger?: ITelemetryLoggerExt,
315
- ) {
316
- this.localSession = this.createSession(localSessionId);
175
+ // If there exists a cluster of final IDs already claimed by the local session that still has room in it,
176
+ // it is known prior to range sequencing what a local ID's corresponding final ID will be.
177
+ // In this case, it is safe to return the final ID immediately. This is guaranteed to be safe because
178
+ // any op that the local session sends that contains one of those final IDs are guaranteed to arrive to
179
+ // collaborators *after* the one containing the creation range.
180
+ const clusterOffset = this.localGenCount - genCountFromLocalId(lastCluster.baseLocalId);
181
+ if (lastCluster.capacity > clusterOffset) {
182
+ this.telemetryEagerFinalIdCount++;
183
+ // Space in the cluster: eager final
184
+ return ((lastCluster.baseFinalId as number) +
185
+ clusterOffset) as SessionSpaceCompressedId;
186
+ }
187
+ // No space in the cluster, return next local
188
+ this.telemetryLocalIdCount++;
189
+ return this.generateNextLocalId();
317
190
  }
318
191
 
319
- /**
320
- * Creates a session object for the supplied ID.
321
- * Must only be called once per ID.
322
- * @param sessionId - the ID for the session
323
- * @returns the session object for the supplied ID
324
- */
325
- private createSession(sessionId: SessionId): Session {
326
- assert(
327
- !this.clustersAndOverridesInversion.has(sessionId),
328
- 0x484 /* Attempted to create duplicate session */,
329
- );
330
- const existingSession = this.sessions.get(sessionId);
331
- if (existingSession !== undefined) {
332
- fail("createSession must only be called once for each session ID.");
333
- }
334
- const sessionUuid = numericUuidFromStableId(sessionId);
335
- const session: Session = {
336
- sessionUuid,
337
- currentClusterDetails: undefined,
338
- lastFinalizedLocalId: undefined,
339
- };
340
- this.sessions.set(sessionId, session);
341
- return session;
192
+ private generateNextLocalId(): LocalCompressedId {
193
+ // Must tell the normalizer that we generated a local ID
194
+ this.normalizer.addLocalRange(this.localGenCount, 1);
195
+ return localIdFromGenCount(this.localGenCount);
342
196
  }
343
197
 
344
- /**
345
- * Returns a range of local IDs created by this session in a format for sending to the server for finalizing.
346
- * The range will include all local IDs generated via calls to `generateCompressedId` since the last time this method was called.
347
- * @returns the range of session-local IDs, which may be empty. This range must be sent to the server for ordering before
348
- * it is finalized. Ranges must be sent to the server in the order that they are taken via calls to this method.
349
- */
350
198
  public takeNextCreationRange(): IdCreationRange {
351
- const lastLocalInRange = -this.localIdCount as UnackedLocalId;
352
- const lastTakenNormalized = this.lastTakenLocalId ?? 0;
353
- assert(lastLocalInRange <= lastTakenNormalized, 0x485 /* Inconsistent local ID state */);
354
-
355
- let ids: IdCreationRange.Ids | undefined;
356
- if (lastLocalInRange !== lastTakenNormalized) {
357
- const firstLocalInRange = (lastTakenNormalized - 1) as UnackedLocalId;
358
- const overrides = [
359
- ...this.localOverrides.getRange(
360
- (lastTakenNormalized - 1) as LocalCompressedId,
361
- lastLocalInRange as LocalCompressedId,
362
- ),
363
- ] as (readonly [UnackedLocalId, string])[];
364
- if (hasAtLeastLength(overrides, 1)) {
365
- assert(
366
- overrides[0][0] <= firstLocalInRange,
367
- 0x486 /* Inconsistent override state */,
368
- );
369
- assert(
370
- overrides[overrides.length - 1][0] >= lastLocalInRange,
371
- 0x487 /* Inconsistent override state */,
372
- );
373
- ids = {
374
- overrides,
375
- };
376
- const first = firstLocalInRange === overrides[0][0] ? undefined : firstLocalInRange;
377
- const last =
378
- lastLocalInRange === overrides[overrides.length - 1][0]
379
- ? undefined
380
- : lastLocalInRange;
381
- setPropertyIfDefined(first, ids, "first");
382
- setPropertyIfDefined(last, ids, "last");
383
- } else {
384
- ids = {
385
- first: firstLocalInRange,
386
- last: lastLocalInRange,
387
- };
388
- }
389
- this.lastTakenLocalId = lastLocalInRange;
390
- }
391
-
392
- const range: Mutable<IdCreationRange> = { sessionId: this.localSessionId };
393
-
394
- if (ids === undefined) {
395
- return range;
199
+ const count = this.localGenCount - (this.nextRangeBaseGenCount - 1);
200
+ if (count === 0) {
201
+ return {
202
+ sessionId: this.localSessionId,
203
+ };
396
204
  }
397
-
398
- assert(
399
- this.lastTakenLocalId === -this.localIdCount &&
400
- this.lastTakenLocalId !== lastTakenNormalized,
401
- 0x488 /* Non-empty range must properly consume local IDs */,
402
- );
403
-
404
- range.ids = ids;
205
+ const range: IdCreationRange = {
206
+ sessionId: this.localSessionId,
207
+ ids: {
208
+ firstGenCount: this.nextRangeBaseGenCount,
209
+ count,
210
+ },
211
+ };
212
+ this.nextRangeBaseGenCount = this.localGenCount + 1;
405
213
  return range;
406
214
  }
407
215
 
408
- /**
409
- * Finalizes the supplied range of IDs (which may be from either a remote or local session).
410
- * @param range - the range of session-local IDs to finalize.
411
- */
412
216
  public finalizeCreationRange(range: IdCreationRange): void {
413
- const { sessionId } = range;
414
-
415
- const isLocal = sessionId === this.localSessionId;
416
- const session = this.sessions.get(sessionId) ?? this.createSession(sessionId);
417
-
418
- const ids = getIds(range);
419
- if (ids === undefined) {
217
+ // Check if the range has IDs
218
+ if (range.ids === undefined) {
420
219
  return;
421
220
  }
422
221
 
423
- const { currentClusterDetails } = session;
424
- const { cluster: currentCluster, clusterBase: currentBaseFinalId } =
425
- currentClusterDetails ?? {
426
- cluster: undefined,
427
- clusterBase: undefined,
428
- };
429
- const currentClusterExists =
430
- currentCluster !== undefined && currentBaseFinalId !== undefined;
431
-
432
- const normalizedLastFinalizedLocal = session.lastFinalizedLocalId ?? 0;
433
- const { first: newFirstFinalizedLocal, last: newLastFinalizedLocal } = ids;
434
- assert(
435
- newFirstFinalizedLocal === normalizedLastFinalizedLocal - 1,
436
- 0x489 /* Ranges finalized out of order. */,
437
- );
438
-
439
- // The total number of session-local IDs to finalize
440
- const finalizeCount = normalizedLastFinalizedLocal - newLastFinalizedLocal;
441
- assert(finalizeCount >= 1, 0x48a /* Cannot finalize an empty range. */);
442
-
443
- let eagerFinalIdCount = 0;
444
- let initialClusterCount = 0;
445
- let remainingCount = finalizeCount;
446
- let newBaseUuid: NumericUuid | undefined;
447
- if (currentClusterExists) {
448
- if (isLocal) {
449
- const lastKnownFinal =
450
- this.sessionIdNormalizer.getLastFinalId() ??
451
- fail("Cluster exists but normalizer does not have an entry for it.");
452
- const lastAlignedFinalInCluster = (currentBaseFinalId +
453
- Math.min(currentCluster.count + finalizeCount, currentCluster.capacity) -
454
- 1) as FinalCompressedId;
455
- if (lastAlignedFinalInCluster > lastKnownFinal) {
456
- this.sessionIdNormalizer.addFinalIds(
457
- (lastKnownFinal + 1) as FinalCompressedId,
458
- lastAlignedFinalInCluster,
459
- currentCluster,
460
- );
461
- }
462
- }
463
- initialClusterCount = currentCluster.count;
464
- const remainingCapacity = currentCluster.capacity - initialClusterCount;
465
- const overflow = remainingCount - remainingCapacity;
466
- const hasRoom = overflow <= 0;
467
- if (hasRoom || currentBaseFinalId === this.finalIdToCluster.maxKey()) {
468
- currentCluster.count += remainingCount;
469
- eagerFinalIdCount = remainingCount;
470
- remainingCount = 0;
471
- // The common case is that there is room in the cluster, and the new final IDs can simply be added to it
472
- if (!hasRoom) {
473
- // The cluster is full but is the last in the list of clusters.
474
- // This allows it to be expanded instead of allocating a new one.
475
- const expansionAmount = this.newClusterCapacity + overflow;
476
- const previousCapacity = currentCluster.capacity;
477
- currentCluster.capacity += expansionAmount;
478
- this.nextClusterBaseFinalId = (this.nextClusterBaseFinalId +
479
- expansionAmount) as FinalCompressedId;
480
- assert(
481
- this.nextClusterBaseFinalId < Number.MAX_SAFE_INTEGER,
482
- 0x48b /* The number of allocated final IDs must not exceed the JS maximum safe integer. */,
483
- );
484
- this.checkClusterForCollision(currentCluster);
485
- if (isLocal) {
486
- // Example with cluster size of 3:
487
- // Ids generated so far: -1 1 2 -4 -5 <-- note positive numbers are eager finals
488
- // Cluster: [ 0 1 2 ]
489
- // ~ finalizing happens, causing expansion of 2 (overflow) + 3 (cluster capacity) ~
490
- // Cluster: [ 0 1 2 3 4 _ _ _ ]
491
- // corresponding locals: -1 -4 -5
492
- // lastFinalizedLocalId^ ^newLastFinalizedLocalId = -5
493
- // overflow = 2: ----
494
- // localIdPivot^
495
- // lastFinalizedFinal^
496
- const newLastFinalizedFinal = (currentBaseFinalId +
497
- currentCluster.count -
498
- 1) as FinalCompressedId;
499
- assert(
500
- session.lastFinalizedLocalId !== undefined,
501
- 0x48c /* Cluster already exists for session but there is no finalized local ID */,
502
- );
503
- const finalPivot = (newLastFinalizedFinal -
504
- overflow +
505
- 1) as FinalCompressedId;
506
- // Inform the normalizer of all IDs that we now know will end up being finalized into this cluster, including the ones
507
- // that were given out as locals (non-eager) because they exceeded the bounds of the current cluster before it was expanded.
508
- // It is safe to associate the unfinalized locals with their future final IDs even before the ranges for those locals are
509
- // actually finalized, because total order broadcast guarantees that any usage of those final IDs will be observed after
510
- // the finalization of the ranges.
511
- this.sessionIdNormalizer.registerFinalIdBlock(
512
- finalPivot,
513
- expansionAmount,
514
- currentCluster,
515
- );
516
- this.logger?.sendTelemetryEvent({
517
- eventName: "RuntimeIdCompressor:ClusterExpansion",
518
- sessionId: this.localSessionId,
519
- previousCapacity,
520
- newCapacity: currentCluster.capacity,
521
- overflow,
522
- });
523
- }
524
- }
525
- } else {
526
- // The range cannot be fully allocated in the existing cluster, so allocate any space left in it and
527
- // form a new one by incrementing the previous baseUuid
528
- newBaseUuid = incrementUuid(currentCluster.baseUuid, currentCluster.capacity);
529
- currentCluster.count += remainingCapacity;
530
- remainingCount -= remainingCapacity;
531
- this.logger?.sendTelemetryEvent({
532
- eventName: "RuntimeIdCompressor:OverfilledCluster",
533
- sessionId: this.localSessionId,
534
- });
222
+ assert(range.ids.count > 0, 0x755 /* Malformed ID Range. */);
223
+ const { sessionId, ids } = range;
224
+ const { count, firstGenCount } = ids;
225
+ const session = this.sessions.getOrCreate(sessionId);
226
+ const isLocal = session === this.localSession;
227
+ const rangeBaseLocal = localIdFromGenCount(firstGenCount);
228
+ let lastCluster = session.getLastCluster();
229
+ if (lastCluster === undefined) {
230
+ // This is the first cluster in the session space
231
+ if (rangeBaseLocal !== -1) {
232
+ throw new Error("Ranges finalized out of order.");
535
233
  }
536
- } else {
537
- // Session has never made a cluster, form a new one with the session UUID as the baseUuid
538
- newBaseUuid = session.sessionUuid;
234
+ lastCluster = this.addEmptyCluster(session, this.clusterCapacity + count);
539
235
  if (isLocal) {
540
236
  this.logger?.sendTelemetryEvent({
541
237
  eventName: "RuntimeIdCompressor:FirstCluster",
@@ -544,177 +240,44 @@ export class IdCompressor implements IIdCompressorCore, IIdCompressor {
544
240
  }
545
241
  }
546
242
 
547
- // Finalizing a range results in one of three cases:
548
- // 1. All local IDs are finalized into a new cluster (because there was either never a cluster for that session, or the current
549
- // cluster for the session was full).
550
- // 2. All local IDs are finalized into the existing (current) cluster for the session.
551
- // 3. Local IDs are finalized into both the current cluster and a new one, as the current cluster did not have enough room.
552
- let newCluster: IdCluster | undefined;
553
- let newBaseFinalId: FinalCompressedId | undefined;
554
- // The first local ID that will be finalized into a new cluster, if there is one.
555
- // This lets us quickly compare which cluster an override string will go into.
556
- let localIdPivot: LocalCompressedId | undefined;
557
-
558
- // Need to make a new cluster
559
- if (newBaseUuid !== undefined) {
560
- if (remainingCount <= 0) {
561
- fail("Should not create an empty cluster.");
562
- }
563
- if (currentCluster !== undefined && currentCluster.capacity !== currentCluster.count) {
564
- fail("Cluster must be filled before another is allocated.");
565
- }
566
-
567
- newBaseFinalId = this.nextClusterBaseFinalId;
568
- const newCapacity = Math.max(this.newClusterCapacity, remainingCount);
569
- newCluster = {
570
- baseUuid: newBaseUuid,
571
- capacity: newCapacity,
572
- count: remainingCount,
573
- session,
574
- };
575
-
576
- const usedCapacity = finalizeCount - remainingCount;
577
- localIdPivot = (newFirstFinalizedLocal - usedCapacity) as LocalCompressedId;
578
-
579
- if (isLocal) {
580
- this.logger?.sendTelemetryEvent({
581
- eventName: "RuntimeIdCompressor:NewCluster",
582
- sessionId: this.localSessionId,
583
- clusterCapacity: newCapacity,
584
- clusterCount: remainingCount,
585
- });
586
- this.sessionIdNormalizer.registerFinalIdBlock(
587
- newBaseFinalId,
588
- newCluster.capacity,
589
- newCluster,
590
- );
591
- }
592
-
593
- this.checkClusterForCollision(newCluster);
594
- this.clustersAndOverridesInversion.set(stableIdFromNumericUuid(newCluster.baseUuid), {
595
- clusterBase: newBaseFinalId,
596
- cluster: newCluster,
597
- });
598
- session.currentClusterDetails = { cluster: newCluster, clusterBase: newBaseFinalId };
599
- this.nextClusterBaseFinalId = (this.nextClusterBaseFinalId +
600
- newCluster.capacity) as FinalCompressedId;
601
- assert(
602
- this.nextClusterBaseFinalId < Number.MAX_SAFE_INTEGER,
603
- 0x48e /* The number of allocated final IDs must not exceed the JS maximum safe integer. */,
604
- );
605
- this.finalIdToCluster.append(newBaseFinalId, newCluster);
243
+ const remainingCapacity = lastCluster.capacity - lastCluster.count;
244
+ if (lastCluster.baseLocalId - lastCluster.count !== rangeBaseLocal) {
245
+ throw new Error("Ranges finalized out of order.");
606
246
  }
607
247
 
608
- // If there are overrides, we must determine which cluster object (current or overflow) each belongs to and add it.
609
- const overrides = ids.overrides;
610
- if (overrides !== undefined) {
611
- for (let i = 0; i < overrides.length; i++) {
612
- const [overriddenLocal, override] = overrides[i];
613
- // Note: recall that local IDs are negative
614
- assert(
615
- i === 0 || overriddenLocal < overrides[i - 1][0],
616
- 0x48f /* Override IDs must be in sorted order. */,
617
- );
618
- assert(
619
- overriddenLocal < normalizedLastFinalizedLocal,
620
- 0x490 /* Ranges finalized out of order. */,
621
- );
622
- assert(
623
- overriddenLocal >= newLastFinalizedLocal,
624
- 0x491 /* Malformed range: override ID ahead of range start. */,
625
- );
626
- let cluster: IdCluster;
627
- let overriddenFinal: FinalCompressedId;
628
- if (localIdPivot !== undefined && overriddenLocal <= localIdPivot) {
629
- // Override is at or past the pivot, so it is in a new cluster.
630
- assert(
631
- newCluster !== undefined && newBaseFinalId !== undefined,
632
- 0x492 /* No cluster was created when overflow occurred. */,
633
- );
634
- cluster = newCluster;
635
- overriddenFinal = (newBaseFinalId +
636
- (localIdPivot - overriddenLocal)) as FinalCompressedId;
637
- } else {
638
- // Override was finalized into an existing cluster
639
- assert(
640
- currentCluster !== undefined && currentBaseFinalId !== undefined,
641
- 0x493 /* No cluster exists but IDs were finalized. */,
642
- );
643
- cluster = currentCluster;
644
- overriddenFinal = (currentBaseFinalId +
645
- initialClusterCount +
646
- (normalizedLastFinalizedLocal - overriddenLocal) -
647
- 1) as FinalCompressedId;
648
- }
649
- cluster.overrides ??= new Map();
650
-
651
- const inversionKey = IdCompressor.createInversionKey(override);
652
- const existingIds = this.getExistingIdsForNewOverride(inversionKey, true);
653
- let overrideForCluster: string | FinalCompressedId;
654
- let associatedLocal: LocalCompressedId | undefined;
655
- if (existingIds !== undefined) {
656
- let mostFinalExistingOverride: CompressedId;
657
- if (typeof existingIds === "number") {
658
- mostFinalExistingOverride = existingIds;
659
- if (isLocalId(mostFinalExistingOverride)) {
660
- associatedLocal = mostFinalExistingOverride;
661
- }
662
- } else {
663
- [associatedLocal, mostFinalExistingOverride] = existingIds;
664
- }
665
- if (isFinalId(mostFinalExistingOverride)) {
666
- // A previous range already finalized an ID with this override. See `IdCluster` for more.
667
- overrideForCluster = mostFinalExistingOverride;
668
- } else {
669
- assert(
670
- !isLocal || mostFinalExistingOverride === overriddenLocal,
671
- 0x494 /* Cannot have multiple local IDs with identical overrides. */,
672
- );
673
- // This session has created an ID with this override before, but has not finalized it yet. The incoming
674
- // range "wins" and will contain the final ID associated with that override, regardless of if that range was
675
- // made by this session or not.
676
- overrideForCluster = override;
677
- }
678
- } else {
679
- // This is the first time this override has been associated with any ID
680
- overrideForCluster = override;
681
- }
682
-
248
+ if (remainingCapacity >= count) {
249
+ // The current range fits in the existing cluster
250
+ lastCluster.count += count;
251
+ } else {
252
+ const overflow = count - remainingCapacity;
253
+ const newClaimedFinalCount = overflow + this.clusterCapacity;
254
+ if (lastCluster === this.finalSpace.getLastCluster()) {
255
+ // The last cluster in the sessions chain is the last cluster globally, so it can be expanded.
256
+ lastCluster.capacity += newClaimedFinalCount;
257
+ lastCluster.count += count;
683
258
  assert(
684
- !cluster.overrides.has(overriddenFinal),
685
- 0x495 /* Cannot add a second override for final id */,
259
+ !this.sessions.clusterCollides(lastCluster),
260
+ 0x756 /* Cluster collision detected. */,
686
261
  );
687
- if (typeof overrideForCluster === "string") {
688
- if (isLocal || associatedLocal === undefined) {
689
- cluster.overrides.set(overriddenFinal, override);
690
- } else {
691
- cluster.overrides.set(overriddenFinal, {
692
- override,
693
- originalOverridingFinal: overriddenFinal,
694
- associatedLocalId: associatedLocal,
695
- });
696
- }
697
- } else {
698
- const unifiedOverride: UnifiedOverride = {
699
- override,
700
- originalOverridingFinal: overrideForCluster,
701
- };
702
- setPropertyIfDefined(associatedLocal, unifiedOverride, "associatedLocalId");
703
- cluster.overrides.set(overriddenFinal, unifiedOverride);
262
+ if (isLocal) {
263
+ this.logger?.sendTelemetryEvent({
264
+ eventName: "RuntimeIdCompressor:ClusterExpansion",
265
+ sessionId: this.localSessionId,
266
+ previousCapacity: lastCluster.capacity - newClaimedFinalCount,
267
+ newCapacity: lastCluster.capacity,
268
+ overflow,
269
+ });
704
270
  }
705
- const finalizedOverride: Mutable<FinalizedOverride> = {
706
- cluster,
707
- originalOverridingFinal: overriddenFinal,
708
- };
709
- setPropertyIfDefined(associatedLocal, finalizedOverride, "associatedLocalId");
710
- const currentOverride = this.clustersAndOverridesInversion.get(inversionKey);
711
- if (
712
- currentOverride === undefined ||
713
- IdCompressor.isUnfinalizedOverride(currentOverride)
714
- ) {
715
- // Update the map to contain a finalized override, but never update it with future finalized overrides with
716
- // the same string; those should decompress to the first final ID with that override.
717
- this.clustersAndOverridesInversion.set(inversionKey, finalizedOverride);
271
+ } else {
272
+ // The last cluster in the sessions chain is *not* the last cluster globally. Fill and overflow to new.
273
+ lastCluster.count = lastCluster.capacity;
274
+ const newCluster = this.addEmptyCluster(session, newClaimedFinalCount);
275
+ newCluster.count += overflow;
276
+ if (isLocal) {
277
+ this.logger?.sendTelemetryEvent({
278
+ eventName: "RuntimeIdCompressor:NewCluster",
279
+ sessionId: this.localSessionId,
280
+ });
718
281
  }
719
282
  }
720
283
  }
@@ -722,1133 +285,346 @@ export class IdCompressor implements IIdCompressorCore, IIdCompressor {
722
285
  if (isLocal) {
723
286
  this.logger?.sendTelemetryEvent({
724
287
  eventName: "RuntimeIdCompressor:IdCompressorStatus",
725
- eagerFinalIdCount: eagerFinalIdCount - (overrides?.length ?? 0),
726
- localIdCount: remainingCount + (overrides?.length ?? 0),
727
- overridesCount: overrides?.length ?? 0,
288
+ eagerFinalIdCount: this.telemetryEagerFinalIdCount,
289
+ localIdCount: this.telemetryLocalIdCount,
728
290
  sessionId: this.localSessionId,
729
291
  });
292
+ this.telemetryEagerFinalIdCount = 0;
293
+ this.telemetryLocalIdCount = 0;
730
294
  }
731
295
 
732
- session.lastFinalizedLocalId = newLastFinalizedLocal;
733
- }
734
-
735
- private checkClusterForCollision(cluster: IdCluster): void {
736
- const maxClusterUuid = incrementUuid(cluster.baseUuid, cluster.capacity - 1);
737
- const maxClusterStableId = stableIdFromNumericUuid(maxClusterUuid);
738
- const closestMatch =
739
- this.clustersAndOverridesInversion.getPairOrNextLower(maxClusterStableId);
740
- if (closestMatch !== undefined) {
741
- const [inversionKey, compressionMapping] = closestMatch;
742
- if (!IdCompressor.isClusterInfo(compressionMapping)) {
743
- if (
744
- isStableId(inversionKey) &&
745
- IdCompressor.uuidsMightCollide(
746
- inversionKey,
747
- maxClusterStableId,
748
- cluster.capacity,
749
- )
750
- ) {
751
- const numericOverride = numericUuidFromStableId(inversionKey);
752
- const delta = getPositiveDelta(
753
- maxClusterUuid,
754
- numericOverride,
755
- cluster.capacity - 1,
756
- );
757
- if (delta !== undefined) {
758
- IdCompressor.failWithCollidingOverride(inversionKey);
759
- }
760
- }
761
- }
762
- }
763
- }
764
-
765
- private static failWithCollidingOverride(override: string): void {
766
- fail(`Override '${override}' collides with another allocated UUID.`);
767
- }
768
-
769
- private static isClusterInfo(
770
- compressionMapping: CompressionMapping,
771
- ): compressionMapping is ClusterInfo {
772
- return (compressionMapping as ClusterInfo).clusterBase !== undefined;
773
- }
774
-
775
- private static isUnfinalizedOverride(
776
- compressionMapping: CompressionMapping,
777
- ): compressionMapping is UnackedLocalId {
778
- return typeof compressionMapping === "number";
779
- }
780
-
781
- private static createInversionKey(inversionKey: string): InversionKey {
782
- return isStableId(inversionKey)
783
- ? inversionKey
784
- : `${nonStableOverridePrefix}${inversionKey}`;
296
+ assert(!session.isEmpty(), 0x757 /* Empty sessions should not be created. */);
785
297
  }
786
298
 
787
- private static isStableInversionKey(inversionKey: InversionKey): inversionKey is StableId {
788
- return inversionKey.charAt(0) !== nonStableOverridePrefix;
789
- }
790
-
791
- /**
792
- * Returns an existing ID associated with an override, or undefined if none exists.
793
- */
794
- private getExistingIdsForNewOverride(
795
- inversionKey: InversionKey,
796
- isFinalOverride: boolean,
797
- ): SessionSpaceCompressedId | [LocalCompressedId, FinalCompressedId] | undefined {
798
- const closestMatch = this.clustersAndOverridesInversion.getPairOrNextLower(
799
- inversionKey,
800
- reusedArray,
299
+ private addEmptyCluster(session: Session, capacity: number): IdCluster {
300
+ const newCluster = session.addNewCluster(
301
+ this.finalSpace.getAllocatedIdLimit(),
302
+ capacity,
303
+ 0,
801
304
  );
802
- let numericOverride: NumericUuid | undefined;
803
- let stableOverride: StableId | undefined;
804
- if (closestMatch !== undefined) {
805
- const [key, compressionMapping] = closestMatch;
806
- if (!IdCompressor.isClusterInfo(compressionMapping)) {
807
- if (key === inversionKey) {
808
- if (IdCompressor.isUnfinalizedOverride(compressionMapping)) {
809
- return compressionMapping;
810
- }
811
- const finalizedOverride = compressionMapping;
812
- return finalizedOverride.associatedLocalId !== undefined
813
- ? [
814
- finalizedOverride.associatedLocalId,
815
- finalizedOverride.originalOverridingFinal,
816
- ]
817
- : (finalizedOverride.originalOverridingFinal as SessionSpaceCompressedId);
818
- }
819
- } else if (IdCompressor.isStableInversionKey(inversionKey)) {
820
- stableOverride = inversionKey;
821
- const cluster = compressionMapping.cluster;
822
- if (
823
- IdCompressor.uuidsMightCollide(inversionKey, key as StableId, cluster.capacity)
824
- ) {
825
- numericOverride = numericUuidFromStableId(stableOverride);
826
- const delta = getPositiveDelta(
827
- numericOverride,
828
- cluster.baseUuid,
829
- cluster.capacity - 1,
830
- );
831
- if (delta !== undefined) {
832
- if (!isFinalOverride) {
833
- if (delta >= cluster.count) {
834
- // TODO:#283: Properly implement unification
835
- return undefined;
836
- }
837
- return this.normalizeToSessionSpace(
838
- (compressionMapping.clusterBase + delta) as FinalCompressedId,
839
- );
840
- }
841
- }
842
- }
843
- }
844
- }
845
-
846
- const override =
847
- numericOverride ??
848
- stableOverride ??
849
- (IdCompressor.isStableInversionKey(inversionKey) ? inversionKey : undefined);
850
-
851
- if (override !== undefined) {
852
- const sessionSpaceId = this.getCompressedIdForStableId(override);
853
- if (sessionSpaceId !== undefined) {
854
- return sessionSpaceId;
855
- }
856
- }
857
-
858
- return undefined;
305
+ assert(!this.sessions.clusterCollides(newCluster), 0x758 /* Cluster collision detected. */);
306
+ this.finalSpace.addCluster(newCluster);
307
+ return newCluster;
859
308
  }
860
309
 
861
- /**
862
- * Check if `a` might be within `range` of `b`, where both are treated as hex numbers.
863
- * @param range - an integer
864
- */
865
- private static uuidsMightCollide(a: StableId, b: StableId, range: number): boolean {
866
- // Check if any of the UUIDs in the cluster collide (i.e. any in [base, base + capacity)).
867
- // Optimization: All UUIDs in a cluster are the same string up until the last few characters which encode the offset from
868
- // the cluster base. So, first compute the length of that shared string, and early out if it is different from the override
869
- // UUID. This way we usually need not do the more expensive check below.
870
- const hexDigitsToCheck = 32 - Math.ceil(Math.log2(range) / 2);
871
- if (a.startsWith(b.slice(0, hexDigitsToCheck))) {
872
- return true;
873
- }
874
-
875
- return false;
876
- }
877
-
878
- /**
879
- * Helper for retrieving an override.
880
- */
881
- private static tryGetOverride(
882
- cluster: IdCluster,
883
- finalId: FinalCompressedId,
884
- ): string | undefined {
885
- const override = cluster.overrides?.get(finalId);
886
- if (override === undefined) {
887
- return undefined;
888
- }
889
- if (typeof override === "string") {
890
- return override;
891
- }
892
- return override.override;
893
- }
894
-
895
- /**
896
- * Generates a new compressed ID or returns an existing one.
897
- * This should ONLY be called to generate IDs for local operations.
898
- * @param override - Specifies a specific string to be associated with the returned compressed ID.
899
- * Performance note: assigning override strings incurs a performance overhead.
900
- * @returns an existing ID if one already exists for `override`, and a new local ID otherwise. The returned ID is in session space.
901
- */
902
- public generateCompressedId(override?: string): SessionSpaceCompressedId {
903
- let overrideInversionKey: InversionKey | undefined;
904
- if (override !== undefined) {
905
- overrideInversionKey = IdCompressor.createInversionKey(override);
906
- const existingIds = this.getExistingIdsForNewOverride(overrideInversionKey, false);
907
- if (existingIds !== undefined) {
908
- return typeof existingIds === "number" ? existingIds : existingIds[0];
909
- }
910
- }
911
-
912
- // Bump local counter regardless, then attempt to optimistically return a final ID.
913
- // If the local session has reserved a cluster range via consensus, it is safe to hand out final IDs prior to
914
- // finalizing the range that includes these locals.
915
- const newLocalId = -++this.localIdCount as LocalCompressedId;
916
- const { currentClusterDetails } = this.localSession;
917
- const { sessionIdNormalizer } = this;
918
- let eagerFinalId: (FinalCompressedId & SessionSpaceCompressedId) | undefined;
919
- let cluster: IdCluster | undefined;
920
- if (currentClusterDetails !== undefined) {
921
- cluster = currentClusterDetails.cluster;
922
- const lastFinalKnown = sessionIdNormalizer.getLastFinalId();
923
- if (
924
- lastFinalKnown !== undefined &&
925
- lastFinalKnown - currentClusterDetails.clusterBase + 1 < cluster.capacity
926
- ) {
927
- eagerFinalId = (lastFinalKnown + 1) as FinalCompressedId & SessionSpaceCompressedId;
928
- }
929
- }
930
-
931
- if (overrideInversionKey !== undefined) {
932
- const registeredLocal = sessionIdNormalizer.addLocalId();
933
- assert(
934
- registeredLocal === newLocalId,
935
- 0x496 /* Session ID Normalizer produced unexpected local ID */,
936
- );
937
- if (eagerFinalId !== undefined) {
938
- sessionIdNormalizer.addFinalIds(
939
- eagerFinalId,
940
- eagerFinalId,
941
- cluster ?? fail("No cluster when generating compressed ID"),
942
- );
943
- }
944
- this.localOverrides.append(newLocalId, override ?? fail("Override must be defined"));
945
- // Since the local ID was just created, it is in both session and op space
946
- const compressionMapping = newLocalId as UnackedLocalId;
947
- this.clustersAndOverridesInversion.set(overrideInversionKey, compressionMapping);
948
- } else if (eagerFinalId !== undefined) {
949
- sessionIdNormalizer.addFinalIds(
950
- eagerFinalId,
951
- eagerFinalId,
952
- cluster ?? fail("No cluster when generating compressed ID"),
953
- );
954
- return eagerFinalId;
310
+ public normalizeToOpSpace(id: SessionSpaceCompressedId): OpSpaceCompressedId {
311
+ if (isFinalId(id)) {
312
+ return id;
955
313
  } else {
956
- const registeredLocal = sessionIdNormalizer.addLocalId();
957
- assert(
958
- registeredLocal === newLocalId,
959
- 0x497 /* Session ID Normalizer produced unexpected local ID */,
960
- );
314
+ const local = id as unknown as LocalCompressedId;
315
+ if (!this.normalizer.contains(local)) {
316
+ throw new Error("Invalid ID to normalize.");
317
+ }
318
+ const finalForm = this.localSession.tryConvertToFinal(local, true);
319
+ return finalForm === undefined
320
+ ? (local as unknown as OpSpaceCompressedId)
321
+ : (finalForm as OpSpaceCompressedId);
961
322
  }
962
-
963
- return newLocalId;
964
- }
965
-
966
- /**
967
- * Decompresses a previously compressed ID into a UUID or override string.
968
- * @param id - the compressed ID to be decompressed.
969
- * @returns the UUID or override string associated with the compressed ID. Fails if the ID was not generated by this compressor.
970
- */
971
- public decompress(id: SessionSpaceCompressedId | FinalCompressedId): StableId | string {
972
- return this.tryDecompress(id) ?? fail("Compressed ID was not generated by this compressor");
973
323
  }
974
324
 
975
- /**
976
- * Attempts to decompress a previously compressed ID into a UUID or override string.
977
- * @param id - the compressed ID to be decompressed.
978
- * @returns the UUID or override string associated with the compressed ID, or undefined if the ID was not generated by this compressor.
979
- */
980
- public tryDecompress(
981
- id: SessionSpaceCompressedId | FinalCompressedId,
982
- ): StableId | string | undefined {
325
+ public normalizeToSessionSpace(
326
+ id: OpSpaceCompressedId,
327
+ originSessionId: SessionId,
328
+ ): SessionSpaceCompressedId {
983
329
  if (isFinalId(id)) {
984
- const possibleCluster = this.getClusterForFinalId(id);
985
- if (possibleCluster === undefined) {
986
- // It may be an unfinalized eager final ID, so check with normalizer to get the offset from the session UUID
987
- const creationIndex = this.sessionIdNormalizer.getCreationIndex(id);
988
- if (creationIndex !== undefined) {
989
- return stableIdFromNumericUuid(this.localSession.sessionUuid, creationIndex);
330
+ const containingCluster = this.localSession.getClusterByAllocatedFinal(id);
331
+ if (containingCluster === undefined) {
332
+ // Does not exist in local cluster chain
333
+ if (id >= this.finalSpace.getFinalizedIdLimit()) {
334
+ throw new Error("Unknown op space ID.");
990
335
  }
991
- return undefined;
336
+ return id as unknown as SessionSpaceCompressedId;
992
337
  } else {
993
- const [baseFinalId, cluster] = possibleCluster;
994
- const override = IdCompressor.tryGetOverride(cluster, id);
995
- if (override !== undefined) {
996
- return override;
338
+ const alignedLocal = getAlignedLocal(containingCluster, id);
339
+ if (this.normalizer.contains(alignedLocal)) {
340
+ return alignedLocal;
997
341
  } else {
998
- const offsetInCluster = id - baseFinalId;
999
- return stableIdFromNumericUuid(cluster.baseUuid, offsetInCluster);
342
+ if (genCountFromLocalId(alignedLocal) > this.localGenCount) {
343
+ throw new Error("Unknown op space ID.");
344
+ }
345
+ return id as unknown as SessionSpaceCompressedId;
1000
346
  }
1001
347
  }
1002
348
  } else {
1003
- const idOffset = -id; // Convert to a positive number
1004
- if (idOffset > this.localIdCount) {
1005
- // This local ID was never allocated.
1006
- return undefined;
1007
- }
1008
-
1009
- // If this is a local ID with an override, then it must have been allocated on this machine and will be contained in
1010
- // `localOverrides`s. Otherwise, it is a sequential allocation from the session UUID and can simply be negated and
1011
- // added to that UUID to obtain the stable ID associated with it.
1012
- const localOverride = this.localOverrides?.get(id);
1013
- return localOverride !== undefined
1014
- ? localOverride
1015
- : stableIdFromNumericUuid(this.localSession.sessionUuid, idOffset - 1);
1016
- }
1017
- }
1018
-
1019
- /**
1020
- * Recompresses a decompressed ID, which could be a UUID or an override string.
1021
- * @param uncompressed - the UUID or override string to recompress.
1022
- * @returns the `CompressedId` associated with `uncompressed`. Fails if it has not been previously compressed by this compressor.
1023
- */
1024
- public recompress(uncompressed: string): SessionSpaceCompressedId {
1025
- return this.tryRecompress(uncompressed) ?? fail("No such string has ever been compressed");
1026
- }
1027
-
1028
- /**
1029
- * Attempts to recompresses a decompressed ID, which could be a UUID or an override string.
1030
- * @param uncompressed - the UUID or override string to recompress,
1031
- * @returns the `CompressedId` associated with `uncompressed` or undefined if it has not been previously compressed by this compressor.
1032
- */
1033
- public tryRecompress(uncompressed: string): SessionSpaceCompressedId | undefined {
1034
- return this.recompressInternal(uncompressed);
1035
- }
1036
-
1037
- /**
1038
- * Helper to compress an uncompressed UUID. It can optionally be supplied with the numeric form of `uncompressedUuid` as a
1039
- * performance optimization.
1040
- */
1041
- private recompressInternal(
1042
- uncompressed: string,
1043
- uncompressedUuidNumeric?: NumericUuid,
1044
- ): SessionSpaceCompressedId | undefined {
1045
- let numericUuid = uncompressedUuidNumeric;
1046
- const inversionKey = IdCompressor.createInversionKey(uncompressed);
1047
- const isStable = IdCompressor.isStableInversionKey(inversionKey);
1048
- const closestMatch = this.clustersAndOverridesInversion.getPairOrNextLower(
1049
- inversionKey,
1050
- reusedArray,
1051
- );
1052
- if (closestMatch !== undefined) {
1053
- const [key, compressionMapping] = closestMatch;
1054
- if (!IdCompressor.isClusterInfo(compressionMapping)) {
1055
- if (key === inversionKey) {
1056
- return IdCompressor.isUnfinalizedOverride(compressionMapping)
1057
- ? compressionMapping
1058
- : compressionMapping.associatedLocalId ??
1059
- (compressionMapping.originalOverridingFinal as SessionSpaceCompressedId);
349
+ const localToNormalize = id as unknown as LocalCompressedId;
350
+ if (originSessionId === this.localSessionId) {
351
+ if (this.normalizer.contains(localToNormalize)) {
352
+ return localToNormalize;
353
+ } else {
354
+ // We never generated this local ID, so fail
355
+ throw new Error("Unknown op space ID.");
1060
356
  }
1061
357
  } else {
1062
- if (!isStable) {
1063
- return undefined;
358
+ // LocalId from a remote session
359
+ const remoteSession = this.sessions.get(originSessionId);
360
+ if (remoteSession === undefined) {
361
+ throw new Error("No IDs have ever been finalized by the supplied session.");
1064
362
  }
1065
- const { clusterBase: closestBaseFinalId, cluster: closestCluster } =
1066
- compressionMapping;
1067
- numericUuid ??= numericUuidFromStableId(inversionKey);
1068
- const uuidOffset = getPositiveDelta(
1069
- numericUuid,
1070
- closestCluster.baseUuid,
1071
- closestCluster.count - 1,
1072
- );
1073
- if (uuidOffset !== undefined) {
1074
- let targetFinalId = (closestBaseFinalId + uuidOffset) as FinalCompressedId;
1075
- const override = closestCluster.overrides?.get(targetFinalId);
1076
- if (typeof override === "object") {
1077
- if (override.associatedLocalId !== undefined) {
1078
- return override.associatedLocalId;
1079
- }
1080
- // This may be a UUID that should actually compress into a different final ID that it aligns with, due to
1081
- // another session having an identical override (see `IdCluster` for more).
1082
- targetFinalId = override.originalOverridingFinal;
1083
- }
1084
- return this.normalizeToSessionSpace(targetFinalId);
363
+ const correspondingFinal = remoteSession.tryConvertToFinal(localToNormalize, false);
364
+ if (correspondingFinal === undefined) {
365
+ throw new Error("Unknown op space ID.");
1085
366
  }
367
+ return correspondingFinal as unknown as SessionSpaceCompressedId;
1086
368
  }
1087
369
  }
1088
-
1089
- if (isStable) {
1090
- // May have already computed the numeric UUID, so avoid recomputing if possible
1091
- const sessionSpaceId = this.getCompressedIdForStableId(numericUuid ?? inversionKey);
1092
- if (sessionSpaceId !== undefined) {
1093
- return sessionSpaceId;
1094
- }
1095
- }
1096
- return undefined;
1097
370
  }
1098
371
 
1099
- /**
1100
- * Normalizes a session space ID into op space.
1101
- * @param id - the local ID to normalize.
1102
- * @returns the ID in op space.
1103
- */
1104
- public normalizeToOpSpace(id: SessionSpaceCompressedId): OpSpaceCompressedId {
372
+ public decompress(id: SessionSpaceCompressedId): StableId {
1105
373
  if (isFinalId(id)) {
1106
- return id;
1107
- }
1108
-
1109
- // Check if this local ID has not been allocated yet
1110
- if (-id > this.localIdCount) {
1111
- fail("Supplied local ID was not created by this compressor.");
1112
- }
1113
-
1114
- // Check if this local ID has not been finalized yet.
1115
- // Comparing lastFinalizedLocalId is a safe check for eager final IDs because the local IDs corresponding to them
1116
- // are never handed out to a consumer, and thus could not be passed into this method.
1117
- const { lastFinalizedLocalId } = this.localSession;
1118
- if (lastFinalizedLocalId === undefined || id < lastFinalizedLocalId) {
1119
- // Eager final IDs do not have overrides in the cluster until finalizing
1120
- // This means that using the normalizer to get the final/cluster associated would succeed but would not have the override,
1121
- // so checking localOverrides first is necessary.
1122
- const override = this.localOverrides.get(id);
1123
- if (override !== undefined) {
1124
- const inversionKey = IdCompressor.createInversionKey(override);
1125
- const compressionMapping =
1126
- this.clustersAndOverridesInversion.get(inversionKey) ??
1127
- fail("Bimap is malformed.");
1128
- return !IdCompressor.isClusterInfo(compressionMapping) &&
1129
- !IdCompressor.isUnfinalizedOverride(compressionMapping) &&
1130
- compressionMapping.associatedLocalId === id
1131
- ? compressionMapping.originalOverridingFinal
1132
- : (id as OpSpaceCompressedId);
1133
- }
1134
- const possibleFinal = this.sessionIdNormalizer.getFinalId(id);
1135
- return possibleFinal?.[0] ?? (id as OpSpaceCompressedId);
1136
- }
1137
- const [correspondingFinal, cluster] =
1138
- this.sessionIdNormalizer.getFinalId(id) ??
1139
- fail("Locally created cluster should be added to the map when allocated");
1140
- if (cluster.overrides) {
1141
- const override = cluster.overrides.get(correspondingFinal);
1142
- if (typeof override === "object" && override.originalOverridingFinal !== undefined) {
1143
- // Rare case of two local IDs with same overrides are created concurrently. See `IdCluster` for more.
1144
- return override.originalOverridingFinal;
1145
- }
1146
- }
1147
- return correspondingFinal;
1148
- }
1149
-
1150
- /**
1151
- * Normalizes an ID into session space.
1152
- * @param id - the ID to normalize. If it is a local ID, it is assumed to have been created by the session corresponding
1153
- * to `sessionId`.
1154
- * @param originSessionId - the session from which `id` originated
1155
- * @returns the session-space ID corresponding to `id`, which might not have been a final ID if the client that created it had not yet
1156
- * finalized it. This can occur when a client references an ID during the window of time in which it is waiting to receive the ordered
1157
- * range that contained it from the server.
1158
- */
1159
- public normalizeToSessionSpace(
1160
- id: OpSpaceCompressedId,
1161
- originSessionId: SessionId,
1162
- ): SessionSpaceCompressedId;
1163
-
1164
- /**
1165
- * Normalizes a final ID into session space.
1166
- * @param id - the final ID to normalize.
1167
- * @returns the session-space ID corresponding to `id`.
1168
- */
1169
- public normalizeToSessionSpace(id: FinalCompressedId): SessionSpaceCompressedId;
1170
-
1171
- public normalizeToSessionSpace(
1172
- id: OpSpaceCompressedId,
1173
- sessionIdIfLocal?: SessionId,
1174
- ): SessionSpaceCompressedId {
1175
- if (isLocalId(id)) {
1176
- if (sessionIdIfLocal === undefined || sessionIdIfLocal === this.localSessionId) {
1177
- const localIndex = -id;
1178
- if (localIndex > this.localIdCount) {
1179
- fail("Supplied local ID was not created by this compressor.");
374
+ const containingCluster = Session.getContainingCluster(id, this.finalSpace.clusters);
375
+ if (containingCluster === undefined) {
376
+ throw new Error("Unknown ID");
377
+ }
378
+ const alignedLocal = getAlignedLocal(containingCluster, id);
379
+ const alignedGenCount = genCountFromLocalId(alignedLocal);
380
+ const lastFinalizedGenCount = genCountFromLocalId(
381
+ lastFinalizedLocal(containingCluster),
382
+ );
383
+ if (alignedGenCount > lastFinalizedGenCount) {
384
+ // should be an eager final id generated by the local session
385
+ if (containingCluster.session === this.localSession) {
386
+ assert(
387
+ !this.normalizer.contains(alignedLocal),
388
+ 0x759 /* Normalizer out of sync. */,
389
+ );
390
+ } else {
391
+ throw new Error("Unknown ID");
1180
392
  }
1181
- return id;
1182
- } else {
1183
- const session =
1184
- this.sessions.get(sessionIdIfLocal) ??
1185
- fail("No IDs have ever been finalized by the supplied session.");
1186
- const localCount = -id;
1187
- const numericUuid = incrementUuid(session.sessionUuid, localCount - 1);
1188
- return (
1189
- this.compressNumericUuid(numericUuid) ??
1190
- fail("ID is not known to this compressor.")
1191
- );
1192
393
  }
1193
- }
1194
-
1195
- const normalizedId = this.sessionIdNormalizer.getSessionSpaceId(id);
1196
- if (normalizedId !== undefined) {
1197
- return normalizedId;
1198
- }
1199
394
 
1200
- // Check for a unified override finalized first by another session but to which the local session
1201
- // still has an associated local ID.
1202
- const [_, cluster] =
1203
- this.getClusterForFinalId(id) ??
1204
- fail("Supplied final ID was not finalized by this compressor.");
1205
- const override = cluster.overrides?.get(id);
1206
- if (typeof override === "object" && override.associatedLocalId !== undefined) {
1207
- return override.associatedLocalId;
395
+ return stableIdFromNumericUuid(
396
+ offsetNumericUuid(containingCluster.session.sessionUuid, alignedGenCount - 1),
397
+ );
398
+ } else {
399
+ const localToDecompress = id as unknown as LocalCompressedId;
400
+ if (!this.normalizer.contains(localToDecompress)) {
401
+ throw new Error("Unknown ID");
402
+ }
403
+ return stableIdFromNumericUuid(
404
+ offsetNumericUuid(
405
+ this.localSession.sessionUuid,
406
+ genCountFromLocalId(localToDecompress) - 1,
407
+ ),
408
+ );
1208
409
  }
1209
- return id as SessionSpaceCompressedId;
1210
410
  }
1211
411
 
1212
- /**
1213
- * Returns the session-space compressed ID corresponding to the numeric UUID, or undefined if it is not known to this compressor.
1214
- * Typically, it will return the session-space ID sequentially aligned with it (which will be local if `numericUuid` was made by
1215
- * the local session, or final otherwise). However, in the event that the aligned session-space ID was overridden with a UUID
1216
- * *and* that override UUID was concurrently used in an older ID (earlier, w.r.t. sequencing), this method can return the first
1217
- * ID to correspond to that override.
1218
- *
1219
- * As an example, consider the following two clients:
1220
- * ClientA, session UUID: A0000000-0000-0000-0000-000000000000
1221
- * ClientB, session UUID: B0000000-0000-0000-0000-000000000000
1222
- *
1223
- * If concurrently, two clients performed:
1224
- * ClientA: generateCompressedId(override: 'X0000000-0000-0000-0000-000000000000') // aligned with A0000000-0000-0000-0000-000000000000
1225
- *
1226
- * ClientB: generateCompressedId() // aligned with B0000000-0000-0000-0000-000000000000
1227
- * ClientB: generateCompressedId(override: 'X0000000-0000-0000-0000-000000000000') // aligned with B0000000-0000-0000-0000-000000000001
1228
- *
1229
- * After sequencing, calling this method and passing the numeric UUID for B0000000-0000-0000-0000-000000000001 would return the
1230
- * session-space ID corresponding to A0000000-0000-0000-0000-000000000000 (with override X0000000-0000-0000-0000-000000000000).
1231
- */
1232
- private compressNumericUuid(numericUuid: NumericUuid): SessionSpaceCompressedId | undefined {
1233
- const stableId = stableIdFromNumericUuid(numericUuid);
1234
- const sessionSpaceId = this.recompressInternal(stableId, numericUuid);
1235
- if (sessionSpaceId === undefined) {
1236
- return undefined;
412
+ public recompress(uncompressed: StableId): SessionSpaceCompressedId {
413
+ const recompressed = this.tryRecompress(uncompressed);
414
+ if (recompressed === undefined) {
415
+ throw new Error("Could not recompress.");
1237
416
  }
1238
- return sessionSpaceId;
417
+ return recompressed;
1239
418
  }
1240
419
 
1241
- /**
1242
- * Returns a compressed ID for the supplied stable ID if it was created by the local session, and undefined otherwise.
1243
- */
1244
- private getCompressedIdForStableId(
1245
- stableId: StableId | NumericUuid,
1246
- ): SessionSpaceCompressedId | undefined {
1247
- const numericUuid =
1248
- typeof stableId === "string" ? numericUuidFromStableId(stableId) : stableId;
1249
- const creationIndex = getPositiveDelta(
1250
- numericUuid,
1251
- this.localSession.sessionUuid,
1252
- this.localIdCount - 1,
1253
- );
1254
- if (creationIndex !== undefined) {
1255
- const sessionSpaceId = this.sessionIdNormalizer.getIdByCreationIndex(creationIndex);
1256
- if (sessionSpaceId !== undefined) {
1257
- return sessionSpaceId;
420
+ public tryRecompress(uncompressed: StableId): SessionSpaceCompressedId | undefined {
421
+ const match = this.sessions.getContainingCluster(uncompressed);
422
+ if (match === undefined) {
423
+ const numericUncompressed = numericUuidFromStableId(uncompressed);
424
+ const offset = subtractNumericUuids(numericUncompressed, this.localSession.sessionUuid);
425
+ if (offset < Number.MAX_SAFE_INTEGER) {
426
+ const genCountEquivalent = Number(offset) + 1;
427
+ const localEquivalent = localIdFromGenCount(genCountEquivalent);
428
+ if (this.normalizer.contains(localEquivalent)) {
429
+ return localEquivalent;
430
+ }
1258
431
  }
1259
- }
1260
- return undefined;
1261
- }
1262
-
1263
- private getClusterForFinalId(
1264
- finalId: FinalCompressedId,
1265
- ): readonly [baseFinalId: FinalCompressedId, cluster: IdCluster] | undefined {
1266
- const possibleCluster = this.finalIdToCluster.getPairOrNextLower(finalId);
1267
- if (possibleCluster === undefined) {
1268
- return undefined;
1269
- }
1270
- const [clusterBase, cluster] = possibleCluster;
1271
- if (finalId - clusterBase >= cluster.count) {
1272
432
  return undefined;
1273
- }
1274
- return possibleCluster;
1275
- }
1276
-
1277
- /**
1278
- * @returns if `other` is equal to this `IdCompressor`. The equality check includes local session state only if specified.
1279
- * \@testOnly
1280
- */
1281
- public equals(other: IdCompressor, compareLocalState: boolean): boolean {
1282
- if (compareLocalState) {
1283
- if (
1284
- this.localIdCount !== other.localIdCount ||
1285
- this.localSessionId !== other.localSessionId ||
1286
- this.lastTakenLocalId !== other.lastTakenLocalId
1287
- ) {
1288
- return false;
1289
- }
1290
- if (!this.localOverrides.equals(other.localOverrides, (a, b) => a === b)) {
1291
- return false;
1292
- }
1293
- if (
1294
- !compareMaps(this.sessions, other.sessions, (a, b) =>
1295
- IdCompressor.sessionDataEqual(a, b, true, compareLocalState),
1296
- )
1297
- ) {
1298
- return false;
1299
- }
1300
- if (
1301
- !this.sessionIdNormalizer.equals(other.sessionIdNormalizer, (a, b) =>
1302
- IdCompressor.idClustersEqual(a, b, false, compareLocalState),
1303
- )
1304
- ) {
1305
- return false;
1306
- }
1307
433
  } else {
1308
- for (const [keyA, valueA] of this.sessions) {
1309
- const valueB = other.sessions.get(keyA);
1310
- if (valueB === undefined) {
1311
- if (valueA.lastFinalizedLocalId !== undefined) {
1312
- return false;
1313
- }
1314
- } else if (
1315
- !IdCompressor.sessionDataEqual(valueA, valueB, true, compareLocalState)
1316
- ) {
1317
- return false;
1318
- }
1319
- }
1320
-
1321
- for (const [keyB, valueB] of other.sessions) {
1322
- const valueA = this.sessions.get(keyB);
1323
- if (valueA === undefined) {
1324
- if (valueB.lastFinalizedLocalId !== undefined) {
1325
- return false;
1326
- }
1327
- }
1328
- }
1329
- }
1330
- if (
1331
- this.nextClusterBaseFinalId !== other.nextClusterBaseFinalId ||
1332
- this.newClusterCapacity !== other.newClusterCapacity
1333
- ) {
1334
- return false;
1335
- }
1336
- if (
1337
- !this.finalIdToCluster.equals(other.finalIdToCluster, (a, b) =>
1338
- IdCompressor.idClustersEqual(a, b, true, compareLocalState),
1339
- )
1340
- ) {
1341
- return false;
1342
- }
1343
-
1344
- const missingInOne = (
1345
- _: string,
1346
- value: CompressionMapping,
1347
- ): { break: boolean } | undefined => {
1348
- if (!compareLocalState && IdCompressor.isUnfinalizedOverride(value)) {
1349
- return undefined;
1350
- }
1351
- return { break: true };
1352
- };
1353
-
1354
- const compareCompressionMappings = (a: CompressionMapping, b: CompressionMapping) => {
1355
- const unfinalizedA = IdCompressor.isUnfinalizedOverride(a);
1356
- const unfinalizedB = IdCompressor.isUnfinalizedOverride(b);
1357
- if (unfinalizedA) {
1358
- if (unfinalizedB) {
1359
- return a === b;
1360
- }
1361
- return false;
1362
- } else if (unfinalizedB) {
1363
- return false;
1364
- }
1365
-
1366
- if (IdCompressor.isClusterInfo(a)) {
1367
- if (!IdCompressor.isClusterInfo(b) || a.clusterBase !== b.clusterBase) {
1368
- return false;
434
+ const [containingCluster, alignedLocal] = match;
435
+ if (containingCluster.session === this.localSession) {
436
+ // Local session
437
+ if (this.normalizer.contains(alignedLocal)) {
438
+ return alignedLocal;
439
+ } else {
440
+ assert(
441
+ genCountFromLocalId(alignedLocal) <= this.localGenCount,
442
+ 0x75a /* Clusters out of sync. */,
443
+ );
444
+ // Id is an eager final
445
+ return getAlignedFinal(containingCluster, alignedLocal) as
446
+ | SessionSpaceCompressedId
447
+ | undefined;
1369
448
  }
1370
449
  } else {
1371
- if (
1372
- IdCompressor.isClusterInfo(b) ||
1373
- (compareLocalState && a.associatedLocalId !== b.associatedLocalId) ||
1374
- a.originalOverridingFinal !== b.originalOverridingFinal
1375
- ) {
1376
- return false;
1377
- }
450
+ // Not the local session
451
+ return genCountFromLocalId(alignedLocal) >= lastFinalizedLocal(containingCluster)
452
+ ? (getAlignedFinal(containingCluster, alignedLocal) as
453
+ | SessionSpaceCompressedId
454
+ | undefined)
455
+ : undefined;
1378
456
  }
1379
- if (!IdCompressor.idClustersEqual(a.cluster, b.cluster, true, compareLocalState)) {
1380
- return false;
1381
- }
1382
- return true;
1383
- };
1384
-
1385
- const diff = this.clustersAndOverridesInversion.diffAgainst(
1386
- other.clustersAndOverridesInversion,
1387
- missingInOne,
1388
- missingInOne,
1389
- (_, valA, valB) => {
1390
- if (!compareCompressionMappings(valA, valB)) {
1391
- return { break: true };
1392
- }
1393
- return undefined;
1394
- },
1395
- );
1396
-
1397
- return diff === undefined;
1398
- }
1399
-
1400
- private static sessionDataEqual(
1401
- a: Session,
1402
- b: Session,
1403
- checkCluster = true,
1404
- compareLocalState = true,
1405
- ): boolean {
1406
- if (
1407
- !numericUuidEquals(a.sessionUuid, b.sessionUuid) ||
1408
- a.lastFinalizedLocalId !== b.lastFinalizedLocalId
1409
- ) {
1410
- return false;
1411
- }
1412
- if (a.currentClusterDetails === undefined || b.currentClusterDetails === undefined) {
1413
- if (a.currentClusterDetails !== b.currentClusterDetails) {
1414
- return false;
1415
- }
1416
- return true;
1417
- }
1418
- if (
1419
- checkCluster &&
1420
- !IdCompressor.idClustersEqual(
1421
- a.currentClusterDetails.cluster,
1422
- b.currentClusterDetails.cluster,
1423
- false,
1424
- compareLocalState,
1425
- )
1426
- ) {
1427
- return false;
1428
457
  }
1429
- return true;
1430
- }
1431
-
1432
- private static idClustersEqual(
1433
- a: IdCluster,
1434
- b: IdCluster,
1435
- checkSessionData = true,
1436
- compareLocalState = true,
1437
- ): boolean {
1438
- const areEqual =
1439
- numericUuidEquals(a.baseUuid, b.baseUuid) &&
1440
- a.capacity === b.capacity &&
1441
- a.count === b.count &&
1442
- (!checkSessionData ||
1443
- IdCompressor.sessionDataEqual(a.session, b.session, false, compareLocalState)) &&
1444
- (a.overrides === undefined) === (b.overrides === undefined) &&
1445
- (a.overrides === undefined ||
1446
- compareMaps(
1447
- a.overrides ?? fail("Overrides must be defined"),
1448
- b.overrides ?? fail("Overrides must be defined"),
1449
- (overrideA, overrideB) => {
1450
- if (compareLocalState) {
1451
- if (typeof overrideA === "string" || typeof overrideB === "string") {
1452
- return overrideA === overrideB;
1453
- }
1454
- const overridesEqual =
1455
- overrideA.override === overrideB.override &&
1456
- overrideA.originalOverridingFinal ===
1457
- overrideB.originalOverridingFinal &&
1458
- (!compareLocalState ||
1459
- overrideA.associatedLocalId === overrideB.associatedLocalId);
1460
- return overridesEqual;
1461
- }
1462
-
1463
- const uuidA =
1464
- typeof overrideA === "string" ? overrideA : overrideA.override;
1465
- const uuidB =
1466
- typeof overrideB === "string" ? overrideB : overrideB.override;
1467
- if (
1468
- typeof overrideA !== "string" &&
1469
- typeof overrideB !== "string" &&
1470
- overrideA.originalOverridingFinal !== overrideB.originalOverridingFinal
1471
- ) {
1472
- return false;
1473
- }
1474
- return uuidA === uuidB;
1475
- },
1476
- ));
1477
- return areEqual;
1478
458
  }
1479
459
 
1480
- /**
1481
- * Returns a persistable form of the current state of this `IdCompressor` which can be rehydrated via `IdCompressor.deserialize()`.
1482
- * This includes finalized state as well as un-finalized state and is therefore suitable for use in offline scenarios.
1483
- */
1484
- public serialize(
1485
- withSession: boolean,
1486
- ): SerializedIdCompressorWithOngoingSession | SerializedIdCompressorWithNoSession;
1487
-
1488
- /**
1489
- * Returns a persistable form of the current state of this `IdCompressor` which can be rehydrated via `IdCompressor.deserialize()`.
1490
- * This includes finalized state as well as un-finalized state and is therefore suitable for use in offline scenarios.
1491
- */
1492
460
  public serialize(withSession: true): SerializedIdCompressorWithOngoingSession;
1493
-
1494
- /**
1495
- * Returns a persistable form of the current state of this `IdCompressor` which can be rehydrated via `IdCompressor.deserialize()`.
1496
- * This only includes finalized state and is therefore suitable for use in summaries.
1497
- */
1498
461
  public serialize(withSession: false): SerializedIdCompressorWithNoSession;
1499
-
1500
- public serialize(withSession: boolean): SerializedIdCompressor {
1501
- const serializedSessions: SerializedSessionData[] = [];
1502
- const sessionIdToSessionIndex = new Map<SessionId, number>();
1503
-
1504
- for (const [sessionId, session] of this.sessions) {
1505
- const isLocalSession = sessionId === this.localSessionId;
1506
- const includeSession =
1507
- sessionId !== reservedSessionId && // Ignore reserved clusters, but
1508
- (session.lastFinalizedLocalId !== undefined || // always serialize sessions that made final IDs,
1509
- (isLocalSession && withSession)); // include the un-acked local session if requested
1510
-
1511
- if (includeSession) {
1512
- const sessionData: Mutable<SerializedSessionData> = [sessionId];
1513
- sessionIdToSessionIndex.set(sessionId, serializedSessions.length);
1514
- serializedSessions.push(sessionData);
1515
- }
1516
- }
1517
-
1518
- const serializedClusters: SerializedCluster[] = [];
1519
- for (const [baseFinalId, cluster] of this.finalIdToCluster.entries()) {
1520
- const sessionId = stableIdFromNumericUuid(cluster.session.sessionUuid) as SessionId;
1521
- if (sessionId !== reservedSessionId) {
1522
- const sessionIndex =
1523
- sessionIdToSessionIndex.get(sessionId) ??
1524
- fail("Session object contains wrong session numeric UUID");
1525
-
1526
- const serializedCluster: Mutable<SerializedCluster> = [
1527
- sessionIndex,
1528
- cluster.capacity,
1529
- ];
1530
- if (cluster.count !== cluster.capacity) {
1531
- serializedCluster.push(cluster.count);
1532
- }
1533
-
1534
- if (cluster.overrides !== undefined) {
1535
- const serializedOverrides: Mutable<SerializedClusterOverrides> = [];
1536
- for (const [finalId, override] of cluster.overrides) {
1537
- const finalIdIndex = finalId - baseFinalId;
1538
- if (typeof override === "string") {
1539
- serializedOverrides.push([finalIdIndex, override]);
1540
- } else if (override.originalOverridingFinal === finalId) {
1541
- serializedOverrides.push([finalIdIndex, override.override]);
1542
- } else {
1543
- serializedOverrides.push([
1544
- finalIdIndex,
1545
- override.override,
1546
- override.originalOverridingFinal,
1547
- ]);
1548
- }
1549
- }
1550
- serializedCluster.push(serializedOverrides);
1551
- }
1552
-
1553
- serializedClusters.push(serializedCluster);
1554
- }
1555
- }
1556
-
1557
- // Reserved session not serialized, and local session is present but may not make IDs
1558
- assert(
1559
- serializedSessions.length - this.sessions.size <= 2,
1560
- 0x498 /* session not serialized */,
1561
- );
1562
-
1563
- const serializedIdCompressor: Omit<
1564
- SerializedIdCompressor,
1565
- "_versionedSerializedIdCompressor"
1566
- > = {
1567
- version: currentWrittenVersion,
1568
- clusterCapacity: this.clusterCapacity,
1569
- sessions: serializedSessions,
1570
- clusters: serializedClusters,
1571
- };
1572
-
1573
- if (withSession) {
1574
- const serializedWithSession =
1575
- serializedIdCompressor as Mutable<SerializedIdCompressorWithOngoingSession>;
1576
- serializedWithSession.localSessionIndex = serializedWithSession.sessions.findIndex(
1577
- ([sessionId]) => sessionId === this.localSessionId,
462
+ public serialize(hasLocalState: boolean): SerializedIdCompressor {
463
+ const { normalizer, finalSpace, sessions } = this;
464
+ const sessionIndexMap = new Map<Session, number>();
465
+ let sessionIndex = 0;
466
+ for (const session of sessions.sessions()) {
467
+ // Filter empty sessions to prevent them accumulating in the serialized state
468
+ if (!session.isEmpty() || hasLocalState) {
469
+ sessionIndexMap.set(session, sessionIndex);
470
+ sessionIndex++;
471
+ }
472
+ }
473
+ const localStateSize = hasLocalState
474
+ ? 1 + // generated ID count
475
+ 1 + // next range base genCount
476
+ 1 + // count of normalizer pairs
477
+ this.normalizer.idRanges.size * 2 // pairs
478
+ : 0;
479
+ // Layout size, in 8 byte increments
480
+ const totalSize =
481
+ 1 + // version
482
+ 1 + // hasLocalState
483
+ 1 + // cluster capacity
484
+ 1 + // session count
485
+ 1 + // cluster count
486
+ sessionIndexMap.size * 2 + // session IDs
487
+ finalSpace.clusters.length * 3 + // clusters: (sessionIndex, capacity, count)[]
488
+ localStateSize; // local state, if present
489
+
490
+ const serializedFloat = new Float64Array(totalSize);
491
+ const serializedUint = new BigUint64Array(serializedFloat.buffer);
492
+ let index = 0;
493
+ index = writeNumber(serializedFloat, index, currentWrittenVersion);
494
+ index = writeBoolean(serializedFloat, index, hasLocalState);
495
+ index = writeNumber(serializedFloat, index, this.clusterCapacity);
496
+ index = writeNumber(serializedFloat, index, sessionIndexMap.size);
497
+ index = writeNumber(serializedFloat, index, finalSpace.clusters.length);
498
+
499
+ for (const [session] of sessionIndexMap.entries()) {
500
+ index = writeNumericUuid(serializedUint, index, session.sessionUuid);
501
+ }
502
+
503
+ finalSpace.clusters.forEach((cluster) => {
504
+ index = writeNumber(
505
+ serializedFloat,
506
+ index,
507
+ sessionIndexMap.get(cluster.session) as number,
1578
508
  );
1579
- if (this.localIdCount > 0) {
1580
- serializedWithSession.localState = {
1581
- localIdCount: this.localIdCount,
1582
- overrides: [...this.localOverrides.entries()].map((entry) => [...entry]),
1583
- lastTakenLocalId: this.lastTakenLocalId,
1584
- sessionNormalizer: this.sessionIdNormalizer.serialize(),
1585
- };
1586
- }
509
+ index = writeNumber(serializedFloat, index, cluster.capacity);
510
+ index = writeNumber(serializedFloat, index, cluster.count);
511
+ });
1587
512
 
1588
- return serializedWithSession;
513
+ if (hasLocalState) {
514
+ index = writeNumber(serializedFloat, index, this.localGenCount);
515
+ index = writeNumber(serializedFloat, index, this.nextRangeBaseGenCount);
516
+ index = writeNumber(serializedFloat, index, normalizer.idRanges.size);
517
+ for (const [leadingGenCount, count] of normalizer.idRanges.entries()) {
518
+ index = writeNumber(serializedFloat, index, leadingGenCount);
519
+ index = writeNumber(serializedFloat, index, count);
520
+ }
1589
521
  }
1590
522
 
523
+ assert(index === totalSize, 0x75b /* Serialized size was incorrectly calculated. */);
1591
524
  this.logger?.sendTelemetryEvent({
1592
525
  eventName: "RuntimeIdCompressor:SerializedIdCompressorSize",
1593
- size: JSON.stringify(serializedIdCompressor).length,
1594
- clusterCount: serializedIdCompressor.clusters.length,
1595
- sessionCount: serializedIdCompressor.sessions.length,
526
+ size: serializedFloat.byteLength,
527
+ clusterCount: finalSpace.clusters.length,
528
+ sessionCount: sessionIndexMap.size,
1596
529
  });
1597
530
 
1598
- return serializedIdCompressor as SerializedIdCompressor;
531
+ return bufferToString(serializedFloat.buffer, "base64") as SerializedIdCompressor;
1599
532
  }
1600
533
 
1601
- /**
1602
- * Deserialize an serialized IdCompressor that is part of an ongoing session, thereby resuming that session.
1603
- */
1604
534
  public static deserialize(serialized: SerializedIdCompressorWithOngoingSession): IdCompressor;
1605
-
1606
- /**
1607
- * Deserialize a serialized IdCompressor with a new session.
1608
- * @param serialized - the serialized compressor state
1609
- * @param newSessionId - the session ID for the new compressor.
1610
- */
1611
535
  public static deserialize(
1612
536
  serialized: SerializedIdCompressorWithNoSession,
1613
537
  newSessionId: SessionId,
1614
538
  ): IdCompressor;
1615
-
1616
539
  public static deserialize(
1617
- ...args:
1618
- | [serialized: SerializedIdCompressorWithNoSession, newSessionIdMaybe: SessionId]
1619
- | [serialized: SerializedIdCompressorWithOngoingSession, newSessionIdMaybe?: undefined]
540
+ serialized: SerializedIdCompressor,
541
+ sessionId?: SessionId,
1620
542
  ): IdCompressor {
1621
- const [serialized, newSessionIdMaybe] = args;
1622
-
1623
- const {
1624
- clusterCapacity,
1625
- sessions: serializedSessions,
1626
- clusters: serializedClusters,
1627
- } = serialized;
1628
-
1629
- let localSessionId: SessionId;
1630
- let serializedLocalState: SerializedLocalState | undefined;
1631
- if (newSessionIdMaybe === undefined) {
1632
- // Alias of serialized, but known to be a SerializedIdCompressorWithOngoingSession
1633
- const [serializedWithSession] = args;
1634
- const serializedSessionData =
1635
- serializedSessions[serializedWithSession.localSessionIndex];
1636
- localSessionId = serializedSessionData[0];
1637
- serializedLocalState = serializedWithSession.localState;
543
+ const buffer = stringToBuffer(serialized, "base64");
544
+ const index: Index = {
545
+ index: 0,
546
+ bufferFloat: new Float64Array(buffer),
547
+ bufferUint: new BigUint64Array(buffer),
548
+ };
549
+ const version = readNumber(index);
550
+ assert(version === currentWrittenVersion, 0x75c /* Unknown serialized version. */);
551
+ const hasLocalState = readBoolean(index);
552
+ const clusterCapacity = readNumber(index);
553
+ const sessionCount = readNumber(index);
554
+ const clusterCount = readNumber(index);
555
+
556
+ // Sessions
557
+ let sessionOffset = 0;
558
+ const sessions: [NumericUuid, Session][] = [];
559
+ if (!hasLocalState) {
560
+ // If !hasLocalState, there won't be a serialized local session ID so insert one at the beginning
561
+ assert(sessionId !== undefined, 0x75d /* Local session ID is undefined. */);
562
+ const localSessionNumeric = numericUuidFromStableId(sessionId);
563
+ sessions.push([localSessionNumeric, new Session(localSessionNumeric)]);
564
+ sessionOffset = 1;
1638
565
  } else {
1639
- localSessionId = newSessionIdMaybe;
1640
- }
1641
-
1642
- const compressor = new IdCompressor(localSessionId);
1643
- compressor.clusterCapacity = clusterCapacity;
1644
-
1645
- const localOverridesInverse = new Map<string, LocalCompressedId>();
1646
- if (serializedLocalState !== undefined) {
1647
- // Do this part of local rehydration first since the cluster map population needs to query to local overrides
1648
- compressor.localIdCount = serializedLocalState.localIdCount;
1649
- compressor.lastTakenLocalId = serializedLocalState.lastTakenLocalId;
1650
- if (serializedLocalState.overrides !== undefined) {
1651
- for (const [localId, override] of serializedLocalState.overrides) {
1652
- compressor.localOverrides.append(localId, override);
1653
- localOverridesInverse.set(override, localId);
1654
- compressor.clustersAndOverridesInversion.set(
1655
- IdCompressor.createInversionKey(override),
1656
- localId as UnackedLocalId,
1657
- );
1658
- }
1659
- }
566
+ assert(
567
+ sessionId === undefined,
568
+ 0x75e /* Local state should not exist in serialized form. */,
569
+ );
1660
570
  }
1661
571
 
1662
- const sessionInfos: {
1663
- readonly session: Session;
1664
- readonly sessionId: SessionId;
1665
- }[] = [];
1666
- for (const serializedSession of serializedSessions) {
1667
- const [sessionId] = serializedSession;
1668
- if (sessionId === localSessionId) {
1669
- assert(hasOngoingSession(serialized), 0x499 /* Cannot resume existing session. */);
1670
- sessionInfos.push({ session: compressor.localSession, sessionId });
1671
- } else {
1672
- const session = compressor.createSession(sessionId);
1673
- sessionInfos.push({ session, sessionId });
1674
- }
572
+ for (let i = 0; i < sessionCount; i++) {
573
+ const numeric = readNumericUuid(index);
574
+ sessions.push([numeric, new Session(numeric)]);
1675
575
  }
1676
576
 
1677
- for (const serializedCluster of serializedClusters) {
1678
- const { sessionIndex, capacity, count, overrides } =
1679
- deserializeCluster(serializedCluster);
1680
- const { session, sessionId } = sessionInfos[sessionIndex];
1681
- const { lastFinalizedLocalId, sessionUuid } = session;
1682
- const currentIdCount = lastFinalizedLocalId === undefined ? 0 : -lastFinalizedLocalId;
577
+ const compressor = new IdCompressor(new Sessions(sessions));
578
+ compressor.clusterCapacity = clusterCapacity;
1683
579
 
1684
- const cluster: Mutable<IdCluster> = {
580
+ // Clusters
581
+ let baseFinalId = 0;
582
+ for (let i = 0; i < clusterCount; i++) {
583
+ const sessionIndex = readNumber(index);
584
+ const session = sessions[sessionIndex + sessionOffset][1];
585
+ const capacity = readNumber(index);
586
+ const count = readNumber(index);
587
+ const cluster = session.addNewCluster(
588
+ baseFinalId as FinalCompressedId,
1685
589
  capacity,
1686
590
  count,
1687
- baseUuid: incrementUuid(sessionUuid, currentIdCount),
1688
- session,
1689
- };
1690
-
1691
- const lastFinalizedNormalized = lastFinalizedLocalId ?? 0;
1692
- const clusterBase = compressor.nextClusterBaseFinalId;
1693
-
1694
- session.lastFinalizedLocalId = (lastFinalizedNormalized - count) as LocalCompressedId;
1695
- session.currentClusterDetails = { clusterBase, cluster };
1696
- compressor.nextClusterBaseFinalId = (compressor.nextClusterBaseFinalId +
1697
- capacity) as FinalCompressedId;
1698
- compressor.finalIdToCluster.append(clusterBase, cluster);
1699
- compressor.clustersAndOverridesInversion.set(
1700
- stableIdFromNumericUuid(cluster.baseUuid),
1701
- {
1702
- clusterBase,
1703
- cluster,
1704
- },
1705
591
  );
1706
-
1707
- if (overrides !== undefined) {
1708
- cluster.overrides = new Map();
1709
- for (const [finalIdIndex, override, originalOverridingFinal] of overrides) {
1710
- const finalId = (clusterBase + finalIdIndex) as FinalCompressedId;
1711
- if (originalOverridingFinal !== undefined) {
1712
- const unifiedOverride: Mutable<UnifiedOverride> = {
1713
- override,
1714
- originalOverridingFinal,
1715
- };
1716
- if (serializedLocalState !== undefined) {
1717
- setPropertyIfDefined(
1718
- localOverridesInverse.get(override),
1719
- unifiedOverride,
1720
- "associatedLocalId",
1721
- );
1722
- }
1723
- cluster.overrides.set(finalId, unifiedOverride);
1724
- } else {
1725
- const associatedLocal = localOverridesInverse.get(override);
1726
- if (associatedLocal !== undefined && sessionId !== localSessionId) {
1727
- // In this case, there is a local ID associated with this override, but this is the first cluster to contain
1728
- // that override (because only the first cluster will have the string serialized). In this case, the override
1729
- // needs to hold that local value.
1730
- cluster.overrides.set(finalId, {
1731
- override,
1732
- originalOverridingFinal: finalId,
1733
- associatedLocalId: associatedLocal,
1734
- });
1735
- } else {
1736
- cluster.overrides.set(finalId, override);
1737
- }
1738
- const finalizedOverride: Mutable<FinalizedOverride> = {
1739
- cluster,
1740
- originalOverridingFinal: finalId,
1741
- };
1742
- if (serializedLocalState !== undefined) {
1743
- setPropertyIfDefined(
1744
- associatedLocal,
1745
- finalizedOverride,
1746
- "associatedLocalId",
1747
- );
1748
- }
1749
- compressor.clustersAndOverridesInversion.set(
1750
- IdCompressor.createInversionKey(override),
1751
- finalizedOverride,
1752
- );
1753
- }
1754
- }
1755
- }
592
+ compressor.finalSpace.addCluster(cluster);
593
+ baseFinalId += capacity;
1756
594
  }
1757
595
 
1758
- if (serializedLocalState !== undefined) {
1759
- compressor.sessionIdNormalizer = SessionIdNormalizer.deserialize(
1760
- serializedLocalState.sessionNormalizer,
1761
- (finalId) => {
1762
- const [_, cluster] =
1763
- compressor.finalIdToCluster.getPairOrNextLower(finalId) ??
1764
- fail("Final in serialized normalizer was never created.");
1765
- return cluster;
1766
- },
1767
- );
596
+ // Local state
597
+ if (hasLocalState) {
598
+ compressor.localGenCount = readNumber(index);
599
+ compressor.nextRangeBaseGenCount = readNumber(index);
600
+ const normalizerCount = readNumber(index);
601
+ for (let i = 0; i < normalizerCount; i++) {
602
+ compressor.normalizer.addLocalRange(readNumber(index), readNumber(index));
603
+ }
1768
604
  }
1769
605
 
1770
606
  assert(
1771
- compressor.localSession.lastFinalizedLocalId === undefined ||
1772
- compressor.localIdCount >= -compressor.localSession.lastFinalizedLocalId,
1773
- 0x49a /* Inconsistent last finalized state when deserializing */,
607
+ index.index === index.bufferFloat.length,
608
+ 0x75f /* Failed to read entire serialized compressor. */,
1774
609
  );
1775
-
1776
610
  return compressor;
1777
611
  }
1778
612
 
1779
- /**
1780
- * Converts the given serialized compressor to the current version.
1781
- * @param serializedCompressor - the serialized compressor to convert. Must not have been serialized with an ongoing session.
1782
- * @returns a serialized compressor with no ongoing session.
1783
- */
1784
- public static convertToCurrentVersion(
1785
- serializedCompressor: VersionedSerializedIdCompressor,
1786
- hasSession: false,
1787
- ): SerializedIdCompressorWithNoSession;
1788
-
1789
- /**
1790
- * Converts the given serialized compressor to the current version.
1791
- * @param serializedCompressor - the serialized compressor to convert. Must have been serialized with an ongoing session.
1792
- * @returns a serialized compressor with the same ongoing session.
1793
- */
1794
- public static convertToCurrentVersion(
1795
- serializedCompressor: VersionedSerializedIdCompressor,
1796
- hasSession: true,
1797
- ): SerializedIdCompressorWithOngoingSession;
1798
-
1799
- public static convertToCurrentVersion(
1800
- serializedCompressor: VersionedSerializedIdCompressor,
1801
- hasSession: boolean,
1802
- ): SerializedIdCompressor | undefined {
1803
- if (serializedCompressor.version !== currentWrittenVersion) {
1804
- fail("Unknown SerializedIdCompressor version number");
1805
- }
1806
- const serialized = serializedCompressor as SerializedIdCompressorWithOngoingSession;
1807
- if (hasSession !== hasOngoingSession(serialized)) {
1808
- return undefined;
613
+ public equals(other: IdCompressor, includeLocalState: boolean): boolean {
614
+ if (
615
+ includeLocalState &&
616
+ (this.localSessionId !== other.localSessionId ||
617
+ !this.localSession.equals(other.localSession) ||
618
+ !this.normalizer.equals(other.normalizer) ||
619
+ this.nextRangeBaseGenCount !== other.nextRangeBaseGenCount ||
620
+ this.localGenCount !== other.localGenCount)
621
+ ) {
622
+ return false;
1809
623
  }
1810
- return serialized;
624
+ return (
625
+ this.newClusterCapacity === other.newClusterCapacity &&
626
+ this.sessions.equals(other.sessions, includeLocalState) &&
627
+ this.finalSpace.equals(other.finalSpace)
628
+ );
1811
629
  }
1812
630
  }
1813
-
1814
- /**
1815
- * The version of `IdCompressor` that is currently persisted.
1816
- */
1817
- const currentWrittenVersion = "0.0.1";
1818
-
1819
- /**
1820
- * @returns whether or not the given serialized ID compressor has an ongoing session.
1821
- */
1822
- export function hasOngoingSession(
1823
- serialized: SerializedIdCompressorWithNoSession | SerializedIdCompressorWithOngoingSession,
1824
- ): serialized is SerializedIdCompressorWithOngoingSession {
1825
- return (
1826
- (serialized as Partial<SerializedIdCompressorWithOngoingSession>).localSessionIndex !==
1827
- undefined
1828
- );
1829
- }
1830
-
1831
- function deserializeCluster(serializedCluster: SerializedCluster): {
1832
- sessionIndex: number;
1833
- capacity: number;
1834
- count: number;
1835
- overrides?: SerializedClusterOverrides;
1836
- } {
1837
- const [sessionIndex, capacity, countOrOverrides, overrides] = serializedCluster;
1838
- const hasCount = typeof countOrOverrides === "number";
1839
-
1840
- return {
1841
- sessionIndex,
1842
- capacity,
1843
- count: hasCount ? countOrOverrides : capacity,
1844
- overrides: hasCount ? overrides : countOrOverrides,
1845
- };
1846
- }
1847
-
1848
- /**
1849
- * Optimization used by the sorted-btree library to avoid allocating tuples every time a lookup method is called.
1850
- * Lookup methods on BTree accept a pre-allocated array that it populates with the result of the lookup and retains no ownership
1851
- * of after the call, so this array may be supplied to any of them. References to this array should not be retained elsewhere and
1852
- * lookup results should be extracted from the tuple immediately after invocation.
1853
- */
1854
- const reusedArray: [any, any] = [] as unknown as [any, any];