@fluidframework/id-compressor 2.0.0-dev.7.4.0.221926

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 (157) hide show
  1. package/.eslintrc.js +27 -0
  2. package/.mocharc.js +12 -0
  3. package/CHANGELOG.md +3 -0
  4. package/LICENSE +21 -0
  5. package/README.md +170 -0
  6. package/api-extractor-lint.json +13 -0
  7. package/api-extractor.json +12 -0
  8. package/api-report/id-compressor.api.md +143 -0
  9. package/dist/appendOnlySortedMap.d.ts +124 -0
  10. package/dist/appendOnlySortedMap.d.ts.map +1 -0
  11. package/dist/appendOnlySortedMap.js +318 -0
  12. package/dist/appendOnlySortedMap.js.map +1 -0
  13. package/dist/finalSpace.d.ts +29 -0
  14. package/dist/finalSpace.d.ts.map +1 -0
  15. package/dist/finalSpace.js +62 -0
  16. package/dist/finalSpace.js.map +1 -0
  17. package/dist/id-compressor-alpha.d.ts +311 -0
  18. package/dist/id-compressor-beta.d.ts +41 -0
  19. package/dist/id-compressor-public.d.ts +41 -0
  20. package/dist/id-compressor-untrimmed.d.ts +329 -0
  21. package/dist/idCompressor.d.ts +85 -0
  22. package/dist/idCompressor.d.ts.map +1 -0
  23. package/dist/idCompressor.js +509 -0
  24. package/dist/idCompressor.js.map +1 -0
  25. package/dist/identifiers.d.ts +32 -0
  26. package/dist/identifiers.d.ts.map +1 -0
  27. package/dist/identifiers.js +15 -0
  28. package/dist/identifiers.js.map +1 -0
  29. package/dist/index.d.ts +11 -0
  30. package/dist/index.d.ts.map +1 -0
  31. package/dist/index.js +22 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/packageVersion.d.ts +9 -0
  34. package/dist/packageVersion.d.ts.map +1 -0
  35. package/dist/packageVersion.js +12 -0
  36. package/dist/packageVersion.js.map +1 -0
  37. package/dist/persistanceUtilities.d.ts +22 -0
  38. package/dist/persistanceUtilities.d.ts.map +1 -0
  39. package/dist/persistanceUtilities.js +43 -0
  40. package/dist/persistanceUtilities.js.map +1 -0
  41. package/dist/sessionSpaceNormalizer.d.ts +46 -0
  42. package/dist/sessionSpaceNormalizer.d.ts.map +1 -0
  43. package/dist/sessionSpaceNormalizer.js +80 -0
  44. package/dist/sessionSpaceNormalizer.js.map +1 -0
  45. package/dist/sessions.d.ts +115 -0
  46. package/dist/sessions.d.ts.map +1 -0
  47. package/dist/sessions.js +305 -0
  48. package/dist/sessions.js.map +1 -0
  49. package/dist/tsdoc-metadata.json +11 -0
  50. package/dist/types/idCompressor.d.ts +139 -0
  51. package/dist/types/idCompressor.d.ts.map +1 -0
  52. package/dist/types/idCompressor.js +7 -0
  53. package/dist/types/idCompressor.js.map +1 -0
  54. package/dist/types/identifiers.d.ts +40 -0
  55. package/dist/types/identifiers.d.ts.map +1 -0
  56. package/dist/types/identifiers.js +7 -0
  57. package/dist/types/identifiers.js.map +1 -0
  58. package/dist/types/index.d.ts +8 -0
  59. package/dist/types/index.d.ts.map +1 -0
  60. package/dist/types/index.js +10 -0
  61. package/dist/types/index.js.map +1 -0
  62. package/dist/types/persisted-types/0.0.1.d.ts +46 -0
  63. package/dist/types/persisted-types/0.0.1.d.ts.map +1 -0
  64. package/dist/types/persisted-types/0.0.1.js +14 -0
  65. package/dist/types/persisted-types/0.0.1.js.map +1 -0
  66. package/dist/types/persisted-types/index.d.ts +6 -0
  67. package/dist/types/persisted-types/index.d.ts.map +1 -0
  68. package/dist/types/persisted-types/index.js +10 -0
  69. package/dist/types/persisted-types/index.js.map +1 -0
  70. package/dist/utilities.d.ts +53 -0
  71. package/dist/utilities.d.ts.map +1 -0
  72. package/dist/utilities.js +170 -0
  73. package/dist/utilities.js.map +1 -0
  74. package/lib/appendOnlySortedMap.d.ts +124 -0
  75. package/lib/appendOnlySortedMap.d.ts.map +1 -0
  76. package/lib/appendOnlySortedMap.js +314 -0
  77. package/lib/appendOnlySortedMap.js.map +1 -0
  78. package/lib/finalSpace.d.ts +29 -0
  79. package/lib/finalSpace.d.ts.map +1 -0
  80. package/lib/finalSpace.js +58 -0
  81. package/lib/finalSpace.js.map +1 -0
  82. package/lib/id-compressor-alpha.d.ts +311 -0
  83. package/lib/id-compressor-beta.d.ts +41 -0
  84. package/lib/id-compressor-public.d.ts +41 -0
  85. package/lib/id-compressor-untrimmed.d.ts +329 -0
  86. package/lib/idCompressor.d.ts +85 -0
  87. package/lib/idCompressor.d.ts.map +1 -0
  88. package/lib/idCompressor.js +503 -0
  89. package/lib/idCompressor.js.map +1 -0
  90. package/lib/identifiers.d.ts +32 -0
  91. package/lib/identifiers.d.ts.map +1 -0
  92. package/lib/identifiers.js +11 -0
  93. package/lib/identifiers.js.map +1 -0
  94. package/lib/index.d.ts +11 -0
  95. package/lib/index.d.ts.map +1 -0
  96. package/lib/index.js +11 -0
  97. package/lib/index.js.map +1 -0
  98. package/lib/packageVersion.d.ts +9 -0
  99. package/lib/packageVersion.d.ts.map +1 -0
  100. package/lib/packageVersion.js +9 -0
  101. package/lib/packageVersion.js.map +1 -0
  102. package/lib/persistanceUtilities.d.ts +22 -0
  103. package/lib/persistanceUtilities.d.ts.map +1 -0
  104. package/lib/persistanceUtilities.js +34 -0
  105. package/lib/persistanceUtilities.js.map +1 -0
  106. package/lib/sessionSpaceNormalizer.d.ts +46 -0
  107. package/lib/sessionSpaceNormalizer.d.ts.map +1 -0
  108. package/lib/sessionSpaceNormalizer.js +76 -0
  109. package/lib/sessionSpaceNormalizer.js.map +1 -0
  110. package/lib/sessions.d.ts +115 -0
  111. package/lib/sessions.d.ts.map +1 -0
  112. package/lib/sessions.js +290 -0
  113. package/lib/sessions.js.map +1 -0
  114. package/lib/types/idCompressor.d.ts +139 -0
  115. package/lib/types/idCompressor.d.ts.map +1 -0
  116. package/lib/types/idCompressor.js +6 -0
  117. package/lib/types/idCompressor.js.map +1 -0
  118. package/lib/types/identifiers.d.ts +40 -0
  119. package/lib/types/identifiers.d.ts.map +1 -0
  120. package/lib/types/identifiers.js +6 -0
  121. package/lib/types/identifiers.js.map +1 -0
  122. package/lib/types/index.d.ts +8 -0
  123. package/lib/types/index.d.ts.map +1 -0
  124. package/lib/types/index.js +6 -0
  125. package/lib/types/index.js.map +1 -0
  126. package/lib/types/persisted-types/0.0.1.d.ts +46 -0
  127. package/lib/types/persisted-types/0.0.1.d.ts.map +1 -0
  128. package/lib/types/persisted-types/0.0.1.js +11 -0
  129. package/lib/types/persisted-types/0.0.1.js.map +1 -0
  130. package/lib/types/persisted-types/index.d.ts +6 -0
  131. package/lib/types/persisted-types/index.d.ts.map +1 -0
  132. package/lib/types/persisted-types/index.js +6 -0
  133. package/lib/types/persisted-types/index.js.map +1 -0
  134. package/lib/utilities.d.ts +53 -0
  135. package/lib/utilities.d.ts.map +1 -0
  136. package/lib/utilities.js +152 -0
  137. package/lib/utilities.js.map +1 -0
  138. package/package.json +110 -0
  139. package/prettier.config.cjs +8 -0
  140. package/src/appendOnlySortedMap.ts +366 -0
  141. package/src/finalSpace.ts +67 -0
  142. package/src/idCompressor.ts +689 -0
  143. package/src/identifiers.ts +42 -0
  144. package/src/index.ts +24 -0
  145. package/src/packageVersion.ts +9 -0
  146. package/src/persistanceUtilities.ts +58 -0
  147. package/src/sessionSpaceNormalizer.ts +83 -0
  148. package/src/sessions.ts +405 -0
  149. package/src/types/idCompressor.ts +155 -0
  150. package/src/types/identifiers.ts +39 -0
  151. package/src/types/index.ts +16 -0
  152. package/src/types/persisted-types/0.0.1.ts +51 -0
  153. package/src/types/persisted-types/README.md +3 -0
  154. package/src/types/persisted-types/index.ts +12 -0
  155. package/src/utilities.ts +191 -0
  156. package/tsconfig.esnext.json +7 -0
  157. package/tsconfig.json +10 -0
@@ -0,0 +1,290 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+ import BTree from "sorted-btree";
6
+ import { assert } from "@fluidframework/core-utils";
7
+ import { compareBigints, localIdFromGenCount, genCountFromLocalId, numericUuidFromStableId, stableIdFromNumericUuid, subtractNumericUuids, offsetNumericUuid, } from "./utilities";
8
+ /**
9
+ * A collection of all sessions known to the compressor (i.e. all finalized/acked allocated UUIDs and their corresponding local and final forms).
10
+ * This collection of all sessions comprises a distributed document's IDs.
11
+ */
12
+ export class Sessions {
13
+ constructor(sessions) {
14
+ // A range-queryable store of all sessions. A btree is used as it solves the predecessor problem for any given UUID, allowing
15
+ // us to quickly find the session that may have produced it.
16
+ this.uuidSpace = new BTree(undefined, compareBigints);
17
+ // A fast lookup table from session ID to the session object, used to avoid accessing the slower btree
18
+ this.sessionCache = new Map();
19
+ if (sessions !== undefined) {
20
+ // bulk load path
21
+ for (const [numeric, session] of sessions) {
22
+ this.sessionCache.set(stableIdFromNumericUuid(numeric), session);
23
+ }
24
+ this.uuidSpace = new BTree(sessions, compareBigints);
25
+ if (this.sessionCache.size !== sessions.length ||
26
+ sessions.length !== this.uuidSpace.size) {
27
+ throw new Error("Cannot resume existing session.");
28
+ }
29
+ }
30
+ }
31
+ sessions() {
32
+ return this.sessionCache.values();
33
+ }
34
+ getOrCreate(sessionId) {
35
+ const existing = this.sessionCache.get(sessionId);
36
+ if (existing !== undefined) {
37
+ return existing;
38
+ }
39
+ const session = new Session(sessionId);
40
+ assert(this.uuidSpace.set(session.sessionUuid, session), 0x760 /* Duplicate session in map. */);
41
+ this.sessionCache.set(sessionId, session);
42
+ return session;
43
+ }
44
+ get(sessionId) {
45
+ return this.sessionCache.get(sessionId);
46
+ }
47
+ getContainingCluster(query) {
48
+ const numericStable = numericUuidFromStableId(query);
49
+ const possibleMatch = this.uuidSpace.getPairOrNextLower(numericStable);
50
+ if (possibleMatch === undefined) {
51
+ return undefined;
52
+ }
53
+ const [_, session] = possibleMatch;
54
+ const numericDelta = subtractNumericUuids(numericStable, session.sessionUuid);
55
+ if (numericDelta > Number.MAX_SAFE_INTEGER) {
56
+ return undefined;
57
+ }
58
+ const alignedLocal = localIdFromGenCount(Number(numericDelta) + 1);
59
+ const containingCluster = session.getClusterByLocal(alignedLocal, true);
60
+ if (containingCluster === undefined) {
61
+ return undefined;
62
+ }
63
+ return [containingCluster, alignedLocal];
64
+ }
65
+ clusterCollides(cluster) {
66
+ const { session: owningSession, baseLocalId, capacity } = cluster;
67
+ const clusterBaseNumeric = offsetNumericUuid(owningSession.sessionUuid, genCountFromLocalId(baseLocalId) - 1);
68
+ const clusterMaxNumeric = offsetNumericUuid(clusterBaseNumeric, capacity - 1);
69
+ let closestMatch = this.uuidSpace.getPairOrNextLower(clusterMaxNumeric);
70
+ // Find the first session that is not the owner of this new cluster.
71
+ // Once we have that, check to see if its cluster chain overlaps with the new cluster.
72
+ // Consider the following diagram of UUID space:
73
+ // Cluster chain A: |----------------------|
74
+ // Cluster chain B: |----------|
75
+ // Cluster chain C: |-------|
76
+ // While it is true that when adding a cluster to chain C, we would find
77
+ // the next lower session (which is B) and erroneously determine we do not collide
78
+ // with any other session, but this situation is impossible to get into as B would
79
+ // have detected that it collided with A (or the other way around, depending on ordering).
80
+ while (closestMatch !== undefined && closestMatch[1] === owningSession) {
81
+ closestMatch = this.uuidSpace.nextLowerPair(closestMatch[0]);
82
+ }
83
+ if (closestMatch === undefined) {
84
+ return false;
85
+ }
86
+ const [_, session] = closestMatch;
87
+ assert(session !== owningSession, 0x761 /* Failed to attempt to detect collisions. */);
88
+ const lastCluster = session.getLastCluster();
89
+ if (lastCluster === undefined) {
90
+ // If the closest session is empty (the local session), then it is guaranteed (probabilistically) that there are no
91
+ // non-empty sessions that have a cluster chain that starts prior to the empty session and collides with the cluster
92
+ // we are checking, so we can return false.
93
+ return false;
94
+ }
95
+ const lastAllocatedNumeric = offsetNumericUuid(session.sessionUuid, genCountFromLocalId(lastAllocatedLocal(lastCluster)) - 1);
96
+ return lastAllocatedNumeric >= clusterBaseNumeric;
97
+ }
98
+ equals(other, includeLocalState) {
99
+ const checkIsSubset = (sessionsA, sessionsB) => {
100
+ const first = sessionsA.sessions().next();
101
+ const firstSessionThis = first.done ? undefined : first.value;
102
+ for (const [stableId, session] of sessionsA.sessionCache.entries()) {
103
+ const otherSession = sessionsB.sessionCache.get(stableId);
104
+ if (otherSession === undefined) {
105
+ if (!session.isEmpty() || includeLocalState) {
106
+ return false;
107
+ }
108
+ assert(session === firstSessionThis, 0x762 /* The only non-empty session must be the local session. */);
109
+ }
110
+ else if (!session.equals(otherSession)) {
111
+ return false;
112
+ }
113
+ }
114
+ return true;
115
+ };
116
+ return checkIsSubset(this, other) && checkIsSubset(other, this);
117
+ }
118
+ }
119
+ /**
120
+ * The IDs created by a specific session, stored as a cluster chain to allow for fast conversions.
121
+ */
122
+ export class Session {
123
+ constructor(sessionId) {
124
+ // All clusters created by this session, in creation order (thus sorted by base final and local ID).
125
+ this.clusterChain = [];
126
+ this.sessionUuid =
127
+ typeof sessionId === "string" ? numericUuidFromStableId(sessionId) : sessionId;
128
+ }
129
+ /**
130
+ * Adds a new empty cluster to the cluster chain of this session.
131
+ */
132
+ addNewCluster(baseFinalId, capacity, count) {
133
+ const lastCluster = this.getLastCluster();
134
+ const newCluster = {
135
+ session: this,
136
+ baseFinalId,
137
+ baseLocalId: (lastCluster === undefined
138
+ ? -1
139
+ : lastAllocatedLocal(lastCluster) - 1),
140
+ capacity,
141
+ count,
142
+ };
143
+ this.clusterChain.push(newCluster);
144
+ return newCluster;
145
+ }
146
+ isEmpty() {
147
+ return this.clusterChain.length === 0;
148
+ }
149
+ /**
150
+ * Returns the last cluster in this session's cluster chain, if any.
151
+ */
152
+ getLastCluster() {
153
+ return this.clusterChain[this.clusterChain.length - 1];
154
+ }
155
+ /**
156
+ * Converts the local ID from this session to a final ID, if possible.
157
+ * @param includeAllocated - true if the conversion should succeed even if the local ID aligns with a part of the cluster that is allocated but not finalized.
158
+ */
159
+ tryConvertToFinal(searchLocal, includeAllocated) {
160
+ const containingCluster = this.getClusterByLocal(searchLocal, includeAllocated);
161
+ if (containingCluster === undefined) {
162
+ return undefined;
163
+ }
164
+ return getAlignedFinal(containingCluster, searchLocal);
165
+ }
166
+ /**
167
+ * Returns the cluster containing the supplied local ID, if possible.
168
+ * @param includeAllocated - true if the conversion should succeed even if the local ID aligns with a part of the cluster that is allocated but not finalized.
169
+ */
170
+ getClusterByLocal(localId, includeAllocated) {
171
+ const lastValidLocal = includeAllocated
172
+ ? lastAllocatedLocal
173
+ : lastFinalizedLocal;
174
+ const matchedCluster = Session.binarySearch(localId, this.clusterChain, (local, cluster) => {
175
+ const lastLocal = lastValidLocal(cluster);
176
+ if (local < lastLocal) {
177
+ return 1;
178
+ }
179
+ else if (local > cluster.baseLocalId) {
180
+ return -1;
181
+ }
182
+ else {
183
+ return 0;
184
+ }
185
+ });
186
+ return matchedCluster;
187
+ }
188
+ /**
189
+ * Returns the cluster containing the supplied final ID, if possible.
190
+ */
191
+ getClusterByAllocatedFinal(final) {
192
+ return Session.getContainingCluster(final, this.clusterChain);
193
+ }
194
+ /**
195
+ * Returns the cluster from the supplied cluster chain containing the supplied final ID, if possible.
196
+ * `clusterChain` must be sorted by final/local base ID.
197
+ */
198
+ static getContainingCluster(finalId, clusterChain) {
199
+ return Session.binarySearch(finalId, clusterChain, (final, cluster) => {
200
+ const lastFinal = lastAllocatedFinal(cluster);
201
+ if (final < cluster.baseFinalId) {
202
+ return -1;
203
+ }
204
+ else if (final > lastFinal) {
205
+ return 1;
206
+ }
207
+ else {
208
+ return 0;
209
+ }
210
+ });
211
+ }
212
+ static binarySearch(search, arr, comparator) {
213
+ let left = 0;
214
+ let right = arr.length - 1;
215
+ while (left <= right) {
216
+ const mid = Math.floor((left + right) / 2);
217
+ const c = comparator(search, arr[mid]);
218
+ if (c === 0) {
219
+ return arr[mid]; // Found the target, return its index.
220
+ }
221
+ else if (c > 0) {
222
+ left = mid + 1; // Continue search on right half.
223
+ }
224
+ else {
225
+ right = mid - 1; // Continue search on left half.
226
+ }
227
+ }
228
+ return undefined; // If we reach here, target is not in array.
229
+ }
230
+ equals(other) {
231
+ for (let i = 0; i < this.clusterChain.length; i++) {
232
+ if (!clustersEqual(this.clusterChain[i], other.clusterChain[i])) {
233
+ return false;
234
+ }
235
+ }
236
+ return this.sessionUuid === other.sessionUuid;
237
+ }
238
+ }
239
+ export function clustersEqual(a, b) {
240
+ return (a.session.sessionUuid === b.session.sessionUuid &&
241
+ a.baseFinalId === b.baseFinalId &&
242
+ a.baseLocalId === b.baseLocalId &&
243
+ a.capacity === b.capacity &&
244
+ a.count === b.count);
245
+ }
246
+ /**
247
+ * Returns the final ID that is aligned with the supplied local ID within a cluster.
248
+ * Includes allocated IDs.
249
+ */
250
+ export function getAlignedFinal(cluster, localWithin) {
251
+ const clusterOffset = genCountFromLocalId(localWithin) - genCountFromLocalId(cluster.baseLocalId);
252
+ if (clusterOffset < cluster.capacity) {
253
+ return (cluster.baseFinalId + clusterOffset);
254
+ }
255
+ return undefined;
256
+ }
257
+ /**
258
+ * Returns the local ID that is aligned with the supplied final ID within a cluster.
259
+ * Fails if the supplied ID does not fall within the cluster bounds.
260
+ */
261
+ export function getAlignedLocal(cluster, finalWithin) {
262
+ assert(finalWithin >= cluster.baseFinalId && finalWithin <= lastAllocatedFinal(cluster), 0x763 /* Supplied ID is not within the cluster. */);
263
+ const finalDelta = finalWithin - cluster.baseFinalId;
264
+ return (cluster.baseLocalId - finalDelta);
265
+ }
266
+ /**
267
+ * Returns the last allocated final ID (i.e. any ID between base final and base final + capacity) within a cluster
268
+ */
269
+ export function lastAllocatedFinal(cluster) {
270
+ return (cluster.baseFinalId + (cluster.capacity - 1));
271
+ }
272
+ /**
273
+ * Returns the last allocated final ID (i.e. any ID between base final and base final + count) within a cluster
274
+ */
275
+ export function lastFinalizedFinal(cluster) {
276
+ return (cluster.baseFinalId + (cluster.count - 1));
277
+ }
278
+ /**
279
+ * Returns the last allocated local ID (i.e. any ID between base local and base local + capacity) within a cluster
280
+ */
281
+ export function lastAllocatedLocal(cluster) {
282
+ return (cluster.baseLocalId - (cluster.capacity - 1));
283
+ }
284
+ /**
285
+ * Returns the last allocated local ID (i.e. any ID between base local and base local + count) within a cluster
286
+ */
287
+ export function lastFinalizedLocal(cluster) {
288
+ return (cluster.baseLocalId - (cluster.count - 1));
289
+ }
290
+ //# sourceMappingURL=sessions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sessions.js","sourceRoot":"","sources":["../src/sessions.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,MAAM,cAAc,CAAC;AACjC,OAAO,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAC;AAEpD,OAAO,EACN,cAAc,EACd,mBAAmB,EACnB,mBAAmB,EACnB,uBAAuB,EACvB,uBAAuB,EACvB,oBAAoB,EACpB,iBAAiB,GACjB,MAAM,aAAa,CAAC;AAGrB;;;GAGG;AACH,MAAM,OAAO,QAAQ;IAOpB,YAAmB,QAAyD;QAN5E,6HAA6H;QAC7H,4DAA4D;QAC3C,cAAS,GAAG,IAAI,KAAK,CAAuB,SAAS,EAAE,cAAc,CAAC,CAAC;QACxF,sGAAsG;QACrF,iBAAY,GAAG,IAAI,GAAG,EAAsB,CAAC;QAG7D,IAAI,QAAQ,KAAK,SAAS,EAAE;YAC3B,iBAAiB;YACjB,KAAK,MAAM,CAAC,OAAO,EAAE,OAAO,CAAC,IAAI,QAAQ,EAAE;gBAC1C,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,uBAAuB,CAAC,OAAO,CAAc,EAAE,OAAO,CAAC,CAAC;aAC9E;YACD,IAAI,CAAC,SAAS,GAAG,IAAI,KAAK,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAC;YACrD,IACC,IAAI,CAAC,YAAY,CAAC,IAAI,KAAK,QAAQ,CAAC,MAAM;gBAC1C,QAAQ,CAAC,MAAM,KAAK,IAAI,CAAC,SAAS,CAAC,IAAI,EACtC;gBACD,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;aACnD;SACD;IACF,CAAC;IAEM,QAAQ;QACd,OAAO,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE,CAAC;IACnC,CAAC;IAEM,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* Licensed under the MIT License.\n */\n\nimport BTree from \"sorted-btree\";\nimport { assert } from \"@fluidframework/core-utils\";\nimport { SessionId, StableId } from \"./types\";\nimport {\n\tcompareBigints,\n\tlocalIdFromGenCount,\n\tgenCountFromLocalId,\n\tnumericUuidFromStableId,\n\tstableIdFromNumericUuid,\n\tsubtractNumericUuids,\n\toffsetNumericUuid,\n} from \"./utilities\";\nimport { FinalCompressedId, LocalCompressedId, NumericUuid } from \"./identifiers\";\n\n/**\n * A collection of all sessions known to the compressor (i.e. all finalized/acked allocated UUIDs and their corresponding local and final forms).\n * This collection of all sessions comprises a distributed document's IDs.\n */\nexport class Sessions {\n\t// A range-queryable store of all sessions. A btree is used as it solves the predecessor problem for any given UUID, allowing\n\t// us to quickly find the session that may have produced it.\n\tprivate readonly uuidSpace = new BTree<NumericUuid, Session>(undefined, compareBigints);\n\t// A fast lookup table from session ID to the session object, used to avoid accessing the slower btree\n\tprivate readonly sessionCache = new Map<SessionId, Session>();\n\n\tpublic constructor(sessions?: [sessionBase: NumericUuid, session: Session][]) {\n\t\tif (sessions !== undefined) {\n\t\t\t// bulk load path\n\t\t\tfor (const [numeric, session] of sessions) {\n\t\t\t\tthis.sessionCache.set(stableIdFromNumericUuid(numeric) as SessionId, session);\n\t\t\t}\n\t\t\tthis.uuidSpace = new BTree(sessions, compareBigints);\n\t\t\tif (\n\t\t\t\tthis.sessionCache.size !== sessions.length ||\n\t\t\t\tsessions.length !== this.uuidSpace.size\n\t\t\t) {\n\t\t\t\tthrow new Error(\"Cannot resume existing session.\");\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic sessions(): IterableIterator<Session> {\n\t\treturn this.sessionCache.values();\n\t}\n\n\tpublic getOrCreate(sessionId: SessionId): Session {\n\t\tconst existing = this.sessionCache.get(sessionId);\n\t\tif (existing !== undefined) {\n\t\t\treturn existing;\n\t\t}\n\t\tconst session = new Session(sessionId);\n\t\tassert(\n\t\t\tthis.uuidSpace.set(session.sessionUuid, session),\n\t\t\t0x760 /* Duplicate session in map. */,\n\t\t);\n\t\tthis.sessionCache.set(sessionId, session);\n\t\treturn session;\n\t}\n\n\tpublic get(sessionId: SessionId): Session | undefined {\n\t\treturn this.sessionCache.get(sessionId);\n\t}\n\n\tpublic getContainingCluster(\n\t\tquery: StableId,\n\t): [cluster: IdCluster, alignedLocal: LocalCompressedId] | undefined {\n\t\tconst numericStable = numericUuidFromStableId(query);\n\t\tconst possibleMatch = this.uuidSpace.getPairOrNextLower(numericStable);\n\t\tif (possibleMatch === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst [_, session] = possibleMatch;\n\t\tconst numericDelta = subtractNumericUuids(numericStable, session.sessionUuid);\n\t\tif (numericDelta > Number.MAX_SAFE_INTEGER) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst alignedLocal = localIdFromGenCount(Number(numericDelta) + 1);\n\t\tconst containingCluster = session.getClusterByLocal(alignedLocal, true);\n\t\tif (containingCluster === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn [containingCluster, alignedLocal];\n\t}\n\n\tpublic clusterCollides(cluster: IdCluster): boolean {\n\t\tconst { session: owningSession, baseLocalId, capacity } = cluster;\n\t\tconst clusterBaseNumeric = offsetNumericUuid(\n\t\t\towningSession.sessionUuid,\n\t\t\tgenCountFromLocalId(baseLocalId) - 1,\n\t\t);\n\t\tconst clusterMaxNumeric = offsetNumericUuid(clusterBaseNumeric, capacity - 1);\n\t\tlet closestMatch: [NumericUuid, Session] | undefined =\n\t\t\tthis.uuidSpace.getPairOrNextLower(clusterMaxNumeric);\n\t\t// Find the first session that is not the owner of this new cluster.\n\t\t// Once we have that, check to see if its cluster chain overlaps with the new cluster.\n\t\t// Consider the following diagram of UUID space:\n\t\t// Cluster chain A: |----------------------|\n\t\t// Cluster chain B: |----------|\n\t\t// Cluster chain C: |-------|\n\t\t// While it is true that when adding a cluster to chain C, we would find\n\t\t// the next lower session (which is B) and erroneously determine we do not collide\n\t\t// with any other session, but this situation is impossible to get into as B would\n\t\t// have detected that it collided with A (or the other way around, depending on ordering).\n\t\twhile (closestMatch !== undefined && closestMatch[1] === owningSession) {\n\t\t\tclosestMatch = this.uuidSpace.nextLowerPair(closestMatch[0]);\n\t\t}\n\t\tif (closestMatch === undefined) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst [_, session] = closestMatch;\n\t\tassert(session !== owningSession, 0x761 /* Failed to attempt to detect collisions. */);\n\t\tconst lastCluster = session.getLastCluster();\n\t\tif (lastCluster === undefined) {\n\t\t\t// If the closest session is empty (the local session), then it is guaranteed (probabilistically) that there are no\n\t\t\t// non-empty sessions that have a cluster chain that starts prior to the empty session and collides with the cluster\n\t\t\t// we are checking, so we can return false.\n\t\t\treturn false;\n\t\t}\n\t\tconst lastAllocatedNumeric = offsetNumericUuid(\n\t\t\tsession.sessionUuid,\n\t\t\tgenCountFromLocalId(lastAllocatedLocal(lastCluster)) - 1,\n\t\t);\n\t\treturn lastAllocatedNumeric >= clusterBaseNumeric;\n\t}\n\n\tpublic equals(other: Sessions, includeLocalState: boolean): boolean {\n\t\tconst checkIsSubset = (sessionsA: Sessions, sessionsB: Sessions) => {\n\t\t\tconst first = sessionsA.sessions().next();\n\t\t\tconst firstSessionThis = first.done ? undefined : first.value;\n\t\t\tfor (const [stableId, session] of sessionsA.sessionCache.entries()) {\n\t\t\t\tconst otherSession = sessionsB.sessionCache.get(stableId);\n\t\t\t\tif (otherSession === undefined) {\n\t\t\t\t\tif (!session.isEmpty() || includeLocalState) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tassert(\n\t\t\t\t\t\tsession === firstSessionThis,\n\t\t\t\t\t\t0x762 /* The only non-empty session must be the local session. */,\n\t\t\t\t\t);\n\t\t\t\t} else if (!session.equals(otherSession)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t};\n\t\treturn checkIsSubset(this, other) && checkIsSubset(other, this);\n\t}\n}\n\n/**\n * The IDs created by a specific session, stored as a cluster chain to allow for fast conversions.\n */\nexport class Session {\n\t// All clusters created by this session, in creation order (thus sorted by base final and local ID).\n\tprivate readonly clusterChain: IdCluster[] = [];\n\t// The numeric form of the SessionId\n\tpublic readonly sessionUuid: NumericUuid;\n\n\tpublic constructor(sessionId: SessionId | NumericUuid) {\n\t\tthis.sessionUuid =\n\t\t\ttypeof sessionId === \"string\" ? numericUuidFromStableId(sessionId) : sessionId;\n\t}\n\n\t/**\n\t * Adds a new empty cluster to the cluster chain of this session.\n\t */\n\tpublic addNewCluster(\n\t\tbaseFinalId: FinalCompressedId,\n\t\tcapacity: number,\n\t\tcount: number,\n\t): IdCluster {\n\t\tconst lastCluster = this.getLastCluster();\n\t\tconst newCluster: IdCluster = {\n\t\t\tsession: this,\n\t\t\tbaseFinalId,\n\t\t\tbaseLocalId: (lastCluster === undefined\n\t\t\t\t? -1\n\t\t\t\t: lastAllocatedLocal(lastCluster) - 1) as LocalCompressedId,\n\t\t\tcapacity,\n\t\t\tcount,\n\t\t};\n\t\tthis.clusterChain.push(newCluster);\n\t\treturn newCluster;\n\t}\n\n\tpublic isEmpty(): boolean {\n\t\treturn this.clusterChain.length === 0;\n\t}\n\n\t/**\n\t * Returns the last cluster in this session's cluster chain, if any.\n\t */\n\tpublic getLastCluster(): IdCluster | undefined {\n\t\treturn this.clusterChain[this.clusterChain.length - 1];\n\t}\n\n\t/**\n\t * Converts the local ID from this session to a final ID, if possible.\n\t * @param includeAllocated - true if the conversion should succeed even if the local ID aligns with a part of the cluster that is allocated but not finalized.\n\t */\n\tpublic tryConvertToFinal(\n\t\tsearchLocal: LocalCompressedId,\n\t\tincludeAllocated: boolean,\n\t): FinalCompressedId | undefined {\n\t\tconst containingCluster = this.getClusterByLocal(searchLocal, includeAllocated);\n\t\tif (containingCluster === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn getAlignedFinal(containingCluster, searchLocal);\n\t}\n\n\t/**\n\t * Returns the cluster containing the supplied local ID, if possible.\n\t * @param includeAllocated - true if the conversion should succeed even if the local ID aligns with a part of the cluster that is allocated but not finalized.\n\t */\n\tpublic getClusterByLocal(\n\t\tlocalId: LocalCompressedId,\n\t\tincludeAllocated: boolean,\n\t): IdCluster | undefined {\n\t\tconst lastValidLocal: (cluster: IdCluster) => LocalCompressedId = includeAllocated\n\t\t\t? lastAllocatedLocal\n\t\t\t: lastFinalizedLocal;\n\t\tconst matchedCluster = Session.binarySearch(\n\t\t\tlocalId,\n\t\t\tthis.clusterChain,\n\t\t\t(local, cluster): number => {\n\t\t\t\tconst lastLocal = lastValidLocal(cluster);\n\t\t\t\tif (local < lastLocal) {\n\t\t\t\t\treturn 1;\n\t\t\t\t} else if (local > cluster.baseLocalId) {\n\t\t\t\t\treturn -1;\n\t\t\t\t} else {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\t\treturn matchedCluster;\n\t}\n\n\t/**\n\t * Returns the cluster containing the supplied final ID, if possible.\n\t */\n\tpublic getClusterByAllocatedFinal(final: FinalCompressedId): IdCluster | undefined {\n\t\treturn Session.getContainingCluster(final, this.clusterChain);\n\t}\n\n\t/**\n\t * Returns the cluster from the supplied cluster chain containing the supplied final ID, if possible.\n\t * `clusterChain` must be sorted by final/local base ID.\n\t */\n\tpublic static getContainingCluster(\n\t\tfinalId: FinalCompressedId,\n\t\tclusterChain: readonly IdCluster[],\n\t): IdCluster | undefined {\n\t\treturn Session.binarySearch(finalId, clusterChain, (final, cluster) => {\n\t\t\tconst lastFinal = lastAllocatedFinal(cluster);\n\t\t\tif (final < cluster.baseFinalId) {\n\t\t\t\treturn -1;\n\t\t\t} else if (final > lastFinal) {\n\t\t\t\treturn 1;\n\t\t\t} else {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t});\n\t}\n\n\tstatic binarySearch<S, T>(\n\t\tsearch: S,\n\t\tarr: readonly T[],\n\t\tcomparator: (a: S, b: T) => number,\n\t): T | undefined {\n\t\tlet left = 0;\n\t\tlet right = arr.length - 1;\n\t\twhile (left <= right) {\n\t\t\tconst mid = Math.floor((left + right) / 2);\n\t\t\tconst c = comparator(search, arr[mid]);\n\t\t\tif (c === 0) {\n\t\t\t\treturn arr[mid]; // Found the target, return its index.\n\t\t\t} else if (c > 0) {\n\t\t\t\tleft = mid + 1; // Continue search on right half.\n\t\t\t} else {\n\t\t\t\tright = mid - 1; // Continue search on left half.\n\t\t\t}\n\t\t}\n\t\treturn undefined; // If we reach here, target is not in array.\n\t}\n\n\tpublic equals(other: Session): boolean {\n\t\tfor (let i = 0; i < this.clusterChain.length; i++) {\n\t\t\tif (!clustersEqual(this.clusterChain[i], other.clusterChain[i])) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn this.sessionUuid === other.sessionUuid;\n\t}\n}\n\n/**\n * A cluster of final (sequenced via consensus), sequentially allocated compressed IDs.\n * A final ID in a cluster decompresses to a sequentially allocated UUID that is the result of adding its offset within\n * the cluster to base UUID for the session that created it.\n */\nexport interface IdCluster {\n\t/**\n\t * The session that created this cluster.\n\t */\n\treadonly session: Session;\n\n\t/**\n\t * The first final ID in the cluster.\n\t */\n\treadonly baseFinalId: FinalCompressedId;\n\n\t/**\n\t * The local ID aligned with `baseFinalId`.\n\t */\n\treadonly baseLocalId: LocalCompressedId;\n\n\t/**\n\t * The total number of final IDs reserved for allocation in the cluster.\n\t * Clusters are reserved in blocks as a performance optimization.\n\t */\n\tcapacity: number;\n\n\t/**\n\t * The number of final IDs currently allocated in the cluster.\n\t */\n\tcount: number;\n}\n\nexport function clustersEqual(a: IdCluster, b: IdCluster): boolean {\n\treturn (\n\t\ta.session.sessionUuid === b.session.sessionUuid &&\n\t\ta.baseFinalId === b.baseFinalId &&\n\t\ta.baseLocalId === b.baseLocalId &&\n\t\ta.capacity === b.capacity &&\n\t\ta.count === b.count\n\t);\n}\n\n/**\n * Returns the final ID that is aligned with the supplied local ID within a cluster.\n * Includes allocated IDs.\n */\nexport function getAlignedFinal(\n\tcluster: IdCluster,\n\tlocalWithin: LocalCompressedId,\n): FinalCompressedId | undefined {\n\tconst clusterOffset =\n\t\tgenCountFromLocalId(localWithin) - genCountFromLocalId(cluster.baseLocalId);\n\tif (clusterOffset < cluster.capacity) {\n\t\treturn ((cluster.baseFinalId as number) + clusterOffset) as FinalCompressedId;\n\t}\n\treturn undefined;\n}\n\n/**\n * Returns the local ID that is aligned with the supplied final ID within a cluster.\n * Fails if the supplied ID does not fall within the cluster bounds.\n */\nexport function getAlignedLocal(\n\tcluster: IdCluster,\n\tfinalWithin: FinalCompressedId,\n): LocalCompressedId {\n\tassert(\n\t\tfinalWithin >= cluster.baseFinalId && finalWithin <= lastAllocatedFinal(cluster),\n\t\t0x763 /* Supplied ID is not within the cluster. */,\n\t);\n\tconst finalDelta = finalWithin - cluster.baseFinalId;\n\treturn (cluster.baseLocalId - finalDelta) as LocalCompressedId;\n}\n\n/**\n * Returns the last allocated final ID (i.e. any ID between base final and base final + capacity) within a cluster\n */\nexport function lastAllocatedFinal(cluster: IdCluster): FinalCompressedId {\n\treturn ((cluster.baseFinalId as number) + (cluster.capacity - 1)) as FinalCompressedId;\n}\n\n/**\n * Returns the last allocated final ID (i.e. any ID between base final and base final + count) within a cluster\n */\nexport function lastFinalizedFinal(cluster: IdCluster): FinalCompressedId {\n\treturn ((cluster.baseFinalId as number) + (cluster.count - 1)) as FinalCompressedId;\n}\n\n/**\n * Returns the last allocated local ID (i.e. any ID between base local and base local + capacity) within a cluster\n */\nexport function lastAllocatedLocal(cluster: IdCluster): LocalCompressedId {\n\treturn ((cluster.baseLocalId as number) - (cluster.capacity - 1)) as LocalCompressedId;\n}\n\n/**\n * Returns the last allocated local ID (i.e. any ID between base local and base local + count) within a cluster\n */\nexport function lastFinalizedLocal(cluster: IdCluster): LocalCompressedId {\n\treturn ((cluster.baseLocalId as number) - (cluster.count - 1)) as LocalCompressedId;\n}\n"]}
@@ -0,0 +1,139 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+ import { SessionSpaceCompressedId, OpSpaceCompressedId, SessionId, StableId } from "./identifiers";
6
+ import { IdCreationRange, SerializedIdCompressorWithNoSession, SerializedIdCompressorWithOngoingSession } from "./persisted-types";
7
+ /**
8
+ * @alpha
9
+ */
10
+ export interface IIdCompressorCore {
11
+ /**
12
+ * Returns a range of IDs created by this session in a format for sending to the server for finalizing.
13
+ * The range will include all IDs generated via calls to `generateCompressedId` since the last time this method was called.
14
+ * @returns the range of IDs, which may be empty. This range must be sent to the server for ordering before
15
+ * it is finalized. Ranges must be sent to the server in the order that they are taken via calls to this method.
16
+ */
17
+ takeNextCreationRange(): IdCreationRange;
18
+ /**
19
+ * Finalizes the supplied range of IDs (which may be from either a remote or local session).
20
+ * @param range - the range of session-local IDs to finalize.
21
+ */
22
+ finalizeCreationRange(range: IdCreationRange): void;
23
+ /**
24
+ * Returns a persistable form of the current state of this `IdCompressor` which can be rehydrated via `IdCompressor.deserialize()`.
25
+ * This includes finalized state as well as un-finalized state and is therefore suitable for use in offline scenarios.
26
+ */
27
+ serialize(withSession: true): SerializedIdCompressorWithOngoingSession;
28
+ /**
29
+ * Returns a persistable form of the current state of this `IdCompressor` which can be rehydrated via `IdCompressor.deserialize()`.
30
+ * This only includes finalized state and is therefore suitable for use in summaries.
31
+ */
32
+ serialize(withSession: false): SerializedIdCompressorWithNoSession;
33
+ }
34
+ /**
35
+ * A distributed UUID generator and compressor.
36
+ *
37
+ * Generates arbitrary non-colliding v4 UUIDs, called stable IDs, for multiple "sessions" (which can be distributed across the network),
38
+ * providing each session with the ability to map these UUIDs to `numbers`.
39
+ *
40
+ * A session is a unique identifier that denotes a single compressor. New IDs are created through a single compressor API
41
+ * which should then sent in ranges to the server for total ordering (and are subsequently relayed to other clients). When a new ID is
42
+ * created it is said to be created by the compressor's "local" session.
43
+ *
44
+ * For each stable ID created, two numeric IDs are provided by the compressor:
45
+ *
46
+ * 1. A session-local ID, which is stable for the lifetime of the session (which could be longer than that of the compressor object, as it may
47
+ * be serialized for offline usage). Available as soon as the stable ID is allocated. These IDs are session-unique and are thus only
48
+ * safely usable within the scope of the compressor that created it.
49
+ *
50
+ * 2. A final ID, which is stable across serialization and deserialization of an IdCompressor. Available as soon as the range containing
51
+ * the corresponding session-local ID is totally ordered (via consensus) with respect to other sessions' allocations.
52
+ * Final IDs are known to and publicly usable by any compressor that has received them.
53
+ *
54
+ * Compressors will allocate UUIDs in non-random ways to reduce entropy allowing for optimized storage of the data needed
55
+ * to map the UUIDs to the numbers.
56
+ *
57
+ * The following invariants are upheld by IdCompressor:
58
+ *
59
+ * 1. Session-local IDs will always decompress to the same UUIDs for the lifetime of the session.
60
+ *
61
+ * 2. Final IDs will always decompress to the same UUIDs.
62
+ *
63
+ * 3. After a server-processed range of session-local IDs (from any session) is received by a compressor, any of those session-local IDs may be
64
+ * translated by the compressor into the corresponding final ID. For any given session-local ID, this translation will always yield the
65
+ * same final ID.
66
+ *
67
+ * 4. A UUID will always compress into the same session-local ID for the lifetime of the session.
68
+ *
69
+ * Session-local IDs are sent across the wire in efficiently-represented ranges. These ranges are created by querying the compressor, and *must*
70
+ * be ordered (i.e. sent to the server) in the order they are created in order to preserve the above invariants.
71
+ *
72
+ * Session-local IDs can be used immediately after creation, but will eventually (after being sequenced) have a corresponding final ID. This
73
+ * could make reasoning about equality of those two forms difficult. For example, if a cache is keyed off of a
74
+ * session-local ID but is later queried using the final ID (which is semantically equal, as it decompresses to the same UUID/string) it will
75
+ * produce a cache miss. In order to make using collections of both remotely created and locally created IDs easy, regardless of whether the
76
+ * session-local IDs have been finalized, the compressor defines two "spaces" of IDs:
77
+ *
78
+ * 1. Session space: in this space, all IDs are normalized to their "most local form". This means that all IDs created by the local session
79
+ * will be in local form, regardless of if they have been finalized. Remotely created IDs, which could only have been received after
80
+ * finalizing and will never have a local form for the compressor, will of course be final IDs. This space should be used with consumer APIs
81
+ * and data structures, as the lifetime of the IDs is guaranteed to be the same as the compressor object. Care must be taken to not use
82
+ * these IDs across compressor objects, as the local IDs are specific to the compressor that created them.
83
+ *
84
+ * 2. Op space: in this space, all IDs are normalized to their "most final form". This means that all IDs except session-local IDs that
85
+ * have not yet been finalized will be in final ID form. This space is useful for serialization in ops (e.g. references), as other clients
86
+ * that receive them need not do any work to normalize them to *their* session-space in the common case. Note that IDs in op space may move
87
+ * out of Op space over time, namely, when a session-local ID in this space becomes finalized, and thereafter has a "more final form".
88
+ * Consequentially, it may be useful to restrict parameters of a persisted type to this space (to optimize perf), but it is potentially
89
+ * incorrect to use this type for a runtime variable. This is an asymmetry that does not affect session space, as local IDs are always as
90
+ * "local as possible".
91
+ *
92
+ * These two spaces naturally define a rule: consumers of compressed IDs should use session-space IDs, but serialized forms such as ops
93
+ * should use op-space IDs.
94
+ * @alpha
95
+ */
96
+ export interface IIdCompressor {
97
+ localSessionId: SessionId;
98
+ /**
99
+ * Generates a new compressed ID or returns an existing one.
100
+ * This should ONLY be called to generate IDs for local operations.
101
+ * @returns A new local ID in session space.
102
+ */
103
+ generateCompressedId(): SessionSpaceCompressedId;
104
+ /**
105
+ * Normalizes a session space ID into op space.
106
+ * @param id - the local ID to normalize.
107
+ * @returns the ID in op space.
108
+ */
109
+ normalizeToOpSpace(id: SessionSpaceCompressedId): OpSpaceCompressedId;
110
+ /**
111
+ * Normalizes an ID into session space.
112
+ * @param id - the ID to normalize. If it is a local ID, it is assumed to have been created by the session corresponding
113
+ * to `sessionId`.
114
+ * @param originSessionId - the session from which `id` originated
115
+ * @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
116
+ * 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
117
+ * range that contained it from the server.
118
+ */
119
+ normalizeToSessionSpace(id: OpSpaceCompressedId, originSessionId: SessionId): SessionSpaceCompressedId;
120
+ /**
121
+ * Decompresses a previously compressed ID into a UUID.
122
+ * @param id - the compressed ID to be decompressed.
123
+ * @returns the UUID associated with the compressed ID. Fails if the ID was not generated by this compressor.
124
+ */
125
+ decompress(id: SessionSpaceCompressedId): StableId;
126
+ /**
127
+ * Recompresses a UUID.
128
+ * @param uncompressed - the UUID to recompress.
129
+ * @returns the `CompressedId` associated with `uncompressed`. Fails if it has not been previously compressed by this compressor.
130
+ */
131
+ recompress(uncompressed: StableId): SessionSpaceCompressedId;
132
+ /**
133
+ * Attempts to recompresses a UUID.
134
+ * @param uncompressed - the UUID to recompress,
135
+ * @returns the `CompressedId` associated with `uncompressed` or undefined if it has not been previously compressed by this compressor.
136
+ */
137
+ tryRecompress(uncompressed: StableId): SessionSpaceCompressedId | undefined;
138
+ }
139
+ //# sourceMappingURL=idCompressor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"idCompressor.d.ts","sourceRoot":"","sources":["../../src/types/idCompressor.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,wBAAwB,EAAE,mBAAmB,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACnG,OAAO,EACN,eAAe,EACf,mCAAmC,EACnC,wCAAwC,EACxC,MAAM,mBAAmB,CAAC;AAE3B;;GAEG;AACH,MAAM,WAAW,iBAAiB;IACjC;;;;;OAKG;IACH,qBAAqB,IAAI,eAAe,CAAC;IAEzC;;;OAGG;IACH,qBAAqB,CAAC,KAAK,EAAE,eAAe,GAAG,IAAI,CAAC;IAEpD;;;OAGG;IACH,SAAS,CAAC,WAAW,EAAE,IAAI,GAAG,wCAAwC,CAAC;IAEvE;;;OAGG;IACH,SAAS,CAAC,WAAW,EAAE,KAAK,GAAG,mCAAmC,CAAC;CACnE;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6DG;AACH,MAAM,WAAW,aAAa;IAC7B,cAAc,EAAE,SAAS,CAAC;IAE1B;;;;OAIG;IACH,oBAAoB,IAAI,wBAAwB,CAAC;IACjD;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,EAAE,wBAAwB,GAAG,mBAAmB,CAAC;IACtE;;;;;;;;OAQG;IACH,uBAAuB,CACtB,EAAE,EAAE,mBAAmB,EACvB,eAAe,EAAE,SAAS,GACxB,wBAAwB,CAAC;IAE5B;;;;OAIG;IACH,UAAU,CAAC,EAAE,EAAE,wBAAwB,GAAG,QAAQ,CAAC;IAEnD;;;;OAIG;IACH,UAAU,CAAC,YAAY,EAAE,QAAQ,GAAG,wBAAwB,CAAC;IAE7D;;;;OAIG;IACH,aAAa,CAAC,YAAY,EAAE,QAAQ,GAAG,wBAAwB,GAAG,SAAS,CAAC;CAC5E"}
@@ -0,0 +1,6 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+ export {};
6
+ //# sourceMappingURL=idCompressor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"idCompressor.js","sourceRoot":"","sources":["../../src/types/idCompressor.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { SessionSpaceCompressedId, OpSpaceCompressedId, SessionId, StableId } from \"./identifiers\";\nimport {\n\tIdCreationRange,\n\tSerializedIdCompressorWithNoSession,\n\tSerializedIdCompressorWithOngoingSession,\n} from \"./persisted-types\";\n\n/**\n * @alpha\n */\nexport interface IIdCompressorCore {\n\t/**\n\t * Returns a range of IDs created by this session in a format for sending to the server for finalizing.\n\t * The range will include all IDs generated via calls to `generateCompressedId` since the last time this method was called.\n\t * @returns the range of IDs, which may be empty. This range must be sent to the server for ordering before\n\t * it is finalized. Ranges must be sent to the server in the order that they are taken via calls to this method.\n\t */\n\ttakeNextCreationRange(): IdCreationRange;\n\n\t/**\n\t * Finalizes the supplied range of IDs (which may be from either a remote or local session).\n\t * @param range - the range of session-local IDs to finalize.\n\t */\n\tfinalizeCreationRange(range: IdCreationRange): void;\n\n\t/**\n\t * Returns a persistable form of the current state of this `IdCompressor` which can be rehydrated via `IdCompressor.deserialize()`.\n\t * This includes finalized state as well as un-finalized state and is therefore suitable for use in offline scenarios.\n\t */\n\tserialize(withSession: true): SerializedIdCompressorWithOngoingSession;\n\n\t/**\n\t * Returns a persistable form of the current state of this `IdCompressor` which can be rehydrated via `IdCompressor.deserialize()`.\n\t * This only includes finalized state and is therefore suitable for use in summaries.\n\t */\n\tserialize(withSession: false): SerializedIdCompressorWithNoSession;\n}\n\n/**\n * A distributed UUID generator and compressor.\n *\n * Generates arbitrary non-colliding v4 UUIDs, called stable IDs, for multiple \"sessions\" (which can be distributed across the network),\n * providing each session with the ability to map these UUIDs to `numbers`.\n *\n * A session is a unique identifier that denotes a single compressor. New IDs are created through a single compressor API\n * which should then sent in ranges to the server for total ordering (and are subsequently relayed to other clients). When a new ID is\n * created it is said to be created by the compressor's \"local\" session.\n *\n * For each stable ID created, two numeric IDs are provided by the compressor:\n *\n * 1. A session-local ID, which is stable for the lifetime of the session (which could be longer than that of the compressor object, as it may\n * be serialized for offline usage). Available as soon as the stable ID is allocated. These IDs are session-unique and are thus only\n * safely usable within the scope of the compressor that created it.\n *\n * 2. A final ID, which is stable across serialization and deserialization of an IdCompressor. Available as soon as the range containing\n * the corresponding session-local ID is totally ordered (via consensus) with respect to other sessions' allocations.\n * Final IDs are known to and publicly usable by any compressor that has received them.\n *\n * Compressors will allocate UUIDs in non-random ways to reduce entropy allowing for optimized storage of the data needed\n * to map the UUIDs to the numbers.\n *\n * The following invariants are upheld by IdCompressor:\n *\n * 1. Session-local IDs will always decompress to the same UUIDs for the lifetime of the session.\n *\n * 2. Final IDs will always decompress to the same UUIDs.\n *\n * 3. After a server-processed range of session-local IDs (from any session) is received by a compressor, any of those session-local IDs may be\n * translated by the compressor into the corresponding final ID. For any given session-local ID, this translation will always yield the\n * same final ID.\n *\n * 4. A UUID will always compress into the same session-local ID for the lifetime of the session.\n *\n * Session-local IDs are sent across the wire in efficiently-represented ranges. These ranges are created by querying the compressor, and *must*\n * be ordered (i.e. sent to the server) in the order they are created in order to preserve the above invariants.\n *\n * Session-local IDs can be used immediately after creation, but will eventually (after being sequenced) have a corresponding final ID. This\n * could make reasoning about equality of those two forms difficult. For example, if a cache is keyed off of a\n * session-local ID but is later queried using the final ID (which is semantically equal, as it decompresses to the same UUID/string) it will\n * produce a cache miss. In order to make using collections of both remotely created and locally created IDs easy, regardless of whether the\n * session-local IDs have been finalized, the compressor defines two \"spaces\" of IDs:\n *\n * 1. Session space: in this space, all IDs are normalized to their \"most local form\". This means that all IDs created by the local session\n * will be in local form, regardless of if they have been finalized. Remotely created IDs, which could only have been received after\n * finalizing and will never have a local form for the compressor, will of course be final IDs. This space should be used with consumer APIs\n * and data structures, as the lifetime of the IDs is guaranteed to be the same as the compressor object. Care must be taken to not use\n * these IDs across compressor objects, as the local IDs are specific to the compressor that created them.\n *\n * 2. Op space: in this space, all IDs are normalized to their \"most final form\". This means that all IDs except session-local IDs that\n * have not yet been finalized will be in final ID form. This space is useful for serialization in ops (e.g. references), as other clients\n * that receive them need not do any work to normalize them to *their* session-space in the common case. Note that IDs in op space may move\n * out of Op space over time, namely, when a session-local ID in this space becomes finalized, and thereafter has a \"more final form\".\n * Consequentially, it may be useful to restrict parameters of a persisted type to this space (to optimize perf), but it is potentially\n * incorrect to use this type for a runtime variable. This is an asymmetry that does not affect session space, as local IDs are always as\n * \"local as possible\".\n *\n * These two spaces naturally define a rule: consumers of compressed IDs should use session-space IDs, but serialized forms such as ops\n * should use op-space IDs.\n * @alpha\n */\nexport interface IIdCompressor {\n\tlocalSessionId: SessionId;\n\n\t/**\n\t * Generates a new compressed ID or returns an existing one.\n\t * This should ONLY be called to generate IDs for local operations.\n\t * @returns A new local ID in session space.\n\t */\n\tgenerateCompressedId(): SessionSpaceCompressedId;\n\t/**\n\t * Normalizes a session space ID into op space.\n\t * @param id - the local ID to normalize.\n\t * @returns the ID in op space.\n\t */\n\tnormalizeToOpSpace(id: SessionSpaceCompressedId): OpSpaceCompressedId;\n\t/**\n\t * Normalizes an ID into session space.\n\t * @param id - the ID to normalize. If it is a local ID, it is assumed to have been created by the session corresponding\n\t * to `sessionId`.\n\t * @param originSessionId - the session from which `id` originated\n\t * @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\n\t * 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\n\t * range that contained it from the server.\n\t */\n\tnormalizeToSessionSpace(\n\t\tid: OpSpaceCompressedId,\n\t\toriginSessionId: SessionId,\n\t): SessionSpaceCompressedId;\n\n\t/**\n\t * Decompresses a previously compressed ID into a UUID.\n\t * @param id - the compressed ID to be decompressed.\n\t * @returns the UUID associated with the compressed ID. Fails if the ID was not generated by this compressor.\n\t */\n\tdecompress(id: SessionSpaceCompressedId): StableId;\n\n\t/**\n\t * Recompresses a UUID.\n\t * @param uncompressed - the UUID to recompress.\n\t * @returns the `CompressedId` associated with `uncompressed`. Fails if it has not been previously compressed by this compressor.\n\t */\n\trecompress(uncompressed: StableId): SessionSpaceCompressedId;\n\n\t/**\n\t * Attempts to recompresses a UUID.\n\t * @param uncompressed - the UUID to recompress,\n\t * @returns the `CompressedId` associated with `uncompressed` or undefined if it has not been previously compressed by this compressor.\n\t */\n\ttryRecompress(uncompressed: StableId): SessionSpaceCompressedId | undefined;\n}\n"]}
@@ -0,0 +1,40 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+ /**
6
+ * A compressed ID that has been normalized into "session space" (see `IdCompressor` for more).
7
+ * Consumer-facing APIs and data structures should use session-space IDs as their lifetime and equality is stable and tied to
8
+ * the scope of the session (i.e. compressor) that produced them.
9
+ * @alpha
10
+ */
11
+ export type SessionSpaceCompressedId = number & {
12
+ readonly SessionUnique: "cea55054-6b82-4cbf-ad19-1fa645ea3b3e";
13
+ };
14
+ /**
15
+ * A compressed ID that has been normalized into "op space".
16
+ * Serialized/persisted structures (e.g. ops) should use op-space IDs as a performance optimization, as they require less normalizing when
17
+ * received by a remote client due to the fact that op space for a given compressor is session space for all other compressors.
18
+ * @alpha
19
+ */
20
+ export type OpSpaceCompressedId = number & {
21
+ readonly OpNormalized: "9209432d-a959-4df7-b2ad-767ead4dbcae";
22
+ };
23
+ /**
24
+ * A version 4, variant 1 uuid (https://datatracker.ietf.org/doc/html/rfc4122).
25
+ * A 128-bit Universally Unique IDentifier. Represented here
26
+ * with a string of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx,
27
+ * where x is a lowercase hex digit.
28
+ * @alpha
29
+ */
30
+ export type StableId = string & {
31
+ readonly StableId: "53172b0d-a3d5-41ea-bd75-b43839c97f5a";
32
+ };
33
+ /**
34
+ * A StableId which is suitable for use as a session identifier
35
+ * @alpha
36
+ */
37
+ export type SessionId = StableId & {
38
+ readonly SessionId: "4498f850-e14e-4be9-8db0-89ec00997e58";
39
+ };
40
+ //# sourceMappingURL=identifiers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identifiers.d.ts","sourceRoot":"","sources":["../../src/types/identifiers.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;;;GAKG;AACH,MAAM,MAAM,wBAAwB,GAAG,MAAM,GAAG;IAC/C,QAAQ,CAAC,aAAa,EAAE,sCAAsC,CAAC;CAC/D,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,mBAAmB,GAAG,MAAM,GAAG;IAC1C,QAAQ,CAAC,YAAY,EAAE,sCAAsC,CAAC;CAC9D,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG;IAAE,QAAQ,CAAC,QAAQ,EAAE,sCAAsC,CAAA;CAAE,CAAC;AAE9F;;;GAGG;AACH,MAAM,MAAM,SAAS,GAAG,QAAQ,GAAG;IAAE,QAAQ,CAAC,SAAS,EAAE,sCAAsC,CAAA;CAAE,CAAC"}
@@ -0,0 +1,6 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+ export {};
6
+ //# sourceMappingURL=identifiers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identifiers.js","sourceRoot":"","sources":["../../src/types/identifiers.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * A compressed ID that has been normalized into \"session space\" (see `IdCompressor` for more).\n * Consumer-facing APIs and data structures should use session-space IDs as their lifetime and equality is stable and tied to\n * the scope of the session (i.e. compressor) that produced them.\n * @alpha\n */\nexport type SessionSpaceCompressedId = number & {\n\treadonly SessionUnique: \"cea55054-6b82-4cbf-ad19-1fa645ea3b3e\";\n};\n\n/**\n * A compressed ID that has been normalized into \"op space\".\n * Serialized/persisted structures (e.g. ops) should use op-space IDs as a performance optimization, as they require less normalizing when\n * received by a remote client due to the fact that op space for a given compressor is session space for all other compressors.\n * @alpha\n */\nexport type OpSpaceCompressedId = number & {\n\treadonly OpNormalized: \"9209432d-a959-4df7-b2ad-767ead4dbcae\";\n};\n\n/**\n * A version 4, variant 1 uuid (https://datatracker.ietf.org/doc/html/rfc4122).\n * A 128-bit Universally Unique IDentifier. Represented here\n * with a string of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx,\n * where x is a lowercase hex digit.\n * @alpha\n */\nexport type StableId = string & { readonly StableId: \"53172b0d-a3d5-41ea-bd75-b43839c97f5a\" };\n\n/**\n * A StableId which is suitable for use as a session identifier\n * @alpha\n */\nexport type SessionId = StableId & { readonly SessionId: \"4498f850-e14e-4be9-8db0-89ec00997e58\" };\n"]}
@@ -0,0 +1,8 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+ export { IdCreationRange, SerializedIdCompressor, SerializedIdCompressorWithNoSession, SerializedIdCompressorWithOngoingSession, initialClusterCapacity, } from "./persisted-types";
6
+ export { IIdCompressorCore, IIdCompressor } from "./idCompressor";
7
+ export { SessionSpaceCompressedId, OpSpaceCompressedId, SessionId, StableId } from "./identifiers";
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACN,eAAe,EACf,sBAAsB,EACtB,mCAAmC,EACnC,wCAAwC,EACxC,sBAAsB,GACtB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAElE,OAAO,EAAE,wBAAwB,EAAE,mBAAmB,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC"}
@@ -0,0 +1,6 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+ export { initialClusterCapacity, } from "./persisted-types";
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAKN,sBAAsB,GACtB,MAAM,mBAAmB,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nexport {\n\tIdCreationRange,\n\tSerializedIdCompressor,\n\tSerializedIdCompressorWithNoSession,\n\tSerializedIdCompressorWithOngoingSession,\n\tinitialClusterCapacity,\n} from \"./persisted-types\";\n\nexport { IIdCompressorCore, IIdCompressor } from \"./idCompressor\";\n\nexport { SessionSpaceCompressedId, OpSpaceCompressedId, SessionId, StableId } from \"./identifiers\";\n"]}
@@ -0,0 +1,46 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+ import type { SessionId } from "../identifiers";
6
+ /**
7
+ * The serialized contents of an IdCompressor, suitable for persistence in a summary.
8
+ * @alpha
9
+ */
10
+ export type SerializedIdCompressor = string & {
11
+ readonly _serializedIdCompressor: "8c73c57c-1cf4-4278-8915-6444cb4f6af5";
12
+ };
13
+ /**
14
+ * The serialized contents of an IdCompressor, suitable for persistence in a summary.
15
+ * @alpha
16
+ */
17
+ export type SerializedIdCompressorWithNoSession = SerializedIdCompressor & {
18
+ readonly _noLocalState: "3aa2e1e8-cc28-4ea7-bc1a-a11dc3f26dfb";
19
+ };
20
+ /**
21
+ * The serialized contents of an IdCompressor, suitable for persistence in a summary.
22
+ * @alpha
23
+ */
24
+ export type SerializedIdCompressorWithOngoingSession = SerializedIdCompressor & {
25
+ readonly _hasLocalState: "1281acae-6d14-47e7-bc92-71c8ee0819cb";
26
+ };
27
+ /**
28
+ * Data describing a range of session-local IDs (from a remote or local session).
29
+ *
30
+ * A range is composed of local IDs that were generated.
31
+ * @alpha
32
+ */
33
+ export interface IdCreationRange {
34
+ readonly sessionId: SessionId;
35
+ readonly ids?: {
36
+ readonly firstGenCount: number;
37
+ readonly count: number;
38
+ };
39
+ }
40
+ /**
41
+ * Roughly equates to a minimum of 1M sessions before we start allocating 64 bit IDs.
42
+ * This value must *NOT* change without careful consideration to compatibility.
43
+ * @internal
44
+ */
45
+ export declare const initialClusterCapacity = 512;
46
+ //# sourceMappingURL=0.0.1.d.ts.map