@fluidframework/shared-object-base 1.4.0-115997 → 2.0.0-dev-rc.1.0.0.224419

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