@fluidframework/shared-object-base 2.0.0-dev.2.2.0.111723 → 2.0.0-dev.3.1.0.125672

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