@fluidframework/container-runtime 2.0.0-internal.6.1.1 → 2.0.0-internal.6.3.0

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