@fluidframework/map 2.0.0-dev.2.3.0.115467 → 2.0.0-dev.4.1.0.148229

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 (72) hide show
  1. package/.eslintrc.js +12 -14
  2. package/.mocharc.js +2 -2
  3. package/README.md +3 -3
  4. package/api-extractor.json +2 -2
  5. package/dist/directory.d.ts +38 -5
  6. package/dist/directory.d.ts.map +1 -1
  7. package/dist/directory.js +285 -88
  8. package/dist/directory.js.map +1 -1
  9. package/dist/index.d.ts +1 -1
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js.map +1 -1
  12. package/dist/interfaces.d.ts +27 -17
  13. package/dist/interfaces.d.ts.map +1 -1
  14. package/dist/interfaces.js.map +1 -1
  15. package/dist/internalInterfaces.d.ts +39 -0
  16. package/dist/internalInterfaces.d.ts.map +1 -1
  17. package/dist/internalInterfaces.js.map +1 -1
  18. package/dist/localValues.d.ts +12 -3
  19. package/dist/localValues.d.ts.map +1 -1
  20. package/dist/localValues.js +10 -0
  21. package/dist/localValues.js.map +1 -1
  22. package/dist/map.d.ts +5 -5
  23. package/dist/map.d.ts.map +1 -1
  24. package/dist/map.js +15 -2
  25. package/dist/map.js.map +1 -1
  26. package/dist/mapKernel.d.ts +5 -5
  27. package/dist/mapKernel.d.ts.map +1 -1
  28. package/dist/mapKernel.js +58 -33
  29. package/dist/mapKernel.js.map +1 -1
  30. package/dist/packageVersion.d.ts +1 -1
  31. package/dist/packageVersion.js +1 -1
  32. package/dist/packageVersion.js.map +1 -1
  33. package/lib/directory.d.ts +38 -5
  34. package/lib/directory.d.ts.map +1 -1
  35. package/lib/directory.js +287 -90
  36. package/lib/directory.js.map +1 -1
  37. package/lib/index.d.ts +1 -1
  38. package/lib/index.d.ts.map +1 -1
  39. package/lib/index.js.map +1 -1
  40. package/lib/interfaces.d.ts +27 -17
  41. package/lib/interfaces.d.ts.map +1 -1
  42. package/lib/interfaces.js.map +1 -1
  43. package/lib/internalInterfaces.d.ts +39 -0
  44. package/lib/internalInterfaces.d.ts.map +1 -1
  45. package/lib/internalInterfaces.js.map +1 -1
  46. package/lib/localValues.d.ts +12 -3
  47. package/lib/localValues.d.ts.map +1 -1
  48. package/lib/localValues.js +10 -0
  49. package/lib/localValues.js.map +1 -1
  50. package/lib/map.d.ts +5 -5
  51. package/lib/map.d.ts.map +1 -1
  52. package/lib/map.js +16 -3
  53. package/lib/map.js.map +1 -1
  54. package/lib/mapKernel.d.ts +5 -5
  55. package/lib/mapKernel.d.ts.map +1 -1
  56. package/lib/mapKernel.js +59 -34
  57. package/lib/mapKernel.js.map +1 -1
  58. package/lib/packageVersion.d.ts +1 -1
  59. package/lib/packageVersion.js +1 -1
  60. package/lib/packageVersion.js.map +1 -1
  61. package/package.json +60 -59
  62. package/prettier.config.cjs +1 -1
  63. package/src/directory.ts +2207 -1848
  64. package/src/index.ts +1 -0
  65. package/src/interfaces.ts +309 -288
  66. package/src/internalInterfaces.ts +83 -38
  67. package/src/localValues.ts +95 -93
  68. package/src/map.ts +364 -345
  69. package/src/mapKernel.ts +729 -676
  70. package/src/packageVersion.ts +1 -1
  71. package/tsconfig.esnext.json +5 -5
  72. package/tsconfig.json +9 -15
package/src/mapKernel.ts CHANGED
@@ -6,50 +6,38 @@
6
6
  import { IFluidHandle } from "@fluidframework/core-interfaces";
7
7
  import { IFluidSerializer, ValueType } from "@fluidframework/shared-object-base";
8
8
  import { assert, TypedEventEmitter } from "@fluidframework/common-utils";
9
+ import { ISerializableValue, ISerializedValue, ISharedMapEvents } from "./interfaces";
9
10
  import {
10
- ISerializableValue,
11
- ISerializedValue,
12
- ISharedMapEvents,
13
- } from "./interfaces";
14
- import {
15
- IMapSetOperation,
16
- IMapDeleteOperation,
17
- IMapClearOperation,
18
- IMapKeyEditLocalOpMetadata,
19
- IMapKeyAddLocalOpMetadata,
20
- IMapClearLocalOpMetadata,
11
+ IMapSetOperation,
12
+ IMapDeleteOperation,
13
+ IMapClearOperation,
14
+ IMapKeyEditLocalOpMetadata,
15
+ IMapKeyAddLocalOpMetadata,
16
+ IMapClearLocalOpMetadata,
21
17
  } from "./internalInterfaces";
22
- import {
23
- ILocalValue,
24
- LocalValueMaker,
25
- makeSerializable,
26
- } from "./localValues";
18
+ import { ILocalValue, LocalValueMaker, makeSerializable } from "./localValues";
27
19
 
28
20
  /**
29
21
  * Defines the means to process and submit a given op on a map.
30
22
  */
31
23
  interface IMapMessageHandler {
32
- /**
33
- * Apply the given operation.
34
- * @param op - The map operation to apply
35
- * @param local - Whether the message originated from the local client
36
- * @param localOpMetadata - For local client messages, this is the metadata that was submitted with the message.
37
- * For messages from a remote client, this will be undefined.
38
- */
39
- process(
40
- op: IMapOperation,
41
- local: boolean,
42
- localOpMetadata: MapLocalOpMetadata,
43
- ): void;
44
-
45
- /**
46
- * Communicate the operation to remote clients.
47
- * @param op - The map operation to submit
48
- * @param localOpMetadata - The metadata to be submitted with the message.
49
- */
50
- submit(op: IMapOperation, localOpMetadata: MapLocalOpMetadata): void;
51
-
52
- applyStashedOp(op: IMapOperation): MapLocalOpMetadata;
24
+ /**
25
+ * Apply the given operation.
26
+ * @param op - The map operation to apply
27
+ * @param local - Whether the message originated from the local client
28
+ * @param localOpMetadata - For local client messages, this is the metadata that was submitted with the message.
29
+ * For messages from a remote client, this will be undefined.
30
+ */
31
+ process(op: IMapOperation, local: boolean, localOpMetadata: MapLocalOpMetadata): void;
32
+
33
+ /**
34
+ * Communicate the operation to remote clients.
35
+ * @param op - The map operation to submit
36
+ * @param localOpMetadata - The metadata to be submitted with the message.
37
+ */
38
+ submit(op: IMapOperation, localOpMetadata: MapLocalOpMetadata): void;
39
+
40
+ applyStashedOp(op: IMapOperation): MapLocalOpMetadata;
53
41
  }
54
42
 
55
43
  /**
@@ -71,671 +59,736 @@ export type IMapOperation = IMapKeyOperation | IMapClearOperation;
71
59
  * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse | JSON.parse}.
72
60
  */
73
61
  export interface IMapDataObjectSerializable {
74
- [key: string]: ISerializableValue;
62
+ [key: string]: ISerializableValue;
75
63
  }
76
64
 
77
65
  /**
78
66
  * Serialized key/value data.
79
67
  */
80
68
  export interface IMapDataObjectSerialized {
81
- [key: string]: ISerializedValue;
69
+ [key: string]: ISerializedValue;
82
70
  }
83
71
 
84
72
  type MapKeyLocalOpMetadata = IMapKeyEditLocalOpMetadata | IMapKeyAddLocalOpMetadata;
85
73
  type MapLocalOpMetadata = IMapClearLocalOpMetadata | MapKeyLocalOpMetadata;
86
74
 
75
+ /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */
76
+
87
77
  function isMapKeyLocalOpMetadata(metadata: any): metadata is MapKeyLocalOpMetadata {
88
- return metadata !== undefined && typeof metadata.pendingMessageId === "number" &&
89
- (metadata.type === "add" || metadata.type === "edit");
78
+ return (
79
+ metadata !== undefined &&
80
+ typeof metadata.pendingMessageId === "number" &&
81
+ (metadata.type === "add" || metadata.type === "edit")
82
+ );
90
83
  }
91
84
 
92
85
  function isClearLocalOpMetadata(metadata: any): metadata is IMapClearLocalOpMetadata {
93
- return metadata !== undefined && metadata.type === "clear" && typeof metadata.pendingMessageId === "number";
86
+ return (
87
+ metadata !== undefined &&
88
+ metadata.type === "clear" &&
89
+ typeof metadata.pendingMessageId === "number"
90
+ );
94
91
  }
95
92
 
96
93
  function isMapLocalOpMetadata(metadata: any): metadata is MapLocalOpMetadata {
97
- return metadata !== undefined && typeof metadata.pendingMessageId === "number" &&
98
- (metadata.type === "add" || metadata.type === "edit" || metadata.type === "clear");
94
+ return (
95
+ metadata !== undefined &&
96
+ typeof metadata.pendingMessageId === "number" &&
97
+ (metadata.type === "add" || metadata.type === "edit" || metadata.type === "clear")
98
+ );
99
99
  }
100
100
 
101
- function createClearLocalOpMetadata(op: IMapClearOperation,
102
- pendingClearMessageId: number, previousMap?: Map<string, ILocalValue>): IMapClearLocalOpMetadata {
103
- const localMetadata: IMapClearLocalOpMetadata = {
104
- type: "clear",
105
- pendingMessageId: pendingClearMessageId, previousMap,
106
- };
107
- return localMetadata;
101
+ /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */
102
+
103
+ function createClearLocalOpMetadata(
104
+ op: IMapClearOperation,
105
+ pendingClearMessageId: number,
106
+ previousMap?: Map<string, ILocalValue>,
107
+ ): IMapClearLocalOpMetadata {
108
+ const localMetadata: IMapClearLocalOpMetadata = {
109
+ type: "clear",
110
+ pendingMessageId: pendingClearMessageId,
111
+ previousMap,
112
+ };
113
+ return localMetadata;
108
114
  }
109
115
 
110
- function createKeyLocalOpMetadata(op: IMapKeyOperation,
111
- pendingMessageId: number, previousValue?: ILocalValue): MapKeyLocalOpMetadata {
112
- const localMetadata: MapKeyLocalOpMetadata = previousValue ?
113
- { type: "edit", pendingMessageId, previousValue } :
114
- { type: "add", pendingMessageId };
115
- return localMetadata;
116
+ function createKeyLocalOpMetadata(
117
+ op: IMapKeyOperation,
118
+ pendingMessageId: number,
119
+ previousValue?: ILocalValue,
120
+ ): MapKeyLocalOpMetadata {
121
+ const localMetadata: MapKeyLocalOpMetadata = previousValue
122
+ ? { type: "edit", pendingMessageId, previousValue }
123
+ : { type: "add", pendingMessageId };
124
+ return localMetadata;
116
125
  }
117
126
 
118
127
  /**
119
128
  * A SharedMap is a map-like distributed data structure.
120
129
  */
121
130
  export class MapKernel {
122
- /**
123
- * The number of key/value pairs stored in the map.
124
- */
125
- public get size(): number {
126
- return this.data.size;
127
- }
128
-
129
- /**
130
- * Mapping of op types to message handlers.
131
- */
132
- private readonly messageHandlers: ReadonlyMap<string, IMapMessageHandler> = new Map();
133
-
134
- /**
135
- * The in-memory data the map is storing.
136
- */
137
- private readonly data = new Map<string, ILocalValue>();
138
-
139
- /**
140
- * Keys that have been modified locally but not yet ack'd from the server.
141
- */
142
- private readonly pendingKeys: Map<string, number[]> = new Map();
143
-
144
- /**
145
- * This is used to assign a unique id to every outgoing operation and helps in tracking unack'd ops.
146
- */
147
- private pendingMessageId: number = -1;
148
-
149
- /**
150
- * The pending ids of any clears that have been performed locally but not yet ack'd from the server
151
- */
152
- private readonly pendingClearMessageIds: number[] = [];
153
-
154
- /**
155
- * Object to create encapsulations of the values stored in the map.
156
- */
157
- private readonly localValueMaker: LocalValueMaker;
158
-
159
- /**
160
- * Create a new shared map kernel.
161
- * @param serializer - The serializer to serialize / parse handles
162
- * @param handle - The handle of the shared object using the kernel
163
- * @param submitMessage - A callback to submit a message through the shared object
164
- * @param isAttached - To query whether the shared object should generate ops
165
- * @param valueTypes - The value types to register
166
- * @param eventEmitter - The object that will emit map events
167
- */
168
- constructor(
169
- private readonly serializer: IFluidSerializer,
170
- private readonly handle: IFluidHandle,
171
- private readonly submitMessage: (op: any, localOpMetadata: unknown) => void,
172
- private readonly isAttached: () => boolean,
173
- private readonly eventEmitter: TypedEventEmitter<ISharedMapEvents>,
174
- ) {
175
- this.localValueMaker = new LocalValueMaker(serializer);
176
- this.messageHandlers = this.getMessageHandlers();
177
- }
178
-
179
- /**
180
- * Get an iterator over the keys in this map.
181
- * @returns The iterator
182
- */
183
- public keys(): IterableIterator<string> {
184
- return this.data.keys();
185
- }
186
-
187
- /**
188
- * Get an iterator over the entries in this map.
189
- * @returns The iterator
190
- */
191
- public entries(): IterableIterator<[string, any]> {
192
- const localEntriesIterator = this.data.entries();
193
- const iterator = {
194
- next(): IteratorResult<[string, any]> {
195
- const nextVal = localEntriesIterator.next();
196
- return nextVal.done
197
- ? { value: undefined, done: true }
198
- // Unpack the stored value
199
- : { value: [nextVal.value[0], nextVal.value[1].value], done: false };
200
- },
201
- [Symbol.iterator]() {
202
- return this;
203
- },
204
- };
205
- return iterator;
206
- }
207
-
208
- /**
209
- * Get an iterator over the values in this map.
210
- * @returns The iterator
211
- */
212
- public values(): IterableIterator<any> {
213
- const localValuesIterator = this.data.values();
214
- const iterator = {
215
- next(): IteratorResult<any> {
216
- const nextVal = localValuesIterator.next();
217
- return nextVal.done
218
- ? { value: undefined, done: true }
219
- // Unpack the stored value
220
- : { value: nextVal.value.value, done: false };
221
- },
222
- [Symbol.iterator]() {
223
- return this;
224
- },
225
- };
226
- return iterator;
227
- }
228
-
229
- /**
230
- * Get an iterator over the entries in this map.
231
- * @returns The iterator
232
- */
233
- public [Symbol.iterator](): IterableIterator<[string, any]> {
234
- return this.entries();
235
- }
236
-
237
- /**
238
- * Executes the given callback on each entry in the map.
239
- * @param callbackFn - Callback function
240
- */
241
- public forEach(callbackFn: (value: any, key: string, map: Map<string, any>) => void): void {
242
- this.data.forEach((localValue, key, m) => {
243
- callbackFn(localValue.value, key, m);
244
- });
245
- }
246
-
247
- /**
248
- * {@inheritDoc ISharedMap.get}
249
- */
250
- public get<T = any>(key: string): T | undefined {
251
- const localValue = this.data.get(key);
252
- return localValue === undefined ? undefined : localValue.value as T;
253
- }
254
-
255
- /**
256
- * Check if a key exists in the map.
257
- * @param key - The key to check
258
- * @returns True if the key exists, false otherwise
259
- */
260
- public has(key: string): boolean {
261
- return this.data.has(key);
262
- }
263
-
264
- /**
265
- * {@inheritDoc ISharedMap.set}
266
- */
267
- public set(key: string, value: any) {
268
- // Undefined/null keys can't be serialized to JSON in the manner we currently snapshot.
269
- if (key === undefined || key === null) {
270
- throw new Error("Undefined and null keys are not supported");
271
- }
272
-
273
- // Create a local value and serialize it.
274
- const localValue = this.localValueMaker.fromInMemory(value);
275
- const serializableValue = makeSerializable(
276
- localValue,
277
- this.serializer,
278
- this.handle);
279
-
280
- // Set the value locally.
281
- const previousValue = this.setCore(
282
- key,
283
- localValue,
284
- true,
285
- );
286
-
287
- // If we are not attached, don't submit the op.
288
- if (!this.isAttached()) {
289
- return;
290
- }
291
-
292
- const op: IMapSetOperation = {
293
- key,
294
- type: "set",
295
- value: serializableValue,
296
- };
297
- this.submitMapKeyMessage(op, previousValue);
298
- }
299
-
300
- /**
301
- * Delete a key from the map.
302
- * @param key - Key to delete
303
- * @returns True if the key existed and was deleted, false if it did not exist
304
- */
305
- public delete(key: string): boolean {
306
- // Delete the key locally first.
307
- const previousValue = this.deleteCore(key, true);
308
-
309
- // If we are not attached, don't submit the op.
310
- if (!this.isAttached()) {
311
- return previousValue !== undefined;
312
- }
313
-
314
- const op: IMapDeleteOperation = {
315
- key,
316
- type: "delete",
317
- };
318
- this.submitMapKeyMessage(op, previousValue);
319
-
320
- return previousValue !== undefined;
321
- }
322
-
323
- /**
324
- * Clear all data from the map.
325
- */
326
- public clear(): void {
327
- const copy = this.isAttached() ? new Map<string, ILocalValue>(this.data) : undefined;
328
-
329
- // Clear the data locally first.
330
- this.clearCore(true);
331
-
332
- // If we are not attached, don't submit the op.
333
- if (!this.isAttached()) {
334
- return;
335
- }
336
-
337
- const op: IMapClearOperation = {
338
- type: "clear",
339
- };
340
- this.submitMapClearMessage(op, copy);
341
- }
342
-
343
- /**
344
- * Serializes the data stored in the shared map to a JSON string
345
- * @param serializer - The serializer to use to serialize handles in its values.
346
- * @returns A JSON string containing serialized map data
347
- */
348
- public getSerializedStorage(serializer: IFluidSerializer): IMapDataObjectSerialized {
349
- const serializableMapData: IMapDataObjectSerialized = {};
350
- this.data.forEach((localValue, key) => {
351
- serializableMapData[key] = localValue.makeSerialized(serializer, this.handle);
352
- });
353
- return serializableMapData;
354
- }
355
-
356
- public getSerializableStorage(serializer: IFluidSerializer): IMapDataObjectSerializable {
357
- const serializableMapData: IMapDataObjectSerializable = {};
358
- this.data.forEach((localValue, key) => {
359
- serializableMapData[key] = makeSerializable(localValue, serializer, this.handle);
360
- });
361
- return serializableMapData;
362
- }
363
-
364
- public serialize(serializer: IFluidSerializer): string {
365
- return JSON.stringify(this.getSerializableStorage(serializer));
366
- }
367
-
368
- /**
369
- * Populate the kernel with the given map data.
370
- * @param data - A JSON string containing serialized map data
371
- */
372
- public populateFromSerializable(json: IMapDataObjectSerializable): void {
373
- for (const [key, serializable] of Object.entries(json)) {
374
- const localValue = {
375
- key,
376
- value: this.makeLocal(key, serializable),
377
- };
378
-
379
- this.data.set(localValue.key, localValue.value);
380
- }
381
- }
382
-
383
- public populate(json: string): void {
384
- this.populateFromSerializable(JSON.parse(json) as IMapDataObjectSerializable);
385
- }
386
-
387
- /**
388
- * Submit the given op if a handler is registered.
389
- * @param op - The operation to attempt to submit
390
- * @param localOpMetadata - The local metadata associated with the op. This is kept locally by the runtime
391
- * and not sent to the server. This will be sent back when this message is received back from the server. This is
392
- * also sent if we are asked to resubmit the message.
393
- * @returns True if the operation was submitted, false otherwise.
394
- */
395
- public trySubmitMessage(op: any, localOpMetadata: unknown): boolean {
396
- const handler = this.messageHandlers.get(op.type);
397
- if (handler === undefined) {
398
- return false;
399
- }
400
- handler.submit(op as IMapOperation, localOpMetadata as MapLocalOpMetadata);
401
- return true;
402
- }
403
-
404
- public tryApplyStashedOp(op: any): unknown {
405
- const handler = this.messageHandlers.get(op.type);
406
- if (handler === undefined) {
407
- throw new Error("no apply stashed op handler");
408
- }
409
- return handler.applyStashedOp(op as IMapOperation);
410
- }
411
-
412
- /**
413
- * Process the given op if a handler is registered.
414
- * @param op - The message to process
415
- * @param local - Whether the message originated from the local client
416
- * @param localOpMetadata - For local client messages, this is the metadata that was submitted with the message.
417
- * For messages from a remote client, this will be undefined.
418
- * @returns True if the operation was processed, false otherwise.
419
- */
420
- public tryProcessMessage(
421
- op: IMapOperation,
422
- local: boolean,
423
- localOpMetadata: unknown,
424
- ): boolean {
425
- const handler = this.messageHandlers.get(op.type);
426
- if (handler === undefined) {
427
- return false;
428
- }
429
- handler.process(op, local, localOpMetadata as MapLocalOpMetadata);
430
- return true;
431
- }
432
-
433
- /**
434
- * Rollback a local op
435
- * @param op - The operation to rollback
436
- * @param localOpMetadata - The local metadata associated with the op.
437
- */
438
- public rollback(op: any, localOpMetadata: unknown) {
439
- if (!isMapLocalOpMetadata(localOpMetadata)) {
440
- throw new Error("Invalid localOpMetadata");
441
- }
442
-
443
- if (op.type === "clear" && localOpMetadata.type === "clear") {
444
- if (localOpMetadata.previousMap === undefined) {
445
- throw new Error("Cannot rollback without previous map");
446
- }
447
- localOpMetadata.previousMap.forEach((localValue, key) => {
448
- this.setCore(key, localValue, true);
449
- });
450
-
451
- const lastPendingClearId = this.pendingClearMessageIds.pop();
452
- if (lastPendingClearId === undefined || lastPendingClearId !== localOpMetadata.pendingMessageId) {
453
- throw new Error("Rollback op does match last clear");
454
- }
455
- } else if (op.type === "delete" || op.type === "set") {
456
- if (localOpMetadata.type === "add") {
457
- this.deleteCore(op.key, true);
458
- } else if (localOpMetadata.type === "edit" && localOpMetadata.previousValue !== undefined) {
459
- this.setCore(op.key, localOpMetadata.previousValue, true);
460
- } else {
461
- throw new Error("Cannot rollback without previous value");
462
- }
463
-
464
- const pendingMessageIds = this.pendingKeys.get(op.key);
465
- const lastPendingMessageId = pendingMessageIds?.pop();
466
- if (!pendingMessageIds || lastPendingMessageId !== localOpMetadata.pendingMessageId) {
467
- throw new Error("Rollback op does not match last pending");
468
- }
469
- if (pendingMessageIds.length === 0) {
470
- this.pendingKeys.delete(op.key);
471
- }
472
- } else {
473
- throw new Error("Unsupported op for rollback");
474
- }
475
- }
476
-
477
- /**
478
- * Set implementation used for both locally sourced sets as well as incoming remote sets.
479
- * @param key - The key being set
480
- * @param value - The value being set
481
- * @param local - Whether the message originated from the local client
482
- * @returns Previous local value of the key, if any
483
- */
484
- private setCore(key: string, value: ILocalValue, local: boolean): ILocalValue | undefined {
485
- const previousLocalValue = this.data.get(key);
486
- const previousValue = previousLocalValue?.value;
487
- this.data.set(key, value);
488
- this.eventEmitter.emit("valueChanged", { key, previousValue }, local, this.eventEmitter);
489
- return previousLocalValue;
490
- }
491
-
492
- /**
493
- * Clear implementation used for both locally sourced clears as well as incoming remote clears.
494
- * @param local - Whether the message originated from the local client
495
- */
496
- private clearCore(local: boolean): void {
497
- this.data.clear();
498
- this.eventEmitter.emit("clear", local, this.eventEmitter);
499
- }
500
-
501
- /**
502
- * Delete implementation used for both locally sourced deletes as well as incoming remote deletes.
503
- * @param key - The key being deleted
504
- * @param local - Whether the message originated from the local client
505
- * @returns Previous local value of the key if it existed, undefined if it did not exist
506
- */
507
- private deleteCore(key: string, local: boolean): ILocalValue | undefined {
508
- const previousLocalValue = this.data.get(key);
509
- const previousValue = previousLocalValue?.value;
510
- const successfullyRemoved = this.data.delete(key);
511
- if (successfullyRemoved) {
512
- this.eventEmitter.emit("valueChanged", { key, previousValue }, local, this.eventEmitter);
513
- }
514
- return previousLocalValue;
515
- }
516
-
517
- /**
518
- * Clear all keys in memory in response to a remote clear, but retain keys we have modified but not yet been ack'd.
519
- */
520
- private clearExceptPendingKeys(): void {
521
- // Assuming the pendingKeys is small and the map is large
522
- // we will get the value for the pendingKeys and clear the map
523
- const temp = new Map<string, ILocalValue>();
524
- this.pendingKeys.forEach((value, key) => {
525
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
526
- temp.set(key, this.data.get(key)!);
527
- });
528
- this.clearCore(false);
529
- temp.forEach((value, key) => {
530
- this.setCore(key, value, true);
531
- });
532
- }
533
-
534
- /**
535
- * The remote ISerializableValue we're receiving (either as a result of a load or an incoming set op) will
536
- * have the information we need to create a real object, but will not be the real object yet. For example,
537
- * we might know it's a map and the map's ID but not have the actual map or its data yet. makeLocal's
538
- * job is to convert that information into a real object for local usage.
539
- * @param key - The key that the caller intends to store the local value into (used for ops later). But
540
- * doesn't actually store the local value into that key. So better not lie!
541
- * @param serializable - The remote information that we can convert into a real object
542
- * @returns The local value that was produced
543
- */
544
- private makeLocal(key: string, serializable: ISerializableValue): ILocalValue {
545
- if (serializable.type === ValueType[ValueType.Plain] || serializable.type === ValueType[ValueType.Shared]) {
546
- return this.localValueMaker.fromSerializable(serializable);
547
- } else {
548
- throw new Error("Unknown local value type");
549
- }
550
- }
551
-
552
- /**
553
- * If our local operations that have not yet been ack'd will eventually overwrite an incoming operation, we should
554
- * not process the incoming operation.
555
- * @param op - Operation to check
556
- * @param local - Whether the message originated from the local client
557
- * @param localOpMetadata - For local client messages, this is the metadata that was submitted with the message.
558
- * For messages from a remote client, this will be undefined.
559
- * @returns True if the operation should be processed, false otherwise
560
- */
561
- private needProcessKeyOperation(
562
- op: IMapKeyOperation,
563
- local: boolean,
564
- localOpMetadata: MapLocalOpMetadata,
565
- ): boolean {
566
- if (this.pendingClearMessageIds.length > 0) {
567
- if (local) {
568
- assert(localOpMetadata !== undefined && isMapKeyLocalOpMetadata(localOpMetadata) &&
569
- localOpMetadata.pendingMessageId < this.pendingClearMessageIds[0],
570
- 0x013 /* "Received out of order op when there is an unackd clear message" */);
571
- }
572
- // If we have an unack'd clear, we can ignore all ops.
573
- return false;
574
- }
575
-
576
- const pendingKeyMessageId = this.pendingKeys.get(op.key);
577
- if (pendingKeyMessageId !== undefined) {
578
- // Found an unack'd op. Clear it from the map if the pendingMessageId in the map matches this message's
579
- // and don't process the op.
580
- if (local) {
581
- assert(localOpMetadata !== undefined && isMapKeyLocalOpMetadata(localOpMetadata),
582
- 0x014 /* pendingMessageId is missing from the local client's operation */);
583
- const pendingMessageIds = this.pendingKeys.get(op.key);
584
- assert(pendingMessageIds !== undefined && pendingMessageIds[0] === localOpMetadata.pendingMessageId,
585
- 0x2fa /* Unexpected pending message received */);
586
- pendingMessageIds.shift();
587
- if (pendingMessageIds.length === 0) {
588
- this.pendingKeys.delete(op.key);
589
- }
590
- }
591
- return false;
592
- }
593
-
594
- // If we don't have a NACK op on the key, we need to process the remote ops.
595
- return !local;
596
- }
597
-
598
- /**
599
- * Get the message handlers for the map.
600
- * @returns A map of string op names to IMapMessageHandlers for those ops
601
- */
602
- private getMessageHandlers() {
603
- const messageHandlers = new Map<string, IMapMessageHandler>();
604
- messageHandlers.set(
605
- "clear",
606
- {
607
- process: (op: IMapClearOperation, local, localOpMetadata) => {
608
- if (local) {
609
- assert(isClearLocalOpMetadata(localOpMetadata),
610
- 0x015 /* "pendingMessageId is missing from the local client's clear operation" */);
611
- const pendingClearMessageId = this.pendingClearMessageIds.shift();
612
- assert(pendingClearMessageId === localOpMetadata.pendingMessageId,
613
- 0x2fb /* pendingMessageId does not match */);
614
- return;
615
- }
616
- if (this.pendingKeys.size !== 0) {
617
- this.clearExceptPendingKeys();
618
- return;
619
- }
620
- this.clearCore(local);
621
- },
622
- submit: (op: IMapClearOperation, localOpMetadata: IMapClearLocalOpMetadata) => {
623
- assert(isClearLocalOpMetadata(localOpMetadata), 0x2fc /* Invalid localOpMetadata for clear */);
624
- // We don't reuse the metadata pendingMessageId but send a new one on each submit.
625
- const pendingClearMessageId = this.pendingClearMessageIds.shift();
626
- assert(pendingClearMessageId === localOpMetadata.pendingMessageId,
627
- 0x2fd /* pendingMessageId does not match */);
628
- this.submitMapClearMessage(op, localOpMetadata.previousMap);
629
- },
630
- applyStashedOp: (op: IMapClearOperation) => {
631
- const copy = new Map<string, ILocalValue>(this.data);
632
- this.clearCore(true);
633
- // We don't reuse the metadata pendingMessageId but send a new one on each submit.
634
- return createClearLocalOpMetadata(op, this.getMapClearMessageId(), copy);
635
- },
636
- });
637
- messageHandlers.set(
638
- "delete",
639
- {
640
- process: (op: IMapDeleteOperation, local, localOpMetadata) => {
641
- if (!this.needProcessKeyOperation(op, local, localOpMetadata)) {
642
- return;
643
- }
644
- this.deleteCore(op.key, local);
645
- },
646
- submit: (op: IMapDeleteOperation, localOpMetadata: MapKeyLocalOpMetadata) => {
647
- this.resubmitMapKeyMessage(op, localOpMetadata);
648
- },
649
- applyStashedOp: (op: IMapDeleteOperation) => {
650
- // We don't reuse the metadata pendingMessageId but send a new one on each submit.
651
- const previousValue = this.deleteCore(op.key, true);
652
- return createKeyLocalOpMetadata(op, this.getMapKeyMessageId(op), previousValue);
653
- },
654
- });
655
- messageHandlers.set(
656
- "set",
657
- {
658
- process: (op: IMapSetOperation, local, localOpMetadata) => {
659
- if (!this.needProcessKeyOperation(op, local, localOpMetadata)) {
660
- return;
661
- }
662
-
663
- // needProcessKeyOperation should have returned false if local is true
664
- const context = this.makeLocal(op.key, op.value);
665
- this.setCore(op.key, context, local);
666
- },
667
- submit: (op: IMapSetOperation, localOpMetadata: MapKeyLocalOpMetadata) => {
668
- this.resubmitMapKeyMessage(op, localOpMetadata);
669
- },
670
- applyStashedOp: (op: IMapSetOperation) => {
671
- // We don't reuse the metadata pendingMessageId but send a new one on each submit.
672
- const context = this.makeLocal(op.key, op.value);
673
- const previousValue = this.setCore(op.key, context, true);
674
- return createKeyLocalOpMetadata(op, this.getMapKeyMessageId(op), previousValue);
675
- },
676
- });
677
-
678
- return messageHandlers;
679
- }
680
-
681
- private getMapClearMessageId(): number {
682
- const pendingMessageId = ++this.pendingMessageId;
683
- this.pendingClearMessageIds.push(pendingMessageId);
684
- return pendingMessageId;
685
- }
686
-
687
- /**
688
- * Submit a clear message to remote clients.
689
- * @param op - The clear message
690
- */
691
- private submitMapClearMessage(op: IMapClearOperation, previousMap?: Map<string, ILocalValue>): void {
692
- const metadata = createClearLocalOpMetadata(op, this.getMapClearMessageId(), previousMap);
693
- this.submitMessage(op, metadata);
694
- }
695
-
696
- private getMapKeyMessageId(op: IMapKeyOperation): number {
697
- const pendingMessageId = ++this.pendingMessageId;
698
- const pendingMessageIds = this.pendingKeys.get(op.key);
699
- if (pendingMessageIds !== undefined) {
700
- pendingMessageIds.push(pendingMessageId);
701
- } else {
702
- this.pendingKeys.set(op.key, [pendingMessageId]);
703
- }
704
- return pendingMessageId;
705
- }
706
-
707
- /**
708
- * Submit a map key message to remote clients.
709
- * @param op - The map key message
710
- * @param previousValue - The value of the key before this op
711
- */
712
- private submitMapKeyMessage(op: IMapKeyOperation, previousValue?: ILocalValue): void {
713
- const localMetadata = createKeyLocalOpMetadata(op, this.getMapKeyMessageId(op), previousValue);
714
- this.submitMessage(op, localMetadata);
715
- }
716
-
717
- /**
718
- * Submit a map key message to remote clients based on a previous submit.
719
- * @param op - The map key message
720
- * @param localOpMetadata - Metadata from the previous submit
721
- */
722
- private resubmitMapKeyMessage(op: IMapKeyOperation, localOpMetadata: MapLocalOpMetadata): void {
723
- assert(isMapKeyLocalOpMetadata(localOpMetadata), 0x2fe /* Invalid localOpMetadata in submit */);
724
-
725
- // clear the old pending message id
726
- const pendingMessageIds = this.pendingKeys.get(op.key);
727
- assert(pendingMessageIds !== undefined && pendingMessageIds[0] === localOpMetadata.pendingMessageId,
728
- 0x2ff /* Unexpected pending message received */);
729
- pendingMessageIds.shift();
730
- if (pendingMessageIds.length === 0) {
731
- this.pendingKeys.delete(op.key);
732
- }
733
-
734
- // We don't reuse the metadata pendingMessageId but send a new one on each submit.
735
- const pendingMessageId = this.getMapKeyMessageId(op);
736
- const localMetadata = localOpMetadata.type === "edit" ?
737
- { type: "edit", pendingMessageId, previousValue: localOpMetadata.previousValue } :
738
- { type: "add", pendingMessageId };
739
- this.submitMessage(op, localMetadata);
740
- }
131
+ /**
132
+ * The number of key/value pairs stored in the map.
133
+ */
134
+ public get size(): number {
135
+ return this.data.size;
136
+ }
137
+
138
+ /**
139
+ * Mapping of op types to message handlers.
140
+ */
141
+ private readonly messageHandlers: ReadonlyMap<string, IMapMessageHandler> = new Map();
142
+
143
+ /**
144
+ * The in-memory data the map is storing.
145
+ */
146
+ private readonly data = new Map<string, ILocalValue>();
147
+
148
+ /**
149
+ * Keys that have been modified locally but not yet ack'd from the server.
150
+ */
151
+ private readonly pendingKeys: Map<string, number[]> = new Map();
152
+
153
+ /**
154
+ * This is used to assign a unique id to every outgoing operation and helps in tracking unack'd ops.
155
+ */
156
+ private pendingMessageId: number = -1;
157
+
158
+ /**
159
+ * The pending ids of any clears that have been performed locally but not yet ack'd from the server
160
+ */
161
+ private readonly pendingClearMessageIds: number[] = [];
162
+
163
+ /**
164
+ * Object to create encapsulations of the values stored in the map.
165
+ */
166
+ private readonly localValueMaker: LocalValueMaker;
167
+
168
+ /**
169
+ * Create a new shared map kernel.
170
+ * @param serializer - The serializer to serialize / parse handles
171
+ * @param handle - The handle of the shared object using the kernel
172
+ * @param submitMessage - A callback to submit a message through the shared object
173
+ * @param isAttached - To query whether the shared object should generate ops
174
+ * @param valueTypes - The value types to register
175
+ * @param eventEmitter - The object that will emit map events
176
+ */
177
+ public constructor(
178
+ private readonly serializer: IFluidSerializer,
179
+ private readonly handle: IFluidHandle,
180
+ private readonly submitMessage: (op: unknown, localOpMetadata: unknown) => void,
181
+ private readonly isAttached: () => boolean,
182
+ private readonly eventEmitter: TypedEventEmitter<ISharedMapEvents>,
183
+ ) {
184
+ this.localValueMaker = new LocalValueMaker(serializer);
185
+ this.messageHandlers = this.getMessageHandlers();
186
+ }
187
+
188
+ /**
189
+ * Get an iterator over the keys in this map.
190
+ * @returns The iterator
191
+ */
192
+ public keys(): IterableIterator<string> {
193
+ return this.data.keys();
194
+ }
195
+
196
+ /**
197
+ * Get an iterator over the entries in this map.
198
+ * @returns The iterator
199
+ */
200
+ // TODO: Use `unknown` instead (breaking change).
201
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
202
+ public entries(): IterableIterator<[string, any]> {
203
+ const localEntriesIterator = this.data.entries();
204
+ const iterator = {
205
+ next(): IteratorResult<[string, unknown]> {
206
+ const nextVal = localEntriesIterator.next();
207
+ return nextVal.done
208
+ ? { value: undefined, done: true }
209
+ : // Unpack the stored value
210
+ { value: [nextVal.value[0], nextVal.value[1].value], done: false };
211
+ },
212
+ [Symbol.iterator](): IterableIterator<[string, unknown]> {
213
+ return this;
214
+ },
215
+ };
216
+ return iterator;
217
+ }
218
+
219
+ /**
220
+ * Get an iterator over the values in this map.
221
+ * @returns The iterator
222
+ */
223
+ // TODO: Use `unknown` instead (breaking change).
224
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
225
+ public values(): IterableIterator<any> {
226
+ const localValuesIterator = this.data.values();
227
+ const iterator = {
228
+ next(): IteratorResult<unknown> {
229
+ const nextVal = localValuesIterator.next();
230
+ return nextVal.done
231
+ ? { value: undefined, done: true }
232
+ : // Unpack the stored value
233
+ { value: nextVal.value.value as unknown, done: false };
234
+ },
235
+ [Symbol.iterator](): IterableIterator<unknown> {
236
+ return this;
237
+ },
238
+ };
239
+ return iterator;
240
+ }
241
+
242
+ /**
243
+ * Get an iterator over the entries in this map.
244
+ * @returns The iterator
245
+ */
246
+ // TODO: Use `unknown` instead (breaking change).
247
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
248
+ public [Symbol.iterator](): IterableIterator<[string, any]> {
249
+ return this.entries();
250
+ }
251
+
252
+ /**
253
+ * Executes the given callback on each entry in the map.
254
+ * @param callbackFn - Callback function
255
+ */
256
+ public forEach(
257
+ callbackFn: (value: unknown, key: string, map: Map<string, unknown>) => void,
258
+ ): void {
259
+ // eslint-disable-next-line unicorn/no-array-for-each
260
+ this.data.forEach((localValue, key, m) => {
261
+ callbackFn(localValue.value, key, m);
262
+ });
263
+ }
264
+
265
+ /**
266
+ * {@inheritDoc ISharedMap.get}
267
+ */
268
+ // TODO: Use `unknown` instead (breaking change).
269
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
270
+ public get<T = any>(key: string): T | undefined {
271
+ const localValue = this.data.get(key);
272
+ return localValue === undefined ? undefined : (localValue.value as T);
273
+ }
274
+
275
+ /**
276
+ * Check if a key exists in the map.
277
+ * @param key - The key to check
278
+ * @returns True if the key exists, false otherwise
279
+ */
280
+ public has(key: string): boolean {
281
+ return this.data.has(key);
282
+ }
283
+
284
+ /**
285
+ * {@inheritDoc ISharedMap.set}
286
+ */
287
+ public set(key: string, value: unknown): void {
288
+ // Undefined/null keys can't be serialized to JSON in the manner we currently snapshot.
289
+ if (key === undefined || key === null) {
290
+ throw new Error("Undefined and null keys are not supported");
291
+ }
292
+
293
+ // Create a local value and serialize it.
294
+ const localValue = this.localValueMaker.fromInMemory(value);
295
+ const serializableValue = makeSerializable(localValue, this.serializer, this.handle);
296
+
297
+ // Set the value locally.
298
+ const previousValue = this.setCore(key, localValue, true);
299
+
300
+ // If we are not attached, don't submit the op.
301
+ if (!this.isAttached()) {
302
+ return;
303
+ }
304
+
305
+ const op: IMapSetOperation = {
306
+ key,
307
+ type: "set",
308
+ value: serializableValue,
309
+ };
310
+ this.submitMapKeyMessage(op, previousValue);
311
+ }
312
+
313
+ /**
314
+ * Delete a key from the map.
315
+ * @param key - Key to delete
316
+ * @returns True if the key existed and was deleted, false if it did not exist
317
+ */
318
+ public delete(key: string): boolean {
319
+ // Delete the key locally first.
320
+ const previousValue = this.deleteCore(key, true);
321
+
322
+ // If we are not attached, don't submit the op.
323
+ if (!this.isAttached()) {
324
+ return previousValue !== undefined;
325
+ }
326
+
327
+ const op: IMapDeleteOperation = {
328
+ key,
329
+ type: "delete",
330
+ };
331
+ this.submitMapKeyMessage(op, previousValue);
332
+
333
+ return previousValue !== undefined;
334
+ }
335
+
336
+ /**
337
+ * Clear all data from the map.
338
+ */
339
+ public clear(): void {
340
+ const copy = this.isAttached() ? new Map<string, ILocalValue>(this.data) : undefined;
341
+
342
+ // Clear the data locally first.
343
+ this.clearCore(true);
344
+
345
+ // If we are not attached, don't submit the op.
346
+ if (!this.isAttached()) {
347
+ return;
348
+ }
349
+
350
+ const op: IMapClearOperation = {
351
+ type: "clear",
352
+ };
353
+ this.submitMapClearMessage(op, copy);
354
+ }
355
+
356
+ /**
357
+ * Serializes the data stored in the shared map to a JSON string
358
+ * @param serializer - The serializer to use to serialize handles in its values.
359
+ * @returns A JSON string containing serialized map data
360
+ */
361
+ public getSerializedStorage(serializer: IFluidSerializer): IMapDataObjectSerialized {
362
+ const serializableMapData: IMapDataObjectSerialized = {};
363
+ for (const [key, localValue] of this.data.entries()) {
364
+ serializableMapData[key] = localValue.makeSerialized(serializer, this.handle);
365
+ }
366
+ return serializableMapData;
367
+ }
368
+
369
+ public getSerializableStorage(serializer: IFluidSerializer): IMapDataObjectSerializable {
370
+ const serializableMapData: IMapDataObjectSerializable = {};
371
+ for (const [key, localValue] of this.data.entries()) {
372
+ serializableMapData[key] = makeSerializable(localValue, serializer, this.handle);
373
+ }
374
+ return serializableMapData;
375
+ }
376
+
377
+ public serialize(serializer: IFluidSerializer): string {
378
+ return JSON.stringify(this.getSerializableStorage(serializer));
379
+ }
380
+
381
+ /**
382
+ * Populate the kernel with the given map data.
383
+ * @param data - A JSON string containing serialized map data
384
+ */
385
+ public populateFromSerializable(json: IMapDataObjectSerializable): void {
386
+ for (const [key, serializable] of Object.entries(json)) {
387
+ const localValue = {
388
+ key,
389
+ value: this.makeLocal(key, serializable),
390
+ };
391
+
392
+ this.data.set(localValue.key, localValue.value);
393
+ }
394
+ }
395
+
396
+ public populate(json: string): void {
397
+ this.populateFromSerializable(JSON.parse(json) as IMapDataObjectSerializable);
398
+ }
399
+
400
+ /**
401
+ * Submit the given op if a handler is registered.
402
+ * @param op - The operation to attempt to submit
403
+ * @param localOpMetadata - The local metadata associated with the op. This is kept locally by the runtime
404
+ * and not sent to the server. This will be sent back when this message is received back from the server. This is
405
+ * also sent if we are asked to resubmit the message.
406
+ * @returns True if the operation was submitted, false otherwise.
407
+ */
408
+ public trySubmitMessage(op: IMapOperation, localOpMetadata: unknown): boolean {
409
+ const handler = this.messageHandlers.get(op.type);
410
+ if (handler === undefined) {
411
+ return false;
412
+ }
413
+ handler.submit(op, localOpMetadata as MapLocalOpMetadata);
414
+ return true;
415
+ }
416
+
417
+ public tryApplyStashedOp(op: IMapOperation): unknown {
418
+ const handler = this.messageHandlers.get(op.type);
419
+ if (handler === undefined) {
420
+ throw new Error("no apply stashed op handler");
421
+ }
422
+ return handler.applyStashedOp(op);
423
+ }
424
+
425
+ /**
426
+ * Process the given op if a handler is registered.
427
+ * @param op - The message to process
428
+ * @param local - Whether the message originated from the local client
429
+ * @param localOpMetadata - For local client messages, this is the metadata that was submitted with the message.
430
+ * For messages from a remote client, this will be undefined.
431
+ * @returns True if the operation was processed, false otherwise.
432
+ */
433
+ public tryProcessMessage(op: IMapOperation, local: boolean, localOpMetadata: unknown): boolean {
434
+ const handler = this.messageHandlers.get(op.type);
435
+ if (handler === undefined) {
436
+ return false;
437
+ }
438
+ handler.process(op, local, localOpMetadata as MapLocalOpMetadata);
439
+ return true;
440
+ }
441
+
442
+ /* eslint-disable @typescript-eslint/no-unsafe-member-access */
443
+
444
+ /**
445
+ * Rollback a local op
446
+ * @param op - The operation to rollback
447
+ * @param localOpMetadata - The local metadata associated with the op.
448
+ */
449
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
450
+ public rollback(op: any, localOpMetadata: unknown): void {
451
+ if (!isMapLocalOpMetadata(localOpMetadata)) {
452
+ throw new Error("Invalid localOpMetadata");
453
+ }
454
+
455
+ if (op.type === "clear" && localOpMetadata.type === "clear") {
456
+ if (localOpMetadata.previousMap === undefined) {
457
+ throw new Error("Cannot rollback without previous map");
458
+ }
459
+ for (const [key, localValue] of localOpMetadata.previousMap.entries()) {
460
+ this.setCore(key, localValue, true);
461
+ }
462
+
463
+ const lastPendingClearId = this.pendingClearMessageIds.pop();
464
+ if (
465
+ lastPendingClearId === undefined ||
466
+ lastPendingClearId !== localOpMetadata.pendingMessageId
467
+ ) {
468
+ throw new Error("Rollback op does match last clear");
469
+ }
470
+ } else if (op.type === "delete" || op.type === "set") {
471
+ if (localOpMetadata.type === "add") {
472
+ this.deleteCore(op.key as string, true);
473
+ } else if (
474
+ localOpMetadata.type === "edit" &&
475
+ localOpMetadata.previousValue !== undefined
476
+ ) {
477
+ this.setCore(op.key as string, localOpMetadata.previousValue, true);
478
+ } else {
479
+ throw new Error("Cannot rollback without previous value");
480
+ }
481
+
482
+ const pendingMessageIds = this.pendingKeys.get(op.key as string);
483
+ const lastPendingMessageId = pendingMessageIds?.pop();
484
+ if (!pendingMessageIds || lastPendingMessageId !== localOpMetadata.pendingMessageId) {
485
+ throw new Error("Rollback op does not match last pending");
486
+ }
487
+ if (pendingMessageIds.length === 0) {
488
+ this.pendingKeys.delete(op.key as string);
489
+ }
490
+ } else {
491
+ throw new Error("Unsupported op for rollback");
492
+ }
493
+ }
494
+
495
+ /* eslint-enable @typescript-eslint/no-unsafe-member-access */
496
+
497
+ /**
498
+ * Set implementation used for both locally sourced sets as well as incoming remote sets.
499
+ * @param key - The key being set
500
+ * @param value - The value being set
501
+ * @param local - Whether the message originated from the local client
502
+ * @returns Previous local value of the key, if any
503
+ */
504
+ private setCore(key: string, value: ILocalValue, local: boolean): ILocalValue | undefined {
505
+ const previousLocalValue = this.data.get(key);
506
+ const previousValue: unknown = previousLocalValue?.value;
507
+ this.data.set(key, value);
508
+ this.eventEmitter.emit("valueChanged", { key, previousValue }, local, this.eventEmitter);
509
+ return previousLocalValue;
510
+ }
511
+
512
+ /**
513
+ * Clear implementation used for both locally sourced clears as well as incoming remote clears.
514
+ * @param local - Whether the message originated from the local client
515
+ */
516
+ private clearCore(local: boolean): void {
517
+ this.data.clear();
518
+ this.eventEmitter.emit("clear", local, this.eventEmitter);
519
+ }
520
+
521
+ /**
522
+ * Delete implementation used for both locally sourced deletes as well as incoming remote deletes.
523
+ * @param key - The key being deleted
524
+ * @param local - Whether the message originated from the local client
525
+ * @returns Previous local value of the key if it existed, undefined if it did not exist
526
+ */
527
+ private deleteCore(key: string, local: boolean): ILocalValue | undefined {
528
+ const previousLocalValue = this.data.get(key);
529
+ const previousValue: unknown = previousLocalValue?.value;
530
+ const successfullyRemoved = this.data.delete(key);
531
+ if (successfullyRemoved) {
532
+ this.eventEmitter.emit(
533
+ "valueChanged",
534
+ { key, previousValue },
535
+ local,
536
+ this.eventEmitter,
537
+ );
538
+ }
539
+ return previousLocalValue;
540
+ }
541
+
542
+ /**
543
+ * Clear all keys in memory in response to a remote clear, but retain keys we have modified but not yet been ack'd.
544
+ */
545
+ private clearExceptPendingKeys(): void {
546
+ // Assuming the pendingKeys is small and the map is large
547
+ // we will get the value for the pendingKeys and clear the map
548
+ const temp = new Map<string, ILocalValue>();
549
+ for (const key of this.pendingKeys.keys()) {
550
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
551
+ temp.set(key, this.data.get(key)!);
552
+ }
553
+ this.clearCore(false);
554
+ for (const [key, value] of temp.entries()) {
555
+ this.setCore(key, value, true);
556
+ }
557
+ }
558
+
559
+ /**
560
+ * The remote ISerializableValue we're receiving (either as a result of a load or an incoming set op) will
561
+ * have the information we need to create a real object, but will not be the real object yet. For example,
562
+ * we might know it's a map and the map's ID but not have the actual map or its data yet. makeLocal's
563
+ * job is to convert that information into a real object for local usage.
564
+ * @param key - The key that the caller intends to store the local value into (used for ops later). But
565
+ * doesn't actually store the local value into that key. So better not lie!
566
+ * @param serializable - The remote information that we can convert into a real object
567
+ * @returns The local value that was produced
568
+ */
569
+ private makeLocal(key: string, serializable: ISerializableValue): ILocalValue {
570
+ if (
571
+ serializable.type === ValueType[ValueType.Plain] ||
572
+ serializable.type === ValueType[ValueType.Shared]
573
+ ) {
574
+ return this.localValueMaker.fromSerializable(serializable);
575
+ } else {
576
+ throw new Error("Unknown local value type");
577
+ }
578
+ }
579
+
580
+ /**
581
+ * If our local operations that have not yet been ack'd will eventually overwrite an incoming operation, we should
582
+ * not process the incoming operation.
583
+ * @param op - Operation to check
584
+ * @param local - Whether the message originated from the local client
585
+ * @param localOpMetadata - For local client messages, this is the metadata that was submitted with the message.
586
+ * For messages from a remote client, this will be undefined.
587
+ * @returns True if the operation should be processed, false otherwise
588
+ */
589
+ private needProcessKeyOperation(
590
+ op: IMapKeyOperation,
591
+ local: boolean,
592
+ localOpMetadata: MapLocalOpMetadata,
593
+ ): boolean {
594
+ if (this.pendingClearMessageIds.length > 0) {
595
+ if (local) {
596
+ assert(
597
+ localOpMetadata !== undefined &&
598
+ isMapKeyLocalOpMetadata(localOpMetadata) &&
599
+ localOpMetadata.pendingMessageId < this.pendingClearMessageIds[0],
600
+ 0x013 /* "Received out of order op when there is an unackd clear message" */,
601
+ );
602
+ }
603
+ // If we have an unack'd clear, we can ignore all ops.
604
+ return false;
605
+ }
606
+
607
+ const pendingKeyMessageId = this.pendingKeys.get(op.key);
608
+ if (pendingKeyMessageId !== undefined) {
609
+ // Found an unack'd op. Clear it from the map if the pendingMessageId in the map matches this message's
610
+ // and don't process the op.
611
+ if (local) {
612
+ assert(
613
+ localOpMetadata !== undefined && isMapKeyLocalOpMetadata(localOpMetadata),
614
+ 0x014 /* pendingMessageId is missing from the local client's operation */,
615
+ );
616
+ const pendingMessageIds = this.pendingKeys.get(op.key);
617
+ assert(
618
+ pendingMessageIds !== undefined &&
619
+ pendingMessageIds[0] === localOpMetadata.pendingMessageId,
620
+ 0x2fa /* Unexpected pending message received */,
621
+ );
622
+ pendingMessageIds.shift();
623
+ if (pendingMessageIds.length === 0) {
624
+ this.pendingKeys.delete(op.key);
625
+ }
626
+ }
627
+ return false;
628
+ }
629
+
630
+ // If we don't have a NACK op on the key, we need to process the remote ops.
631
+ return !local;
632
+ }
633
+
634
+ /**
635
+ * Get the message handlers for the map.
636
+ * @returns A map of string op names to IMapMessageHandlers for those ops
637
+ */
638
+ private getMessageHandlers(): Map<string, IMapMessageHandler> {
639
+ const messageHandlers = new Map<string, IMapMessageHandler>();
640
+ messageHandlers.set("clear", {
641
+ process: (op: IMapClearOperation, local, localOpMetadata) => {
642
+ if (local) {
643
+ assert(
644
+ isClearLocalOpMetadata(localOpMetadata),
645
+ 0x015 /* "pendingMessageId is missing from the local client's clear operation" */,
646
+ );
647
+ const pendingClearMessageId = this.pendingClearMessageIds.shift();
648
+ assert(
649
+ pendingClearMessageId === localOpMetadata.pendingMessageId,
650
+ 0x2fb /* pendingMessageId does not match */,
651
+ );
652
+ return;
653
+ }
654
+ if (this.pendingKeys.size > 0) {
655
+ this.clearExceptPendingKeys();
656
+ return;
657
+ }
658
+ this.clearCore(local);
659
+ },
660
+ submit: (op: IMapClearOperation, localOpMetadata: IMapClearLocalOpMetadata) => {
661
+ assert(
662
+ isClearLocalOpMetadata(localOpMetadata),
663
+ 0x2fc /* Invalid localOpMetadata for clear */,
664
+ );
665
+ // We don't reuse the metadata pendingMessageId but send a new one on each submit.
666
+ const pendingClearMessageId = this.pendingClearMessageIds.shift();
667
+ assert(
668
+ pendingClearMessageId === localOpMetadata.pendingMessageId,
669
+ 0x2fd /* pendingMessageId does not match */,
670
+ );
671
+ this.submitMapClearMessage(op, localOpMetadata.previousMap);
672
+ },
673
+ applyStashedOp: (op: IMapClearOperation) => {
674
+ const copy = new Map<string, ILocalValue>(this.data);
675
+ this.clearCore(true);
676
+ // We don't reuse the metadata pendingMessageId but send a new one on each submit.
677
+ return createClearLocalOpMetadata(op, this.getMapClearMessageId(), copy);
678
+ },
679
+ });
680
+ messageHandlers.set("delete", {
681
+ process: (op: IMapDeleteOperation, local, localOpMetadata) => {
682
+ if (!this.needProcessKeyOperation(op, local, localOpMetadata)) {
683
+ return;
684
+ }
685
+ this.deleteCore(op.key, local);
686
+ },
687
+ submit: (op: IMapDeleteOperation, localOpMetadata: MapKeyLocalOpMetadata) => {
688
+ this.resubmitMapKeyMessage(op, localOpMetadata);
689
+ },
690
+ applyStashedOp: (op: IMapDeleteOperation) => {
691
+ // We don't reuse the metadata pendingMessageId but send a new one on each submit.
692
+ const previousValue = this.deleteCore(op.key, true);
693
+ return createKeyLocalOpMetadata(op, this.getMapKeyMessageId(op), previousValue);
694
+ },
695
+ });
696
+ messageHandlers.set("set", {
697
+ process: (op: IMapSetOperation, local, localOpMetadata) => {
698
+ if (!this.needProcessKeyOperation(op, local, localOpMetadata)) {
699
+ return;
700
+ }
701
+
702
+ // needProcessKeyOperation should have returned false if local is true
703
+ const context = this.makeLocal(op.key, op.value);
704
+ this.setCore(op.key, context, local);
705
+ },
706
+ submit: (op: IMapSetOperation, localOpMetadata: MapKeyLocalOpMetadata) => {
707
+ this.resubmitMapKeyMessage(op, localOpMetadata);
708
+ },
709
+ applyStashedOp: (op: IMapSetOperation) => {
710
+ // We don't reuse the metadata pendingMessageId but send a new one on each submit.
711
+ const context = this.makeLocal(op.key, op.value);
712
+ const previousValue = this.setCore(op.key, context, true);
713
+ return createKeyLocalOpMetadata(op, this.getMapKeyMessageId(op), previousValue);
714
+ },
715
+ });
716
+
717
+ return messageHandlers;
718
+ }
719
+
720
+ private getMapClearMessageId(): number {
721
+ const pendingMessageId = ++this.pendingMessageId;
722
+ this.pendingClearMessageIds.push(pendingMessageId);
723
+ return pendingMessageId;
724
+ }
725
+
726
+ /**
727
+ * Submit a clear message to remote clients.
728
+ * @param op - The clear message
729
+ */
730
+ private submitMapClearMessage(
731
+ op: IMapClearOperation,
732
+ previousMap?: Map<string, ILocalValue>,
733
+ ): void {
734
+ const metadata = createClearLocalOpMetadata(op, this.getMapClearMessageId(), previousMap);
735
+ this.submitMessage(op, metadata);
736
+ }
737
+
738
+ private getMapKeyMessageId(op: IMapKeyOperation): number {
739
+ const pendingMessageId = ++this.pendingMessageId;
740
+ const pendingMessageIds = this.pendingKeys.get(op.key);
741
+ if (pendingMessageIds !== undefined) {
742
+ pendingMessageIds.push(pendingMessageId);
743
+ } else {
744
+ this.pendingKeys.set(op.key, [pendingMessageId]);
745
+ }
746
+ return pendingMessageId;
747
+ }
748
+
749
+ /**
750
+ * Submit a map key message to remote clients.
751
+ * @param op - The map key message
752
+ * @param previousValue - The value of the key before this op
753
+ */
754
+ private submitMapKeyMessage(op: IMapKeyOperation, previousValue?: ILocalValue): void {
755
+ const localMetadata = createKeyLocalOpMetadata(
756
+ op,
757
+ this.getMapKeyMessageId(op),
758
+ previousValue,
759
+ );
760
+ this.submitMessage(op, localMetadata);
761
+ }
762
+
763
+ /**
764
+ * Submit a map key message to remote clients based on a previous submit.
765
+ * @param op - The map key message
766
+ * @param localOpMetadata - Metadata from the previous submit
767
+ */
768
+ private resubmitMapKeyMessage(op: IMapKeyOperation, localOpMetadata: MapLocalOpMetadata): void {
769
+ assert(
770
+ isMapKeyLocalOpMetadata(localOpMetadata),
771
+ 0x2fe /* Invalid localOpMetadata in submit */,
772
+ );
773
+
774
+ // clear the old pending message id
775
+ const pendingMessageIds = this.pendingKeys.get(op.key);
776
+ assert(
777
+ pendingMessageIds !== undefined &&
778
+ pendingMessageIds[0] === localOpMetadata.pendingMessageId,
779
+ 0x2ff /* Unexpected pending message received */,
780
+ );
781
+ pendingMessageIds.shift();
782
+ if (pendingMessageIds.length === 0) {
783
+ this.pendingKeys.delete(op.key);
784
+ }
785
+
786
+ // We don't reuse the metadata pendingMessageId but send a new one on each submit.
787
+ const pendingMessageId = this.getMapKeyMessageId(op);
788
+ const localMetadata =
789
+ localOpMetadata.type === "edit"
790
+ ? { type: "edit", pendingMessageId, previousValue: localOpMetadata.previousValue }
791
+ : { type: "add", pendingMessageId };
792
+ this.submitMessage(op, localMetadata);
793
+ }
741
794
  }