@fluidframework/container-runtime 2.0.0-dev.4.2.0.153917 → 2.0.0-dev.4.3.0.158678

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