@fluidframework/shared-object-base 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 (75) hide show
  1. package/.eslintrc.js +5 -8
  2. package/.mocharc.js +2 -2
  3. package/README.md +1 -1
  4. package/api-extractor.json +2 -2
  5. package/bench/src/index.ts +37 -33
  6. package/bench/src/util.ts +26 -26
  7. package/dist/handle.d.ts.map +1 -1
  8. package/dist/handle.js.map +1 -1
  9. package/dist/index.d.ts +2 -2
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js.map +1 -1
  12. package/dist/packageVersion.d.ts +1 -1
  13. package/dist/packageVersion.js +1 -1
  14. package/dist/packageVersion.js.map +1 -1
  15. package/dist/remoteObjectHandle.d.ts.map +1 -1
  16. package/dist/remoteObjectHandle.js +16 -8
  17. package/dist/remoteObjectHandle.js.map +1 -1
  18. package/dist/serializer.d.ts.map +1 -1
  19. package/dist/serializer.js +5 -7
  20. package/dist/serializer.js.map +1 -1
  21. package/dist/sharedObject.d.ts +3 -3
  22. package/dist/sharedObject.d.ts.map +1 -1
  23. package/dist/sharedObject.js +26 -9
  24. package/dist/sharedObject.js.map +1 -1
  25. package/dist/summarySerializer.d.ts.map +1 -1
  26. package/dist/summarySerializer.js.map +1 -1
  27. package/dist/types.d.ts.map +1 -1
  28. package/dist/types.js.map +1 -1
  29. package/dist/utils.d.ts.map +1 -1
  30. package/dist/utils.js +1 -3
  31. package/dist/utils.js.map +1 -1
  32. package/dist/valueType.d.ts.map +1 -1
  33. package/dist/valueType.js.map +1 -1
  34. package/lib/handle.d.ts.map +1 -1
  35. package/lib/handle.js.map +1 -1
  36. package/lib/index.d.ts +2 -2
  37. package/lib/index.d.ts.map +1 -1
  38. package/lib/index.js +2 -2
  39. package/lib/index.js.map +1 -1
  40. package/lib/packageVersion.d.ts +1 -1
  41. package/lib/packageVersion.js +1 -1
  42. package/lib/packageVersion.js.map +1 -1
  43. package/lib/remoteObjectHandle.d.ts.map +1 -1
  44. package/lib/remoteObjectHandle.js +17 -9
  45. package/lib/remoteObjectHandle.js.map +1 -1
  46. package/lib/serializer.d.ts.map +1 -1
  47. package/lib/serializer.js +5 -7
  48. package/lib/serializer.js.map +1 -1
  49. package/lib/sharedObject.d.ts +3 -3
  50. package/lib/sharedObject.d.ts.map +1 -1
  51. package/lib/sharedObject.js +26 -9
  52. package/lib/sharedObject.js.map +1 -1
  53. package/lib/summarySerializer.d.ts.map +1 -1
  54. package/lib/summarySerializer.js.map +1 -1
  55. package/lib/types.d.ts.map +1 -1
  56. package/lib/types.js.map +1 -1
  57. package/lib/utils.d.ts.map +1 -1
  58. package/lib/utils.js +1 -3
  59. package/lib/utils.js.map +1 -1
  60. package/lib/valueType.d.ts.map +1 -1
  61. package/lib/valueType.js.map +1 -1
  62. package/package.json +58 -58
  63. package/prettier.config.cjs +1 -1
  64. package/src/handle.ts +28 -28
  65. package/src/index.ts +12 -2
  66. package/src/packageVersion.ts +1 -1
  67. package/src/remoteObjectHandle.ts +70 -55
  68. package/src/serializer.ts +182 -187
  69. package/src/sharedObject.ts +709 -636
  70. package/src/summarySerializer.ts +8 -8
  71. package/src/types.ts +50 -32
  72. package/src/utils.ts +20 -26
  73. package/src/valueType.ts +9 -9
  74. package/tsconfig.esnext.json +6 -6
  75. package/tsconfig.json +8 -12
@@ -9,26 +9,27 @@ import { assert, EventEmitterEventType } from "@fluidframework/common-utils";
9
9
  import { AttachState } from "@fluidframework/container-definitions";
10
10
  import { IFluidHandle } from "@fluidframework/core-interfaces";
11
11
  import {
12
- IChannelAttributes,
13
- IFluidDataStoreRuntime,
14
- IChannelStorageService,
15
- IChannelServices,
12
+ IChannelAttributes,
13
+ IFluidDataStoreRuntime,
14
+ IChannelStorageService,
15
+ IChannelServices,
16
16
  } from "@fluidframework/datastore-definitions";
17
17
  import { ISequencedDocumentMessage } from "@fluidframework/protocol-definitions";
18
18
  import {
19
- IGarbageCollectionData,
20
- ISummaryTreeWithStats,
21
- ITelemetryContext,
22
- blobCountPropertyName,
23
- totalBlobSizePropertyName,
19
+ IGarbageCollectionData,
20
+ ISummaryTreeWithStats,
21
+ ITelemetryContext,
22
+ blobCountPropertyName,
23
+ totalBlobSizePropertyName,
24
+ IExperimentalIncrementalSummaryContext,
24
25
  } from "@fluidframework/runtime-definitions";
25
26
  import {
26
- ChildLogger,
27
- EventEmitterWithErrorHandling,
28
- loggerToMonitoringContext,
29
- MonitoringContext,
30
- SampledTelemetryHelper,
31
- TelemetryDataTag,
27
+ ChildLogger,
28
+ EventEmitterWithErrorHandling,
29
+ loggerToMonitoringContext,
30
+ MonitoringContext,
31
+ SampledTelemetryHelper,
32
+ TelemetryDataTag,
32
33
  } from "@fluidframework/telemetry-utils";
33
34
  import { DataProcessingError } from "@fluidframework/container-utils";
34
35
  import { FluidSerializer, IFluidSerializer } from "./serializer";
@@ -40,631 +41,703 @@ import { ISharedObject, ISharedObjectEvents } from "./types";
40
41
  * Base class from which all shared objects derive.
41
42
  */
42
43
  export abstract class SharedObjectCore<TEvent extends ISharedObjectEvents = ISharedObjectEvents>
43
- extends EventEmitterWithErrorHandling<TEvent> implements ISharedObject<TEvent> {
44
- public get IFluidLoadable() { return this; }
45
-
46
- private readonly opProcessingHelper: SampledTelemetryHelper;
47
- private readonly callbacksHelper: SampledTelemetryHelper;
48
-
49
- /**
50
- * The handle referring to this SharedObject
51
- */
52
- public readonly handle: IFluidHandle;
53
-
54
- /**
55
- * Telemetry logger for the shared object
56
- */
57
- protected readonly logger: ITelemetryLogger;
58
- private readonly mc: MonitoringContext;
59
-
60
- /**
61
- * Connection state
62
- */
63
- private _connected = false;
64
-
65
- /**
66
- * Services used by the shared object
67
- */
68
- private services: IChannelServices | undefined;
69
-
70
- /**
71
- * True if the dds is bound to its parent.
72
- */
73
- private _isBoundToContext: boolean = false;
74
-
75
- /**
76
- * Tracks error that closed this object.
77
- */
78
- private closeError?: ReturnType<typeof DataProcessingError.wrapIfUnrecognized>;
79
-
80
- /**
81
- * Gets the connection state
82
- * @returns The state of the connection
83
- */
84
- public get connected(): boolean {
85
- return this._connected;
86
- }
87
-
88
- /**
89
- * @param id - The id of the shared object
90
- * @param runtime - The IFluidDataStoreRuntime which contains the shared object
91
- * @param attributes - Attributes of the shared object
92
- */
93
- constructor(
94
- public id: string,
95
- protected runtime: IFluidDataStoreRuntime,
96
- public readonly attributes: IChannelAttributes) {
97
- super((event: EventEmitterEventType, e: any) => this.eventListenerErrorHandler(event, e));
98
-
99
- assert(!id.includes("/"), 0x304 /* Id cannot contain slashes */);
100
-
101
- this.handle = new SharedObjectHandle(
102
- this,
103
- id,
104
- runtime.IFluidHandleContext);
105
-
106
- this.logger = ChildLogger.create(
107
- runtime.logger,
108
- undefined,
109
- {
110
- all: {
111
- sharedObjectId: uuid(),
112
- ddsType: {
113
- value: this.attributes.type,
114
- tag: TelemetryDataTag.CodeArtifact,
115
- },
116
- },
117
- },
118
- );
119
- this.mc = loggerToMonitoringContext(this.logger);
120
-
121
- [this.opProcessingHelper, this.callbacksHelper] = this.setUpSampledTelemetryHelpers();
122
-
123
- this.attachListeners();
124
- }
125
-
126
- /**
127
- * This function is only supposed to be called from SharedObjectCore's constructor and
128
- * depends on a few things being set already. assert() calls make sure of it.
129
- * @returns The telemetry sampling helpers, so the constructor can be the one to assign them
130
- * to variables to avoid complaints from TypeScript.
131
- */
132
- private setUpSampledTelemetryHelpers(): SampledTelemetryHelper[] {
133
- assert(this.mc !== undefined && this.logger !== undefined,
134
- 0x349 /* this.mc and/or this.logger has not been set */);
135
- const opProcessingHelper = new SampledTelemetryHelper(
136
- {
137
- eventName: "ddsOpProcessing",
138
- category: "performance",
139
- },
140
- this.logger,
141
- this.mc.config.getNumber("Fluid.SharedObject.OpProcessingTelemetrySampling") ?? 100,
142
- true,
143
- new Map<string, ITelemetryProperties>([
144
- ["local", { localOp: true }],
145
- ["remote", { localOp: false }],
146
- ]));
147
- const callbacksHelper = new SampledTelemetryHelper(
148
- {
149
- eventName: "ddsEventCallbacks",
150
- category: "performance",
151
- },
152
- this.logger,
153
- this.mc.config.getNumber("Fluid.SharedObject.DdsCallbacksTelemetrySampling") ?? 100,
154
- true);
155
-
156
- this.runtime.once("dispose", () => {
157
- this.callbacksHelper.dispose();
158
- this.opProcessingHelper.dispose();
159
- });
160
-
161
- return [opProcessingHelper, callbacksHelper];
162
- }
163
-
164
- /**
165
- * Marks this objects as closed. Any attempt to change it (local changes or processing remote ops)
166
- * would result in same error thrown. If called multiple times, only first error is remembered.
167
- * @param error - error object that is thrown whenever an attempt is made to modify this object
168
- */
169
- private closeWithError(error: any) {
170
- if (this.closeError === undefined) {
171
- this.closeError = error;
172
- }
173
- }
174
-
175
- /**
176
- * Verifies that this object is not closed via closeWithError(). If it is, throws an error used to close it.
177
- */
178
- private verifyNotClosed() {
179
- if (this.closeError !== undefined) {
180
- throw this.closeError;
181
- }
182
- }
183
-
184
- /**
185
- * Event listener handler helper that can be used to react to exceptions thrown from event listeners
186
- * It wraps error with DataProcessingError, closes this object and throws resulting error.
187
- * See closeWithError() for more details
188
- * Ideally such situation never happens, as consumers of DDS should never throw exceptions
189
- * in event listeners (i.e. catch any of the issues and make determination on how to handle it).
190
- * When such exceptions propagate through, most likely data model is no longer consistent, i.e.
191
- * DDS state does not match what user sees. Because of it DDS moves to "corrupted state" and does not
192
- * allow processing of ops or local changes, which very quickly results in container closure.
193
- */
194
- private eventListenerErrorHandler(event: EventEmitterEventType, e: any) {
195
- const error = DataProcessingError.wrapIfUnrecognized(
196
- e,
197
- "SharedObjectEventListenerException");
198
- error.addTelemetryProperties({ emittedEventName: String(event) });
199
-
200
- this.closeWithError(error);
201
- throw error;
202
- }
203
-
204
- private attachListeners() {
205
- // Only listen to these events if not attached.
206
- if (!this.isAttached()) {
207
- this.runtime.once("attaching", () => {
208
- // Calling this will let the dds to do any custom processing based on attached
209
- // like starting generating ops.
210
- this.didAttach();
211
- });
212
- }
213
- }
214
-
215
- /**
216
- * A shared object, after construction, can either be loaded in the case that it is already part of
217
- * a shared document. Or later attached if it is being newly added.
218
- * @param services - Services used by the shared object
219
- */
220
- public async load(services: IChannelServices): Promise<void> {
221
- if (this.runtime.attachState !== AttachState.Detached) {
222
- this.services = services;
223
- }
224
- await this.loadCore(services.objectStorage);
225
- if (this.runtime.attachState !== AttachState.Detached) {
226
- this.attachDeltaHandler();
227
- }
228
- }
229
-
230
- /**
231
- * Initializes the object as a local, non-shared object. This object can become shared after
232
- * it is attached to the document.
233
- */
234
- public initializeLocal(): void {
235
- this.initializeLocalCore();
236
- }
237
-
238
- /**
239
- * {@inheritDoc (ISharedObject:interface).bindToContext}
240
- */
241
- public bindToContext(): void {
242
- if (this._isBoundToContext) {
243
- return;
244
- }
245
-
246
- this._isBoundToContext = true;
247
-
248
- this.runtime.bindChannel(this);
249
- }
250
-
251
- /**
252
- * {@inheritDoc @fluidframework/datastore-definitions#(IChannel:interface).connect}
253
- */
254
- public connect(services: IChannelServices) {
255
- this.services = services;
256
- this.attachDeltaHandler();
257
- }
258
-
259
- /**
260
- * {@inheritDoc @fluidframework/datastore-definitions#(IChannel:interface).isAttached}
261
- */
262
- public isAttached(): boolean {
263
- return this.services !== undefined && this.runtime.attachState !== AttachState.Detached;
264
- }
265
-
266
- /**
267
- * {@inheritDoc @fluidframework/datastore-definitions#(IChannel:interface).getAttachSummary}
268
- */
269
- public abstract getAttachSummary(
270
- fullTree?: boolean,
271
- trackState?: boolean,
272
- telemetryContext?: ITelemetryContext,
273
- ): ISummaryTreeWithStats;
274
-
275
- /**
276
- * {@inheritDoc @fluidframework/datastore-definitions#(IChannel:interface).summarize}
277
- */
278
- public abstract summarize(
279
- fullTree?: boolean,
280
- trackState?: boolean,
281
- telemetryContext?: ITelemetryContext,
282
- ): Promise<ISummaryTreeWithStats>;
283
-
284
- /**
285
- * {@inheritDoc (ISharedObject:interface).getGCData}
286
- */
287
- public abstract getGCData(fullGC?: boolean): IGarbageCollectionData;
288
-
289
- /**
290
- * Called when a handle is decoded by this object. A handle in the object's data represents an outbound reference
291
- * to another object in the container.
292
- * @param decodedHandle - The handle of the Fluid object that is decoded.
293
- */
294
- protected handleDecoded(decodedHandle: IFluidHandle) {
295
- if (this.isAttached()) {
296
- // This represents an outbound reference from this object to the node represented by decodedHandle.
297
- this.services?.deltaConnection.addedGCOutboundReference?.(this.handle, decodedHandle);
298
- }
299
- }
300
-
301
- /**
302
- * Allows the distributed data type to perform custom loading
303
- * @param services - Storage used by the shared object
304
- */
305
- protected abstract loadCore(services: IChannelStorageService): Promise<void>;
306
-
307
- /**
308
- * Allows the distributed data type to perform custom local loading.
309
- */
310
- protected initializeLocalCore() {
311
- return;
312
- }
313
-
314
- /**
315
- * Allows the distributive data type the ability to perform custom processing once an attach has happened.
316
- * Also called after non-local data type get loaded.
317
- */
318
- protected didAttach() {
319
- return;
320
- }
321
-
322
- /**
323
- * Derived classes must override this to do custom processing on a remote message.
324
- * @param message - The message to process
325
- * @param local - True if the shared object is local
326
- * @param localOpMetadata - For local client messages, this is the metadata that was submitted with the message.
327
- * For messages from a remote client, this will be undefined.
328
- */
329
- protected abstract processCore(message: ISequencedDocumentMessage, local: boolean, localOpMetadata: unknown);
330
-
331
- /**
332
- * Called when the object has disconnected from the delta stream.
333
- */
334
- protected abstract onDisconnect();
335
-
336
- /**
337
- * Submits a message by the local client to the runtime.
338
- * @param content - Content of the message
339
- * @param localOpMetadata - The local metadata associated with the message. This is kept locally by the runtime
340
- * and not sent to the server. This will be sent back when this message is received back from the server. This is
341
- * also sent if we are asked to resubmit the message.
342
- */
343
- protected submitLocalMessage(content: any, localOpMetadata: unknown = undefined): void {
344
- this.verifyNotClosed();
345
- if (this.isAttached()) {
346
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
347
- this.services!.deltaConnection.submit(content, localOpMetadata);
348
- }
349
- }
350
-
351
- /**
352
- * Marks this object as dirty so that it is part of the next summary. It is called by a SharedSummaryBlock
353
- * that want to be part of summary but does not generate ops.
354
- */
355
- protected dirty(): void {
356
- if (!this.isAttached()) {
357
- return;
358
- }
359
-
360
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
361
- this.services!.deltaConnection.dirty();
362
- }
363
-
364
- /**
365
- * Called when the object has fully connected to the delta stream
366
- * Default implementation for DDS, override if different behavior is required.
367
- */
368
- protected onConnect() { }
369
-
370
- /**
371
- * Called when a message has to be resubmitted. This typically happens after a reconnection for unacked messages.
372
- * The default implementation here is to resubmit the same message. The client can override if different behavior
373
- * is required. It can choose to resubmit the same message, submit different / multiple messages or not submit
374
- * anything at all.
375
- * @param content - The content of the original message.
376
- * @param localOpMetadata - The local metadata associated with the original message.
377
- */
378
- protected reSubmitCore(content: any, localOpMetadata: unknown) {
379
- this.submitLocalMessage(content, localOpMetadata);
380
- }
381
-
382
- /**
383
- * Promises that are waiting for an ack from the server before resolving should use this instead of new Promise.
384
- * It ensures that if something changes that will interrupt that ack (e.g. the FluidDataStoreRuntime disposes),
385
- * the Promise will reject.
386
- * If runtime is disposed when this call is made, executor is not run and promise is rejected right away.
387
- */
388
- protected async newAckBasedPromise<T>(
389
- executor: (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void,
390
- ): Promise<T> {
391
- let rejectBecauseDispose: () => void;
392
- return new Promise<T>((resolve, reject) => {
393
- rejectBecauseDispose =
394
- () => reject(new Error("FluidDataStoreRuntime disposed while this ack-based Promise was pending"));
395
-
396
- if (this.runtime.disposed) {
397
- rejectBecauseDispose();
398
- return;
399
- }
400
-
401
- this.runtime.on("dispose", rejectBecauseDispose);
402
- executor(resolve, reject);
403
- }).finally(() => {
404
- // Note: rejectBecauseDispose will never be undefined here
405
- this.runtime.off("dispose", rejectBecauseDispose);
406
- });
407
- }
408
-
409
- private attachDeltaHandler() {
410
- // Services should already be there in case we are attaching delta handler.
411
- assert(this.services !== undefined, 0x07a /* "Services should be there to attach delta handler" */);
412
- this._isBoundToContext = true;
413
- // Allows objects to do any custom processing if it is attached.
414
- this.didAttach();
415
-
416
- // attachDeltaHandler is only called after services is assigned
417
- this.services.deltaConnection.attach({
418
- process: (message: ISequencedDocumentMessage, local: boolean, localOpMetadata: unknown) => {
419
- this.process(message, local, localOpMetadata);
420
- },
421
- setConnectionState: (connected: boolean) => {
422
- this.setConnectionState(connected);
423
- },
424
- reSubmit: (content: any, localOpMetadata: unknown) => {
425
- this.reSubmit(content, localOpMetadata);
426
- },
427
- applyStashedOp: (content: any): unknown => {
428
- return this.applyStashedOp(content);
429
- },
430
- rollback: (content: any, localOpMetadata: unknown) => {
431
- this.rollback(content, localOpMetadata);
432
- },
433
- });
434
-
435
- // Trigger initial state
436
- // attachDeltaHandler is only called after services is assigned
437
- this.setConnectionState(this.services.deltaConnection.connected);
438
- }
439
-
440
- /**
441
- * Set the state of connection to services.
442
- * @param connected - true if connected, false otherwise.
443
- */
444
- private setConnectionState(connected: boolean) {
445
- if (this._connected === connected) {
446
- // Not changing state, nothing the same.
447
- return;
448
- }
449
-
450
- // Should I change the state at the end? So that we *can't* send new stuff before we send old?
451
- this._connected = connected;
452
-
453
- if (!connected) {
454
- // Things that are true now...
455
- // - if we had a connection we can no longer send messages over it
456
- // - if we had outbound messages some may or may not be ACK'd. Won't know until next message
457
- //
458
- // - nack could get a new msn - but might as well do it in the join?
459
- this.onDisconnect();
460
- } else {
461
- // Call this for now so that DDSes like ConsensusOrderedCollection that maintain their own pending
462
- // messages will work.
463
- this.onConnect();
464
- }
465
- }
466
-
467
- /**
468
- * Handles a message being received from the remote delta server.
469
- * @param message - The message to process
470
- * @param local - Whether the message originated from the local client
471
- * @param localOpMetadata - For local client messages, this is the metadata that was submitted with the message.
472
- * For messages from a remote client, this will be undefined.
473
- */
474
- private process(message: ISequencedDocumentMessage, local: boolean, localOpMetadata: unknown) {
475
- this.verifyNotClosed(); // This will result in container closure.
476
- this.emitInternal("pre-op", message, local, this);
477
-
478
- this.opProcessingHelper.measure(
479
- () => { this.processCore(message, local, localOpMetadata); },
480
- local ? "local" : "remote");
481
-
482
- this.emitInternal("op", message, local, this);
483
- }
484
-
485
- /**
486
- * Called when a message has to be resubmitted. This typically happens for unacked messages after a
487
- * reconnection.
488
- * @param content - The content of the original message.
489
- * @param localOpMetadata - The local metadata associated with the original message.
490
- */
491
- private reSubmit(content: any, localOpMetadata: unknown) {
492
- this.reSubmitCore(content, localOpMetadata);
493
- }
494
-
495
- /**
496
- * Revert an op
497
- */
498
- protected rollback(content: any, localOpMetadata: unknown) {
499
- throw new Error("rollback not supported");
500
- }
501
-
502
- /**
503
- * Apply changes from an op. Used when rehydrating an attached container
504
- * with pending changes. This prepares the SharedObject for seeing an ACK
505
- * for the op or resubmitting the op upon reconnection.
506
- * @param content - Contents of a stashed op.
507
- * @returns localMetadata of the op, to be passed to process() or resubmit()
508
- * when the op is ACKed or resubmitted, respectively
509
- */
510
- protected abstract applyStashedOp(content: any): unknown;
511
-
512
- /**
513
- * Emit an event. This function is only intended for use by DDS classes that extend SharedObject/SharedObjectCore,
514
- * specifically to emit events that are part of the public interface of the DDS (i.e. those that can have listeners
515
- * attached to them by the consumers of the DDS). It should not be called from outside the class or to emit events
516
- * which are only internal to the DDS. Support for calling it from outside the DDS instance might be removed in the
517
- * future.
518
- *
519
- * @internal
520
- *
521
- * @param event - The event to emit.
522
- * @param args - Arguments to pass to the event listeners.
523
- * @returns `true` if the event had listeners, `false` otherwise.
524
- */
525
- public emit(event: EventEmitterEventType, ...args: any[]): boolean {
526
- return this.callbacksHelper.measure(() => super.emit(event, ...args));
527
- }
528
-
529
- /**
530
- * Use to emit events inside {@link SharedObjectCore}, with no telemetry measurement
531
- * done on the duration of the callbacks. Simply calls `super.emit()`.
532
- * @param event - Event to emit
533
- * @param args - Arguments for the event
534
- * @returns Whatever `super.emit()` returns.
535
- */
536
- private emitInternal(
537
- event: EventEmitterEventType,
538
- ...args: any[]): boolean {
539
- return super.emit(event, ...args);
540
- }
44
+ extends EventEmitterWithErrorHandling<TEvent>
45
+ implements ISharedObject<TEvent>
46
+ {
47
+ public get IFluidLoadable() {
48
+ return this;
49
+ }
50
+
51
+ private readonly opProcessingHelper: SampledTelemetryHelper;
52
+ private readonly callbacksHelper: SampledTelemetryHelper;
53
+
54
+ /**
55
+ * The handle referring to this SharedObject
56
+ */
57
+ public readonly handle: IFluidHandle;
58
+
59
+ /**
60
+ * Telemetry logger for the shared object
61
+ */
62
+ protected readonly logger: ITelemetryLogger;
63
+ private readonly mc: MonitoringContext;
64
+
65
+ /**
66
+ * Connection state
67
+ */
68
+ private _connected = false;
69
+
70
+ /**
71
+ * Services used by the shared object
72
+ */
73
+ private services: IChannelServices | undefined;
74
+
75
+ /**
76
+ * True if the dds is bound to its parent.
77
+ */
78
+ private _isBoundToContext: boolean = false;
79
+
80
+ /**
81
+ * Tracks error that closed this object.
82
+ */
83
+ private closeError?: ReturnType<typeof DataProcessingError.wrapIfUnrecognized>;
84
+
85
+ /**
86
+ * Gets the connection state
87
+ * @returns The state of the connection
88
+ */
89
+ public get connected(): boolean {
90
+ return this._connected;
91
+ }
92
+
93
+ /**
94
+ * @param id - The id of the shared object
95
+ * @param runtime - The IFluidDataStoreRuntime which contains the shared object
96
+ * @param attributes - Attributes of the shared object
97
+ */
98
+ constructor(
99
+ public id: string,
100
+ protected runtime: IFluidDataStoreRuntime,
101
+ public readonly attributes: IChannelAttributes,
102
+ ) {
103
+ super((event: EventEmitterEventType, e: any) => this.eventListenerErrorHandler(event, e));
104
+
105
+ assert(!id.includes("/"), 0x304 /* Id cannot contain slashes */);
106
+
107
+ this.handle = new SharedObjectHandle(this, id, runtime.IFluidHandleContext);
108
+
109
+ this.logger = ChildLogger.create(runtime.logger, undefined, {
110
+ all: {
111
+ sharedObjectId: uuid(),
112
+ ddsType: {
113
+ value: this.attributes.type,
114
+ tag: TelemetryDataTag.CodeArtifact,
115
+ },
116
+ },
117
+ });
118
+ this.mc = loggerToMonitoringContext(this.logger);
119
+
120
+ [this.opProcessingHelper, this.callbacksHelper] = this.setUpSampledTelemetryHelpers();
121
+
122
+ this.attachListeners();
123
+ }
124
+
125
+ /**
126
+ * This function is only supposed to be called from SharedObjectCore's constructor and
127
+ * depends on a few things being set already. assert() calls make sure of it.
128
+ * @returns The telemetry sampling helpers, so the constructor can be the one to assign them
129
+ * to variables to avoid complaints from TypeScript.
130
+ */
131
+ private setUpSampledTelemetryHelpers(): SampledTelemetryHelper[] {
132
+ assert(
133
+ this.mc !== undefined && this.logger !== undefined,
134
+ 0x349 /* this.mc and/or this.logger has not been set */,
135
+ );
136
+ const opProcessingHelper = new SampledTelemetryHelper(
137
+ {
138
+ eventName: "ddsOpProcessing",
139
+ category: "performance",
140
+ },
141
+ this.logger,
142
+ this.mc.config.getNumber("Fluid.SharedObject.OpProcessingTelemetrySampling") ?? 1000,
143
+ true,
144
+ new Map<string, ITelemetryProperties>([
145
+ ["local", { localOp: true }],
146
+ ["remote", { localOp: false }],
147
+ ]),
148
+ );
149
+ const callbacksHelper = new SampledTelemetryHelper(
150
+ {
151
+ eventName: "ddsEventCallbacks",
152
+ category: "performance",
153
+ },
154
+ this.logger,
155
+ this.mc.config.getNumber("Fluid.SharedObject.DdsCallbacksTelemetrySampling") ?? 1000,
156
+ true,
157
+ );
158
+
159
+ this.runtime.once("dispose", () => {
160
+ this.callbacksHelper.dispose();
161
+ this.opProcessingHelper.dispose();
162
+ });
163
+
164
+ return [opProcessingHelper, callbacksHelper];
165
+ }
166
+
167
+ /**
168
+ * Marks this objects as closed. Any attempt to change it (local changes or processing remote ops)
169
+ * would result in same error thrown. If called multiple times, only first error is remembered.
170
+ * @param error - error object that is thrown whenever an attempt is made to modify this object
171
+ */
172
+ private closeWithError(error: any) {
173
+ if (this.closeError === undefined) {
174
+ this.closeError = error;
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Verifies that this object is not closed via closeWithError(). If it is, throws an error used to close it.
180
+ */
181
+ private verifyNotClosed() {
182
+ if (this.closeError !== undefined) {
183
+ throw this.closeError;
184
+ }
185
+ }
186
+
187
+ /**
188
+ * Event listener handler helper that can be used to react to exceptions thrown from event listeners
189
+ * It wraps error with DataProcessingError, closes this object and throws resulting error.
190
+ * See closeWithError() for more details
191
+ * Ideally such situation never happens, as consumers of DDS should never throw exceptions
192
+ * in event listeners (i.e. catch any of the issues and make determination on how to handle it).
193
+ * When such exceptions propagate through, most likely data model is no longer consistent, i.e.
194
+ * DDS state does not match what user sees. Because of it DDS moves to "corrupted state" and does not
195
+ * allow processing of ops or local changes, which very quickly results in container closure.
196
+ */
197
+ private eventListenerErrorHandler(event: EventEmitterEventType, e: any) {
198
+ const error = DataProcessingError.wrapIfUnrecognized(
199
+ e,
200
+ "SharedObjectEventListenerException",
201
+ );
202
+ error.addTelemetryProperties({ emittedEventName: String(event) });
203
+
204
+ this.closeWithError(error);
205
+ throw error;
206
+ }
207
+
208
+ private attachListeners() {
209
+ // Only listen to these events if not attached.
210
+ if (!this.isAttached()) {
211
+ this.runtime.once("attaching", () => {
212
+ // Calling this will let the dds to do any custom processing based on attached
213
+ // like starting generating ops.
214
+ this.didAttach();
215
+ });
216
+ }
217
+ }
218
+
219
+ /**
220
+ * A shared object, after construction, can either be loaded in the case that it is already part of
221
+ * a shared document. Or later attached if it is being newly added.
222
+ * @param services - Services used by the shared object
223
+ */
224
+ public async load(services: IChannelServices): Promise<void> {
225
+ if (this.runtime.attachState !== AttachState.Detached) {
226
+ this.services = services;
227
+ }
228
+ await this.loadCore(services.objectStorage);
229
+ if (this.runtime.attachState !== AttachState.Detached) {
230
+ this.attachDeltaHandler();
231
+ }
232
+ }
233
+
234
+ /**
235
+ * Initializes the object as a local, non-shared object. This object can become shared after
236
+ * it is attached to the document.
237
+ */
238
+ public initializeLocal(): void {
239
+ this.initializeLocalCore();
240
+ }
241
+
242
+ /**
243
+ * {@inheritDoc (ISharedObject:interface).bindToContext}
244
+ */
245
+ public bindToContext(): void {
246
+ if (this._isBoundToContext) {
247
+ return;
248
+ }
249
+
250
+ this._isBoundToContext = true;
251
+
252
+ this.runtime.bindChannel(this);
253
+ }
254
+
255
+ /**
256
+ * {@inheritDoc @fluidframework/datastore-definitions#(IChannel:interface).connect}
257
+ */
258
+ public connect(services: IChannelServices) {
259
+ this.services = services;
260
+ this.attachDeltaHandler();
261
+ }
262
+
263
+ /**
264
+ * {@inheritDoc @fluidframework/datastore-definitions#(IChannel:interface).isAttached}
265
+ */
266
+ public isAttached(): boolean {
267
+ return this.services !== undefined && this.runtime.attachState !== AttachState.Detached;
268
+ }
269
+
270
+ /**
271
+ * {@inheritDoc @fluidframework/datastore-definitions#(IChannel:interface).getAttachSummary}
272
+ */
273
+ public abstract getAttachSummary(
274
+ fullTree?: boolean,
275
+ trackState?: boolean,
276
+ telemetryContext?: ITelemetryContext,
277
+ ): ISummaryTreeWithStats;
278
+
279
+ /**
280
+ * {@inheritDoc @fluidframework/datastore-definitions#(IChannel:interface).summarize}
281
+ */
282
+ public abstract summarize(
283
+ fullTree?: boolean,
284
+ trackState?: boolean,
285
+ telemetryContext?: ITelemetryContext,
286
+ ): Promise<ISummaryTreeWithStats>;
287
+
288
+ /**
289
+ * {@inheritDoc (ISharedObject:interface).getGCData}
290
+ */
291
+ public abstract getGCData(fullGC?: boolean): IGarbageCollectionData;
292
+
293
+ /**
294
+ * Called when a handle is decoded by this object. A handle in the object's data represents an outbound reference
295
+ * to another object in the container.
296
+ * @param decodedHandle - The handle of the Fluid object that is decoded.
297
+ */
298
+ protected handleDecoded(decodedHandle: IFluidHandle) {
299
+ if (this.isAttached()) {
300
+ // This represents an outbound reference from this object to the node represented by decodedHandle.
301
+ this.services?.deltaConnection.addedGCOutboundReference?.(this.handle, decodedHandle);
302
+ }
303
+ }
304
+
305
+ /**
306
+ * Allows the distributed data type to perform custom loading
307
+ * @param services - Storage used by the shared object
308
+ */
309
+ protected abstract loadCore(services: IChannelStorageService): Promise<void>;
310
+
311
+ /**
312
+ * Allows the distributed data type to perform custom local loading.
313
+ */
314
+ protected initializeLocalCore() {
315
+ return;
316
+ }
317
+
318
+ /**
319
+ * Allows the distributive data type the ability to perform custom processing once an attach has happened.
320
+ * Also called after non-local data type get loaded.
321
+ */
322
+ protected didAttach() {
323
+ return;
324
+ }
325
+
326
+ /**
327
+ * Derived classes must override this to do custom processing on a remote message.
328
+ * @param message - The message to process
329
+ * @param local - True if the shared object is local
330
+ * @param localOpMetadata - For local client messages, this is the metadata that was submitted with the message.
331
+ * For messages from a remote client, this will be undefined.
332
+ */
333
+ protected abstract processCore(
334
+ message: ISequencedDocumentMessage,
335
+ local: boolean,
336
+ localOpMetadata: unknown,
337
+ );
338
+
339
+ /**
340
+ * Called when the object has disconnected from the delta stream.
341
+ */
342
+ protected abstract onDisconnect();
343
+
344
+ /**
345
+ * Submits a message by the local client to the runtime.
346
+ * @param content - Content of the message
347
+ * @param localOpMetadata - The local metadata associated with the message. This is kept locally by the runtime
348
+ * and not sent to the server. This will be sent back when this message is received back from the server. This is
349
+ * also sent if we are asked to resubmit the message.
350
+ */
351
+ protected submitLocalMessage(content: any, localOpMetadata: unknown = undefined): void {
352
+ this.verifyNotClosed();
353
+ if (this.isAttached()) {
354
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
355
+ this.services!.deltaConnection.submit(content, localOpMetadata);
356
+ }
357
+ }
358
+
359
+ /**
360
+ * Marks this object as dirty so that it is part of the next summary. It is called by a SharedSummaryBlock
361
+ * that want to be part of summary but does not generate ops.
362
+ */
363
+ protected dirty(): void {
364
+ if (!this.isAttached()) {
365
+ return;
366
+ }
367
+
368
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
369
+ this.services!.deltaConnection.dirty();
370
+ }
371
+
372
+ /**
373
+ * Called when the object has fully connected to the delta stream
374
+ * Default implementation for DDS, override if different behavior is required.
375
+ */
376
+ protected onConnect() {}
377
+
378
+ /**
379
+ * Called when a message has to be resubmitted. This typically happens after a reconnection for unacked messages.
380
+ * The default implementation here is to resubmit the same message. The client can override if different behavior
381
+ * is required. It can choose to resubmit the same message, submit different / multiple messages or not submit
382
+ * anything at all.
383
+ * @param content - The content of the original message.
384
+ * @param localOpMetadata - The local metadata associated with the original message.
385
+ */
386
+ protected reSubmitCore(content: any, localOpMetadata: unknown) {
387
+ this.submitLocalMessage(content, localOpMetadata);
388
+ }
389
+
390
+ /**
391
+ * Promises that are waiting for an ack from the server before resolving should use this instead of new Promise.
392
+ * It ensures that if something changes that will interrupt that ack (e.g. the FluidDataStoreRuntime disposes),
393
+ * the Promise will reject.
394
+ * If runtime is disposed when this call is made, executor is not run and promise is rejected right away.
395
+ */
396
+ protected async newAckBasedPromise<T>(
397
+ executor: (
398
+ resolve: (value: T | PromiseLike<T>) => void,
399
+ reject: (reason?: any) => void,
400
+ ) => void,
401
+ ): Promise<T> {
402
+ let rejectBecauseDispose: () => void;
403
+ return new Promise<T>((resolve, reject) => {
404
+ rejectBecauseDispose = () =>
405
+ reject(
406
+ new Error(
407
+ "FluidDataStoreRuntime disposed while this ack-based Promise was pending",
408
+ ),
409
+ );
410
+
411
+ if (this.runtime.disposed) {
412
+ rejectBecauseDispose();
413
+ return;
414
+ }
415
+
416
+ this.runtime.on("dispose", rejectBecauseDispose);
417
+ executor(resolve, reject);
418
+ }).finally(() => {
419
+ // Note: rejectBecauseDispose will never be undefined here
420
+ this.runtime.off("dispose", rejectBecauseDispose);
421
+ });
422
+ }
423
+
424
+ private attachDeltaHandler() {
425
+ // Services should already be there in case we are attaching delta handler.
426
+ assert(
427
+ this.services !== undefined,
428
+ 0x07a /* "Services should be there to attach delta handler" */,
429
+ );
430
+ this._isBoundToContext = true;
431
+ // Allows objects to do any custom processing if it is attached.
432
+ this.didAttach();
433
+
434
+ // attachDeltaHandler is only called after services is assigned
435
+ this.services.deltaConnection.attach({
436
+ process: (
437
+ message: ISequencedDocumentMessage,
438
+ local: boolean,
439
+ localOpMetadata: unknown,
440
+ ) => {
441
+ this.process(message, local, localOpMetadata);
442
+ },
443
+ setConnectionState: (connected: boolean) => {
444
+ this.setConnectionState(connected);
445
+ },
446
+ reSubmit: (content: any, localOpMetadata: unknown) => {
447
+ this.reSubmit(content, localOpMetadata);
448
+ },
449
+ applyStashedOp: (content: any): unknown => {
450
+ return this.applyStashedOp(content);
451
+ },
452
+ rollback: (content: any, localOpMetadata: unknown) => {
453
+ this.rollback(content, localOpMetadata);
454
+ },
455
+ });
456
+
457
+ // Trigger initial state
458
+ // attachDeltaHandler is only called after services is assigned
459
+ this.setConnectionState(this.services.deltaConnection.connected);
460
+ }
461
+
462
+ /**
463
+ * Set the state of connection to services.
464
+ * @param connected - true if connected, false otherwise.
465
+ */
466
+ private setConnectionState(connected: boolean) {
467
+ if (this._connected === connected) {
468
+ // Not changing state, nothing the same.
469
+ return;
470
+ }
471
+
472
+ // Should I change the state at the end? So that we *can't* send new stuff before we send old?
473
+ this._connected = connected;
474
+
475
+ if (!connected) {
476
+ // Things that are true now...
477
+ // - if we had a connection we can no longer send messages over it
478
+ // - if we had outbound messages some may or may not be ACK'd. Won't know until next message
479
+ //
480
+ // - nack could get a new msn - but might as well do it in the join?
481
+ this.onDisconnect();
482
+ } else {
483
+ // Call this for now so that DDSes like ConsensusOrderedCollection that maintain their own pending
484
+ // messages will work.
485
+ this.onConnect();
486
+ }
487
+ }
488
+
489
+ /**
490
+ * Handles a message being received from the remote delta server.
491
+ * @param message - The message to process
492
+ * @param local - Whether the message originated from the local client
493
+ * @param localOpMetadata - For local client messages, this is the metadata that was submitted with the message.
494
+ * For messages from a remote client, this will be undefined.
495
+ */
496
+ private process(message: ISequencedDocumentMessage, local: boolean, localOpMetadata: unknown) {
497
+ this.verifyNotClosed(); // This will result in container closure.
498
+ this.emitInternal("pre-op", message, local, this);
499
+
500
+ this.opProcessingHelper.measure(
501
+ () => {
502
+ this.processCore(message, local, localOpMetadata);
503
+ },
504
+ local ? "local" : "remote",
505
+ );
506
+
507
+ this.emitInternal("op", message, local, this);
508
+ }
509
+
510
+ /**
511
+ * Called when a message has to be resubmitted. This typically happens for unacked messages after a
512
+ * reconnection.
513
+ * @param content - The content of the original message.
514
+ * @param localOpMetadata - The local metadata associated with the original message.
515
+ */
516
+ private reSubmit(content: any, localOpMetadata: unknown) {
517
+ this.reSubmitCore(content, localOpMetadata);
518
+ }
519
+
520
+ /**
521
+ * Revert an op
522
+ */
523
+ protected rollback(content: any, localOpMetadata: unknown) {
524
+ throw new Error("rollback not supported");
525
+ }
526
+
527
+ /**
528
+ * Apply changes from an op. Used when rehydrating an attached container
529
+ * with pending changes. This prepares the SharedObject for seeing an ACK
530
+ * for the op or resubmitting the op upon reconnection.
531
+ * @param content - Contents of a stashed op.
532
+ * @returns localMetadata of the op, to be passed to process() or resubmit()
533
+ * when the op is ACKed or resubmitted, respectively
534
+ */
535
+ protected abstract applyStashedOp(content: any): unknown;
536
+
537
+ /**
538
+ * Emit an event. This function is only intended for use by DDS classes that extend SharedObject/SharedObjectCore,
539
+ * specifically to emit events that are part of the public interface of the DDS (i.e. those that can have listeners
540
+ * attached to them by the consumers of the DDS). It should not be called from outside the class or to emit events
541
+ * which are only internal to the DDS. Support for calling it from outside the DDS instance might be removed in the
542
+ * future.
543
+ *
544
+ * @internal
545
+ *
546
+ * @param event - The event to emit.
547
+ * @param args - Arguments to pass to the event listeners.
548
+ * @returns `true` if the event had listeners, `false` otherwise.
549
+ */
550
+ public emit(event: EventEmitterEventType, ...args: any[]): boolean {
551
+ return this.callbacksHelper.measure(() => {
552
+ // Creating ops while handling a DDS event can lead
553
+ // to undefined behavior and events observed in the wrong order.
554
+ // For example, we have two callbacks registered for a DDS, A and B.
555
+ // Then if on change #1 callback A creates change #2, the invocation flow will be:
556
+ //
557
+ // A because of #1
558
+ // A because of #2
559
+ // B because of #2
560
+ // B because of #1
561
+ //
562
+ // The runtime must enforce op coherence by not allowing any ops to be created during
563
+ // the event handler
564
+ return this.runtime.ensureNoDataModelChanges(() => super.emit(event, ...args));
565
+ });
566
+ }
567
+
568
+ /**
569
+ * Use to emit events inside {@link SharedObjectCore}, with no telemetry measurement
570
+ * done on the duration of the callbacks. Simply calls `super.emit()`.
571
+ * @param event - Event to emit
572
+ * @param args - Arguments for the event
573
+ * @returns Whatever `super.emit()` returns.
574
+ */
575
+ private emitInternal(event: EventEmitterEventType, ...args: any[]): boolean {
576
+ return super.emit(event, ...args);
577
+ }
541
578
  }
542
579
 
543
580
  /**
544
581
  * SharedObject with simplified, synchronous summarization and GC.
545
582
  * DDS implementations with async and incremental summarization should extend SharedObjectCore directly instead.
546
583
  */
547
- export abstract class SharedObject<TEvent extends ISharedObjectEvents = ISharedObjectEvents>
548
- extends SharedObjectCore<TEvent> {
549
- /**
550
- * True while we are garbage collecting this object's data.
551
- */
552
- private _isGCing: boolean = false;
553
-
554
- /**
555
- * The serializer to use to serialize / parse handles, if any.
556
- */
557
- private readonly _serializer: IFluidSerializer;
558
-
559
- protected get serializer(): IFluidSerializer {
560
- /**
561
- * During garbage collection, the SummarySerializer keeps track of IFluidHandles that are serialized. These
562
- * handles represent references to other Fluid objects.
563
- *
564
- * This is fine for now. However, if we implement delay loading in DDss, they may load and de-serialize content
565
- * in summarize. When that happens, they may incorrectly hit this assert and we will have to change this.
566
- */
567
- assert(!this._isGCing,
568
- 0x075 /* "SummarySerializer should be used for serializing data during summary." */);
569
- return this._serializer;
570
- }
571
-
572
- /**
573
- * @param id - The id of the shared object
574
- * @param runtime - The IFluidDataStoreRuntime which contains the shared object
575
- * @param attributes - Attributes of the shared object
576
- */
577
- constructor(
578
- id: string,
579
- runtime: IFluidDataStoreRuntime,
580
- attributes: IChannelAttributes,
581
- private readonly telemetryContextPrefix: string,
582
- ) {
583
- super(id, runtime, attributes);
584
-
585
- this._serializer = new FluidSerializer(
586
- this.runtime.channelsRoutingContext,
587
- (handle: IFluidHandle) => this.handleDecoded(handle),
588
- );
589
- }
590
-
591
- /**
592
- * {@inheritDoc @fluidframework/datastore-definitions#(IChannel:interface).getAttachSummary}
593
- */
594
- public getAttachSummary(
595
- fullTree: boolean = false,
596
- trackState: boolean = false,
597
- telemetryContext?: ITelemetryContext,
598
- ): ISummaryTreeWithStats {
599
- const result = this.summarizeCore(this.serializer, telemetryContext);
600
- this.incrementTelemetryMetric(blobCountPropertyName, result.stats.blobNodeCount, telemetryContext);
601
- this.incrementTelemetryMetric(totalBlobSizePropertyName, result.stats.totalBlobSize, telemetryContext);
602
- return result;
603
- }
604
-
605
- /**
606
- * {@inheritDoc @fluidframework/datastore-definitions#(IChannel:interface).summarize}
607
- */
608
- public async summarize(
609
- fullTree: boolean = false,
610
- trackState: boolean = false,
611
- telemetryContext?: ITelemetryContext,
612
- ): Promise<ISummaryTreeWithStats> {
613
- const result = this.summarizeCore(this.serializer, telemetryContext);
614
- this.incrementTelemetryMetric(blobCountPropertyName, result.stats.blobNodeCount, telemetryContext);
615
- this.incrementTelemetryMetric(totalBlobSizePropertyName, result.stats.totalBlobSize, telemetryContext);
616
- return result;
617
- }
618
-
619
- /**
620
- * {@inheritDoc (ISharedObject:interface).getGCData}
621
- */
622
- public getGCData(fullGC: boolean = false): IGarbageCollectionData {
623
- // Set _isGCing to true. This flag is used to ensure that we only use SummarySerializer to serialize handles
624
- // in this object's data.
625
- assert(!this._isGCing, 0x078 /* "Possible re-entrancy! Summary should not already be in progress." */);
626
- this._isGCing = true;
627
-
628
- let gcData: IGarbageCollectionData;
629
- try {
630
- const serializer = new SummarySerializer(
631
- this.runtime.channelsRoutingContext,
632
- (handle: IFluidHandle) => this.handleDecoded(handle),
633
- );
634
- this.processGCDataCore(serializer);
635
- // The GC data for this shared object contains a single GC node. The outbound routes of this node are the
636
- // routes of handles serialized during summarization.
637
- gcData = { gcNodes: { "/": serializer.getSerializedRoutes() } };
638
- assert(this._isGCing, 0x079 /* "Possible re-entrancy! Summary should have been in progress." */);
639
- } finally {
640
- this._isGCing = false;
641
- }
642
-
643
- return gcData;
644
- }
645
-
646
- /**
647
- * Calls the serializer over all data in this object that reference other GC nodes.
648
- * Derived classes must override this to provide custom list of references to other GC nodes.
649
- */
650
- protected processGCDataCore(serializer: SummarySerializer) {
651
- // We run the full summarize logic to get the list of outbound routes from this object. This is a little
652
- // expensive but its okay for now. It will be updated to not use full summarize and make it more efficient.
653
- // See: https://github.com/microsoft/FluidFramework/issues/4547
654
- this.summarizeCore(serializer);
655
- }
656
-
657
- /**
658
- * Gets a form of the object that can be serialized.
659
- * @returns A tree representing the snapshot of the shared object.
660
- */
661
- protected abstract summarizeCore(
662
- serializer: IFluidSerializer,
663
- telemetryContext?: ITelemetryContext,
664
- ): ISummaryTreeWithStats;
665
-
666
- private incrementTelemetryMetric(propertyName: string, incrementBy: number, telemetryContext?: ITelemetryContext) {
667
- const prevTotal = (telemetryContext?.get(this.telemetryContextPrefix, propertyName) ?? 0) as number;
668
- telemetryContext?.set(this.telemetryContextPrefix, propertyName, prevTotal + incrementBy);
669
- }
584
+ export abstract class SharedObject<
585
+ TEvent extends ISharedObjectEvents = ISharedObjectEvents,
586
+ > extends SharedObjectCore<TEvent> {
587
+ /**
588
+ * True while we are garbage collecting this object's data.
589
+ */
590
+ private _isGCing: boolean = false;
591
+
592
+ /**
593
+ * The serializer to use to serialize / parse handles, if any.
594
+ */
595
+ private readonly _serializer: IFluidSerializer;
596
+
597
+ protected get serializer(): IFluidSerializer {
598
+ /**
599
+ * During garbage collection, the SummarySerializer keeps track of IFluidHandles that are serialized. These
600
+ * handles represent references to other Fluid objects.
601
+ *
602
+ * This is fine for now. However, if we implement delay loading in DDss, they may load and de-serialize content
603
+ * in summarize. When that happens, they may incorrectly hit this assert and we will have to change this.
604
+ */
605
+ assert(
606
+ !this._isGCing,
607
+ 0x075 /* "SummarySerializer should be used for serializing data during summary." */,
608
+ );
609
+ return this._serializer;
610
+ }
611
+
612
+ /**
613
+ * @param id - The id of the shared object
614
+ * @param runtime - The IFluidDataStoreRuntime which contains the shared object
615
+ * @param attributes - Attributes of the shared object
616
+ */
617
+ constructor(
618
+ id: string,
619
+ runtime: IFluidDataStoreRuntime,
620
+ attributes: IChannelAttributes,
621
+ private readonly telemetryContextPrefix: string,
622
+ ) {
623
+ super(id, runtime, attributes);
624
+
625
+ this._serializer = new FluidSerializer(
626
+ this.runtime.channelsRoutingContext,
627
+ (handle: IFluidHandle) => this.handleDecoded(handle),
628
+ );
629
+ }
630
+
631
+ /**
632
+ * {@inheritDoc @fluidframework/datastore-definitions#(IChannel:interface).getAttachSummary}
633
+ */
634
+ public getAttachSummary(
635
+ fullTree: boolean = false,
636
+ trackState: boolean = false,
637
+ telemetryContext?: ITelemetryContext,
638
+ ): ISummaryTreeWithStats {
639
+ const result = this.summarizeCore(this.serializer, telemetryContext);
640
+ this.incrementTelemetryMetric(
641
+ blobCountPropertyName,
642
+ result.stats.blobNodeCount,
643
+ telemetryContext,
644
+ );
645
+ this.incrementTelemetryMetric(
646
+ totalBlobSizePropertyName,
647
+ result.stats.totalBlobSize,
648
+ telemetryContext,
649
+ );
650
+ return result;
651
+ }
652
+
653
+ /**
654
+ * {@inheritDoc @fluidframework/datastore-definitions#(IChannel:interface).summarize}
655
+ */
656
+ public async summarize(
657
+ fullTree: boolean = false,
658
+ trackState: boolean = false,
659
+ telemetryContext?: ITelemetryContext,
660
+ incrementalSummaryContext?: IExperimentalIncrementalSummaryContext,
661
+ ): Promise<ISummaryTreeWithStats> {
662
+ const result = this.summarizeCore(
663
+ this.serializer,
664
+ telemetryContext,
665
+ incrementalSummaryContext,
666
+ );
667
+ this.incrementTelemetryMetric(
668
+ blobCountPropertyName,
669
+ result.stats.blobNodeCount,
670
+ telemetryContext,
671
+ );
672
+ this.incrementTelemetryMetric(
673
+ totalBlobSizePropertyName,
674
+ result.stats.totalBlobSize,
675
+ telemetryContext,
676
+ );
677
+ return result;
678
+ }
679
+
680
+ /**
681
+ * {@inheritDoc (ISharedObject:interface).getGCData}
682
+ */
683
+ public getGCData(fullGC: boolean = false): IGarbageCollectionData {
684
+ // Set _isGCing to true. This flag is used to ensure that we only use SummarySerializer to serialize handles
685
+ // in this object's data.
686
+ assert(
687
+ !this._isGCing,
688
+ 0x078 /* "Possible re-entrancy! Summary should not already be in progress." */,
689
+ );
690
+ this._isGCing = true;
691
+
692
+ let gcData: IGarbageCollectionData;
693
+ try {
694
+ const serializer = new SummarySerializer(
695
+ this.runtime.channelsRoutingContext,
696
+ (handle: IFluidHandle) => this.handleDecoded(handle),
697
+ );
698
+ this.processGCDataCore(serializer);
699
+ // The GC data for this shared object contains a single GC node. The outbound routes of this node are the
700
+ // routes of handles serialized during summarization.
701
+ gcData = { gcNodes: { "/": serializer.getSerializedRoutes() } };
702
+ assert(
703
+ this._isGCing,
704
+ 0x079 /* "Possible re-entrancy! Summary should have been in progress." */,
705
+ );
706
+ } finally {
707
+ this._isGCing = false;
708
+ }
709
+
710
+ return gcData;
711
+ }
712
+
713
+ /**
714
+ * Calls the serializer over all data in this object that reference other GC nodes.
715
+ * Derived classes must override this to provide custom list of references to other GC nodes.
716
+ */
717
+ protected processGCDataCore(serializer: SummarySerializer) {
718
+ // We run the full summarize logic to get the list of outbound routes from this object. This is a little
719
+ // expensive but its okay for now. It will be updated to not use full summarize and make it more efficient.
720
+ // See: https://github.com/microsoft/FluidFramework/issues/4547
721
+ this.summarizeCore(serializer);
722
+ }
723
+
724
+ /**
725
+ * Gets a form of the object that can be serialized.
726
+ * @returns A tree representing the snapshot of the shared object.
727
+ */
728
+ protected abstract summarizeCore(
729
+ serializer: IFluidSerializer,
730
+ telemetryContext?: ITelemetryContext,
731
+ incrementalSummaryContext?: IExperimentalIncrementalSummaryContext,
732
+ ): ISummaryTreeWithStats;
733
+
734
+ private incrementTelemetryMetric(
735
+ propertyName: string,
736
+ incrementBy: number,
737
+ telemetryContext?: ITelemetryContext,
738
+ ) {
739
+ const prevTotal = (telemetryContext?.get(this.telemetryContextPrefix, propertyName) ??
740
+ 0) as number;
741
+ telemetryContext?.set(this.telemetryContextPrefix, propertyName, prevTotal + incrementBy);
742
+ }
670
743
  }