@fluidframework/id-compressor 3.2.0 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/api-report/id-compressor.legacy.beta.api.md +0 -49
- package/dist/idCompressor.d.ts +69 -19
- package/dist/idCompressor.d.ts.map +1 -1
- package/dist/idCompressor.js +365 -57
- package/dist/idCompressor.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/legacy.d.ts +1 -12
- package/dist/packageVersion.d.ts +1 -1
- package/dist/packageVersion.js +1 -1
- package/dist/packageVersion.js.map +1 -1
- package/dist/test/idCompressor.perf.spec.js.map +1 -1
- package/dist/test/idCompressor.spec.js.map +1 -1
- package/dist/test/idCompressorTestUtilities.d.ts.map +1 -1
- package/dist/test/idCompressorTestUtilities.js +8 -3
- package/dist/test/idCompressorTestUtilities.js.map +1 -1
- package/dist/test/sharding.fuzz.spec.d.ts +6 -0
- package/dist/test/sharding.fuzz.spec.d.ts.map +1 -0
- package/dist/test/sharding.fuzz.spec.js.map +1 -0
- package/dist/test/sharding.spec.d.ts +6 -0
- package/dist/test/sharding.spec.d.ts.map +1 -0
- package/dist/test/sharding.spec.js.map +1 -0
- package/dist/test/snapshots/summary.spec.js.map +1 -1
- package/dist/test/types/validateIdCompressorPrevious.generated.js.map +1 -1
- package/dist/types/idCompressor.d.ts +108 -2
- package/dist/types/idCompressor.d.ts.map +1 -1
- package/dist/types/idCompressor.js +15 -0
- package/dist/types/idCompressor.js.map +1 -1
- package/dist/types/index.d.ts +2 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js +3 -0
- package/dist/types/index.js.map +1 -1
- package/dist/types/persisted-types/0.0.1.d.ts +4 -4
- package/dist/types/persisted-types/0.0.1.js.map +1 -1
- package/dist/utilities.d.ts +1 -1
- package/dist/utilities.js +1 -1
- package/dist/utilities.js.map +1 -1
- package/lib/idCompressor.d.ts +69 -19
- package/lib/idCompressor.d.ts.map +1 -1
- package/lib/idCompressor.js +365 -57
- package/lib/idCompressor.js.map +1 -1
- package/lib/index.d.ts +2 -1
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +1 -0
- package/lib/index.js.map +1 -1
- package/lib/legacy.d.ts +1 -12
- package/lib/packageVersion.d.ts +1 -1
- package/lib/packageVersion.js +1 -1
- package/lib/packageVersion.js.map +1 -1
- package/lib/test/idCompressor.perf.spec.js.map +1 -1
- package/lib/test/idCompressor.spec.js.map +1 -1
- package/lib/test/idCompressorTestUtilities.d.ts.map +1 -1
- package/lib/test/idCompressorTestUtilities.js +8 -3
- package/lib/test/idCompressorTestUtilities.js.map +1 -1
- package/lib/test/sharding.fuzz.spec.d.ts +6 -0
- package/lib/test/sharding.fuzz.spec.d.ts.map +1 -0
- package/lib/test/sharding.fuzz.spec.js.map +1 -0
- package/lib/test/sharding.spec.d.ts +6 -0
- package/lib/test/sharding.spec.d.ts.map +1 -0
- package/lib/test/sharding.spec.js.map +1 -0
- package/lib/test/snapshots/summary.spec.js.map +1 -1
- package/lib/test/types/validateIdCompressorPrevious.generated.js.map +1 -1
- package/lib/types/idCompressor.d.ts +108 -2
- package/lib/types/idCompressor.d.ts.map +1 -1
- package/lib/types/idCompressor.js +14 -1
- package/lib/types/idCompressor.js.map +1 -1
- package/lib/types/index.d.ts +2 -1
- package/lib/types/index.d.ts.map +1 -1
- package/lib/types/index.js +1 -1
- package/lib/types/index.js.map +1 -1
- package/lib/types/persisted-types/0.0.1.d.ts +4 -4
- package/lib/types/persisted-types/0.0.1.js.map +1 -1
- package/lib/utilities.d.ts +1 -1
- package/lib/utilities.js +1 -1
- package/lib/utilities.js.map +1 -1
- package/package.json +42 -9
- package/src/idCompressor.ts +497 -73
- package/src/index.ts +3 -0
- package/src/packageVersion.ts +1 -1
- package/src/test/idCompressorTestUtilities.ts +16 -3
- package/src/test/snapshots/v2/compressor-with-finalized-range-from-one-client +1 -0
- package/src/test/snapshots/v2/compressor-with-finalized-range-from-one-client-client2 +1 -0
- package/src/test/snapshots/v2/compressors-with-finalized-ranges-from-two-clients +1 -0
- package/src/test/snapshots/v2/compressors-with-finalized-ranges-from-two-clients-client2 +1 -0
- package/src/test/snapshots/v2/empty-compressor-summary +1 -0
- package/src/test/snapshots/v2/expansion-semantics +1 -0
- package/src/test/snapshots/v2/expansion-semantics-client2 +1 -0
- package/src/test/snapshots/v3/compressor-with-finalized-range-from-one-client +1 -0
- package/src/test/snapshots/v3/compressor-with-finalized-range-from-one-client-client2 +1 -0
- package/src/test/snapshots/v3/compressors-with-finalized-ranges-from-two-clients +1 -0
- package/src/test/snapshots/v3/compressors-with-finalized-ranges-from-two-clients-client2 +1 -0
- package/src/test/snapshots/v3/empty-compressor-summary +1 -0
- package/src/test/snapshots/v3/expansion-semantics +1 -0
- package/src/test/snapshots/v3/expansion-semantics-client2 +1 -0
- package/src/test/types/validateIdCompressorPrevious.generated.ts +13 -1
- package/src/types/idCompressor.ts +119 -2
- package/src/types/index.ts +10 -1
- package/src/types/persisted-types/0.0.1.ts +4 -4
- package/src/utilities.ts +1 -1
package/lib/idCompressor.js
CHANGED
|
@@ -10,23 +10,21 @@ import { isFinalId, } from "./identifiers.js";
|
|
|
10
10
|
import { readBoolean, readNumber, readNumericUuid, writeBoolean, writeNumber, writeNumericUuid, } from "./persistanceUtilities.js";
|
|
11
11
|
import { SessionSpaceNormalizer } from "./sessionSpaceNormalizer.js";
|
|
12
12
|
import { Session, Sessions, getAlignedFinal, getAlignedLocal, lastFinalizedFinal, lastFinalizedLocal, } from "./sessions.js";
|
|
13
|
+
import { SerializationVersion } from "./types/index.js";
|
|
13
14
|
import { createSessionId, genCountFromLocalId, localIdFromGenCount, numericUuidFromStableId, offsetNumericUuid, stableIdFromNumericUuid, subtractNumericUuids, } from "./utilities.js";
|
|
14
|
-
/**
|
|
15
|
-
* The version of IdCompressor that is currently persisted.
|
|
16
|
-
* This should not be changed without careful consideration to compatibility.
|
|
17
|
-
*/
|
|
18
|
-
const currentWrittenVersion = 2;
|
|
19
15
|
function rangeFinalizationError(expectedStart, actualStart) {
|
|
20
16
|
return new LoggingError("Ranges finalized out of order", {
|
|
21
17
|
expectedStart,
|
|
22
18
|
actualStart,
|
|
23
19
|
});
|
|
24
20
|
}
|
|
21
|
+
const MAX_STRIDE_LENGTH = 1000000;
|
|
25
22
|
/**
|
|
26
23
|
* See {@link IIdCompressor} and {@link IIdCompressorCore}
|
|
27
24
|
*/
|
|
28
25
|
export class IdCompressor {
|
|
29
26
|
logger;
|
|
27
|
+
writeVersion;
|
|
30
28
|
/**
|
|
31
29
|
* Max allowed initial cluster size.
|
|
32
30
|
*/
|
|
@@ -37,11 +35,19 @@ export class IdCompressor {
|
|
|
37
35
|
normalizer = new SessionSpaceNormalizer();
|
|
38
36
|
// The number of IDs generated by the local session
|
|
39
37
|
localGenCount = 0;
|
|
38
|
+
/**
|
|
39
|
+
* The sharding state of this compressor, if it has been sharded or is a shard itself.
|
|
40
|
+
* When defined, this compressor operates in "sharding mode" where:
|
|
41
|
+
* - IDs are generated using stride-based allocation (no eager finals)
|
|
42
|
+
* - The normalizer backfills all IDs in each stride cycle
|
|
43
|
+
* - Normal operation resumes when all children are disposed
|
|
44
|
+
*/
|
|
45
|
+
shardingState;
|
|
40
46
|
// #endregion
|
|
41
47
|
// #region Final state
|
|
42
48
|
/**
|
|
43
49
|
* The gen count to be annotated on the range returned by the next call to `takeNextCreationRange`.
|
|
44
|
-
* This is advanced to `
|
|
50
|
+
* This is advanced to `localGenCount` + 1 each time it is called.
|
|
45
51
|
* On the other hand, when `resetUnfinalizedCreationRange` is called,
|
|
46
52
|
* this is moved back to the start of the unfinalized range, to ensure those IDs are included in the next range.
|
|
47
53
|
*/
|
|
@@ -65,8 +71,15 @@ export class IdCompressor {
|
|
|
65
71
|
// The ongoing ghost session, if one exists.
|
|
66
72
|
ongoingGhostSession;
|
|
67
73
|
// #endregion
|
|
68
|
-
constructor(localSessionIdOrDeserialized, logger
|
|
74
|
+
constructor(localSessionIdOrDeserialized, logger,
|
|
75
|
+
/**
|
|
76
|
+
* The version this compressor will write out.
|
|
77
|
+
* This applies to both `serialize` and creation range functions.
|
|
78
|
+
* This number also determines what features are available (e.g. sharding support starts at V3).
|
|
79
|
+
*/
|
|
80
|
+
writeVersion) {
|
|
69
81
|
this.logger = logger;
|
|
82
|
+
this.writeVersion = writeVersion;
|
|
70
83
|
if (typeof localSessionIdOrDeserialized === "string") {
|
|
71
84
|
this.localSessionId = localSessionIdOrDeserialized;
|
|
72
85
|
this.localSession = this.sessions.getOrCreate(localSessionIdOrDeserialized);
|
|
@@ -94,29 +107,38 @@ export class IdCompressor {
|
|
|
94
107
|
this.ongoingGhostSession.cluster.count++;
|
|
95
108
|
return lastFinalizedFinal(this.ongoingGhostSession.cluster);
|
|
96
109
|
}
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
// Space in the cluster: eager final
|
|
113
|
-
return (lastCluster.baseFinalId +
|
|
114
|
-
clusterOffset);
|
|
115
|
-
}
|
|
116
|
-
// No space in the cluster, return next local
|
|
110
|
+
// In sharding mode, always generate local IDs with stride-based allocation.
|
|
111
|
+
// Eager finals are disabled because shards backfill IDs not in their stride cycle.
|
|
112
|
+
// If another shard generated them as eager finals, ingesting IDs from another shard
|
|
113
|
+
// would fail depending on timing.
|
|
114
|
+
if (this.shardingState !== undefined) {
|
|
115
|
+
this.telemetryLocalIdCount++;
|
|
116
|
+
const { currentStride } = this.shardingState;
|
|
117
|
+
this.normalizer.addLocalRange(this.localGenCount + 1, currentStride);
|
|
118
|
+
this.localGenCount += currentStride;
|
|
119
|
+
return localIdFromGenCount(this.localGenCount);
|
|
120
|
+
}
|
|
121
|
+
// Normal ID generation
|
|
122
|
+
this.localGenCount++;
|
|
123
|
+
const lastCluster = this.localSession.getLastCluster();
|
|
124
|
+
if (lastCluster === undefined) {
|
|
117
125
|
this.telemetryLocalIdCount++;
|
|
118
126
|
return this.generateNextLocalId();
|
|
119
127
|
}
|
|
128
|
+
// If there exists a cluster of final IDs already claimed by the local session that still has room in it,
|
|
129
|
+
// it is known prior to range sequencing what a local ID's corresponding final ID will be.
|
|
130
|
+
// In this case, it is safe to return the final ID immediately. This is guaranteed to be safe because
|
|
131
|
+
// any op that the local session sends that contains one of those final IDs are guaranteed to arrive to
|
|
132
|
+
// collaborators *after* the one containing the creation range.
|
|
133
|
+
const clusterOffset = this.localGenCount - genCountFromLocalId(lastCluster.baseLocalId);
|
|
134
|
+
if (lastCluster.capacity > clusterOffset) {
|
|
135
|
+
this.telemetryEagerFinalIdCount++;
|
|
136
|
+
// Space in the cluster: eager final
|
|
137
|
+
return (lastCluster.baseFinalId + clusterOffset);
|
|
138
|
+
}
|
|
139
|
+
// No space in the cluster, return next local
|
|
140
|
+
this.telemetryLocalIdCount++;
|
|
141
|
+
return this.generateNextLocalId();
|
|
120
142
|
}
|
|
121
143
|
generateDocumentUniqueId() {
|
|
122
144
|
const id = this.generateCompressedId();
|
|
@@ -134,6 +156,9 @@ export class IdCompressor {
|
|
|
134
156
|
* {@inheritdoc IIdCompressorCore.beginGhostSession}
|
|
135
157
|
*/
|
|
136
158
|
beginGhostSession(ghostSessionId, ghostSessionCallback) {
|
|
159
|
+
if (this.shardingState) {
|
|
160
|
+
throw new Error("Cannot start a ghost session while sharded.");
|
|
161
|
+
}
|
|
137
162
|
this.startGhostSession(ghostSessionId);
|
|
138
163
|
try {
|
|
139
164
|
ghostSessionCallback();
|
|
@@ -142,12 +167,177 @@ export class IdCompressor {
|
|
|
142
167
|
this.ongoingGhostSession = undefined;
|
|
143
168
|
}
|
|
144
169
|
}
|
|
170
|
+
/**
|
|
171
|
+
* {@inheritdoc IIdCompressorCore.shard}
|
|
172
|
+
*/
|
|
173
|
+
shard(newShardCount) {
|
|
174
|
+
if (!Number.isSafeInteger(newShardCount) || newShardCount <= 0) {
|
|
175
|
+
throw new Error("Shard count must be a positive safe integer");
|
|
176
|
+
}
|
|
177
|
+
if (this.ongoingGhostSession) {
|
|
178
|
+
throw new Error("Cannot shard during ghost session");
|
|
179
|
+
}
|
|
180
|
+
if (this.writeVersion < SerializationVersion.V3) {
|
|
181
|
+
throw new Error(`Sharding requires document version ${SerializationVersion.V3} or higher, but this document is version ${this.writeVersion}`);
|
|
182
|
+
}
|
|
183
|
+
const currentStride = this.shardingState?.currentStride ?? 1;
|
|
184
|
+
const newStride = currentStride * (newShardCount + 1);
|
|
185
|
+
// ID usage is exponential in stride count. Limit to practical size to avoid overflow.
|
|
186
|
+
if (newStride > MAX_STRIDE_LENGTH) {
|
|
187
|
+
throw new Error("Sharding limit reached.");
|
|
188
|
+
}
|
|
189
|
+
assert(Number.isSafeInteger(newStride), 0xd52 /* Shard stride must be a safe integer */);
|
|
190
|
+
if (this.shardingState === undefined) {
|
|
191
|
+
// First time sharding - initialize state
|
|
192
|
+
this.shardingState = {
|
|
193
|
+
currentStride: newStride,
|
|
194
|
+
originalStride: 1,
|
|
195
|
+
activeChildIds: new Set(),
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
else {
|
|
199
|
+
this.shardingState.currentStride = newStride;
|
|
200
|
+
}
|
|
201
|
+
// Cache to avoid repeating per child
|
|
202
|
+
const serialized = this.serialize(true);
|
|
203
|
+
const { localGenCount: parentGenCount } = this;
|
|
204
|
+
const shards = [];
|
|
205
|
+
// Children are positioned at consecutive positions within the parents current stride cycle
|
|
206
|
+
// e.g. if parent owns the "evens" space (-2, -4, -6, ...) and is sharded into 3 (two children)
|
|
207
|
+
// while at -8, then the child shards will start at -10 and -12 with a stride of 6
|
|
208
|
+
for (let i = 1; i <= newShardCount; i++) {
|
|
209
|
+
const childShardId = createSessionId();
|
|
210
|
+
this.shardingState.activeChildIds.add(childShardId);
|
|
211
|
+
const childLocalGenCount = parentGenCount + i * currentStride;
|
|
212
|
+
// This code results in a double roundtrip, but is probably plenty fast enough for scenarios that need sharding,
|
|
213
|
+
// as they necessarily have process boundaries to deal with.
|
|
214
|
+
// If this ever became an issue we can implement a fast clone of compressors
|
|
215
|
+
const child = deserializeIdCompressor(serialized, this.writeVersion);
|
|
216
|
+
const genCountJump = childLocalGenCount - parentGenCount;
|
|
217
|
+
assert(child.localGenCount === parentGenCount && genCountJump > 0, 0xd53 /* Child offsets incorrectly calculated. */);
|
|
218
|
+
child.normalizer.addLocalRange(child.localGenCount + 1, genCountJump);
|
|
219
|
+
child.localGenCount = childLocalGenCount;
|
|
220
|
+
child.shardingState = {
|
|
221
|
+
currentStride: newStride,
|
|
222
|
+
originalStride: newStride,
|
|
223
|
+
activeChildIds: new Set(),
|
|
224
|
+
shardId: childShardId,
|
|
225
|
+
};
|
|
226
|
+
shards.push(child.serialize(true));
|
|
227
|
+
}
|
|
228
|
+
return shards;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* {@inheritdoc IIdCompressorCore.synchronizeWithShard}
|
|
232
|
+
*/
|
|
233
|
+
synchronizeWithShard(syncToken) {
|
|
234
|
+
const isNowLeaf = this.synchronizeChild(syncToken);
|
|
235
|
+
// A disposal token additionally reclaims the child's ID space. If reclaiming the last child
|
|
236
|
+
// returns this compressor to a leaf and it is the root (originalStride === 1), exit sharding mode.
|
|
237
|
+
if (syncToken.disposed) {
|
|
238
|
+
assert(this.shardingState !== undefined, 0xd54 /* Must be sharded */);
|
|
239
|
+
if (isNowLeaf && this.shardingState.originalStride === 1) {
|
|
240
|
+
this.shardingState = undefined;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
synchronizeChild(syncToken) {
|
|
245
|
+
const childDisposed = syncToken.disposed;
|
|
246
|
+
if (this.writeVersion < SerializationVersion.V3) {
|
|
247
|
+
throw new Error(`Sharding requires document version ${SerializationVersion.V3} or higher, but this document is version ${this.writeVersion}`);
|
|
248
|
+
}
|
|
249
|
+
if (this.shardingState === undefined) {
|
|
250
|
+
throw new Error("Must be in sharding mode.");
|
|
251
|
+
}
|
|
252
|
+
const childShardId = syncToken.shardId;
|
|
253
|
+
const { activeChildIds, originalStride } = this.shardingState;
|
|
254
|
+
// Verify this child belongs to us
|
|
255
|
+
if (!activeChildIds.has(childShardId)) {
|
|
256
|
+
throw new Error(`Cannot synchronize with child with ID ${childShardId}: not in active children set`);
|
|
257
|
+
}
|
|
258
|
+
// Only disposal removes the child from the active set. A plain synchronization leaves the
|
|
259
|
+
// child active so it can continue generating IDs and be synchronized with again later.
|
|
260
|
+
if (childDisposed) {
|
|
261
|
+
activeChildIds.delete(childShardId);
|
|
262
|
+
}
|
|
263
|
+
const isLeaf = activeChildIds.size === 0;
|
|
264
|
+
if (isLeaf && childDisposed) {
|
|
265
|
+
this.shardingState.currentStride = originalStride;
|
|
266
|
+
}
|
|
267
|
+
// Read currentStride after the possible stride reset above, so that a leaf-making disposal
|
|
268
|
+
// realigns the parent on its original (reclaimed) stride rather than the wider sharded stride.
|
|
269
|
+
const { currentStride } = this.shardingState;
|
|
270
|
+
const childGenCount = syncToken.localGenCount;
|
|
271
|
+
// Realign parent to next position in its sequence if child is ahead
|
|
272
|
+
if (childGenCount > this.localGenCount) {
|
|
273
|
+
// Find next aligned position in parent's sequence after child's genCount
|
|
274
|
+
const distance = childGenCount - this.localGenCount + 1;
|
|
275
|
+
const steps = Math.ceil(distance / currentStride);
|
|
276
|
+
const count = steps * currentStride;
|
|
277
|
+
this.normalizer.addLocalRange(this.localGenCount + 1, count);
|
|
278
|
+
this.localGenCount += count;
|
|
279
|
+
}
|
|
280
|
+
return isLeaf;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* {@inheritdoc IIdCompressorCore.dispose}
|
|
284
|
+
*/
|
|
285
|
+
disposeShard() {
|
|
286
|
+
if (this.shardingState === undefined) {
|
|
287
|
+
return undefined;
|
|
288
|
+
}
|
|
289
|
+
else {
|
|
290
|
+
if (this.shardingState.activeChildIds.size > 0) {
|
|
291
|
+
throw new Error("Cannot dispose a shard with active children.");
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
// A disposal token is a sync token that additionally signals reclamation of this shard's ID space.
|
|
295
|
+
const token = this.makeShardToken(true);
|
|
296
|
+
// Make this compressor unusable by replacing all methods with throwing stubs
|
|
297
|
+
// This is a one-time mutation that avoids runtime checks in every method
|
|
298
|
+
makeCompressorUnusable(this);
|
|
299
|
+
return token;
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* {@inheritdoc IIdCompressorCore.getShardSyncToken}
|
|
303
|
+
*/
|
|
304
|
+
getShardSyncToken() {
|
|
305
|
+
if (this.shardingState === undefined) {
|
|
306
|
+
return undefined;
|
|
307
|
+
}
|
|
308
|
+
return this.makeShardToken(false);
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Builds a token describing this shard's current progress.
|
|
312
|
+
* @param disposed - Whether the token also signals disposal (reclamation of this shard's ID space).
|
|
313
|
+
*/
|
|
314
|
+
makeShardToken(disposed) {
|
|
315
|
+
assert(this.shardingState !== undefined, 0xd55 /* Compressor is not sharded. */);
|
|
316
|
+
// Root cannot produce a token (shardId is undefined for root)
|
|
317
|
+
if (this.shardingState.shardId === undefined) {
|
|
318
|
+
throw new Error("Cannot get a token for a root compressor - only shards can be disposed");
|
|
319
|
+
}
|
|
320
|
+
const token = {
|
|
321
|
+
localGenCount: this.localGenCount,
|
|
322
|
+
shardId: this.shardingState.shardId,
|
|
323
|
+
disposed,
|
|
324
|
+
};
|
|
325
|
+
return token;
|
|
326
|
+
}
|
|
145
327
|
generateNextLocalId() {
|
|
146
328
|
// Must tell the normalizer that we generated a local ID
|
|
147
329
|
this.normalizer.addLocalRange(this.localGenCount, 1);
|
|
148
330
|
return localIdFromGenCount(this.localGenCount);
|
|
149
331
|
}
|
|
150
332
|
takeNextCreationRange() {
|
|
333
|
+
// Child (non-root) shards must not submit their own creation ranges. All shards in a shard tree share a
|
|
334
|
+
// single session, and only the root shard is responsible for finalizing that session's IDs with the server.
|
|
335
|
+
// A child's generated IDs are reconciled with the root via shard synchronization tokens (see
|
|
336
|
+
// synchronizeWithShard / disposeShard), not by independently sending ranges, which would overlap and
|
|
337
|
+
// conflict with the root's ranges for the shared session.
|
|
338
|
+
if (this.shardingState?.shardId !== undefined) {
|
|
339
|
+
throw new Error("Cannot take a creation range from a non-root shard.");
|
|
340
|
+
}
|
|
151
341
|
assert(!this.ongoingGhostSession, 0x8a6 /* IdCompressor should not be operated normally when in a ghost session */);
|
|
152
342
|
const count = this.localGenCount - (this.nextRangeBaseGenCount - 1);
|
|
153
343
|
if (count === 0) {
|
|
@@ -436,24 +626,36 @@ export class IdCompressor {
|
|
|
436
626
|
sessionIndex++;
|
|
437
627
|
}
|
|
438
628
|
}
|
|
629
|
+
const sizeOfUuid = 2;
|
|
630
|
+
const shardingStateSize = hasLocalState && this.writeVersion >= SerializationVersion.V3
|
|
631
|
+
? this.shardingState === undefined
|
|
632
|
+
? 1 // Boolean: no sharding state
|
|
633
|
+
: 1 + // Boolean: has sharding state
|
|
634
|
+
2 + // Numbers: currentStride, originalStride (Float64)
|
|
635
|
+
1 + // Number: activeChildIds count (Float64)
|
|
636
|
+
this.shardingState.activeChildIds.size * sizeOfUuid + // UUIDs: each is 128-bit
|
|
637
|
+
1 + // Boolean: hasShardId
|
|
638
|
+
(this.shardingState.shardId === undefined ? 0 : sizeOfUuid) // UUID: 128-bit if present
|
|
639
|
+
: 0;
|
|
439
640
|
const localStateSize = hasLocalState
|
|
440
641
|
? 1 + // generated ID count
|
|
441
642
|
1 + // next range base genCount
|
|
442
643
|
1 + // count of normalizer pairs
|
|
443
|
-
normalizer.idRanges.size * 2 // pairs
|
|
644
|
+
normalizer.idRanges.size * 2 + // pairs
|
|
645
|
+
shardingStateSize // sharding state if present
|
|
444
646
|
: 0;
|
|
445
647
|
// Layout size, in 8 byte increments
|
|
446
648
|
const totalSize = 1 + // version
|
|
447
649
|
1 + // hasLocalState
|
|
448
650
|
1 + // session count
|
|
449
651
|
1 + // cluster count
|
|
450
|
-
sessionIndexMap.size *
|
|
652
|
+
sessionIndexMap.size * sizeOfUuid + // session IDs
|
|
451
653
|
finalSpace.clusters.length * 3 + // clusters: (sessionIndex, capacity, count)[]
|
|
452
654
|
localStateSize; // local state, if present
|
|
453
655
|
const serializedFloat = new Float64Array(totalSize);
|
|
454
656
|
const serializedUint = new BigUint64Array(serializedFloat.buffer);
|
|
455
657
|
let index = 0;
|
|
456
|
-
index = writeNumber(serializedFloat, index,
|
|
658
|
+
index = writeNumber(serializedFloat, index, this.writeVersion);
|
|
457
659
|
index = writeBoolean(serializedFloat, index, hasLocalState);
|
|
458
660
|
index = writeNumber(serializedFloat, index, sessionIndexMap.size);
|
|
459
661
|
index = writeNumber(serializedFloat, index, finalSpace.clusters.length);
|
|
@@ -473,6 +675,24 @@ export class IdCompressor {
|
|
|
473
675
|
index = writeNumber(serializedFloat, index, leadingGenCount);
|
|
474
676
|
index = writeNumber(serializedFloat, index, count);
|
|
475
677
|
}
|
|
678
|
+
// Write sharding state (version 3+)
|
|
679
|
+
if (this.writeVersion >= SerializationVersion.V3) {
|
|
680
|
+
index = writeBoolean(serializedFloat, index, this.shardingState !== undefined);
|
|
681
|
+
if (this.shardingState !== undefined) {
|
|
682
|
+
index = writeNumber(serializedFloat, index, this.shardingState.currentStride);
|
|
683
|
+
index = writeNumber(serializedFloat, index, this.shardingState.originalStride);
|
|
684
|
+
// Write activeChildIds Set as count + array of NumericUuids
|
|
685
|
+
index = writeNumber(serializedFloat, index, this.shardingState.activeChildIds.size);
|
|
686
|
+
for (const childId of this.shardingState.activeChildIds) {
|
|
687
|
+
index = writeNumericUuid(serializedUint, index, numericUuidFromStableId(childId));
|
|
688
|
+
}
|
|
689
|
+
// Write shardId (optional)
|
|
690
|
+
index = writeBoolean(serializedFloat, index, this.shardingState.shardId !== undefined);
|
|
691
|
+
if (this.shardingState.shardId !== undefined) {
|
|
692
|
+
index = writeNumericUuid(serializedUint, index, numericUuidFromStableId(this.shardingState.shardId));
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
}
|
|
476
696
|
}
|
|
477
697
|
assert(index === totalSize, 0x75b /* Serialized size was incorrectly calculated. */);
|
|
478
698
|
logger?.sendTelemetryEvent({
|
|
@@ -484,27 +704,29 @@ export class IdCompressor {
|
|
|
484
704
|
return bufferToString(serializedFloat.buffer, "base64");
|
|
485
705
|
}
|
|
486
706
|
static deserialize(params) {
|
|
487
|
-
const { serialized, newSessionId, logger } = params;
|
|
707
|
+
const { serialized, newSessionId: sessionId, logger, requestedWriteVersion } = params;
|
|
488
708
|
const buffer = stringToBuffer(serialized, "base64");
|
|
489
709
|
const index = {
|
|
490
710
|
index: 0,
|
|
491
711
|
bufferFloat: new Float64Array(buffer),
|
|
492
712
|
bufferUint: new BigUint64Array(buffer),
|
|
493
713
|
};
|
|
494
|
-
const
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
case 2:
|
|
500
|
-
|
|
714
|
+
const serializedVersion = readNumber(index);
|
|
715
|
+
// If requested version is < the serialized version, we must write the version serialized
|
|
716
|
+
// to avoid losing data.
|
|
717
|
+
const writeVersion = Math.max(requestedWriteVersion, serializedVersion);
|
|
718
|
+
switch (serializedVersion) {
|
|
719
|
+
case 2:
|
|
720
|
+
case 3: {
|
|
721
|
+
break;
|
|
501
722
|
}
|
|
502
723
|
default: {
|
|
724
|
+
if (serializedVersion === 1) {
|
|
725
|
+
throw new Error("IdCompressor version 1.0 is no longer supported.");
|
|
726
|
+
}
|
|
503
727
|
throw new Error("Unknown IdCompressor serialized version.");
|
|
504
728
|
}
|
|
505
729
|
}
|
|
506
|
-
}
|
|
507
|
-
static deserialize2_0(index, sessionId, logger) {
|
|
508
730
|
const hasLocalState = readBoolean(index);
|
|
509
731
|
const sessionCount = readNumber(index);
|
|
510
732
|
const clusterCount = readNumber(index);
|
|
@@ -525,7 +747,7 @@ export class IdCompressor {
|
|
|
525
747
|
const numeric = readNumericUuid(index);
|
|
526
748
|
sessions.push([numeric, new Session(numeric)]);
|
|
527
749
|
}
|
|
528
|
-
const compressor = new IdCompressor(new Sessions(sessions), logger);
|
|
750
|
+
const compressor = new IdCompressor(new Sessions(sessions), logger, writeVersion);
|
|
529
751
|
// Clusters
|
|
530
752
|
let baseFinalId = 0;
|
|
531
753
|
for (let i = 0; i < clusterCount; i++) {
|
|
@@ -547,6 +769,34 @@ export class IdCompressor {
|
|
|
547
769
|
for (let i = 0; i < normalizerCount; i++) {
|
|
548
770
|
compressor.normalizer.addLocalRange(readNumber(index), readNumber(index));
|
|
549
771
|
}
|
|
772
|
+
// Sharding state (version 3+)
|
|
773
|
+
if (serializedVersion >= 3) {
|
|
774
|
+
const hasShardingState = readBoolean(index);
|
|
775
|
+
if (hasShardingState) {
|
|
776
|
+
const currentStride = readNumber(index);
|
|
777
|
+
const originalStride = readNumber(index);
|
|
778
|
+
// Read activeChildIds Set
|
|
779
|
+
const activeChildCount = readNumber(index);
|
|
780
|
+
const activeChildIds = new Set();
|
|
781
|
+
for (let i = 0; i < activeChildCount; i++) {
|
|
782
|
+
const childIdNumeric = readNumericUuid(index);
|
|
783
|
+
// Safe cast: these were serialized as SessionIds
|
|
784
|
+
activeChildIds.add(stableIdFromNumericUuid(childIdNumeric));
|
|
785
|
+
}
|
|
786
|
+
// Read shardId (optional)
|
|
787
|
+
const hasShardId = readBoolean(index);
|
|
788
|
+
const shardId = hasShardId
|
|
789
|
+
? stableIdFromNumericUuid(readNumericUuid(index))
|
|
790
|
+
: undefined;
|
|
791
|
+
// Build sharding state object, conditionally including shardId
|
|
792
|
+
compressor.shardingState = {
|
|
793
|
+
currentStride,
|
|
794
|
+
originalStride,
|
|
795
|
+
activeChildIds,
|
|
796
|
+
...(shardId !== undefined && { shardId }),
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
}
|
|
550
800
|
}
|
|
551
801
|
assert(index.index === index.bufferFloat.length, 0x75f /* Failed to read entire serialized compressor. */);
|
|
552
802
|
return compressor;
|
|
@@ -560,43 +810,101 @@ export class IdCompressor {
|
|
|
560
810
|
this.localGenCount !== other.localGenCount)) {
|
|
561
811
|
return false;
|
|
562
812
|
}
|
|
813
|
+
// Shard ownership affects future local ID allocation, even when the generated IDs match.
|
|
814
|
+
// It is not part of finalized state, so ignore it when comparing only that state.
|
|
815
|
+
if (includeLocalState) {
|
|
816
|
+
const state = this.shardingState;
|
|
817
|
+
const otherState = other.shardingState;
|
|
818
|
+
if (state === undefined || otherState === undefined) {
|
|
819
|
+
// Two unsharded compressors match here; a sharded and an unsharded compressor do not.
|
|
820
|
+
if (state !== otherState) {
|
|
821
|
+
return false;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
else {
|
|
825
|
+
if (state.currentStride !== otherState.currentStride ||
|
|
826
|
+
state.originalStride !== otherState.originalStride ||
|
|
827
|
+
state.shardId !== otherState.shardId ||
|
|
828
|
+
state.activeChildIds.size !== otherState.activeChildIds.size) {
|
|
829
|
+
return false;
|
|
830
|
+
}
|
|
831
|
+
// Child ownership is an unordered set. Equal sizes and membership imply equal sets,
|
|
832
|
+
// regardless of insertion order or whether the state was deserialized.
|
|
833
|
+
for (const childId of state.activeChildIds) {
|
|
834
|
+
if (!otherState.activeChildIds.has(childId)) {
|
|
835
|
+
return false;
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
}
|
|
563
840
|
return (this.sessions.equals(other.sessions, includeLocalState) &&
|
|
564
841
|
this.finalSpace.equals(other.finalSpace));
|
|
565
842
|
}
|
|
566
843
|
}
|
|
567
|
-
export function createIdCompressor(
|
|
844
|
+
export function createIdCompressor(sessionIdOrDocumentVersion, writeVersionOrLogger, loggerOrUndefined) {
|
|
568
845
|
let localSessionId;
|
|
846
|
+
let writeVersion;
|
|
569
847
|
let logger;
|
|
570
|
-
if (
|
|
571
|
-
|
|
848
|
+
if (typeof sessionIdOrDocumentVersion === "string") {
|
|
849
|
+
// Called with sessionId, writeVersion, logger?
|
|
850
|
+
localSessionId = sessionIdOrDocumentVersion;
|
|
851
|
+
writeVersion = writeVersionOrLogger;
|
|
852
|
+
logger = loggerOrUndefined;
|
|
572
853
|
}
|
|
573
854
|
else {
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
else {
|
|
579
|
-
localSessionId = createSessionId();
|
|
580
|
-
logger = sessionIdOrLogger;
|
|
581
|
-
}
|
|
855
|
+
// Called with writeVersion, logger?
|
|
856
|
+
localSessionId = createSessionId();
|
|
857
|
+
writeVersion = sessionIdOrDocumentVersion;
|
|
858
|
+
logger = writeVersionOrLogger;
|
|
582
859
|
}
|
|
583
|
-
const compressor = new IdCompressor(localSessionId, logger === undefined ? undefined : createChildLogger({ logger }));
|
|
860
|
+
const compressor = new IdCompressor(localSessionId, logger === undefined ? undefined : createChildLogger({ logger }), writeVersion);
|
|
584
861
|
return compressor;
|
|
585
862
|
}
|
|
586
|
-
export function deserializeIdCompressor(serialized,
|
|
587
|
-
if (typeof
|
|
863
|
+
export function deserializeIdCompressor(serialized, sessionIdOrDocumentVersion, writeVersionOrLogger, loggerOrUndefined) {
|
|
864
|
+
if (typeof sessionIdOrDocumentVersion === "string") {
|
|
865
|
+
// Called with (serialized, sessionId, writeVersion, logger?)
|
|
588
866
|
return IdCompressor.deserialize({
|
|
589
867
|
serialized: serialized,
|
|
590
868
|
logger: extractTelemetryLoggerExt(loggerOrUndefined),
|
|
591
|
-
newSessionId:
|
|
869
|
+
newSessionId: sessionIdOrDocumentVersion,
|
|
870
|
+
requestedWriteVersion: writeVersionOrLogger,
|
|
592
871
|
});
|
|
593
872
|
}
|
|
594
873
|
assert(loggerOrUndefined === undefined, 0xc2d /* logger would be in sessionIdOrLogger in this codepath */);
|
|
874
|
+
// Called with (serialized, writeVersion, logger?)
|
|
595
875
|
return IdCompressor.deserialize({
|
|
596
876
|
serialized: serialized,
|
|
597
|
-
logger: extractTelemetryLoggerExt(
|
|
877
|
+
logger: extractTelemetryLoggerExt(writeVersionOrLogger),
|
|
878
|
+
requestedWriteVersion: sessionIdOrDocumentVersion,
|
|
598
879
|
});
|
|
599
880
|
}
|
|
881
|
+
/**
|
|
882
|
+
* Throws an error indicating the compressor has been disposed.
|
|
883
|
+
*/
|
|
884
|
+
const throwDisposed = () => {
|
|
885
|
+
throw new Error("This compressor has been disposed via disposeShard() and can no longer be used.");
|
|
886
|
+
};
|
|
887
|
+
/**
|
|
888
|
+
* Makes an IdCompressor instance unusable by replacing all its methods with functions that throw.
|
|
889
|
+
* This is called once when disposeShard() is invoked to make the compressor permanently unusable.
|
|
890
|
+
* @param compressor - The compressor instance to make unusable
|
|
891
|
+
*/
|
|
892
|
+
function makeCompressorUnusable(compressor) {
|
|
893
|
+
// Get all method names from the prototype (where class methods live)
|
|
894
|
+
const proto = Object.getPrototypeOf(compressor);
|
|
895
|
+
for (const key of Reflect.ownKeys(proto)) {
|
|
896
|
+
if (key !== "constructor" && typeof Reflect.get(proto, key) === "function") {
|
|
897
|
+
// Shadow the method only on this instance so other compressors remain usable.
|
|
898
|
+
// Omitting `enumerable` keeps new overrides non-enumerable, like class methods.
|
|
899
|
+
// Reflection supports string and symbol keys without adding an index signature.
|
|
900
|
+
Object.defineProperty(compressor, key, {
|
|
901
|
+
value: throwDisposed,
|
|
902
|
+
configurable: true,
|
|
903
|
+
writable: true,
|
|
904
|
+
});
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
}
|
|
600
908
|
export function serializeIdCompressor(compressor, withSession) {
|
|
601
909
|
const core = toIdCompressorWithCore(compressor);
|
|
602
910
|
return withSession ? core.serialize(true) : core.serialize(false);
|