@fluidframework/container-runtime 2.0.0-internal.6.1.0 → 2.0.0-internal.6.2.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 (363) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +4 -3
  3. package/dist/batchTracker.d.ts +1 -1
  4. package/dist/batchTracker.js +1 -1
  5. package/dist/batchTracker.js.map +1 -1
  6. package/dist/blobManager.d.ts +4 -20
  7. package/dist/blobManager.d.ts.map +1 -1
  8. package/dist/blobManager.js +47 -125
  9. package/dist/blobManager.js.map +1 -1
  10. package/dist/containerRuntime.d.ts +82 -14
  11. package/dist/containerRuntime.d.ts.map +1 -1
  12. package/dist/containerRuntime.js +236 -138
  13. package/dist/containerRuntime.js.map +1 -1
  14. package/dist/dataStore.d.ts.map +1 -1
  15. package/dist/dataStore.js +1 -2
  16. package/dist/dataStore.js.map +1 -1
  17. package/dist/dataStoreContext.d.ts.map +1 -1
  18. package/dist/dataStoreContext.js +4 -5
  19. package/dist/dataStoreContext.js.map +1 -1
  20. package/dist/dataStoreContexts.d.ts +1 -2
  21. package/dist/dataStoreContexts.d.ts.map +1 -1
  22. package/dist/dataStoreContexts.js.map +1 -1
  23. package/dist/dataStoreRegistry.js +2 -2
  24. package/dist/dataStoreRegistry.js.map +1 -1
  25. package/dist/dataStores.d.ts.map +1 -1
  26. package/dist/dataStores.js +4 -5
  27. package/dist/dataStores.js.map +1 -1
  28. package/dist/error.d.ts +14 -0
  29. package/dist/error.d.ts.map +1 -0
  30. package/dist/error.js +21 -0
  31. package/dist/error.js.map +1 -0
  32. package/dist/gc/garbageCollection.d.ts +1 -1
  33. package/dist/gc/garbageCollection.d.ts.map +1 -1
  34. package/dist/gc/garbageCollection.js +23 -5
  35. package/dist/gc/garbageCollection.js.map +1 -1
  36. package/dist/gc/gcConfigs.d.ts.map +1 -1
  37. package/dist/gc/gcConfigs.js +5 -3
  38. package/dist/gc/gcConfigs.js.map +1 -1
  39. package/dist/gc/gcDefinitions.d.ts +2 -0
  40. package/dist/gc/gcDefinitions.d.ts.map +1 -1
  41. package/dist/gc/gcDefinitions.js.map +1 -1
  42. package/dist/gc/gcTelemetry.d.ts.map +1 -1
  43. package/dist/gc/gcTelemetry.js +2 -0
  44. package/dist/gc/gcTelemetry.js.map +1 -1
  45. package/dist/id-compressor/appendOnlySortedMap.d.ts +8 -30
  46. package/dist/id-compressor/appendOnlySortedMap.d.ts.map +1 -1
  47. package/dist/id-compressor/appendOnlySortedMap.js +25 -67
  48. package/dist/id-compressor/appendOnlySortedMap.js.map +1 -1
  49. package/dist/id-compressor/finalSpace.d.ts +29 -0
  50. package/dist/id-compressor/finalSpace.d.ts.map +1 -0
  51. package/dist/id-compressor/finalSpace.js +62 -0
  52. package/dist/id-compressor/finalSpace.js.map +1 -0
  53. package/dist/id-compressor/idCompressor.d.ts +25 -250
  54. package/dist/id-compressor/idCompressor.d.ts.map +1 -1
  55. package/dist/id-compressor/idCompressor.js +385 -1149
  56. package/dist/id-compressor/idCompressor.js.map +1 -1
  57. package/dist/id-compressor/identifiers.d.ts +32 -0
  58. package/dist/id-compressor/identifiers.d.ts.map +1 -0
  59. package/dist/id-compressor/identifiers.js +15 -0
  60. package/dist/id-compressor/identifiers.js.map +1 -0
  61. package/dist/id-compressor/index.d.ts +5 -6
  62. package/dist/id-compressor/index.d.ts.map +1 -1
  63. package/dist/id-compressor/index.js +20 -26
  64. package/dist/id-compressor/index.js.map +1 -1
  65. package/dist/id-compressor/persistanceUtilities.d.ts +22 -0
  66. package/dist/id-compressor/persistanceUtilities.d.ts.map +1 -0
  67. package/dist/id-compressor/persistanceUtilities.js +43 -0
  68. package/dist/id-compressor/persistanceUtilities.js.map +1 -0
  69. package/dist/id-compressor/sessionSpaceNormalizer.d.ts +46 -0
  70. package/dist/id-compressor/sessionSpaceNormalizer.d.ts.map +1 -0
  71. package/dist/id-compressor/sessionSpaceNormalizer.js +80 -0
  72. package/dist/id-compressor/sessionSpaceNormalizer.js.map +1 -0
  73. package/dist/id-compressor/sessions.d.ts +115 -0
  74. package/dist/id-compressor/sessions.d.ts.map +1 -0
  75. package/dist/id-compressor/sessions.js +305 -0
  76. package/dist/id-compressor/sessions.js.map +1 -0
  77. package/dist/id-compressor/utilities.d.ts +49 -0
  78. package/dist/id-compressor/utilities.d.ts.map +1 -0
  79. package/dist/id-compressor/utilities.js +166 -0
  80. package/dist/id-compressor/utilities.js.map +1 -0
  81. package/dist/index.d.ts +3 -3
  82. package/dist/index.d.ts.map +1 -1
  83. package/dist/index.js +6 -4
  84. package/dist/index.js.map +1 -1
  85. package/dist/opLifecycle/opCompressor.d.ts.map +1 -1
  86. package/dist/opLifecycle/opCompressor.js +1 -2
  87. package/dist/opLifecycle/opCompressor.js.map +1 -1
  88. package/dist/opLifecycle/opSplitter.d.ts.map +1 -1
  89. package/dist/opLifecycle/opSplitter.js +2 -3
  90. package/dist/opLifecycle/opSplitter.js.map +1 -1
  91. package/dist/opLifecycle/outbox.d.ts +1 -0
  92. package/dist/opLifecycle/outbox.d.ts.map +1 -1
  93. package/dist/opLifecycle/outbox.js +10 -11
  94. package/dist/opLifecycle/outbox.js.map +1 -1
  95. package/dist/opLifecycle/remoteMessageProcessor.d.ts.map +1 -1
  96. package/dist/opLifecycle/remoteMessageProcessor.js +11 -5
  97. package/dist/opLifecycle/remoteMessageProcessor.js.map +1 -1
  98. package/dist/packageVersion.d.ts +1 -1
  99. package/dist/packageVersion.js +1 -1
  100. package/dist/packageVersion.js.map +1 -1
  101. package/dist/pendingStateManager.d.ts +12 -5
  102. package/dist/pendingStateManager.d.ts.map +1 -1
  103. package/dist/pendingStateManager.js +24 -10
  104. package/dist/pendingStateManager.js.map +1 -1
  105. package/dist/scheduleManager.d.ts.map +1 -1
  106. package/dist/scheduleManager.js +4 -5
  107. package/dist/scheduleManager.js.map +1 -1
  108. package/dist/summary/index.d.ts +2 -2
  109. package/dist/summary/index.d.ts.map +1 -1
  110. package/dist/summary/index.js +2 -1
  111. package/dist/summary/index.js.map +1 -1
  112. package/dist/summary/orderedClientElection.d.ts +1 -2
  113. package/dist/summary/orderedClientElection.d.ts.map +1 -1
  114. package/dist/summary/orderedClientElection.js +2 -3
  115. package/dist/summary/orderedClientElection.js.map +1 -1
  116. package/dist/summary/runningSummarizer.d.ts +27 -4
  117. package/dist/summary/runningSummarizer.d.ts.map +1 -1
  118. package/dist/summary/runningSummarizer.js +237 -66
  119. package/dist/summary/runningSummarizer.js.map +1 -1
  120. package/dist/summary/summarizer.d.ts +6 -5
  121. package/dist/summary/summarizer.d.ts.map +1 -1
  122. package/dist/summary/summarizer.js +70 -67
  123. package/dist/summary/summarizer.js.map +1 -1
  124. package/dist/summary/summarizerClientElection.d.ts +1 -1
  125. package/dist/summary/summarizerClientElection.d.ts.map +1 -1
  126. package/dist/summary/summarizerClientElection.js.map +1 -1
  127. package/dist/summary/summarizerTypes.d.ts +38 -25
  128. package/dist/summary/summarizerTypes.d.ts.map +1 -1
  129. package/dist/summary/summarizerTypes.js.map +1 -1
  130. package/dist/summary/summaryCollection.d.ts +1 -2
  131. package/dist/summary/summaryCollection.d.ts.map +1 -1
  132. package/dist/summary/summaryCollection.js.map +1 -1
  133. package/dist/summary/summaryGenerator.d.ts +9 -3
  134. package/dist/summary/summaryGenerator.d.ts.map +1 -1
  135. package/dist/summary/summaryGenerator.js +42 -38
  136. package/dist/summary/summaryGenerator.js.map +1 -1
  137. package/dist/summary/summaryManager.d.ts +7 -6
  138. package/dist/summary/summaryManager.d.ts.map +1 -1
  139. package/dist/summary/summaryManager.js +22 -15
  140. package/dist/summary/summaryManager.js.map +1 -1
  141. package/lib/batchTracker.d.ts +1 -1
  142. package/lib/batchTracker.js +1 -1
  143. package/lib/batchTracker.js.map +1 -1
  144. package/lib/blobManager.d.ts +4 -20
  145. package/lib/blobManager.d.ts.map +1 -1
  146. package/lib/blobManager.js +46 -124
  147. package/lib/blobManager.js.map +1 -1
  148. package/lib/containerRuntime.d.ts +82 -14
  149. package/lib/containerRuntime.d.ts.map +1 -1
  150. package/lib/containerRuntime.js +223 -123
  151. package/lib/containerRuntime.js.map +1 -1
  152. package/lib/dataStore.d.ts.map +1 -1
  153. package/lib/dataStore.js +1 -2
  154. package/lib/dataStore.js.map +1 -1
  155. package/lib/dataStoreContext.d.ts.map +1 -1
  156. package/lib/dataStoreContext.js +1 -2
  157. package/lib/dataStoreContext.js.map +1 -1
  158. package/lib/dataStoreContexts.d.ts +1 -2
  159. package/lib/dataStoreContexts.d.ts.map +1 -1
  160. package/lib/dataStoreContexts.js.map +1 -1
  161. package/lib/dataStoreRegistry.js +1 -1
  162. package/lib/dataStoreRegistry.js.map +1 -1
  163. package/lib/dataStores.d.ts.map +1 -1
  164. package/lib/dataStores.js +1 -2
  165. package/lib/dataStores.js.map +1 -1
  166. package/lib/error.d.ts +14 -0
  167. package/lib/error.d.ts.map +1 -0
  168. package/lib/error.js +17 -0
  169. package/lib/error.js.map +1 -0
  170. package/lib/gc/garbageCollection.d.ts +1 -1
  171. package/lib/gc/garbageCollection.d.ts.map +1 -1
  172. package/lib/gc/garbageCollection.js +22 -4
  173. package/lib/gc/garbageCollection.js.map +1 -1
  174. package/lib/gc/gcConfigs.d.ts.map +1 -1
  175. package/lib/gc/gcConfigs.js +3 -1
  176. package/lib/gc/gcConfigs.js.map +1 -1
  177. package/lib/gc/gcDefinitions.d.ts +2 -0
  178. package/lib/gc/gcDefinitions.d.ts.map +1 -1
  179. package/lib/gc/gcDefinitions.js.map +1 -1
  180. package/lib/gc/gcTelemetry.d.ts.map +1 -1
  181. package/lib/gc/gcTelemetry.js +2 -0
  182. package/lib/gc/gcTelemetry.js.map +1 -1
  183. package/lib/id-compressor/appendOnlySortedMap.d.ts +8 -30
  184. package/lib/id-compressor/appendOnlySortedMap.d.ts.map +1 -1
  185. package/lib/id-compressor/appendOnlySortedMap.js +24 -65
  186. package/lib/id-compressor/appendOnlySortedMap.js.map +1 -1
  187. package/lib/id-compressor/finalSpace.d.ts +29 -0
  188. package/lib/id-compressor/finalSpace.d.ts.map +1 -0
  189. package/lib/id-compressor/finalSpace.js +58 -0
  190. package/lib/id-compressor/finalSpace.js.map +1 -0
  191. package/lib/id-compressor/idCompressor.d.ts +25 -250
  192. package/lib/id-compressor/idCompressor.d.ts.map +1 -1
  193. package/lib/id-compressor/idCompressor.js +381 -1139
  194. package/lib/id-compressor/idCompressor.js.map +1 -1
  195. package/lib/id-compressor/identifiers.d.ts +32 -0
  196. package/lib/id-compressor/identifiers.d.ts.map +1 -0
  197. package/lib/id-compressor/identifiers.js +11 -0
  198. package/lib/id-compressor/identifiers.js.map +1 -0
  199. package/lib/id-compressor/index.d.ts +5 -6
  200. package/lib/id-compressor/index.d.ts.map +1 -1
  201. package/lib/id-compressor/index.js +5 -6
  202. package/lib/id-compressor/index.js.map +1 -1
  203. package/lib/id-compressor/persistanceUtilities.d.ts +22 -0
  204. package/lib/id-compressor/persistanceUtilities.d.ts.map +1 -0
  205. package/lib/id-compressor/persistanceUtilities.js +34 -0
  206. package/lib/id-compressor/persistanceUtilities.js.map +1 -0
  207. package/lib/id-compressor/sessionSpaceNormalizer.d.ts +46 -0
  208. package/lib/id-compressor/sessionSpaceNormalizer.d.ts.map +1 -0
  209. package/lib/id-compressor/sessionSpaceNormalizer.js +76 -0
  210. package/lib/id-compressor/sessionSpaceNormalizer.js.map +1 -0
  211. package/lib/id-compressor/sessions.d.ts +115 -0
  212. package/lib/id-compressor/sessions.d.ts.map +1 -0
  213. package/lib/id-compressor/sessions.js +290 -0
  214. package/lib/id-compressor/sessions.js.map +1 -0
  215. package/lib/id-compressor/utilities.d.ts +49 -0
  216. package/lib/id-compressor/utilities.d.ts.map +1 -0
  217. package/lib/id-compressor/utilities.js +148 -0
  218. package/lib/id-compressor/utilities.js.map +1 -0
  219. package/lib/index.d.ts +3 -3
  220. package/lib/index.d.ts.map +1 -1
  221. package/lib/index.js +2 -2
  222. package/lib/index.js.map +1 -1
  223. package/lib/opLifecycle/opCompressor.d.ts.map +1 -1
  224. package/lib/opLifecycle/opCompressor.js +1 -2
  225. package/lib/opLifecycle/opCompressor.js.map +1 -1
  226. package/lib/opLifecycle/opSplitter.d.ts.map +1 -1
  227. package/lib/opLifecycle/opSplitter.js +1 -2
  228. package/lib/opLifecycle/opSplitter.js.map +1 -1
  229. package/lib/opLifecycle/outbox.d.ts +1 -0
  230. package/lib/opLifecycle/outbox.d.ts.map +1 -1
  231. package/lib/opLifecycle/outbox.js +6 -7
  232. package/lib/opLifecycle/outbox.js.map +1 -1
  233. package/lib/opLifecycle/remoteMessageProcessor.d.ts.map +1 -1
  234. package/lib/opLifecycle/remoteMessageProcessor.js +12 -6
  235. package/lib/opLifecycle/remoteMessageProcessor.js.map +1 -1
  236. package/lib/packageVersion.d.ts +1 -1
  237. package/lib/packageVersion.js +1 -1
  238. package/lib/packageVersion.js.map +1 -1
  239. package/lib/pendingStateManager.d.ts +12 -5
  240. package/lib/pendingStateManager.d.ts.map +1 -1
  241. package/lib/pendingStateManager.js +21 -7
  242. package/lib/pendingStateManager.js.map +1 -1
  243. package/lib/scheduleManager.d.ts.map +1 -1
  244. package/lib/scheduleManager.js +1 -2
  245. package/lib/scheduleManager.js.map +1 -1
  246. package/lib/summary/index.d.ts +2 -2
  247. package/lib/summary/index.d.ts.map +1 -1
  248. package/lib/summary/index.js +1 -1
  249. package/lib/summary/index.js.map +1 -1
  250. package/lib/summary/orderedClientElection.d.ts +1 -2
  251. package/lib/summary/orderedClientElection.d.ts.map +1 -1
  252. package/lib/summary/orderedClientElection.js +1 -2
  253. package/lib/summary/orderedClientElection.js.map +1 -1
  254. package/lib/summary/runningSummarizer.d.ts +27 -4
  255. package/lib/summary/runningSummarizer.d.ts.map +1 -1
  256. package/lib/summary/runningSummarizer.js +237 -66
  257. package/lib/summary/runningSummarizer.js.map +1 -1
  258. package/lib/summary/summarizer.d.ts +6 -5
  259. package/lib/summary/summarizer.d.ts.map +1 -1
  260. package/lib/summary/summarizer.js +68 -65
  261. package/lib/summary/summarizer.js.map +1 -1
  262. package/lib/summary/summarizerClientElection.d.ts +1 -1
  263. package/lib/summary/summarizerClientElection.d.ts.map +1 -1
  264. package/lib/summary/summarizerClientElection.js.map +1 -1
  265. package/lib/summary/summarizerTypes.d.ts +38 -25
  266. package/lib/summary/summarizerTypes.d.ts.map +1 -1
  267. package/lib/summary/summarizerTypes.js.map +1 -1
  268. package/lib/summary/summaryCollection.d.ts +1 -2
  269. package/lib/summary/summaryCollection.d.ts.map +1 -1
  270. package/lib/summary/summaryCollection.js.map +1 -1
  271. package/lib/summary/summaryGenerator.d.ts +9 -3
  272. package/lib/summary/summaryGenerator.d.ts.map +1 -1
  273. package/lib/summary/summaryGenerator.js +43 -39
  274. package/lib/summary/summaryGenerator.js.map +1 -1
  275. package/lib/summary/summaryManager.d.ts +7 -6
  276. package/lib/summary/summaryManager.d.ts.map +1 -1
  277. package/lib/summary/summaryManager.js +23 -16
  278. package/lib/summary/summaryManager.js.map +1 -1
  279. package/package.json +27 -24
  280. package/src/batchTracker.ts +1 -1
  281. package/src/blobManager.ts +57 -146
  282. package/src/containerRuntime.ts +331 -158
  283. package/src/dataStore.ts +1 -2
  284. package/src/dataStoreContext.ts +3 -6
  285. package/src/dataStoreContexts.ts +1 -2
  286. package/src/dataStoreRegistry.ts +1 -1
  287. package/src/dataStores.ts +3 -5
  288. package/src/error.ts +18 -0
  289. package/src/gc/garbageCollection.ts +38 -5
  290. package/src/gc/gcConfigs.ts +4 -2
  291. package/src/gc/gcDefinitions.ts +2 -0
  292. package/src/gc/gcTelemetry.ts +2 -0
  293. package/src/id-compressor/appendOnlySortedMap.ts +25 -86
  294. package/src/id-compressor/finalSpace.ts +67 -0
  295. package/src/id-compressor/idCompressor.ts +455 -1681
  296. package/src/id-compressor/identifiers.ts +42 -0
  297. package/src/id-compressor/index.ts +11 -20
  298. package/src/id-compressor/persistanceUtilities.ts +58 -0
  299. package/src/id-compressor/sessionSpaceNormalizer.ts +83 -0
  300. package/src/id-compressor/sessions.ts +405 -0
  301. package/src/id-compressor/utilities.ts +187 -0
  302. package/src/index.ts +7 -1
  303. package/src/opLifecycle/opCompressor.ts +1 -2
  304. package/src/opLifecycle/opSplitter.ts +4 -4
  305. package/src/opLifecycle/outbox.ts +13 -10
  306. package/src/opLifecycle/remoteMessageProcessor.ts +19 -6
  307. package/src/packageVersion.ts +1 -1
  308. package/src/pendingStateManager.ts +49 -27
  309. package/src/scheduleManager.ts +5 -4
  310. package/src/summary/index.ts +3 -1
  311. package/src/summary/orderedClientElection.ts +6 -4
  312. package/src/summary/runningSummarizer.ts +276 -95
  313. package/src/summary/summarizer.ts +22 -12
  314. package/src/summary/summarizerClientElection.ts +1 -1
  315. package/src/summary/summarizerTypes.ts +40 -25
  316. package/src/summary/summaryCollection.ts +1 -2
  317. package/src/summary/summaryGenerator.ts +49 -52
  318. package/src/summary/summaryManager.ts +33 -11
  319. package/dist/id-compressor/idRange.d.ts +0 -11
  320. package/dist/id-compressor/idRange.d.ts.map +0 -1
  321. package/dist/id-compressor/idRange.js +0 -29
  322. package/dist/id-compressor/idRange.js.map +0 -1
  323. package/dist/id-compressor/numericUuid.d.ts +0 -59
  324. package/dist/id-compressor/numericUuid.d.ts.map +0 -1
  325. package/dist/id-compressor/numericUuid.js +0 -325
  326. package/dist/id-compressor/numericUuid.js.map +0 -1
  327. package/dist/id-compressor/sessionIdNormalizer.d.ts +0 -138
  328. package/dist/id-compressor/sessionIdNormalizer.d.ts.map +0 -1
  329. package/dist/id-compressor/sessionIdNormalizer.js +0 -483
  330. package/dist/id-compressor/sessionIdNormalizer.js.map +0 -1
  331. package/dist/id-compressor/utils.d.ts +0 -57
  332. package/dist/id-compressor/utils.d.ts.map +0 -1
  333. package/dist/id-compressor/utils.js +0 -90
  334. package/dist/id-compressor/utils.js.map +0 -1
  335. package/dist/id-compressor/uuidUtilities.d.ts +0 -28
  336. package/dist/id-compressor/uuidUtilities.d.ts.map +0 -1
  337. package/dist/id-compressor/uuidUtilities.js +0 -104
  338. package/dist/id-compressor/uuidUtilities.js.map +0 -1
  339. package/lib/id-compressor/idRange.d.ts +0 -11
  340. package/lib/id-compressor/idRange.d.ts.map +0 -1
  341. package/lib/id-compressor/idRange.js +0 -25
  342. package/lib/id-compressor/idRange.js.map +0 -1
  343. package/lib/id-compressor/numericUuid.d.ts +0 -59
  344. package/lib/id-compressor/numericUuid.d.ts.map +0 -1
  345. package/lib/id-compressor/numericUuid.js +0 -315
  346. package/lib/id-compressor/numericUuid.js.map +0 -1
  347. package/lib/id-compressor/sessionIdNormalizer.d.ts +0 -138
  348. package/lib/id-compressor/sessionIdNormalizer.d.ts.map +0 -1
  349. package/lib/id-compressor/sessionIdNormalizer.js +0 -479
  350. package/lib/id-compressor/sessionIdNormalizer.js.map +0 -1
  351. package/lib/id-compressor/utils.d.ts +0 -57
  352. package/lib/id-compressor/utils.d.ts.map +0 -1
  353. package/lib/id-compressor/utils.js +0 -79
  354. package/lib/id-compressor/utils.js.map +0 -1
  355. package/lib/id-compressor/uuidUtilities.d.ts +0 -28
  356. package/lib/id-compressor/uuidUtilities.d.ts.map +0 -1
  357. package/lib/id-compressor/uuidUtilities.js +0 -96
  358. package/lib/id-compressor/uuidUtilities.js.map +0 -1
  359. package/src/id-compressor/idRange.ts +0 -35
  360. package/src/id-compressor/numericUuid.ts +0 -383
  361. package/src/id-compressor/sessionIdNormalizer.ts +0 -609
  362. package/src/id-compressor/utils.ts +0 -114
  363. package/src/id-compressor/uuidUtilities.ts +0 -120
@@ -3,112 +3,80 @@
3
3
  * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
4
4
  * Licensed under the MIT License.
5
5
  */
6
- var __importDefault = (this && this.__importDefault) || function (mod) {
7
- return (mod && mod.__esModule) ? mod : { "default": mod };
8
- };
9
6
  Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.hasOngoingSession = exports.IdCompressor = exports.isLocalId = exports.isFinalId = exports.defaultClusterCapacity = void 0;
11
- /* eslint-disable @typescript-eslint/restrict-plus-operands */
7
+ exports.IdCompressor = void 0;
12
8
  const common_utils_1 = require("@fluidframework/common-utils");
13
- const sorted_btree_1 = __importDefault(require("sorted-btree"));
9
+ const runtime_definitions_1 = require("@fluidframework/runtime-definitions");
14
10
  const telemetry_utils_1 = require("@fluidframework/telemetry-utils");
15
- const utils_1 = require("./utils");
16
- const uuidUtilities_1 = require("./uuidUtilities");
17
- const appendOnlySortedMap_1 = require("./appendOnlySortedMap");
18
- const idRange_1 = require("./idRange");
19
- const numericUuid_1 = require("./numericUuid");
20
- const sessionIdNormalizer_1 = require("./sessionIdNormalizer");
11
+ const identifiers_1 = require("./identifiers");
12
+ const utilities_1 = require("./utilities");
13
+ const persistanceUtilities_1 = require("./persistanceUtilities");
14
+ const sessions_1 = require("./sessions");
15
+ const sessionSpaceNormalizer_1 = require("./sessionSpaceNormalizer");
16
+ const finalSpace_1 = require("./finalSpace");
21
17
  /**
22
- * Roughly equates to a minimum of 1M sessions before we start allocating 64 bit IDs.
23
- * This value must *NOT* change without careful consideration to compatibility.
18
+ * The version of IdCompressor that is currently persisted.
19
+ * This should not be changed without careful consideration to compatibility.
24
20
  */
25
- exports.defaultClusterCapacity = 512;
21
+ const currentWrittenVersion = 1;
26
22
  /**
27
- * The base UUID for the reserved id cluster.
28
- * This should not be changed without consideration to compatibility.
29
- */
30
- const reservedSessionId = (0, numericUuid_1.ensureSessionUuid)((0, uuidUtilities_1.assertIsStableId)("decaf40b-3c1a-47f8-a7a1-e8461ddb69ce"));
31
- /**
32
- * @returns true if the supplied ID is a final ID.
33
- */
34
- function isFinalId(id) {
35
- return id >= 0;
36
- }
37
- exports.isFinalId = isFinalId;
38
- /**
39
- * @returns true if the supplied ID is a local ID.
40
- */
41
- function isLocalId(id) {
42
- return id < 0;
43
- }
44
- exports.isLocalId = isLocalId;
45
- /** Prepended to all keys in {@link IdCompressor.clustersAndOverridesInversion} that are override strings and not valid `StableIds` */
46
- const nonStableOverridePrefix = "\ue15e"; // A character in the Private Use Area of the BMP (https://en.wikipedia.org/wiki/Private_Use_Areas)
47
- /**
48
- * See {@link IIdCompressor}
23
+ * See {@link IIdCompressor} and {@link IIdCompressorCore}
49
24
  */
50
25
  class IdCompressor {
51
- /**
52
- * @param localSessionId - the `IdCompressor`'s current local session ID.
53
- * {@link generateStableId}.
54
- */
55
- constructor(localSessionId, logger) {
56
- this.localSessionId = localSessionId;
57
- /**
58
- * Trivially reach consensus on default cluster size and reserved IDs.
59
- * These initial values must *NOT* change without careful consideration to compatibility.
60
- */
61
- this.newClusterCapacity = exports.defaultClusterCapacity;
62
- /**
63
- * Session ID -\> data about the session's current cluster.
64
- * Sessions are mutable, and thus should only be created via `createSession`.
65
- */
66
- this.sessions = new Map();
67
- /**
68
- * The base final ID of the next cluster to be created.
69
- */
70
- this.nextClusterBaseFinalId = 0;
71
- /**
72
- * Total number of IDs created locally during the current session.
73
- */
74
- this.localIdCount = 0;
75
- /**
76
- * Maps local IDs to override strings. This will contain an entry for every override assigned to a local ID generated during
77
- * the current session, and retains entries for the lifetime of this compressor.
78
- */
79
- this.localOverrides = new appendOnlySortedMap_1.AppendOnlySortedMap(utils_1.compareFiniteNumbersReversed);
80
- /**
81
- * Maps local IDs to the final ID they are associated with (if any), and maps final IDs to the corresponding local ID (if any).
82
- * This is used to efficiently compute normalization. This map can be thought of as mapping ranges of "optimistic uncertainty"
83
- * (local IDs) to the result of consensus (reserved ranges of final IDs, a.k.a. clusters). Any given range of local IDs
84
- * does not necessarily span an entire cluster, as some session-space IDs may be allocated *after* a cluster has been allocated
85
- * 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.
86
- * However, there is always a range of local IDs with size \>= 1 associated with the beginning of every cluster, as clusters are only
87
- * created *after* they are needed and thus there is some period of uncertainty after local IDs have been handed out but before the
88
- * range containing them has been finalized. There may also be ranges of local IDs that do not start at the beginning of a
89
- * cluster; this happens when a cluster is expanded instead of allocating a new one.
90
- * Additionally, session space IDs associated with an override string will also always be local IDs, because there is uncertainty as
91
- * to whether another client simultaneously allocated the same override and could get sequenced first (a.k.a. unification) and its
92
- * final ID would be associated with that override.
93
- * See `SessionIdNormalizer` for more.
94
- */
95
- this.sessionIdNormalizer = new sessionIdNormalizer_1.SessionIdNormalizer();
96
- /**
97
- * Contains entries for cluster base UUIDs and override strings (both local and final).
98
- * As a performance optimization, entries for finalized strings also include the containing cluster object.
99
- * This can be viewed as three separate tables: the inverse table for `localOverrides`, the inverse table for the union of all
100
- * the overrides of the clusters in `finalIdToCluster`, and the inverse lookup of cluster base UUIDs to their clusters.
101
- * This is unified as a performance optimization, as the common case does not have overridden IDs. It is a btree due to the need
102
- * to make range queries.
103
- */
104
- this.clustersAndOverridesInversion = new sorted_btree_1.default(undefined, utils_1.compareStrings);
105
- /**
106
- * Maps the first final ID in a cluster to its owning cluster.
107
- * Can be searched in O(log n) to determine clusters for any final ID.
108
- */
109
- this.finalIdToCluster = new appendOnlySortedMap_1.AppendOnlySortedMap(utils_1.compareFiniteNumbers);
110
- this.localSession = this.createSession(localSessionId);
111
- this.logger = (0, telemetry_utils_1.createChildLogger)({ logger });
26
+ // -----------------------
27
+ constructor(localSessionIdOrDeserialized, logger) {
28
+ this.logger = logger;
29
+ this.normalizer = new sessionSpaceNormalizer_1.SessionSpaceNormalizer();
30
+ // The number of IDs generated by the local session
31
+ this.localGenCount = 0;
32
+ // -----------------------
33
+ // ----- Final state -----
34
+ // The gen count to be annotated on the range returned by the next call to `takeNextCreationRange`.
35
+ // This is updated to be equal to `generatedIdCount` + 1 each time it is called.
36
+ this.nextRangeBaseGenCount = 1;
37
+ // The capacity of the next cluster to be created
38
+ this.newClusterCapacity = runtime_definitions_1.initialClusterCapacity;
39
+ this.sessions = new sessions_1.Sessions();
40
+ this.finalSpace = new finalSpace_1.FinalSpace();
41
+ // -----------------------
42
+ // ----- Telemetry state -----
43
+ // The number of local IDs generated since the last telemetry was sent.
44
+ this.telemetryLocalIdCount = 0;
45
+ // The number of eager final IDs generated since the last telemetry was sent.
46
+ this.telemetryEagerFinalIdCount = 0;
47
+ if (typeof localSessionIdOrDeserialized === "string") {
48
+ this.localSessionId = localSessionIdOrDeserialized;
49
+ this.localSession = this.sessions.getOrCreate(localSessionIdOrDeserialized);
50
+ }
51
+ else {
52
+ // Deserialize case
53
+ this.sessions = localSessionIdOrDeserialized;
54
+ // As policy, the first session is always the local session. Preserve this invariant
55
+ // during deserialization.
56
+ const firstSession = localSessionIdOrDeserialized.sessions().next();
57
+ (0, common_utils_1.assert)(!firstSession.done, 0x754 /* First session must be present. */);
58
+ this.localSession = firstSession.value;
59
+ this.localSessionId = (0, utilities_1.stableIdFromNumericUuid)(this.localSession.sessionUuid);
60
+ }
61
+ }
62
+ static create(sessionIdOrLogger, loggerOrUndefined) {
63
+ let localSessionId;
64
+ let logger;
65
+ if (sessionIdOrLogger === undefined) {
66
+ localSessionId = (0, utilities_1.createSessionId)();
67
+ }
68
+ else {
69
+ if (typeof sessionIdOrLogger === "string") {
70
+ localSessionId = sessionIdOrLogger;
71
+ logger = loggerOrUndefined;
72
+ }
73
+ else {
74
+ localSessionId = (0, utilities_1.createSessionId)();
75
+ logger = loggerOrUndefined;
76
+ }
77
+ }
78
+ const compressor = new IdCompressor(localSessionId, logger === undefined ? undefined : (0, telemetry_utils_1.createChildLogger)({ logger }));
79
+ return compressor;
112
80
  }
113
81
  /**
114
82
  * The size of each newly created ID cluster.
@@ -121,184 +89,77 @@ class IdCompressor {
121
89
  * `IdCompressor.maxClusterSize`.
122
90
  */
123
91
  set clusterCapacity(value) {
124
- (0, common_utils_1.assert)(value > 0, 0x481 /* Clusters must have a positive capacity */);
125
- (0, common_utils_1.assert)(value <= IdCompressor.maxClusterSize, 0x482 /* Clusters must not exceed max cluster size */);
92
+ if (value <= 0) {
93
+ throw new Error("Clusters must have a positive capacity.");
94
+ }
95
+ if (value > IdCompressor.maxClusterSize) {
96
+ throw new Error("Clusters must not exceed max cluster size.");
97
+ }
126
98
  this.newClusterCapacity = value;
127
99
  }
128
- /**
129
- * Creates a session object for the supplied ID.
130
- * Must only be called once per ID.
131
- * @param sessionId - the ID for the session
132
- * @returns the session object for the supplied ID
133
- */
134
- createSession(sessionId) {
135
- (0, common_utils_1.assert)(!this.clustersAndOverridesInversion.has(sessionId), 0x484 /* Attempted to create duplicate session */);
136
- const existingSession = this.sessions.get(sessionId);
137
- if (existingSession !== undefined) {
138
- (0, utils_1.fail)("createSession must only be called once for each session ID.");
139
- }
140
- const sessionUuid = (0, numericUuid_1.numericUuidFromStableId)(sessionId);
141
- const session = {
142
- sessionUuid,
143
- currentClusterDetails: undefined,
144
- lastFinalizedLocalId: undefined,
145
- };
146
- this.sessions.set(sessionId, session);
147
- return session;
100
+ generateCompressedId() {
101
+ this.localGenCount++;
102
+ const lastCluster = this.localSession.getLastCluster();
103
+ if (lastCluster === undefined) {
104
+ this.telemetryLocalIdCount++;
105
+ return this.generateNextLocalId();
106
+ }
107
+ // If there exists a cluster of final IDs already claimed by the local session that still has room in it,
108
+ // it is known prior to range sequencing what a local ID's corresponding final ID will be.
109
+ // In this case, it is safe to return the final ID immediately. This is guaranteed to be safe because
110
+ // any op that the local session sends that contains one of those final IDs are guaranteed to arrive to
111
+ // collaborators *after* the one containing the creation range.
112
+ const clusterOffset = this.localGenCount - (0, utilities_1.genCountFromLocalId)(lastCluster.baseLocalId);
113
+ if (lastCluster.capacity > clusterOffset) {
114
+ this.telemetryEagerFinalIdCount++;
115
+ // Space in the cluster: eager final
116
+ return (lastCluster.baseFinalId +
117
+ clusterOffset);
118
+ }
119
+ // No space in the cluster, return next local
120
+ this.telemetryLocalIdCount++;
121
+ return this.generateNextLocalId();
122
+ }
123
+ generateNextLocalId() {
124
+ // Must tell the normalizer that we generated a local ID
125
+ this.normalizer.addLocalRange(this.localGenCount, 1);
126
+ return (0, utilities_1.localIdFromGenCount)(this.localGenCount);
148
127
  }
149
- /**
150
- * Returns a range of local IDs created by this session in a format for sending to the server for finalizing.
151
- * The range will include all local IDs generated via calls to `generateCompressedId` since the last time this method was called.
152
- * @returns the range of session-local IDs, which may be empty. This range must be sent to the server for ordering before
153
- * it is finalized. Ranges must be sent to the server in the order that they are taken via calls to this method.
154
- */
155
128
  takeNextCreationRange() {
156
- const lastLocalInRange = -this.localIdCount;
157
- const lastTakenNormalized = this.lastTakenLocalId ?? 0;
158
- (0, common_utils_1.assert)(lastLocalInRange <= lastTakenNormalized, 0x485 /* Inconsistent local ID state */);
159
- let ids;
160
- if (lastLocalInRange !== lastTakenNormalized) {
161
- const firstLocalInRange = (lastTakenNormalized - 1);
162
- const overrides = [
163
- ...this.localOverrides.getRange((lastTakenNormalized - 1), lastLocalInRange),
164
- ];
165
- if ((0, utils_1.hasAtLeastLength)(overrides, 1)) {
166
- (0, common_utils_1.assert)(overrides[0][0] <= firstLocalInRange, 0x486 /* Inconsistent override state */);
167
- (0, common_utils_1.assert)(overrides[overrides.length - 1][0] >= lastLocalInRange, 0x487 /* Inconsistent override state */);
168
- ids = {
169
- overrides,
170
- };
171
- const first = firstLocalInRange === overrides[0][0] ? undefined : firstLocalInRange;
172
- const last = lastLocalInRange === overrides[overrides.length - 1][0]
173
- ? undefined
174
- : lastLocalInRange;
175
- (0, utils_1.setPropertyIfDefined)(first, ids, "first");
176
- (0, utils_1.setPropertyIfDefined)(last, ids, "last");
177
- }
178
- else {
179
- ids = {
180
- first: firstLocalInRange,
181
- last: lastLocalInRange,
182
- };
183
- }
184
- this.lastTakenLocalId = lastLocalInRange;
185
- }
186
- const range = { sessionId: this.localSessionId };
187
- if (ids === undefined) {
188
- return range;
129
+ const count = this.localGenCount - (this.nextRangeBaseGenCount - 1);
130
+ if (count === 0) {
131
+ return {
132
+ sessionId: this.localSessionId,
133
+ };
189
134
  }
190
- (0, common_utils_1.assert)(this.lastTakenLocalId === -this.localIdCount &&
191
- this.lastTakenLocalId !== lastTakenNormalized, 0x488 /* Non-empty range must properly consume local IDs */);
192
- range.ids = ids;
135
+ const range = {
136
+ sessionId: this.localSessionId,
137
+ ids: {
138
+ firstGenCount: this.nextRangeBaseGenCount,
139
+ count,
140
+ },
141
+ };
142
+ this.nextRangeBaseGenCount = this.localGenCount + 1;
193
143
  return range;
194
144
  }
195
- /**
196
- * Finalizes the supplied range of IDs (which may be from either a remote or local session).
197
- * @param range - the range of session-local IDs to finalize.
198
- */
199
145
  finalizeCreationRange(range) {
200
- const { sessionId } = range;
201
- const isLocal = sessionId === this.localSessionId;
202
- const session = this.sessions.get(sessionId) ?? this.createSession(sessionId);
203
- const ids = (0, idRange_1.getIds)(range);
204
- if (ids === undefined) {
146
+ // Check if the range has IDs
147
+ if (range.ids === undefined) {
205
148
  return;
206
149
  }
207
- const { currentClusterDetails } = session;
208
- const { cluster: currentCluster, clusterBase: currentBaseFinalId } = currentClusterDetails ?? {
209
- cluster: undefined,
210
- clusterBase: undefined,
211
- };
212
- const currentClusterExists = currentCluster !== undefined && currentBaseFinalId !== undefined;
213
- const normalizedLastFinalizedLocal = session.lastFinalizedLocalId ?? 0;
214
- const { first: newFirstFinalizedLocal, last: newLastFinalizedLocal } = ids;
215
- (0, common_utils_1.assert)(newFirstFinalizedLocal === normalizedLastFinalizedLocal - 1, 0x489 /* Ranges finalized out of order. */);
216
- // The total number of session-local IDs to finalize
217
- const finalizeCount = normalizedLastFinalizedLocal - newLastFinalizedLocal;
218
- (0, common_utils_1.assert)(finalizeCount >= 1, 0x48a /* Cannot finalize an empty range. */);
219
- let eagerFinalIdCount = 0;
220
- let initialClusterCount = 0;
221
- let remainingCount = finalizeCount;
222
- let newBaseUuid;
223
- if (currentClusterExists) {
224
- if (isLocal) {
225
- const lastKnownFinal = this.sessionIdNormalizer.getLastFinalId() ??
226
- (0, utils_1.fail)("Cluster exists but normalizer does not have an entry for it.");
227
- const lastAlignedFinalInCluster = (currentBaseFinalId +
228
- Math.min(currentCluster.count + finalizeCount, currentCluster.capacity) -
229
- 1);
230
- if (lastAlignedFinalInCluster > lastKnownFinal) {
231
- this.sessionIdNormalizer.addFinalIds((lastKnownFinal + 1), lastAlignedFinalInCluster, currentCluster);
232
- }
233
- }
234
- initialClusterCount = currentCluster.count;
235
- const remainingCapacity = currentCluster.capacity - initialClusterCount;
236
- const overflow = remainingCount - remainingCapacity;
237
- const hasRoom = overflow <= 0;
238
- if (hasRoom || currentBaseFinalId === this.finalIdToCluster.maxKey()) {
239
- currentCluster.count += remainingCount;
240
- eagerFinalIdCount = remainingCount;
241
- remainingCount = 0;
242
- // The common case is that there is room in the cluster, and the new final IDs can simply be added to it
243
- if (!hasRoom) {
244
- // The cluster is full but is the last in the list of clusters.
245
- // This allows it to be expanded instead of allocating a new one.
246
- const expansionAmount = this.newClusterCapacity + overflow;
247
- const previousCapacity = currentCluster.capacity;
248
- currentCluster.capacity += expansionAmount;
249
- this.nextClusterBaseFinalId = (this.nextClusterBaseFinalId +
250
- expansionAmount);
251
- (0, common_utils_1.assert)(this.nextClusterBaseFinalId < Number.MAX_SAFE_INTEGER, 0x48b /* The number of allocated final IDs must not exceed the JS maximum safe integer. */);
252
- this.checkClusterForCollision(currentCluster);
253
- if (isLocal) {
254
- // Example with cluster size of 3:
255
- // Ids generated so far: -1 1 2 -4 -5 <-- note positive numbers are eager finals
256
- // Cluster: [ 0 1 2 ]
257
- // ~ finalizing happens, causing expansion of 2 (overflow) + 3 (cluster capacity) ~
258
- // Cluster: [ 0 1 2 3 4 _ _ _ ]
259
- // corresponding locals: -1 -4 -5
260
- // lastFinalizedLocalId^ ^newLastFinalizedLocalId = -5
261
- // overflow = 2: ----
262
- // localIdPivot^
263
- // lastFinalizedFinal^
264
- const newLastFinalizedFinal = (currentBaseFinalId +
265
- currentCluster.count -
266
- 1);
267
- (0, common_utils_1.assert)(session.lastFinalizedLocalId !== undefined, 0x48c /* Cluster already exists for session but there is no finalized local ID */);
268
- const finalPivot = (newLastFinalizedFinal -
269
- overflow +
270
- 1);
271
- // Inform the normalizer of all IDs that we now know will end up being finalized into this cluster, including the ones
272
- // that were given out as locals (non-eager) because they exceeded the bounds of the current cluster before it was expanded.
273
- // It is safe to associate the unfinalized locals with their future final IDs even before the ranges for those locals are
274
- // actually finalized, because total order broadcast guarantees that any usage of those final IDs will be observed after
275
- // the finalization of the ranges.
276
- this.sessionIdNormalizer.registerFinalIdBlock(finalPivot, expansionAmount, currentCluster);
277
- this.logger?.sendTelemetryEvent({
278
- eventName: "RuntimeIdCompressor:ClusterExpansion",
279
- sessionId: this.localSessionId,
280
- previousCapacity,
281
- newCapacity: currentCluster.capacity,
282
- overflow,
283
- });
284
- }
285
- }
286
- }
287
- else {
288
- // The range cannot be fully allocated in the existing cluster, so allocate any space left in it and
289
- // form a new one by incrementing the previous baseUuid
290
- newBaseUuid = (0, numericUuid_1.incrementUuid)(currentCluster.baseUuid, currentCluster.capacity);
291
- currentCluster.count += remainingCapacity;
292
- remainingCount -= remainingCapacity;
293
- this.logger?.sendTelemetryEvent({
294
- eventName: "RuntimeIdCompressor:OverfilledCluster",
295
- sessionId: this.localSessionId,
296
- });
297
- }
298
- }
299
- else {
300
- // Session has never made a cluster, form a new one with the session UUID as the baseUuid
301
- newBaseUuid = session.sessionUuid;
150
+ (0, common_utils_1.assert)(range.ids.count > 0, 0x755 /* Malformed ID Range. */);
151
+ const { sessionId, ids } = range;
152
+ const { count, firstGenCount } = ids;
153
+ const session = this.sessions.getOrCreate(sessionId);
154
+ const isLocal = session === this.localSession;
155
+ const rangeBaseLocal = (0, utilities_1.localIdFromGenCount)(firstGenCount);
156
+ let lastCluster = session.getLastCluster();
157
+ if (lastCluster === undefined) {
158
+ // This is the first cluster in the session space
159
+ if (rangeBaseLocal !== -1) {
160
+ throw new Error("Ranges finalized out of order.");
161
+ }
162
+ lastCluster = this.addEmptyCluster(session, this.clusterCapacity + count);
302
163
  if (isLocal) {
303
164
  this.logger?.sendTelemetryEvent({
304
165
  eventName: "RuntimeIdCompressor:FirstCluster",
@@ -306,953 +167,328 @@ class IdCompressor {
306
167
  });
307
168
  }
308
169
  }
309
- // Finalizing a range results in one of three cases:
310
- // 1. All local IDs are finalized into a new cluster (because there was either never a cluster for that session, or the current
311
- // cluster for the session was full).
312
- // 2. All local IDs are finalized into the existing (current) cluster for the session.
313
- // 3. Local IDs are finalized into both the current cluster and a new one, as the current cluster did not have enough room.
314
- let newCluster;
315
- let newBaseFinalId;
316
- // The first local ID that will be finalized into a new cluster, if there is one.
317
- // This lets us quickly compare which cluster an override string will go into.
318
- let localIdPivot;
319
- // Need to make a new cluster
320
- if (newBaseUuid !== undefined) {
321
- if (remainingCount <= 0) {
322
- (0, utils_1.fail)("Should not create an empty cluster.");
323
- }
324
- if (currentCluster !== undefined && currentCluster.capacity !== currentCluster.count) {
325
- (0, utils_1.fail)("Cluster must be filled before another is allocated.");
326
- }
327
- newBaseFinalId = this.nextClusterBaseFinalId;
328
- const newCapacity = Math.max(this.newClusterCapacity, remainingCount);
329
- newCluster = {
330
- baseUuid: newBaseUuid,
331
- capacity: newCapacity,
332
- count: remainingCount,
333
- session,
334
- };
335
- const usedCapacity = finalizeCount - remainingCount;
336
- localIdPivot = (newFirstFinalizedLocal - usedCapacity);
337
- if (isLocal) {
338
- this.logger?.sendTelemetryEvent({
339
- eventName: "RuntimeIdCompressor:NewCluster",
340
- sessionId: this.localSessionId,
341
- clusterCapacity: newCapacity,
342
- clusterCount: remainingCount,
343
- });
344
- this.sessionIdNormalizer.registerFinalIdBlock(newBaseFinalId, newCluster.capacity, newCluster);
345
- }
346
- this.checkClusterForCollision(newCluster);
347
- this.clustersAndOverridesInversion.set((0, numericUuid_1.stableIdFromNumericUuid)(newCluster.baseUuid), {
348
- clusterBase: newBaseFinalId,
349
- cluster: newCluster,
350
- });
351
- session.currentClusterDetails = { cluster: newCluster, clusterBase: newBaseFinalId };
352
- this.nextClusterBaseFinalId = (this.nextClusterBaseFinalId +
353
- newCluster.capacity);
354
- (0, common_utils_1.assert)(this.nextClusterBaseFinalId < Number.MAX_SAFE_INTEGER, 0x48e /* The number of allocated final IDs must not exceed the JS maximum safe integer. */);
355
- this.finalIdToCluster.append(newBaseFinalId, newCluster);
170
+ const remainingCapacity = lastCluster.capacity - lastCluster.count;
171
+ if (lastCluster.baseLocalId - lastCluster.count !== rangeBaseLocal) {
172
+ throw new Error("Ranges finalized out of order.");
356
173
  }
357
- // If there are overrides, we must determine which cluster object (current or overflow) each belongs to and add it.
358
- const overrides = ids.overrides;
359
- if (overrides !== undefined) {
360
- for (let i = 0; i < overrides.length; i++) {
361
- const [overriddenLocal, override] = overrides[i];
362
- // Note: recall that local IDs are negative
363
- (0, common_utils_1.assert)(i === 0 || overriddenLocal < overrides[i - 1][0], 0x48f /* Override IDs must be in sorted order. */);
364
- (0, common_utils_1.assert)(overriddenLocal < normalizedLastFinalizedLocal, 0x490 /* Ranges finalized out of order. */);
365
- (0, common_utils_1.assert)(overriddenLocal >= newLastFinalizedLocal, 0x491 /* Malformed range: override ID ahead of range start. */);
366
- let cluster;
367
- let overriddenFinal;
368
- if (localIdPivot !== undefined && overriddenLocal <= localIdPivot) {
369
- // Override is at or past the pivot, so it is in a new cluster.
370
- (0, common_utils_1.assert)(newCluster !== undefined && newBaseFinalId !== undefined, 0x492 /* No cluster was created when overflow occurred. */);
371
- cluster = newCluster;
372
- overriddenFinal = (newBaseFinalId +
373
- (localIdPivot - overriddenLocal));
374
- }
375
- else {
376
- // Override was finalized into an existing cluster
377
- (0, common_utils_1.assert)(currentCluster !== undefined && currentBaseFinalId !== undefined, 0x493 /* No cluster exists but IDs were finalized. */);
378
- cluster = currentCluster;
379
- overriddenFinal = (currentBaseFinalId +
380
- initialClusterCount +
381
- (normalizedLastFinalizedLocal - overriddenLocal) -
382
- 1);
383
- }
384
- cluster.overrides ?? (cluster.overrides = new Map());
385
- const inversionKey = IdCompressor.createInversionKey(override);
386
- const existingIds = this.getExistingIdsForNewOverride(inversionKey, true);
387
- let overrideForCluster;
388
- let associatedLocal;
389
- if (existingIds !== undefined) {
390
- let mostFinalExistingOverride;
391
- if (typeof existingIds === "number") {
392
- mostFinalExistingOverride = existingIds;
393
- if (isLocalId(mostFinalExistingOverride)) {
394
- associatedLocal = mostFinalExistingOverride;
395
- }
396
- }
397
- else {
398
- [associatedLocal, mostFinalExistingOverride] = existingIds;
399
- }
400
- if (isFinalId(mostFinalExistingOverride)) {
401
- // A previous range already finalized an ID with this override. See `IdCluster` for more.
402
- overrideForCluster = mostFinalExistingOverride;
403
- }
404
- else {
405
- (0, common_utils_1.assert)(!isLocal || mostFinalExistingOverride === overriddenLocal, 0x494 /* Cannot have multiple local IDs with identical overrides. */);
406
- // This session has created an ID with this override before, but has not finalized it yet. The incoming
407
- // range "wins" and will contain the final ID associated with that override, regardless of if that range was
408
- // made by this session or not.
409
- overrideForCluster = override;
410
- }
411
- }
412
- else {
413
- // This is the first time this override has been associated with any ID
414
- overrideForCluster = override;
415
- }
416
- (0, common_utils_1.assert)(!cluster.overrides.has(overriddenFinal), 0x495 /* Cannot add a second override for final id */);
417
- if (typeof overrideForCluster === "string") {
418
- if (isLocal || associatedLocal === undefined) {
419
- cluster.overrides.set(overriddenFinal, override);
420
- }
421
- else {
422
- cluster.overrides.set(overriddenFinal, {
423
- override,
424
- originalOverridingFinal: overriddenFinal,
425
- associatedLocalId: associatedLocal,
426
- });
427
- }
428
- }
429
- else {
430
- const unifiedOverride = {
431
- override,
432
- originalOverridingFinal: overrideForCluster,
433
- };
434
- (0, utils_1.setPropertyIfDefined)(associatedLocal, unifiedOverride, "associatedLocalId");
435
- cluster.overrides.set(overriddenFinal, unifiedOverride);
174
+ if (remainingCapacity >= count) {
175
+ // The current range fits in the existing cluster
176
+ lastCluster.count += count;
177
+ }
178
+ else {
179
+ const overflow = count - remainingCapacity;
180
+ const newClaimedFinalCount = overflow + this.clusterCapacity;
181
+ if (lastCluster === this.finalSpace.getLastCluster()) {
182
+ // The last cluster in the sessions chain is the last cluster globally, so it can be expanded.
183
+ lastCluster.capacity += newClaimedFinalCount;
184
+ lastCluster.count += count;
185
+ (0, common_utils_1.assert)(!this.sessions.clusterCollides(lastCluster), 0x756 /* Cluster collision detected. */);
186
+ if (isLocal) {
187
+ this.logger?.sendTelemetryEvent({
188
+ eventName: "RuntimeIdCompressor:ClusterExpansion",
189
+ sessionId: this.localSessionId,
190
+ previousCapacity: lastCluster.capacity - newClaimedFinalCount,
191
+ newCapacity: lastCluster.capacity,
192
+ overflow,
193
+ });
436
194
  }
437
- const finalizedOverride = {
438
- cluster,
439
- originalOverridingFinal: overriddenFinal,
440
- };
441
- (0, utils_1.setPropertyIfDefined)(associatedLocal, finalizedOverride, "associatedLocalId");
442
- const currentOverride = this.clustersAndOverridesInversion.get(inversionKey);
443
- if (currentOverride === undefined ||
444
- IdCompressor.isUnfinalizedOverride(currentOverride)) {
445
- // Update the map to contain a finalized override, but never update it with future finalized overrides with
446
- // the same string; those should decompress to the first final ID with that override.
447
- this.clustersAndOverridesInversion.set(inversionKey, finalizedOverride);
195
+ }
196
+ else {
197
+ // The last cluster in the sessions chain is *not* the last cluster globally. Fill and overflow to new.
198
+ lastCluster.count = lastCluster.capacity;
199
+ const newCluster = this.addEmptyCluster(session, newClaimedFinalCount);
200
+ newCluster.count += overflow;
201
+ if (isLocal) {
202
+ this.logger?.sendTelemetryEvent({
203
+ eventName: "RuntimeIdCompressor:NewCluster",
204
+ sessionId: this.localSessionId,
205
+ });
448
206
  }
449
207
  }
450
208
  }
451
209
  if (isLocal) {
452
210
  this.logger?.sendTelemetryEvent({
453
211
  eventName: "RuntimeIdCompressor:IdCompressorStatus",
454
- eagerFinalIdCount: eagerFinalIdCount - (overrides?.length ?? 0),
455
- localIdCount: remainingCount + (overrides?.length ?? 0),
456
- overridesCount: overrides?.length ?? 0,
212
+ eagerFinalIdCount: this.telemetryEagerFinalIdCount,
213
+ localIdCount: this.telemetryLocalIdCount,
457
214
  sessionId: this.localSessionId,
458
215
  });
216
+ this.telemetryEagerFinalIdCount = 0;
217
+ this.telemetryLocalIdCount = 0;
459
218
  }
460
- session.lastFinalizedLocalId = newLastFinalizedLocal;
461
- }
462
- checkClusterForCollision(cluster) {
463
- const maxClusterUuid = (0, numericUuid_1.incrementUuid)(cluster.baseUuid, cluster.capacity - 1);
464
- const maxClusterStableId = (0, numericUuid_1.stableIdFromNumericUuid)(maxClusterUuid);
465
- const closestMatch = this.clustersAndOverridesInversion.getPairOrNextLower(maxClusterStableId);
466
- if (closestMatch !== undefined) {
467
- const [inversionKey, compressionMapping] = closestMatch;
468
- if (!IdCompressor.isClusterInfo(compressionMapping)) {
469
- if ((0, uuidUtilities_1.isStableId)(inversionKey) &&
470
- IdCompressor.uuidsMightCollide(inversionKey, maxClusterStableId, cluster.capacity)) {
471
- const numericOverride = (0, numericUuid_1.numericUuidFromStableId)(inversionKey);
472
- const delta = (0, numericUuid_1.getPositiveDelta)(maxClusterUuid, numericOverride, cluster.capacity - 1);
473
- if (delta !== undefined) {
474
- IdCompressor.failWithCollidingOverride(inversionKey);
475
- }
476
- }
477
- }
478
- }
479
- }
480
- static failWithCollidingOverride(override) {
481
- (0, utils_1.fail)(`Override '${override}' collides with another allocated UUID.`);
482
- }
483
- static isClusterInfo(compressionMapping) {
484
- return compressionMapping.clusterBase !== undefined;
485
- }
486
- static isUnfinalizedOverride(compressionMapping) {
487
- return typeof compressionMapping === "number";
488
- }
489
- static createInversionKey(inversionKey) {
490
- return (0, uuidUtilities_1.isStableId)(inversionKey)
491
- ? inversionKey
492
- : `${nonStableOverridePrefix}${inversionKey}`;
493
- }
494
- static isStableInversionKey(inversionKey) {
495
- return inversionKey.charAt(0) !== nonStableOverridePrefix;
496
- }
497
- /**
498
- * Returns an existing ID associated with an override, or undefined if none exists.
499
- */
500
- getExistingIdsForNewOverride(inversionKey, isFinalOverride) {
501
- const closestMatch = this.clustersAndOverridesInversion.getPairOrNextLower(inversionKey, reusedArray);
502
- let numericOverride;
503
- let stableOverride;
504
- if (closestMatch !== undefined) {
505
- const [key, compressionMapping] = closestMatch;
506
- if (!IdCompressor.isClusterInfo(compressionMapping)) {
507
- if (key === inversionKey) {
508
- if (IdCompressor.isUnfinalizedOverride(compressionMapping)) {
509
- return compressionMapping;
510
- }
511
- const finalizedOverride = compressionMapping;
512
- return finalizedOverride.associatedLocalId !== undefined
513
- ? [
514
- finalizedOverride.associatedLocalId,
515
- finalizedOverride.originalOverridingFinal,
516
- ]
517
- : finalizedOverride.originalOverridingFinal;
518
- }
519
- }
520
- else if (IdCompressor.isStableInversionKey(inversionKey)) {
521
- stableOverride = inversionKey;
522
- const cluster = compressionMapping.cluster;
523
- if (IdCompressor.uuidsMightCollide(inversionKey, key, cluster.capacity)) {
524
- numericOverride = (0, numericUuid_1.numericUuidFromStableId)(stableOverride);
525
- const delta = (0, numericUuid_1.getPositiveDelta)(numericOverride, cluster.baseUuid, cluster.capacity - 1);
526
- if (delta !== undefined) {
527
- if (!isFinalOverride) {
528
- if (delta >= cluster.count) {
529
- // TODO:#283: Properly implement unification
530
- return undefined;
531
- }
532
- return this.normalizeToSessionSpace((compressionMapping.clusterBase + delta));
533
- }
534
- }
535
- }
536
- }
537
- }
538
- const override = numericOverride ??
539
- stableOverride ??
540
- (IdCompressor.isStableInversionKey(inversionKey) ? inversionKey : undefined);
541
- if (override !== undefined) {
542
- const sessionSpaceId = this.getCompressedIdForStableId(override);
543
- if (sessionSpaceId !== undefined) {
544
- return sessionSpaceId;
545
- }
546
- }
547
- return undefined;
219
+ (0, common_utils_1.assert)(!session.isEmpty(), 0x757 /* Empty sessions should not be created. */);
548
220
  }
549
- /**
550
- * Check if `a` might be within `range` of `b`, where both are treated as hex numbers.
551
- * @param range - an integer
552
- */
553
- static uuidsMightCollide(a, b, range) {
554
- // Check if any of the UUIDs in the cluster collide (i.e. any in [base, base + capacity)).
555
- // Optimization: All UUIDs in a cluster are the same string up until the last few characters which encode the offset from
556
- // the cluster base. So, first compute the length of that shared string, and early out if it is different from the override
557
- // UUID. This way we usually need not do the more expensive check below.
558
- const hexDigitsToCheck = 32 - Math.ceil(Math.log2(range) / 2);
559
- if (a.startsWith(b.slice(0, hexDigitsToCheck))) {
560
- return true;
561
- }
562
- return false;
221
+ addEmptyCluster(session, capacity) {
222
+ const newCluster = session.addNewCluster(this.finalSpace.getAllocatedIdLimit(), capacity, 0);
223
+ (0, common_utils_1.assert)(!this.sessions.clusterCollides(newCluster), 0x758 /* Cluster collision detected. */);
224
+ this.finalSpace.addCluster(newCluster);
225
+ return newCluster;
563
226
  }
564
- /**
565
- * Helper for retrieving an override.
566
- */
567
- static tryGetOverride(cluster, finalId) {
568
- const override = cluster.overrides?.get(finalId);
569
- if (override === undefined) {
570
- return undefined;
571
- }
572
- if (typeof override === "string") {
573
- return override;
574
- }
575
- return override.override;
576
- }
577
- /**
578
- * Generates a new compressed ID or returns an existing one.
579
- * This should ONLY be called to generate IDs for local operations.
580
- * @param override - Specifies a specific string to be associated with the returned compressed ID.
581
- * Performance note: assigning override strings incurs a performance overhead.
582
- * @returns an existing ID if one already exists for `override`, and a new local ID otherwise. The returned ID is in session space.
583
- */
584
- generateCompressedId(override) {
585
- let overrideInversionKey;
586
- if (override !== undefined) {
587
- overrideInversionKey = IdCompressor.createInversionKey(override);
588
- const existingIds = this.getExistingIdsForNewOverride(overrideInversionKey, false);
589
- if (existingIds !== undefined) {
590
- return typeof existingIds === "number" ? existingIds : existingIds[0];
591
- }
592
- }
593
- // Bump local counter regardless, then attempt to optimistically return a final ID.
594
- // If the local session has reserved a cluster range via consensus, it is safe to hand out final IDs prior to
595
- // finalizing the range that includes these locals.
596
- const newLocalId = -++this.localIdCount;
597
- const { currentClusterDetails } = this.localSession;
598
- const { sessionIdNormalizer } = this;
599
- let eagerFinalId;
600
- let cluster;
601
- if (currentClusterDetails !== undefined) {
602
- cluster = currentClusterDetails.cluster;
603
- const lastFinalKnown = sessionIdNormalizer.getLastFinalId();
604
- if (lastFinalKnown !== undefined &&
605
- lastFinalKnown - currentClusterDetails.clusterBase + 1 < cluster.capacity) {
606
- eagerFinalId = (lastFinalKnown + 1);
607
- }
608
- }
609
- if (overrideInversionKey !== undefined) {
610
- const registeredLocal = sessionIdNormalizer.addLocalId();
611
- (0, common_utils_1.assert)(registeredLocal === newLocalId, 0x496 /* Session ID Normalizer produced unexpected local ID */);
612
- if (eagerFinalId !== undefined) {
613
- sessionIdNormalizer.addFinalIds(eagerFinalId, eagerFinalId, cluster ?? (0, utils_1.fail)("No cluster when generating compressed ID"));
614
- }
615
- this.localOverrides.append(newLocalId, override ?? (0, utils_1.fail)("Override must be defined"));
616
- // Since the local ID was just created, it is in both session and op space
617
- const compressionMapping = newLocalId;
618
- this.clustersAndOverridesInversion.set(overrideInversionKey, compressionMapping);
619
- }
620
- else if (eagerFinalId !== undefined) {
621
- sessionIdNormalizer.addFinalIds(eagerFinalId, eagerFinalId, cluster ?? (0, utils_1.fail)("No cluster when generating compressed ID"));
622
- return eagerFinalId;
227
+ normalizeToOpSpace(id) {
228
+ if ((0, identifiers_1.isFinalId)(id)) {
229
+ return id;
623
230
  }
624
231
  else {
625
- const registeredLocal = sessionIdNormalizer.addLocalId();
626
- (0, common_utils_1.assert)(registeredLocal === newLocalId, 0x497 /* Session ID Normalizer produced unexpected local ID */);
627
- }
628
- return newLocalId;
629
- }
630
- /**
631
- * Decompresses a previously compressed ID into a UUID or override string.
632
- * @param id - the compressed ID to be decompressed.
633
- * @returns the UUID or override string associated with the compressed ID. Fails if the ID was not generated by this compressor.
634
- */
635
- decompress(id) {
636
- return this.tryDecompress(id) ?? (0, utils_1.fail)("Compressed ID was not generated by this compressor");
637
- }
638
- /**
639
- * Attempts to decompress a previously compressed ID into a UUID or override string.
640
- * @param id - the compressed ID to be decompressed.
641
- * @returns the UUID or override string associated with the compressed ID, or undefined if the ID was not generated by this compressor.
642
- */
643
- tryDecompress(id) {
644
- if (isFinalId(id)) {
645
- const possibleCluster = this.getClusterForFinalId(id);
646
- if (possibleCluster === undefined) {
647
- // It may be an unfinalized eager final ID, so check with normalizer to get the offset from the session UUID
648
- const creationIndex = this.sessionIdNormalizer.getCreationIndex(id);
649
- if (creationIndex !== undefined) {
650
- return (0, numericUuid_1.stableIdFromNumericUuid)(this.localSession.sessionUuid, creationIndex);
232
+ const local = id;
233
+ if (!this.normalizer.contains(local)) {
234
+ throw new Error("Invalid ID to normalize.");
235
+ }
236
+ const finalForm = this.localSession.tryConvertToFinal(local, true);
237
+ return finalForm === undefined
238
+ ? local
239
+ : finalForm;
240
+ }
241
+ }
242
+ normalizeToSessionSpace(id, originSessionId) {
243
+ if ((0, identifiers_1.isFinalId)(id)) {
244
+ const containingCluster = this.localSession.getClusterByAllocatedFinal(id);
245
+ if (containingCluster === undefined) {
246
+ // Does not exist in local cluster chain
247
+ if (id >= this.finalSpace.getFinalizedIdLimit()) {
248
+ throw new Error("Unknown op space ID.");
651
249
  }
652
- return undefined;
250
+ return id;
653
251
  }
654
252
  else {
655
- const [baseFinalId, cluster] = possibleCluster;
656
- const override = IdCompressor.tryGetOverride(cluster, id);
657
- if (override !== undefined) {
658
- return override;
253
+ const alignedLocal = (0, sessions_1.getAlignedLocal)(containingCluster, id);
254
+ if (this.normalizer.contains(alignedLocal)) {
255
+ return alignedLocal;
659
256
  }
660
257
  else {
661
- const offsetInCluster = id - baseFinalId;
662
- return (0, numericUuid_1.stableIdFromNumericUuid)(cluster.baseUuid, offsetInCluster);
258
+ if ((0, utilities_1.genCountFromLocalId)(alignedLocal) > this.localGenCount) {
259
+ throw new Error("Unknown op space ID.");
260
+ }
261
+ return id;
663
262
  }
664
263
  }
665
264
  }
666
265
  else {
667
- const idOffset = -id; // Convert to a positive number
668
- if (idOffset > this.localIdCount) {
669
- // This local ID was never allocated.
670
- return undefined;
671
- }
672
- // If this is a local ID with an override, then it must have been allocated on this machine and will be contained in
673
- // `localOverrides`s. Otherwise, it is a sequential allocation from the session UUID and can simply be negated and
674
- // added to that UUID to obtain the stable ID associated with it.
675
- const localOverride = this.localOverrides?.get(id);
676
- return localOverride !== undefined
677
- ? localOverride
678
- : (0, numericUuid_1.stableIdFromNumericUuid)(this.localSession.sessionUuid, idOffset - 1);
679
- }
680
- }
681
- /**
682
- * Recompresses a decompressed ID, which could be a UUID or an override string.
683
- * @param uncompressed - the UUID or override string to recompress.
684
- * @returns the `CompressedId` associated with `uncompressed`. Fails if it has not been previously compressed by this compressor.
685
- */
686
- recompress(uncompressed) {
687
- return this.tryRecompress(uncompressed) ?? (0, utils_1.fail)("No such string has ever been compressed");
688
- }
689
- /**
690
- * Attempts to recompresses a decompressed ID, which could be a UUID or an override string.
691
- * @param uncompressed - the UUID or override string to recompress,
692
- * @returns the `CompressedId` associated with `uncompressed` or undefined if it has not been previously compressed by this compressor.
693
- */
694
- tryRecompress(uncompressed) {
695
- return this.recompressInternal(uncompressed);
696
- }
697
- /**
698
- * Helper to compress an uncompressed UUID. It can optionally be supplied with the numeric form of `uncompressedUuid` as a
699
- * performance optimization.
700
- */
701
- recompressInternal(uncompressed, uncompressedUuidNumeric) {
702
- let numericUuid = uncompressedUuidNumeric;
703
- const inversionKey = IdCompressor.createInversionKey(uncompressed);
704
- const isStable = IdCompressor.isStableInversionKey(inversionKey);
705
- const closestMatch = this.clustersAndOverridesInversion.getPairOrNextLower(inversionKey, reusedArray);
706
- if (closestMatch !== undefined) {
707
- const [key, compressionMapping] = closestMatch;
708
- if (!IdCompressor.isClusterInfo(compressionMapping)) {
709
- if (key === inversionKey) {
710
- return IdCompressor.isUnfinalizedOverride(compressionMapping)
711
- ? compressionMapping
712
- : compressionMapping.associatedLocalId ??
713
- compressionMapping.originalOverridingFinal;
266
+ const localToNormalize = id;
267
+ if (originSessionId === this.localSessionId) {
268
+ if (this.normalizer.contains(localToNormalize)) {
269
+ return localToNormalize;
270
+ }
271
+ else {
272
+ // We never generated this local ID, so fail
273
+ throw new Error("Unknown op space ID.");
714
274
  }
715
275
  }
716
276
  else {
717
- if (!isStable) {
718
- return undefined;
277
+ // LocalId from a remote session
278
+ const remoteSession = this.sessions.get(originSessionId);
279
+ if (remoteSession === undefined) {
280
+ throw new Error("No IDs have ever been finalized by the supplied session.");
719
281
  }
720
- const { clusterBase: closestBaseFinalId, cluster: closestCluster } = compressionMapping;
721
- numericUuid ?? (numericUuid = (0, numericUuid_1.numericUuidFromStableId)(inversionKey));
722
- const uuidOffset = (0, numericUuid_1.getPositiveDelta)(numericUuid, closestCluster.baseUuid, closestCluster.count - 1);
723
- if (uuidOffset !== undefined) {
724
- let targetFinalId = (closestBaseFinalId + uuidOffset);
725
- const override = closestCluster.overrides?.get(targetFinalId);
726
- if (typeof override === "object") {
727
- if (override.associatedLocalId !== undefined) {
728
- return override.associatedLocalId;
729
- }
730
- // This may be a UUID that should actually compress into a different final ID that it aligns with, due to
731
- // another session having an identical override (see `IdCluster` for more).
732
- targetFinalId = override.originalOverridingFinal;
733
- }
734
- return this.normalizeToSessionSpace(targetFinalId);
282
+ const correspondingFinal = remoteSession.tryConvertToFinal(localToNormalize, false);
283
+ if (correspondingFinal === undefined) {
284
+ throw new Error("Unknown op space ID.");
735
285
  }
286
+ return correspondingFinal;
736
287
  }
737
288
  }
738
- if (isStable) {
739
- // May have already computed the numeric UUID, so avoid recomputing if possible
740
- const sessionSpaceId = this.getCompressedIdForStableId(numericUuid ?? inversionKey);
741
- if (sessionSpaceId !== undefined) {
742
- return sessionSpaceId;
743
- }
744
- }
745
- return undefined;
746
- }
747
- /**
748
- * Normalizes a session space ID into op space.
749
- * @param id - the local ID to normalize.
750
- * @returns the ID in op space.
751
- */
752
- normalizeToOpSpace(id) {
753
- if (isFinalId(id)) {
754
- return id;
755
- }
756
- // Check if this local ID has not been allocated yet
757
- if (-id > this.localIdCount) {
758
- (0, utils_1.fail)("Supplied local ID was not created by this compressor.");
759
- }
760
- // Check if this local ID has not been finalized yet.
761
- // Comparing lastFinalizedLocalId is a safe check for eager final IDs because the local IDs corresponding to them
762
- // are never handed out to a consumer, and thus could not be passed into this method.
763
- const { lastFinalizedLocalId } = this.localSession;
764
- if (lastFinalizedLocalId === undefined || id < lastFinalizedLocalId) {
765
- // Eager final IDs do not have overrides in the cluster until finalizing
766
- // This means that using the normalizer to get the final/cluster associated would succeed but would not have the override,
767
- // so checking localOverrides first is necessary.
768
- const override = this.localOverrides.get(id);
769
- if (override !== undefined) {
770
- const inversionKey = IdCompressor.createInversionKey(override);
771
- const compressionMapping = this.clustersAndOverridesInversion.get(inversionKey) ??
772
- (0, utils_1.fail)("Bimap is malformed.");
773
- return !IdCompressor.isClusterInfo(compressionMapping) &&
774
- !IdCompressor.isUnfinalizedOverride(compressionMapping) &&
775
- compressionMapping.associatedLocalId === id
776
- ? compressionMapping.originalOverridingFinal
777
- : id;
778
- }
779
- const possibleFinal = this.sessionIdNormalizer.getFinalId(id);
780
- return possibleFinal?.[0] ?? id;
781
- }
782
- const [correspondingFinal, cluster] = this.sessionIdNormalizer.getFinalId(id) ??
783
- (0, utils_1.fail)("Locally created cluster should be added to the map when allocated");
784
- if (cluster.overrides) {
785
- const override = cluster.overrides.get(correspondingFinal);
786
- if (typeof override === "object" && override.originalOverridingFinal !== undefined) {
787
- // Rare case of two local IDs with same overrides are created concurrently. See `IdCluster` for more.
788
- return override.originalOverridingFinal;
789
- }
790
- }
791
- return correspondingFinal;
792
289
  }
793
- normalizeToSessionSpace(id, sessionIdIfLocal) {
794
- if (isLocalId(id)) {
795
- if (sessionIdIfLocal === undefined || sessionIdIfLocal === this.localSessionId) {
796
- const localIndex = -id;
797
- if (localIndex > this.localIdCount) {
798
- (0, utils_1.fail)("Supplied local ID was not created by this compressor.");
290
+ decompress(id) {
291
+ if ((0, identifiers_1.isFinalId)(id)) {
292
+ const containingCluster = sessions_1.Session.getContainingCluster(id, this.finalSpace.clusters);
293
+ if (containingCluster === undefined) {
294
+ throw new Error("Unknown ID");
295
+ }
296
+ const alignedLocal = (0, sessions_1.getAlignedLocal)(containingCluster, id);
297
+ const alignedGenCount = (0, utilities_1.genCountFromLocalId)(alignedLocal);
298
+ const lastFinalizedGenCount = (0, utilities_1.genCountFromLocalId)((0, sessions_1.lastFinalizedLocal)(containingCluster));
299
+ if (alignedGenCount > lastFinalizedGenCount) {
300
+ // should be an eager final id generated by the local session
301
+ if (containingCluster.session === this.localSession) {
302
+ (0, common_utils_1.assert)(!this.normalizer.contains(alignedLocal), 0x759 /* Normalizer out of sync. */);
303
+ }
304
+ else {
305
+ throw new Error("Unknown ID");
799
306
  }
800
- return id;
801
- }
802
- else {
803
- const session = this.sessions.get(sessionIdIfLocal) ??
804
- (0, utils_1.fail)("No IDs have ever been finalized by the supplied session.");
805
- const localCount = -id;
806
- const numericUuid = (0, numericUuid_1.incrementUuid)(session.sessionUuid, localCount - 1);
807
- return (this.compressNumericUuid(numericUuid) ??
808
- (0, utils_1.fail)("ID is not known to this compressor."));
809
307
  }
308
+ return (0, utilities_1.stableIdFromNumericUuid)((0, utilities_1.offsetNumericUuid)(containingCluster.session.sessionUuid, alignedGenCount - 1));
810
309
  }
811
- const normalizedId = this.sessionIdNormalizer.getSessionSpaceId(id);
812
- if (normalizedId !== undefined) {
813
- return normalizedId;
814
- }
815
- // Check for a unified override finalized first by another session but to which the local session
816
- // still has an associated local ID.
817
- const [_, cluster] = this.getClusterForFinalId(id) ??
818
- (0, utils_1.fail)("Supplied final ID was not finalized by this compressor.");
819
- const override = cluster.overrides?.get(id);
820
- if (typeof override === "object" && override.associatedLocalId !== undefined) {
821
- return override.associatedLocalId;
822
- }
823
- return id;
824
- }
825
- /**
826
- * Returns the session-space compressed ID corresponding to the numeric UUID, or undefined if it is not known to this compressor.
827
- * Typically, it will return the session-space ID sequentially aligned with it (which will be local if `numericUuid` was made by
828
- * the local session, or final otherwise). However, in the event that the aligned session-space ID was overridden with a UUID
829
- * *and* that override UUID was concurrently used in an older ID (earlier, w.r.t. sequencing), this method can return the first
830
- * ID to correspond to that override.
831
- *
832
- * As an example, consider the following two clients:
833
- * ClientA, session UUID: A0000000-0000-0000-0000-000000000000
834
- * ClientB, session UUID: B0000000-0000-0000-0000-000000000000
835
- *
836
- * If concurrently, two clients performed:
837
- * ClientA: generateCompressedId(override: 'X0000000-0000-0000-0000-000000000000') // aligned with A0000000-0000-0000-0000-000000000000
838
- *
839
- * ClientB: generateCompressedId() // aligned with B0000000-0000-0000-0000-000000000000
840
- * ClientB: generateCompressedId(override: 'X0000000-0000-0000-0000-000000000000') // aligned with B0000000-0000-0000-0000-000000000001
841
- *
842
- * After sequencing, calling this method and passing the numeric UUID for B0000000-0000-0000-0000-000000000001 would return the
843
- * session-space ID corresponding to A0000000-0000-0000-0000-000000000000 (with override X0000000-0000-0000-0000-000000000000).
844
- */
845
- compressNumericUuid(numericUuid) {
846
- const stableId = (0, numericUuid_1.stableIdFromNumericUuid)(numericUuid);
847
- const sessionSpaceId = this.recompressInternal(stableId, numericUuid);
848
- if (sessionSpaceId === undefined) {
849
- return undefined;
850
- }
851
- return sessionSpaceId;
852
- }
853
- /**
854
- * Returns a compressed ID for the supplied stable ID if it was created by the local session, and undefined otherwise.
855
- */
856
- getCompressedIdForStableId(stableId) {
857
- const numericUuid = typeof stableId === "string" ? (0, numericUuid_1.numericUuidFromStableId)(stableId) : stableId;
858
- const creationIndex = (0, numericUuid_1.getPositiveDelta)(numericUuid, this.localSession.sessionUuid, this.localIdCount - 1);
859
- if (creationIndex !== undefined) {
860
- const sessionSpaceId = this.sessionIdNormalizer.getIdByCreationIndex(creationIndex);
861
- if (sessionSpaceId !== undefined) {
862
- return sessionSpaceId;
310
+ else {
311
+ const localToDecompress = id;
312
+ if (!this.normalizer.contains(localToDecompress)) {
313
+ throw new Error("Unknown ID");
863
314
  }
315
+ return (0, utilities_1.stableIdFromNumericUuid)((0, utilities_1.offsetNumericUuid)(this.localSession.sessionUuid, (0, utilities_1.genCountFromLocalId)(localToDecompress) - 1));
864
316
  }
865
- return undefined;
866
317
  }
867
- getClusterForFinalId(finalId) {
868
- const possibleCluster = this.finalIdToCluster.getPairOrNextLower(finalId);
869
- if (possibleCluster === undefined) {
870
- return undefined;
871
- }
872
- const [clusterBase, cluster] = possibleCluster;
873
- if (finalId - clusterBase >= cluster.count) {
874
- return undefined;
318
+ recompress(uncompressed) {
319
+ const recompressed = this.tryRecompress(uncompressed);
320
+ if (recompressed === undefined) {
321
+ throw new Error("Could not recompress.");
875
322
  }
876
- return possibleCluster;
323
+ return recompressed;
877
324
  }
878
- /**
879
- * @returns if `other` is equal to this `IdCompressor`. The equality check includes local session state only if specified.
880
- * \@testOnly
881
- */
882
- equals(other, compareLocalState) {
883
- if (compareLocalState) {
884
- if (this.localIdCount !== other.localIdCount ||
885
- this.localSessionId !== other.localSessionId ||
886
- this.lastTakenLocalId !== other.lastTakenLocalId) {
887
- return false;
888
- }
889
- if (!this.localOverrides.equals(other.localOverrides, (a, b) => a === b)) {
890
- return false;
891
- }
892
- if (!(0, utils_1.compareMaps)(this.sessions, other.sessions, (a, b) => IdCompressor.sessionDataEqual(a, b, true, compareLocalState))) {
893
- return false;
894
- }
895
- if (!this.sessionIdNormalizer.equals(other.sessionIdNormalizer, (a, b) => IdCompressor.idClustersEqual(a, b, false, compareLocalState))) {
896
- return false;
897
- }
898
- }
899
- else {
900
- for (const [keyA, valueA] of this.sessions) {
901
- const valueB = other.sessions.get(keyA);
902
- if (valueB === undefined) {
903
- if (valueA.lastFinalizedLocalId !== undefined) {
904
- return false;
905
- }
906
- }
907
- else if (!IdCompressor.sessionDataEqual(valueA, valueB, true, compareLocalState)) {
908
- return false;
909
- }
910
- }
911
- for (const [keyB, valueB] of other.sessions) {
912
- const valueA = this.sessions.get(keyB);
913
- if (valueA === undefined) {
914
- if (valueB.lastFinalizedLocalId !== undefined) {
915
- return false;
916
- }
325
+ tryRecompress(uncompressed) {
326
+ const match = this.sessions.getContainingCluster(uncompressed);
327
+ if (match === undefined) {
328
+ const numericUncompressed = (0, utilities_1.numericUuidFromStableId)(uncompressed);
329
+ const offset = (0, utilities_1.subtractNumericUuids)(numericUncompressed, this.localSession.sessionUuid);
330
+ if (offset < Number.MAX_SAFE_INTEGER) {
331
+ const genCountEquivalent = Number(offset) + 1;
332
+ const localEquivalent = (0, utilities_1.localIdFromGenCount)(genCountEquivalent);
333
+ if (this.normalizer.contains(localEquivalent)) {
334
+ return localEquivalent;
917
335
  }
918
336
  }
337
+ return undefined;
919
338
  }
920
- if (this.nextClusterBaseFinalId !== other.nextClusterBaseFinalId ||
921
- this.newClusterCapacity !== other.newClusterCapacity) {
922
- return false;
923
- }
924
- if (!this.finalIdToCluster.equals(other.finalIdToCluster, (a, b) => IdCompressor.idClustersEqual(a, b, true, compareLocalState))) {
925
- return false;
926
- }
927
- const missingInOne = (_, value) => {
928
- if (!compareLocalState && IdCompressor.isUnfinalizedOverride(value)) {
929
- return undefined;
930
- }
931
- return { break: true };
932
- };
933
- const compareCompressionMappings = (a, b) => {
934
- const unfinalizedA = IdCompressor.isUnfinalizedOverride(a);
935
- const unfinalizedB = IdCompressor.isUnfinalizedOverride(b);
936
- if (unfinalizedA) {
937
- if (unfinalizedB) {
938
- return a === b;
339
+ else {
340
+ const [containingCluster, alignedLocal] = match;
341
+ if (containingCluster.session === this.localSession) {
342
+ // Local session
343
+ if (this.normalizer.contains(alignedLocal)) {
344
+ return alignedLocal;
939
345
  }
940
- return false;
941
- }
942
- else if (unfinalizedB) {
943
- return false;
944
- }
945
- if (IdCompressor.isClusterInfo(a)) {
946
- if (!IdCompressor.isClusterInfo(b) || a.clusterBase !== b.clusterBase) {
947
- return false;
346
+ else {
347
+ (0, common_utils_1.assert)((0, utilities_1.genCountFromLocalId)(alignedLocal) <= this.localGenCount, 0x75a /* Clusters out of sync. */);
348
+ // Id is an eager final
349
+ return (0, sessions_1.getAlignedFinal)(containingCluster, alignedLocal);
948
350
  }
949
351
  }
950
352
  else {
951
- if (IdCompressor.isClusterInfo(b) ||
952
- (compareLocalState && a.associatedLocalId !== b.associatedLocalId) ||
953
- a.originalOverridingFinal !== b.originalOverridingFinal) {
954
- return false;
955
- }
956
- }
957
- if (!IdCompressor.idClustersEqual(a.cluster, b.cluster, true, compareLocalState)) {
958
- return false;
959
- }
960
- return true;
961
- };
962
- const diff = this.clustersAndOverridesInversion.diffAgainst(other.clustersAndOverridesInversion, missingInOne, missingInOne, (_, valA, valB) => {
963
- if (!compareCompressionMappings(valA, valB)) {
964
- return { break: true };
965
- }
966
- return undefined;
353
+ // Not the local session
354
+ return (0, utilities_1.genCountFromLocalId)(alignedLocal) >= (0, sessions_1.lastFinalizedLocal)(containingCluster)
355
+ ? (0, sessions_1.getAlignedFinal)(containingCluster, alignedLocal)
356
+ : undefined;
357
+ }
358
+ }
359
+ }
360
+ serialize(hasLocalState) {
361
+ const { normalizer, finalSpace, sessions } = this;
362
+ const sessionIndexMap = new Map();
363
+ let sessionIndex = 0;
364
+ for (const session of sessions.sessions()) {
365
+ // Filter empty sessions to prevent them accumulating in the serialized state
366
+ if (!session.isEmpty() || hasLocalState) {
367
+ sessionIndexMap.set(session, sessionIndex);
368
+ sessionIndex++;
369
+ }
370
+ }
371
+ const localStateSize = hasLocalState
372
+ ? 1 + // generated ID count
373
+ 1 + // next range base genCount
374
+ 1 + // count of normalizer pairs
375
+ this.normalizer.idRanges.size * 2 // pairs
376
+ : 0;
377
+ // Layout size, in 8 byte increments
378
+ const totalSize = 1 + // version
379
+ 1 + // hasLocalState
380
+ 1 + // cluster capacity
381
+ 1 + // session count
382
+ 1 + // cluster count
383
+ sessionIndexMap.size * 2 + // session IDs
384
+ finalSpace.clusters.length * 3 + // clusters: (sessionIndex, capacity, count)[]
385
+ localStateSize; // local state, if present
386
+ const serializedFloat = new Float64Array(totalSize);
387
+ const serializedUint = new BigUint64Array(serializedFloat.buffer);
388
+ let index = 0;
389
+ index = (0, persistanceUtilities_1.writeNumber)(serializedFloat, index, currentWrittenVersion);
390
+ index = (0, persistanceUtilities_1.writeBoolean)(serializedFloat, index, hasLocalState);
391
+ index = (0, persistanceUtilities_1.writeNumber)(serializedFloat, index, this.clusterCapacity);
392
+ index = (0, persistanceUtilities_1.writeNumber)(serializedFloat, index, sessionIndexMap.size);
393
+ index = (0, persistanceUtilities_1.writeNumber)(serializedFloat, index, finalSpace.clusters.length);
394
+ for (const [session] of sessionIndexMap.entries()) {
395
+ index = (0, persistanceUtilities_1.writeNumericUuid)(serializedUint, index, session.sessionUuid);
396
+ }
397
+ finalSpace.clusters.forEach((cluster) => {
398
+ index = (0, persistanceUtilities_1.writeNumber)(serializedFloat, index, sessionIndexMap.get(cluster.session));
399
+ index = (0, persistanceUtilities_1.writeNumber)(serializedFloat, index, cluster.capacity);
400
+ index = (0, persistanceUtilities_1.writeNumber)(serializedFloat, index, cluster.count);
967
401
  });
968
- return diff === undefined;
969
- }
970
- static sessionDataEqual(a, b, checkCluster = true, compareLocalState = true) {
971
- if (!(0, numericUuid_1.numericUuidEquals)(a.sessionUuid, b.sessionUuid) ||
972
- a.lastFinalizedLocalId !== b.lastFinalizedLocalId) {
973
- return false;
974
- }
975
- if (a.currentClusterDetails === undefined || b.currentClusterDetails === undefined) {
976
- if (a.currentClusterDetails !== b.currentClusterDetails) {
977
- return false;
978
- }
979
- return true;
980
- }
981
- if (checkCluster &&
982
- !IdCompressor.idClustersEqual(a.currentClusterDetails.cluster, b.currentClusterDetails.cluster, false, compareLocalState)) {
983
- return false;
984
- }
985
- return true;
986
- }
987
- static idClustersEqual(a, b, checkSessionData = true, compareLocalState = true) {
988
- const areEqual = (0, numericUuid_1.numericUuidEquals)(a.baseUuid, b.baseUuid) &&
989
- a.capacity === b.capacity &&
990
- a.count === b.count &&
991
- (!checkSessionData ||
992
- IdCompressor.sessionDataEqual(a.session, b.session, false, compareLocalState)) &&
993
- (a.overrides === undefined) === (b.overrides === undefined) &&
994
- (a.overrides === undefined ||
995
- (0, utils_1.compareMaps)(a.overrides ?? (0, utils_1.fail)("Overrides must be defined"), b.overrides ?? (0, utils_1.fail)("Overrides must be defined"), (overrideA, overrideB) => {
996
- if (compareLocalState) {
997
- if (typeof overrideA === "string" || typeof overrideB === "string") {
998
- return overrideA === overrideB;
999
- }
1000
- const overridesEqual = overrideA.override === overrideB.override &&
1001
- overrideA.originalOverridingFinal ===
1002
- overrideB.originalOverridingFinal &&
1003
- (!compareLocalState ||
1004
- overrideA.associatedLocalId === overrideB.associatedLocalId);
1005
- return overridesEqual;
1006
- }
1007
- const uuidA = typeof overrideA === "string" ? overrideA : overrideA.override;
1008
- const uuidB = typeof overrideB === "string" ? overrideB : overrideB.override;
1009
- if (typeof overrideA !== "string" &&
1010
- typeof overrideB !== "string" &&
1011
- overrideA.originalOverridingFinal !== overrideB.originalOverridingFinal) {
1012
- return false;
1013
- }
1014
- return uuidA === uuidB;
1015
- }));
1016
- return areEqual;
1017
- }
1018
- serialize(withSession) {
1019
- const serializedSessions = [];
1020
- const sessionIdToSessionIndex = new Map();
1021
- for (const [sessionId, session] of this.sessions) {
1022
- const isLocalSession = sessionId === this.localSessionId;
1023
- const includeSession = sessionId !== reservedSessionId && // Ignore reserved clusters, but
1024
- (session.lastFinalizedLocalId !== undefined || // always serialize sessions that made final IDs,
1025
- (isLocalSession && withSession)); // include the un-acked local session if requested
1026
- if (includeSession) {
1027
- const sessionData = [sessionId];
1028
- sessionIdToSessionIndex.set(sessionId, serializedSessions.length);
1029
- serializedSessions.push(sessionData);
1030
- }
1031
- }
1032
- const serializedClusters = [];
1033
- for (const [baseFinalId, cluster] of this.finalIdToCluster.entries()) {
1034
- const sessionId = (0, numericUuid_1.stableIdFromNumericUuid)(cluster.session.sessionUuid);
1035
- if (sessionId !== reservedSessionId) {
1036
- const sessionIndex = sessionIdToSessionIndex.get(sessionId) ??
1037
- (0, utils_1.fail)("Session object contains wrong session numeric UUID");
1038
- const serializedCluster = [
1039
- sessionIndex,
1040
- cluster.capacity,
1041
- ];
1042
- if (cluster.count !== cluster.capacity) {
1043
- serializedCluster.push(cluster.count);
1044
- }
1045
- if (cluster.overrides !== undefined) {
1046
- const serializedOverrides = [];
1047
- for (const [finalId, override] of cluster.overrides) {
1048
- const finalIdIndex = finalId - baseFinalId;
1049
- if (typeof override === "string") {
1050
- serializedOverrides.push([finalIdIndex, override]);
1051
- }
1052
- else if (override.originalOverridingFinal === finalId) {
1053
- serializedOverrides.push([finalIdIndex, override.override]);
1054
- }
1055
- else {
1056
- serializedOverrides.push([
1057
- finalIdIndex,
1058
- override.override,
1059
- override.originalOverridingFinal,
1060
- ]);
1061
- }
1062
- }
1063
- serializedCluster.push(serializedOverrides);
1064
- }
1065
- serializedClusters.push(serializedCluster);
1066
- }
1067
- }
1068
- // Reserved session not serialized, and local session is present but may not make IDs
1069
- (0, common_utils_1.assert)(serializedSessions.length - this.sessions.size <= 2, 0x498 /* session not serialized */);
1070
- const serializedIdCompressor = {
1071
- version: currentWrittenVersion,
1072
- clusterCapacity: this.clusterCapacity,
1073
- sessions: serializedSessions,
1074
- clusters: serializedClusters,
1075
- };
1076
- if (withSession) {
1077
- const serializedWithSession = serializedIdCompressor;
1078
- serializedWithSession.localSessionIndex = serializedWithSession.sessions.findIndex(([sessionId]) => sessionId === this.localSessionId);
1079
- if (this.localIdCount > 0) {
1080
- serializedWithSession.localState = {
1081
- localIdCount: this.localIdCount,
1082
- overrides: [...this.localOverrides.entries()].map((entry) => [...entry]),
1083
- lastTakenLocalId: this.lastTakenLocalId,
1084
- sessionNormalizer: this.sessionIdNormalizer.serialize(),
1085
- };
402
+ if (hasLocalState) {
403
+ index = (0, persistanceUtilities_1.writeNumber)(serializedFloat, index, this.localGenCount);
404
+ index = (0, persistanceUtilities_1.writeNumber)(serializedFloat, index, this.nextRangeBaseGenCount);
405
+ index = (0, persistanceUtilities_1.writeNumber)(serializedFloat, index, normalizer.idRanges.size);
406
+ for (const [leadingGenCount, count] of normalizer.idRanges.entries()) {
407
+ index = (0, persistanceUtilities_1.writeNumber)(serializedFloat, index, leadingGenCount);
408
+ index = (0, persistanceUtilities_1.writeNumber)(serializedFloat, index, count);
1086
409
  }
1087
- return serializedWithSession;
1088
410
  }
411
+ (0, common_utils_1.assert)(index === totalSize, 0x75b /* Serialized size was incorrectly calculated. */);
1089
412
  this.logger?.sendTelemetryEvent({
1090
413
  eventName: "RuntimeIdCompressor:SerializedIdCompressorSize",
1091
- size: JSON.stringify(serializedIdCompressor).length,
1092
- clusterCount: serializedIdCompressor.clusters.length,
1093
- sessionCount: serializedIdCompressor.sessions.length,
414
+ size: serializedFloat.byteLength,
415
+ clusterCount: finalSpace.clusters.length,
416
+ sessionCount: sessionIndexMap.size,
1094
417
  });
1095
- return serializedIdCompressor;
1096
- }
1097
- static deserialize(...args) {
1098
- const [serialized, newSessionIdMaybe] = args;
1099
- const { clusterCapacity, sessions: serializedSessions, clusters: serializedClusters, } = serialized;
1100
- let localSessionId;
1101
- let serializedLocalState;
1102
- if (newSessionIdMaybe === undefined) {
1103
- // Alias of serialized, but known to be a SerializedIdCompressorWithOngoingSession
1104
- const [serializedWithSession] = args;
1105
- const serializedSessionData = serializedSessions[serializedWithSession.localSessionIndex];
1106
- localSessionId = serializedSessionData[0];
1107
- serializedLocalState = serializedWithSession.localState;
418
+ return (0, common_utils_1.bufferToString)(serializedFloat.buffer, "base64");
419
+ }
420
+ static deserialize(serialized, sessionId) {
421
+ const buffer = (0, common_utils_1.stringToBuffer)(serialized, "base64");
422
+ const index = {
423
+ index: 0,
424
+ bufferFloat: new Float64Array(buffer),
425
+ bufferUint: new BigUint64Array(buffer),
426
+ };
427
+ const version = (0, persistanceUtilities_1.readNumber)(index);
428
+ (0, common_utils_1.assert)(version === currentWrittenVersion, 0x75c /* Unknown serialized version. */);
429
+ const hasLocalState = (0, persistanceUtilities_1.readBoolean)(index);
430
+ const clusterCapacity = (0, persistanceUtilities_1.readNumber)(index);
431
+ const sessionCount = (0, persistanceUtilities_1.readNumber)(index);
432
+ const clusterCount = (0, persistanceUtilities_1.readNumber)(index);
433
+ // Sessions
434
+ let sessionOffset = 0;
435
+ const sessions = [];
436
+ if (!hasLocalState) {
437
+ // If !hasLocalState, there won't be a serialized local session ID so insert one at the beginning
438
+ (0, common_utils_1.assert)(sessionId !== undefined, 0x75d /* Local session ID is undefined. */);
439
+ const localSessionNumeric = (0, utilities_1.numericUuidFromStableId)(sessionId);
440
+ sessions.push([localSessionNumeric, new sessions_1.Session(localSessionNumeric)]);
441
+ sessionOffset = 1;
1108
442
  }
1109
443
  else {
1110
- localSessionId = newSessionIdMaybe;
444
+ (0, common_utils_1.assert)(sessionId === undefined, 0x75e /* Local state should not exist in serialized form. */);
1111
445
  }
1112
- const compressor = new IdCompressor(localSessionId);
1113
- compressor.clusterCapacity = clusterCapacity;
1114
- const localOverridesInverse = new Map();
1115
- if (serializedLocalState !== undefined) {
1116
- // Do this part of local rehydration first since the cluster map population needs to query to local overrides
1117
- compressor.localIdCount = serializedLocalState.localIdCount;
1118
- compressor.lastTakenLocalId = serializedLocalState.lastTakenLocalId;
1119
- if (serializedLocalState.overrides !== undefined) {
1120
- for (const [localId, override] of serializedLocalState.overrides) {
1121
- compressor.localOverrides.append(localId, override);
1122
- localOverridesInverse.set(override, localId);
1123
- compressor.clustersAndOverridesInversion.set(IdCompressor.createInversionKey(override), localId);
1124
- }
1125
- }
446
+ for (let i = 0; i < sessionCount; i++) {
447
+ const numeric = (0, persistanceUtilities_1.readNumericUuid)(index);
448
+ sessions.push([numeric, new sessions_1.Session(numeric)]);
1126
449
  }
1127
- const sessionInfos = [];
1128
- for (const serializedSession of serializedSessions) {
1129
- const [sessionId] = serializedSession;
1130
- if (sessionId === localSessionId) {
1131
- (0, common_utils_1.assert)(hasOngoingSession(serialized), 0x499 /* Cannot resume existing session. */);
1132
- sessionInfos.push({ session: compressor.localSession, sessionId });
1133
- }
1134
- else {
1135
- const session = compressor.createSession(sessionId);
1136
- sessionInfos.push({ session, sessionId });
1137
- }
1138
- }
1139
- for (const serializedCluster of serializedClusters) {
1140
- const { sessionIndex, capacity, count, overrides } = deserializeCluster(serializedCluster);
1141
- const { session, sessionId } = sessionInfos[sessionIndex];
1142
- const { lastFinalizedLocalId, sessionUuid } = session;
1143
- const currentIdCount = lastFinalizedLocalId === undefined ? 0 : -lastFinalizedLocalId;
1144
- const cluster = {
1145
- capacity,
1146
- count,
1147
- baseUuid: (0, numericUuid_1.incrementUuid)(sessionUuid, currentIdCount),
1148
- session,
1149
- };
1150
- const lastFinalizedNormalized = lastFinalizedLocalId ?? 0;
1151
- const clusterBase = compressor.nextClusterBaseFinalId;
1152
- session.lastFinalizedLocalId = (lastFinalizedNormalized - count);
1153
- session.currentClusterDetails = { clusterBase, cluster };
1154
- compressor.nextClusterBaseFinalId = (compressor.nextClusterBaseFinalId +
1155
- capacity);
1156
- compressor.finalIdToCluster.append(clusterBase, cluster);
1157
- compressor.clustersAndOverridesInversion.set((0, numericUuid_1.stableIdFromNumericUuid)(cluster.baseUuid), {
1158
- clusterBase,
1159
- cluster,
1160
- });
1161
- if (overrides !== undefined) {
1162
- cluster.overrides = new Map();
1163
- for (const [finalIdIndex, override, originalOverridingFinal] of overrides) {
1164
- const finalId = (clusterBase + finalIdIndex);
1165
- if (originalOverridingFinal !== undefined) {
1166
- const unifiedOverride = {
1167
- override,
1168
- originalOverridingFinal,
1169
- };
1170
- if (serializedLocalState !== undefined) {
1171
- (0, utils_1.setPropertyIfDefined)(localOverridesInverse.get(override), unifiedOverride, "associatedLocalId");
1172
- }
1173
- cluster.overrides.set(finalId, unifiedOverride);
1174
- }
1175
- else {
1176
- const associatedLocal = localOverridesInverse.get(override);
1177
- if (associatedLocal !== undefined && sessionId !== localSessionId) {
1178
- // In this case, there is a local ID associated with this override, but this is the first cluster to contain
1179
- // that override (because only the first cluster will have the string serialized). In this case, the override
1180
- // needs to hold that local value.
1181
- cluster.overrides.set(finalId, {
1182
- override,
1183
- originalOverridingFinal: finalId,
1184
- associatedLocalId: associatedLocal,
1185
- });
1186
- }
1187
- else {
1188
- cluster.overrides.set(finalId, override);
1189
- }
1190
- const finalizedOverride = {
1191
- cluster,
1192
- originalOverridingFinal: finalId,
1193
- };
1194
- if (serializedLocalState !== undefined) {
1195
- (0, utils_1.setPropertyIfDefined)(associatedLocal, finalizedOverride, "associatedLocalId");
1196
- }
1197
- compressor.clustersAndOverridesInversion.set(IdCompressor.createInversionKey(override), finalizedOverride);
1198
- }
1199
- }
1200
- }
1201
- }
1202
- if (serializedLocalState !== undefined) {
1203
- compressor.sessionIdNormalizer = sessionIdNormalizer_1.SessionIdNormalizer.deserialize(serializedLocalState.sessionNormalizer, (finalId) => {
1204
- const [_, cluster] = compressor.finalIdToCluster.getPairOrNextLower(finalId) ??
1205
- (0, utils_1.fail)("Final in serialized normalizer was never created.");
1206
- return cluster;
1207
- });
1208
- }
1209
- (0, common_utils_1.assert)(compressor.localSession.lastFinalizedLocalId === undefined ||
1210
- compressor.localIdCount >= -compressor.localSession.lastFinalizedLocalId, 0x49a /* Inconsistent last finalized state when deserializing */);
450
+ const compressor = new IdCompressor(new sessions_1.Sessions(sessions));
451
+ compressor.clusterCapacity = clusterCapacity;
452
+ // Clusters
453
+ let baseFinalId = 0;
454
+ for (let i = 0; i < clusterCount; i++) {
455
+ const sessionIndex = (0, persistanceUtilities_1.readNumber)(index);
456
+ const session = sessions[sessionIndex + sessionOffset][1];
457
+ const capacity = (0, persistanceUtilities_1.readNumber)(index);
458
+ const count = (0, persistanceUtilities_1.readNumber)(index);
459
+ const cluster = session.addNewCluster(baseFinalId, capacity, count);
460
+ compressor.finalSpace.addCluster(cluster);
461
+ baseFinalId += capacity;
462
+ }
463
+ // Local state
464
+ if (hasLocalState) {
465
+ compressor.localGenCount = (0, persistanceUtilities_1.readNumber)(index);
466
+ compressor.nextRangeBaseGenCount = (0, persistanceUtilities_1.readNumber)(index);
467
+ const normalizerCount = (0, persistanceUtilities_1.readNumber)(index);
468
+ for (let i = 0; i < normalizerCount; i++) {
469
+ compressor.normalizer.addLocalRange((0, persistanceUtilities_1.readNumber)(index), (0, persistanceUtilities_1.readNumber)(index));
470
+ }
471
+ }
472
+ (0, common_utils_1.assert)(index.index === index.bufferFloat.length, 0x75f /* Failed to read entire serialized compressor. */);
1211
473
  return compressor;
1212
474
  }
1213
- static convertToCurrentVersion(serializedCompressor, hasSession) {
1214
- if (serializedCompressor.version !== currentWrittenVersion) {
1215
- (0, utils_1.fail)("Unknown SerializedIdCompressor version number");
1216
- }
1217
- const serialized = serializedCompressor;
1218
- if (hasSession !== hasOngoingSession(serialized)) {
1219
- return undefined;
475
+ equals(other, includeLocalState) {
476
+ if (includeLocalState &&
477
+ (this.localSessionId !== other.localSessionId ||
478
+ !this.localSession.equals(other.localSession) ||
479
+ !this.normalizer.equals(other.normalizer) ||
480
+ this.nextRangeBaseGenCount !== other.nextRangeBaseGenCount ||
481
+ this.localGenCount !== other.localGenCount)) {
482
+ return false;
1220
483
  }
1221
- return serialized;
484
+ return (this.newClusterCapacity === other.newClusterCapacity &&
485
+ this.sessions.equals(other.sessions, includeLocalState) &&
486
+ this.finalSpace.equals(other.finalSpace));
1222
487
  }
1223
488
  }
1224
489
  exports.IdCompressor = IdCompressor;
1225
490
  /**
1226
- * Max allowed cluster size
491
+ * Max allowed initial cluster size.
1227
492
  */
1228
493
  IdCompressor.maxClusterSize = 2 ** 20;
1229
- /**
1230
- * The version of `IdCompressor` that is currently persisted.
1231
- */
1232
- const currentWrittenVersion = "0.0.1";
1233
- /**
1234
- * @returns whether or not the given serialized ID compressor has an ongoing session.
1235
- */
1236
- function hasOngoingSession(serialized) {
1237
- return (serialized.localSessionIndex !==
1238
- undefined);
1239
- }
1240
- exports.hasOngoingSession = hasOngoingSession;
1241
- function deserializeCluster(serializedCluster) {
1242
- const [sessionIndex, capacity, countOrOverrides, overrides] = serializedCluster;
1243
- const hasCount = typeof countOrOverrides === "number";
1244
- return {
1245
- sessionIndex,
1246
- capacity,
1247
- count: hasCount ? countOrOverrides : capacity,
1248
- overrides: hasCount ? overrides : countOrOverrides,
1249
- };
1250
- }
1251
- /**
1252
- * Optimization used by the sorted-btree library to avoid allocating tuples every time a lookup method is called.
1253
- * Lookup methods on BTree accept a pre-allocated array that it populates with the result of the lookup and retains no ownership
1254
- * of after the call, so this array may be supplied to any of them. References to this array should not be retained elsewhere and
1255
- * lookup results should be extracted from the tuple immediately after invocation.
1256
- */
1257
- const reusedArray = [];
1258
494
  //# sourceMappingURL=idCompressor.js.map