@fluidframework/runtime-utils 2.0.0-internal.3.0.1 → 2.0.0-internal.3.1.0

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 (99) hide show
  1. package/.eslintrc.js +5 -7
  2. package/.mocharc.js +2 -2
  3. package/api-extractor.json +2 -2
  4. package/dist/dataStoreHandleContextUtils.d.ts.map +1 -1
  5. package/dist/dataStoreHandleContextUtils.js +3 -1
  6. package/dist/dataStoreHandleContextUtils.js.map +1 -1
  7. package/dist/dataStoreHelpers.d.ts.map +1 -1
  8. package/dist/dataStoreHelpers.js +23 -7
  9. package/dist/dataStoreHelpers.js.map +1 -1
  10. package/dist/index.d.ts +1 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js.map +1 -1
  13. package/dist/objectstoragepartition.d.ts.map +1 -1
  14. package/dist/objectstoragepartition.js.map +1 -1
  15. package/dist/objectstorageutils.d.ts.map +1 -1
  16. package/dist/objectstorageutils.js.map +1 -1
  17. package/dist/packageVersion.d.ts +1 -1
  18. package/dist/packageVersion.js +1 -1
  19. package/dist/packageVersion.js.map +1 -1
  20. package/dist/requestParser.d.ts.map +1 -1
  21. package/dist/requestParser.js.map +1 -1
  22. package/dist/runtimeFactoryHelper.d.ts.map +1 -1
  23. package/dist/runtimeFactoryHelper.js +6 -2
  24. package/dist/runtimeFactoryHelper.js.map +1 -1
  25. package/dist/summarizerNode/index.d.ts +1 -1
  26. package/dist/summarizerNode/index.d.ts.map +1 -1
  27. package/dist/summarizerNode/index.js.map +1 -1
  28. package/dist/summarizerNode/summarizerNode.d.ts +4 -5
  29. package/dist/summarizerNode/summarizerNode.d.ts.map +1 -1
  30. package/dist/summarizerNode/summarizerNode.js +33 -13
  31. package/dist/summarizerNode/summarizerNode.js.map +1 -1
  32. package/dist/summarizerNode/summarizerNodeUtils.d.ts +14 -5
  33. package/dist/summarizerNode/summarizerNodeUtils.d.ts.map +1 -1
  34. package/dist/summarizerNode/summarizerNodeUtils.js.map +1 -1
  35. package/dist/summarizerNode/summarizerNodeWithGc.d.ts.map +1 -1
  36. package/dist/summarizerNode/summarizerNodeWithGc.js +20 -12
  37. package/dist/summarizerNode/summarizerNodeWithGc.js.map +1 -1
  38. package/dist/summaryUtils.d.ts.map +1 -1
  39. package/dist/summaryUtils.js +3 -2
  40. package/dist/summaryUtils.js.map +1 -1
  41. package/dist/utils.d.ts.map +1 -1
  42. package/dist/utils.js.map +1 -1
  43. package/lib/dataStoreHandleContextUtils.d.ts.map +1 -1
  44. package/lib/dataStoreHandleContextUtils.js +3 -1
  45. package/lib/dataStoreHandleContextUtils.js.map +1 -1
  46. package/lib/dataStoreHelpers.d.ts.map +1 -1
  47. package/lib/dataStoreHelpers.js +23 -7
  48. package/lib/dataStoreHelpers.js.map +1 -1
  49. package/lib/index.d.ts +1 -1
  50. package/lib/index.d.ts.map +1 -1
  51. package/lib/index.js.map +1 -1
  52. package/lib/objectstoragepartition.d.ts.map +1 -1
  53. package/lib/objectstoragepartition.js.map +1 -1
  54. package/lib/objectstorageutils.d.ts.map +1 -1
  55. package/lib/objectstorageutils.js.map +1 -1
  56. package/lib/packageVersion.d.ts +1 -1
  57. package/lib/packageVersion.js +1 -1
  58. package/lib/packageVersion.js.map +1 -1
  59. package/lib/requestParser.d.ts.map +1 -1
  60. package/lib/requestParser.js.map +1 -1
  61. package/lib/runtimeFactoryHelper.d.ts.map +1 -1
  62. package/lib/runtimeFactoryHelper.js +6 -2
  63. package/lib/runtimeFactoryHelper.js.map +1 -1
  64. package/lib/summarizerNode/index.d.ts +1 -1
  65. package/lib/summarizerNode/index.d.ts.map +1 -1
  66. package/lib/summarizerNode/index.js.map +1 -1
  67. package/lib/summarizerNode/summarizerNode.d.ts +4 -5
  68. package/lib/summarizerNode/summarizerNode.d.ts.map +1 -1
  69. package/lib/summarizerNode/summarizerNode.js +33 -13
  70. package/lib/summarizerNode/summarizerNode.js.map +1 -1
  71. package/lib/summarizerNode/summarizerNodeUtils.d.ts +14 -5
  72. package/lib/summarizerNode/summarizerNodeUtils.d.ts.map +1 -1
  73. package/lib/summarizerNode/summarizerNodeUtils.js.map +1 -1
  74. package/lib/summarizerNode/summarizerNodeWithGc.d.ts.map +1 -1
  75. package/lib/summarizerNode/summarizerNodeWithGc.js +21 -13
  76. package/lib/summarizerNode/summarizerNodeWithGc.js.map +1 -1
  77. package/lib/summaryUtils.d.ts.map +1 -1
  78. package/lib/summaryUtils.js +3 -2
  79. package/lib/summaryUtils.js.map +1 -1
  80. package/lib/utils.d.ts.map +1 -1
  81. package/lib/utils.js.map +1 -1
  82. package/package.json +110 -104
  83. package/prettier.config.cjs +1 -1
  84. package/src/dataStoreHandleContextUtils.ts +23 -16
  85. package/src/dataStoreHelpers.ts +104 -86
  86. package/src/index.ts +2 -1
  87. package/src/objectstoragepartition.ts +13 -13
  88. package/src/objectstorageutils.ts +31 -28
  89. package/src/packageVersion.ts +1 -1
  90. package/src/requestParser.ts +80 -82
  91. package/src/runtimeFactoryHelper.ts +24 -17
  92. package/src/summarizerNode/index.ts +5 -1
  93. package/src/summarizerNode/summarizerNode.ts +602 -549
  94. package/src/summarizerNode/summarizerNodeUtils.ts +163 -150
  95. package/src/summarizerNode/summarizerNodeWithGc.ts +508 -472
  96. package/src/summaryUtils.ts +299 -291
  97. package/src/utils.ts +6 -6
  98. package/tsconfig.esnext.json +6 -6
  99. package/tsconfig.json +8 -12
@@ -4,34 +4,35 @@
4
4
  */
5
5
 
6
6
  import {
7
- ISummarizerNode,
8
- ISummarizerNodeConfig,
9
- ISummarizeResult,
10
- ISummaryTreeWithStats,
11
- CreateChildSummarizerNodeParam,
12
- CreateSummarizerNodeSource,
13
- SummarizeInternalFn,
14
- ITelemetryContext,
7
+ ISummarizerNode,
8
+ ISummarizerNodeConfig,
9
+ ISummarizeResult,
10
+ ISummaryTreeWithStats,
11
+ CreateChildSummarizerNodeParam,
12
+ CreateSummarizerNodeSource,
13
+ SummarizeInternalFn,
14
+ ITelemetryContext,
15
15
  } from "@fluidframework/runtime-definitions";
16
16
  import {
17
- ISequencedDocumentMessage,
18
- SummaryType,
19
- ISnapshotTree,
20
- SummaryObject,
17
+ ISequencedDocumentMessage,
18
+ SummaryType,
19
+ ISnapshotTree,
20
+ SummaryObject,
21
21
  } from "@fluidframework/protocol-definitions";
22
22
  import { ITelemetryLogger } from "@fluidframework/common-definitions";
23
23
  import { assert, unreachableCase } from "@fluidframework/common-utils";
24
24
  import { mergeStats, convertToSummaryTree, calculateStats } from "../summaryUtils";
25
25
  import { ReadAndParseBlob } from "../utils";
26
26
  import {
27
- EscapedPath,
28
- ICreateChildDetails,
29
- IInitialSummary,
30
- ISummarizerNodeRootContract,
31
- parseSummaryForSubtrees,
32
- parseSummaryTreeForSubtrees,
33
- RefreshSummaryResult,
34
- SummaryNode,
27
+ EscapedPath,
28
+ ICreateChildDetails,
29
+ IFetchSnapshotResult,
30
+ IInitialSummary,
31
+ ISummarizerNodeRootContract,
32
+ parseSummaryForSubtrees,
33
+ parseSummaryTreeForSubtrees,
34
+ RefreshSummaryResult,
35
+ SummaryNode,
35
36
  } from "./summarizerNodeUtils";
36
37
 
37
38
  export interface IRootSummarizerNode extends ISummarizerNode, ISummarizerNodeRootContract {}
@@ -50,523 +51,572 @@ export interface IRootSummarizerNode extends ISummarizerNode, ISummarizerNodeRoo
50
51
  * latest successful summary.
51
52
  */
52
53
  export class SummarizerNode implements IRootSummarizerNode {
53
- /**
54
- * The reference sequence number of the most recent acked summary.
55
- * Returns 0 if there is not yet an acked summary.
56
- */
57
- public get referenceSequenceNumber() {
58
- return this._latestSummary?.referenceSequenceNumber ?? 0;
59
- }
60
-
61
- protected readonly children = new Map<string, SummarizerNode>();
62
- protected readonly pendingSummaries = new Map<string, SummaryNode>();
63
- private wipReferenceSequenceNumber: number | undefined;
64
- private wipLocalPaths: { localPath: EscapedPath; additionalPath?: EscapedPath; } | undefined;
65
- private wipSkipRecursion = false;
66
-
67
- public startSummary(referenceSequenceNumber: number, summaryLogger: ITelemetryLogger) {
68
- assert(this.wipSummaryLogger === undefined,
69
- 0x19f /* "wipSummaryLogger should not be set yet in startSummary" */);
70
- assert(this.wipReferenceSequenceNumber === undefined, 0x1a0 /* "Already tracking a summary" */);
71
-
72
- this.wipSummaryLogger = summaryLogger;
73
-
74
- for (const child of this.children.values()) {
75
- child.startSummary(referenceSequenceNumber, this.wipSummaryLogger);
76
- }
77
- this.wipReferenceSequenceNumber = referenceSequenceNumber;
78
- }
79
-
80
- public async summarize(
81
- fullTree: boolean,
82
- trackState: boolean = true,
83
- telemetryContext?: ITelemetryContext,
84
- ): Promise<ISummarizeResult> {
85
- assert(this.isTrackingInProgress(), 0x1a1 /* "summarize should not be called when not tracking the summary" */);
86
- assert(this.wipSummaryLogger !== undefined,
87
- 0x1a2 /* "wipSummaryLogger should have been set in startSummary or ctor" */);
88
-
89
- // Try to reuse the tree if unchanged
90
- if (this.canReuseHandle && !fullTree && !this.hasChanged()) {
91
- const latestSummary = this._latestSummary;
92
- if (latestSummary !== undefined) {
93
- this.wipLocalPaths = {
94
- localPath: latestSummary.localPath,
95
- additionalPath: latestSummary.additionalPath,
96
- };
97
- this.wipSkipRecursion = true;
98
- const stats = mergeStats();
99
- stats.handleNodeCount++;
100
- return {
101
- summary: {
102
- type: SummaryType.Handle,
103
- handle: latestSummary.fullPath.path,
104
- handleType: SummaryType.Tree,
105
- },
106
- stats,
107
- };
108
- }
109
- }
110
-
111
- const result = await this.summarizeInternalFn(fullTree, true, telemetryContext);
112
- this.wipLocalPaths = { localPath: EscapedPath.create(result.id) };
113
- if (result.pathPartsForChildren !== undefined) {
114
- this.wipLocalPaths.additionalPath = EscapedPath.createAndConcat(result.pathPartsForChildren);
115
- }
116
- return { summary: result.summary, stats: result.stats };
117
- }
118
-
119
- /**
120
- * Complete the WIP summary for the given proposalHandle
121
- */
122
- public completeSummary(proposalHandle: string) {
123
- this.completeSummaryCore(proposalHandle, undefined, false);
124
- }
125
-
126
- /**
127
- * Recursive implementation for completeSummary, with additional internal-only parameters
128
- */
129
- protected completeSummaryCore(
130
- proposalHandle: string,
131
- parentPath: EscapedPath | undefined,
132
- parentSkipRecursion: boolean,
133
- ) {
134
- assert(this.wipSummaryLogger !== undefined,
135
- 0x1a3 /* "wipSummaryLogger should have been set in startSummary or ctor" */);
136
- assert(this.wipReferenceSequenceNumber !== undefined, 0x1a4 /* "Not tracking a summary" */);
137
- let localPathsToUse = this.wipLocalPaths;
138
-
139
- if (parentSkipRecursion) {
140
- const latestSummary = this._latestSummary;
141
- if (latestSummary !== undefined) {
142
- // This case the parent node created a failure summary or was reused.
143
- // This node and all children should only try to reference their path
144
- // by its last known good state in the actual summary tree.
145
- // If parent fails or is reused, the child summarize is not called so
146
- // it did not get a chance to change its paths.
147
- // In this case, essentially only propagate the new summary ref seq num.
148
- localPathsToUse = {
149
- localPath: latestSummary.localPath,
150
- additionalPath: latestSummary.additionalPath,
151
- };
152
- } else {
153
- // This case the child is added after the latest non-failure summary.
154
- // This node and all children should consider themselves as still not
155
- // having a successful summary yet.
156
- // We cannot "reuse" this node if unchanged since that summary, because
157
- // handles will be unable to point to that node. It never made it to the
158
- // tree itself, and only exists as an attach op in the _outstandingOps.
159
- this.clearSummary();
160
- return;
161
- }
162
- }
163
-
164
- // This should come from wipLocalPaths in normal cases, or from the latestSummary
165
- // if parentIsFailure or parentIsReused is true.
166
- // If there is no latestSummary, clearSummary and return before reaching this code.
167
- assert(!!localPathsToUse, 0x1a5 /* "Tracked summary local paths not set" */);
168
-
169
- const summary = new SummaryNode({
170
- ...localPathsToUse,
171
- referenceSequenceNumber: this.wipReferenceSequenceNumber,
172
- basePath: parentPath,
173
- });
174
- const fullPathForChildren = summary.fullPathForChildren;
175
- for (const child of this.children.values()) {
176
- child.completeSummaryCore(
177
- proposalHandle,
178
- fullPathForChildren,
179
- this.wipSkipRecursion || parentSkipRecursion,
180
- );
181
- }
182
- // Note that this overwrites existing pending summary with
183
- // the same proposalHandle. If proposalHandle is something like
184
- // a hash or unique identifier, this should be fine. If storage
185
- // can return the same proposalHandle for a different summary,
186
- // this should still be okay, because we should be proposing the
187
- // newer one later which would have to overwrite the previous one.
188
- this.pendingSummaries.set(proposalHandle, summary);
189
- this.clearSummary();
190
- }
191
-
192
- public clearSummary() {
193
- this.wipReferenceSequenceNumber = undefined;
194
- this.wipLocalPaths = undefined;
195
- this.wipSkipRecursion = false;
196
- this.wipSummaryLogger = undefined;
197
- for (const child of this.children.values()) {
198
- child.clearSummary();
199
- }
200
- }
201
-
202
- /**
203
- * Refreshes the latest summary tracked by this node. If we have a pending summary for the given proposal handle,
204
- * it becomes the latest summary. If the current summary is already ahead (e.g., loaded from a service summary),
205
- * we skip the update. Otherwise, we get the snapshot by calling `getSnapshot` and update latest
206
- * summary based off of that.
207
- *
208
- * @returns A RefreshSummaryResult type which returns information based on the following three scenarios:
209
- *
210
- * 1. The latest summary was not udpated.
211
- *
212
- * 2. The latest summary was updated and the summary corresponding to the params was being tracked.
213
- *
214
- * 3. The latest summary was updated but the summary corresponding to the params was not tracked. In this
215
- * case, the latest summary is updated based on the downloaded snapshot which is also returned.
216
- */
217
- public async refreshLatestSummary(
218
- proposalHandle: string | undefined,
219
- summaryRefSeq: number,
220
- getSnapshot: () => Promise<ISnapshotTree>,
221
- readAndParseBlob: ReadAndParseBlob,
222
- correlatedSummaryLogger: ITelemetryLogger,
223
- ): Promise<RefreshSummaryResult> {
224
- if (proposalHandle !== undefined) {
225
- const maybeSummaryNode = this.pendingSummaries.get(proposalHandle);
226
-
227
- if (maybeSummaryNode !== undefined) {
228
- this.refreshLatestSummaryFromPending(proposalHandle, maybeSummaryNode.referenceSequenceNumber);
229
- return { latestSummaryUpdated: true, wasSummaryTracked: true };
230
- }
231
-
232
- const props = {
233
- summaryRefSeq,
234
- pendingSize: this.pendingSummaries.size ?? undefined,
235
- };
236
- this.defaultLogger.sendTelemetryEvent({
237
- eventName: "PendingSummaryNotFound",
238
- proposalHandle,
239
- referenceSequenceNumber: this.referenceSequenceNumber,
240
- details: JSON.stringify(props),
241
- });
242
- }
243
-
244
- // If we have seen a summary same or later as the current one, ignore it.
245
- if (this.referenceSequenceNumber >= summaryRefSeq) {
246
- return { latestSummaryUpdated: false };
247
- }
248
-
249
- const snapshotTree = await getSnapshot();
250
- await this.refreshLatestSummaryFromSnapshot(
251
- summaryRefSeq,
252
- snapshotTree,
253
- undefined,
254
- EscapedPath.create(""),
255
- correlatedSummaryLogger,
256
- readAndParseBlob,
257
- );
258
- return { latestSummaryUpdated: true, wasSummaryTracked: false, snapshot: snapshotTree };
259
- }
260
- /**
261
- * Called when we get an ack from the server for a summary we've just sent. Updates the reference state of this node
262
- * from the state in the pending summary queue.
263
- * @param proposalHandle - Handle for the current proposal.
264
- * @param referenceSequenceNumber - reference sequence number of sent summary.
265
- */
266
- protected refreshLatestSummaryFromPending(
267
- proposalHandle: string,
268
- referenceSequenceNumber: number,
269
- ): void {
270
- const summaryNode = this.pendingSummaries.get(proposalHandle);
271
- if (summaryNode === undefined) {
272
- // This should only happen if parent skipped recursion AND no prior summary existed.
273
- assert(
274
- this._latestSummary === undefined,
275
- 0x1a6 /* "Not found pending summary, but this node has previously completed a summary" */,
276
- );
277
- return;
278
- } else {
279
- assert(
280
- referenceSequenceNumber === summaryNode.referenceSequenceNumber,
281
- 0x1a7 /* Pending summary reference sequence number should be consistent */,
282
- );
283
-
284
- // Clear earlier pending summaries
285
- this.pendingSummaries.delete(proposalHandle);
286
- }
287
-
288
- this.refreshLatestSummaryCore(referenceSequenceNumber);
289
-
290
- this._latestSummary = summaryNode;
291
- // Propagate update to all child nodes
292
- for (const child of this.children.values()) {
293
- child.refreshLatestSummaryFromPending(proposalHandle, referenceSequenceNumber);
294
- }
295
- }
296
-
297
- protected async refreshLatestSummaryFromSnapshot(
298
- referenceSequenceNumber: number,
299
- snapshotTree: ISnapshotTree,
300
- basePath: EscapedPath | undefined,
301
- localPath: EscapedPath,
302
- correlatedSummaryLogger: ITelemetryLogger,
303
- readAndParseBlob: ReadAndParseBlob,
304
- ): Promise<void> {
305
- // Possible re-entrancy. If we have already seen a summary later than this one, ignore it.
306
- if (this.referenceSequenceNumber >= referenceSequenceNumber) {
307
- return;
308
- }
309
-
310
- this.refreshLatestSummaryCore(referenceSequenceNumber);
311
-
312
- this._latestSummary = new SummaryNode({
313
- referenceSequenceNumber,
314
- basePath,
315
- localPath,
316
- });
317
-
318
- const pathParts: string[] = [];
319
- const { childrenTree, childrenPathPart } = parseSummaryForSubtrees(snapshotTree);
320
- if (childrenPathPart !== undefined) {
321
- pathParts.push(childrenPathPart);
322
- }
323
-
324
- if (pathParts.length > 0) {
325
- this._latestSummary.additionalPath = EscapedPath.createAndConcat(pathParts);
326
- }
327
-
328
- // Propagate update to all child nodes
329
- const pathForChildren = this._latestSummary.fullPathForChildren;
330
- await Promise.all(Array.from(this.children)
331
- .filter(([id]) => {
332
- // Assuming subtrees missing from snapshot are newer than the snapshot,
333
- // but might be nice to assert this using earliest seq for node.
334
- return childrenTree.trees[id] !== undefined;
335
- }).map(async ([id, child]) => {
336
- return child.refreshLatestSummaryFromSnapshot(
337
- referenceSequenceNumber,
338
- childrenTree.trees[id],
339
- pathForChildren,
340
- EscapedPath.create(id),
341
- correlatedSummaryLogger,
342
- readAndParseBlob,
343
- );
344
- }));
345
- }
346
-
347
- private refreshLatestSummaryCore(referenceSequenceNumber: number): void {
348
- for (const [key, value] of this.pendingSummaries) {
349
- if (value.referenceSequenceNumber < referenceSequenceNumber) {
350
- this.pendingSummaries.delete(key);
351
- }
352
- }
353
- }
354
-
355
- public updateBaseSummaryState(snapshot: ISnapshotTree) {
356
- // Check base summary to see if it has any additional path parts
357
- // separating child SummarizerNodes. Checks for .channels subtrees.
358
- const { childrenPathPart } = parseSummaryForSubtrees(snapshot);
359
- if (childrenPathPart !== undefined && this._latestSummary !== undefined) {
360
- this._latestSummary.additionalPath = EscapedPath.create(childrenPathPart);
361
- }
362
- }
363
-
364
- public recordChange(op: ISequencedDocumentMessage): void {
365
- this.invalidate(op.sequenceNumber);
366
- }
367
-
368
- public invalidate(sequenceNumber: number): void {
369
- if (sequenceNumber > this._changeSequenceNumber) {
370
- this._changeSequenceNumber = sequenceNumber;
371
- }
372
- }
373
-
374
- /**
375
- * True if a change has been recorded with sequence number exceeding
376
- * the latest successfully acked summary reference sequence number.
377
- * False implies that the previous summary can be reused.
378
- */
379
- protected hasChanged(): boolean {
380
- return this._changeSequenceNumber > this.referenceSequenceNumber;
381
- }
382
-
383
- public get latestSummary(): Readonly<SummaryNode> | undefined {
384
- return this._latestSummary;
385
- }
386
-
387
- protected readonly canReuseHandle: boolean;
388
-
389
- /**
390
- * Do not call constructor directly.
391
- * Use createRootSummarizerNode to create root node, or createChild to create child nodes.
392
- */
393
- public constructor(
394
- protected readonly defaultLogger: ITelemetryLogger,
395
- private readonly summarizeInternalFn: SummarizeInternalFn,
396
- config: ISummarizerNodeConfig,
397
- private _changeSequenceNumber: number,
398
- /** Undefined means created without summary */
399
- private _latestSummary?: SummaryNode,
400
- private readonly initialSummary?: IInitialSummary,
401
- protected wipSummaryLogger?: ITelemetryLogger,
402
- ) {
403
- this.canReuseHandle = config.canReuseHandle ?? true;
404
- }
405
-
406
- public createChild(
407
- /** Summarize function */
408
- summarizeInternalFn: SummarizeInternalFn,
409
- /** Initial id or path part of this node */
410
- id: string,
411
- /**
412
- * Information needed to create the node.
413
- * If it is from a base summary, it will assert that a summary has been seen.
414
- * Attach information if it is created from an attach op.
415
- */
416
- createParam: CreateChildSummarizerNodeParam,
417
- config: ISummarizerNodeConfig = {},
418
- ): ISummarizerNode {
419
- assert(!this.children.has(id), 0x1ab /* "Create SummarizerNode child already exists" */);
420
-
421
- const createDetails: ICreateChildDetails = this.getCreateDetailsForChild(id, createParam);
422
- const child = new SummarizerNode(
423
- this.defaultLogger,
424
- summarizeInternalFn,
425
- config,
426
- createDetails.changeSequenceNumber,
427
- createDetails.latestSummary,
428
- createDetails.initialSummary,
429
- this.wipSummaryLogger,
430
- );
431
-
432
- // There may be additional state that has to be updated in this child. For example, if a summary is being
433
- // tracked, the child's summary tracking state needs to be updated too. Same goes for pendingSummaries we might
434
- // have outstanding on the parent in case we realize nodes in between Summary Op and Summary Ack.
435
- this.maybeUpdateChildState(child);
436
-
437
- this.children.set(id, child);
438
- return child;
439
- }
440
-
441
- public getChild(id: string): ISummarizerNode | undefined {
442
- return this.children.get(id);
443
- }
444
-
445
- /**
446
- * Returns the details needed to create a child node.
447
- * @param id - Initial id or path part of the child node.
448
- * @param createParam - Information needed to create the node.
449
- * @returns the details needed to create the child node.
450
- */
451
- protected getCreateDetailsForChild(id: string, createParam: CreateChildSummarizerNodeParam): ICreateChildDetails {
452
- let initialSummary: IInitialSummary | undefined;
453
- let latestSummary: SummaryNode | undefined;
454
- let changeSequenceNumber: number;
455
-
456
- const parentLatestSummary = this._latestSummary;
457
- switch (createParam.type) {
458
- case CreateSummarizerNodeSource.FromAttach: {
459
- if (
460
- parentLatestSummary !== undefined
461
- && createParam.sequenceNumber <= parentLatestSummary.referenceSequenceNumber
462
- ) {
463
- // Prioritize latest summary if it was after this node was attached.
464
- latestSummary = parentLatestSummary.createForChild(id);
465
- } else {
466
- const summary = convertToSummaryTree(createParam.snapshot) as ISummaryTreeWithStats;
467
- initialSummary = {
468
- sequenceNumber: createParam.sequenceNumber,
469
- id,
470
- summary,
471
- };
472
- }
473
- changeSequenceNumber = createParam.sequenceNumber;
474
- break;
475
- }
476
- case CreateSummarizerNodeSource.FromSummary: {
477
- if (this.initialSummary === undefined) {
478
- assert(
479
- !!parentLatestSummary,
480
- 0x1ac /* "Cannot create child from summary if parent does not have latest summary" */);
481
- }
482
- // fallthrough to local
483
- }
484
- case CreateSummarizerNodeSource.Local: {
485
- const parentInitialSummary = this.initialSummary;
486
- if (parentInitialSummary !== undefined) {
487
- let childSummary: SummaryObject | undefined;
488
- if (parentInitialSummary.summary !== undefined) {
489
- const { childrenTree } = parseSummaryTreeForSubtrees(parentInitialSummary.summary.summary);
490
- assert(
491
- childrenTree.type === SummaryType.Tree,
492
- 0x1d6 /* "Parent summary object is not a tree" */,
493
- );
494
- childSummary = childrenTree.tree[id];
495
- }
496
- if (createParam.type === CreateSummarizerNodeSource.FromSummary) {
497
- // Locally created would not have differential subtree.
498
- assert(!!childSummary, 0x1ad /* "Missing child summary tree" */);
499
- }
500
- let childSummaryWithStats: ISummaryTreeWithStats | undefined;
501
- if (childSummary !== undefined) {
502
- assert(
503
- childSummary.type === SummaryType.Tree,
504
- 0x1ae /* "Child summary object is not a tree" */,
505
- );
506
- childSummaryWithStats = {
507
- summary: childSummary,
508
- stats: calculateStats(childSummary),
509
- };
510
- }
511
- initialSummary = {
512
- sequenceNumber: parentInitialSummary.sequenceNumber,
513
- id,
514
- summary: childSummaryWithStats,
515
- };
516
- }
517
- latestSummary = parentLatestSummary?.createForChild(id);
518
- changeSequenceNumber = parentLatestSummary?.referenceSequenceNumber ?? -1;
519
- break;
520
- }
521
- default: {
522
- const type = (createParam as unknown as CreateChildSummarizerNodeParam).type;
523
- unreachableCase(createParam, `Unexpected CreateSummarizerNodeSource: ${type}`);
524
- }
525
- }
526
-
527
- return {
528
- initialSummary,
529
- latestSummary,
530
- changeSequenceNumber,
531
- };
532
- }
533
-
534
- /**
535
- * Updates the state of the child if required. For example, if a summary is currently being tracked, the child's
536
- * summary tracking state needs to be updated too.
537
- * Also, in case a child node gets realized in between Summary Op and Summary Ack, let's initialize the child's
538
- * pending summary as well.
539
- * @param child - The child node whose state is to be updated.
540
- */
541
- protected maybeUpdateChildState(child: SummarizerNode) {
542
- // If we are tracking a summary, this child was created after the tracking started. So, we need to update the
543
- // child's tracking state as well.
544
- if (this.isTrackingInProgress()) {
545
- child.wipReferenceSequenceNumber = this.wipReferenceSequenceNumber;
546
- }
547
- // In case we have pending summaries on the parent, let's initialize it on the child.
548
- if (child._latestSummary !== undefined) {
549
- for (const [key, value] of this.pendingSummaries.entries()) {
550
- const newLatestSummaryNode = new SummaryNode({
551
- referenceSequenceNumber: value.referenceSequenceNumber,
552
- basePath: child._latestSummary.basePath,
553
- localPath: child._latestSummary.localPath,
554
- });
555
-
556
- child.addPendingSummary(key, newLatestSummaryNode);
557
- }
558
- }
559
- }
560
-
561
- protected addPendingSummary(key: string, summary: SummaryNode) {
562
- this.pendingSummaries.set(key, summary);
563
- }
564
- /**
565
- * Tells whether summary tracking is in progress. True if "startSummary" API is called before summarize.
566
- */
567
- protected isTrackingInProgress(): boolean {
568
- return this.wipReferenceSequenceNumber !== undefined;
569
- }
54
+ /**
55
+ * The reference sequence number of the most recent acked summary.
56
+ * Returns 0 if there is not yet an acked summary.
57
+ */
58
+ public get referenceSequenceNumber() {
59
+ return this._latestSummary?.referenceSequenceNumber ?? 0;
60
+ }
61
+
62
+ protected readonly children = new Map<string, SummarizerNode>();
63
+ protected readonly pendingSummaries = new Map<string, SummaryNode>();
64
+ private wipReferenceSequenceNumber: number | undefined;
65
+ private wipLocalPaths: { localPath: EscapedPath; additionalPath?: EscapedPath } | undefined;
66
+ private wipSkipRecursion = false;
67
+
68
+ public startSummary(referenceSequenceNumber: number, summaryLogger: ITelemetryLogger) {
69
+ assert(
70
+ this.wipSummaryLogger === undefined,
71
+ 0x19f /* "wipSummaryLogger should not be set yet in startSummary" */,
72
+ );
73
+ assert(
74
+ this.wipReferenceSequenceNumber === undefined,
75
+ 0x1a0 /* "Already tracking a summary" */,
76
+ );
77
+
78
+ this.wipSummaryLogger = summaryLogger;
79
+
80
+ for (const child of this.children.values()) {
81
+ child.startSummary(referenceSequenceNumber, this.wipSummaryLogger);
82
+ }
83
+ this.wipReferenceSequenceNumber = referenceSequenceNumber;
84
+ }
85
+
86
+ public async summarize(
87
+ fullTree: boolean,
88
+ trackState: boolean = true,
89
+ telemetryContext?: ITelemetryContext,
90
+ ): Promise<ISummarizeResult> {
91
+ assert(
92
+ this.isTrackingInProgress(),
93
+ 0x1a1 /* "summarize should not be called when not tracking the summary" */,
94
+ );
95
+ assert(
96
+ this.wipSummaryLogger !== undefined,
97
+ 0x1a2 /* "wipSummaryLogger should have been set in startSummary or ctor" */,
98
+ );
99
+
100
+ // Try to reuse the tree if unchanged
101
+ if (this.canReuseHandle && !fullTree && !this.hasChanged()) {
102
+ const latestSummary = this._latestSummary;
103
+ if (latestSummary !== undefined) {
104
+ this.wipLocalPaths = {
105
+ localPath: latestSummary.localPath,
106
+ additionalPath: latestSummary.additionalPath,
107
+ };
108
+ this.wipSkipRecursion = true;
109
+ const stats = mergeStats();
110
+ stats.handleNodeCount++;
111
+ return {
112
+ summary: {
113
+ type: SummaryType.Handle,
114
+ handle: latestSummary.fullPath.path,
115
+ handleType: SummaryType.Tree,
116
+ },
117
+ stats,
118
+ };
119
+ }
120
+ }
121
+
122
+ const result = await this.summarizeInternalFn(fullTree, true, telemetryContext);
123
+ this.wipLocalPaths = { localPath: EscapedPath.create(result.id) };
124
+ if (result.pathPartsForChildren !== undefined) {
125
+ this.wipLocalPaths.additionalPath = EscapedPath.createAndConcat(
126
+ result.pathPartsForChildren,
127
+ );
128
+ }
129
+ return { summary: result.summary, stats: result.stats };
130
+ }
131
+
132
+ /**
133
+ * Complete the WIP summary for the given proposalHandle
134
+ */
135
+ public completeSummary(proposalHandle: string) {
136
+ this.completeSummaryCore(proposalHandle, undefined, false);
137
+ }
138
+
139
+ /**
140
+ * Recursive implementation for completeSummary, with additional internal-only parameters
141
+ */
142
+ protected completeSummaryCore(
143
+ proposalHandle: string,
144
+ parentPath: EscapedPath | undefined,
145
+ parentSkipRecursion: boolean,
146
+ ) {
147
+ assert(
148
+ this.wipSummaryLogger !== undefined,
149
+ 0x1a3 /* "wipSummaryLogger should have been set in startSummary or ctor" */,
150
+ );
151
+ assert(this.wipReferenceSequenceNumber !== undefined, 0x1a4 /* "Not tracking a summary" */);
152
+ let localPathsToUse = this.wipLocalPaths;
153
+
154
+ if (parentSkipRecursion) {
155
+ const latestSummary = this._latestSummary;
156
+ if (latestSummary !== undefined) {
157
+ // This case the parent node created a failure summary or was reused.
158
+ // This node and all children should only try to reference their path
159
+ // by its last known good state in the actual summary tree.
160
+ // If parent fails or is reused, the child summarize is not called so
161
+ // it did not get a chance to change its paths.
162
+ // In this case, essentially only propagate the new summary ref seq num.
163
+ localPathsToUse = {
164
+ localPath: latestSummary.localPath,
165
+ additionalPath: latestSummary.additionalPath,
166
+ };
167
+ } else {
168
+ // This case the child is added after the latest non-failure summary.
169
+ // This node and all children should consider themselves as still not
170
+ // having a successful summary yet.
171
+ // We cannot "reuse" this node if unchanged since that summary, because
172
+ // handles will be unable to point to that node. It never made it to the
173
+ // tree itself, and only exists as an attach op in the _outstandingOps.
174
+ this.clearSummary();
175
+ return;
176
+ }
177
+ }
178
+
179
+ // This should come from wipLocalPaths in normal cases, or from the latestSummary
180
+ // if parentIsFailure or parentIsReused is true.
181
+ // If there is no latestSummary, clearSummary and return before reaching this code.
182
+ assert(!!localPathsToUse, 0x1a5 /* "Tracked summary local paths not set" */);
183
+
184
+ const summary = new SummaryNode({
185
+ ...localPathsToUse,
186
+ referenceSequenceNumber: this.wipReferenceSequenceNumber,
187
+ basePath: parentPath,
188
+ });
189
+ const fullPathForChildren = summary.fullPathForChildren;
190
+ for (const child of this.children.values()) {
191
+ child.completeSummaryCore(
192
+ proposalHandle,
193
+ fullPathForChildren,
194
+ this.wipSkipRecursion || parentSkipRecursion,
195
+ );
196
+ }
197
+ // Note that this overwrites existing pending summary with
198
+ // the same proposalHandle. If proposalHandle is something like
199
+ // a hash or unique identifier, this should be fine. If storage
200
+ // can return the same proposalHandle for a different summary,
201
+ // this should still be okay, because we should be proposing the
202
+ // newer one later which would have to overwrite the previous one.
203
+ this.pendingSummaries.set(proposalHandle, summary);
204
+ this.clearSummary();
205
+ }
206
+
207
+ public clearSummary() {
208
+ this.wipReferenceSequenceNumber = undefined;
209
+ this.wipLocalPaths = undefined;
210
+ this.wipSkipRecursion = false;
211
+ this.wipSummaryLogger = undefined;
212
+ for (const child of this.children.values()) {
213
+ child.clearSummary();
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Refreshes the latest summary tracked by this node. If we have a pending summary for the given proposal handle,
219
+ * it becomes the latest summary. If the current summary is already ahead (e.g., loaded from a service summary),
220
+ * we skip the update. Otherwise, we fetch the latest snapshot and update latest summary based off of that.
221
+ *
222
+ * @returns A RefreshSummaryResult type which returns information based on the following three scenarios:
223
+ *
224
+ * 1. The latest summary was not updated.
225
+ *
226
+ * 2. The latest summary was updated and the summary corresponding to the params was being tracked.
227
+ *
228
+ * 3. The latest summary was updated but the summary corresponding to the params was not tracked. In this
229
+ * case, the latest summary is updated based on the downloaded snapshot which is also returned.
230
+ */
231
+ public async refreshLatestSummary(
232
+ proposalHandle: string | undefined,
233
+ summaryRefSeq: number,
234
+ fetchLatestSnapshot: () => Promise<IFetchSnapshotResult>,
235
+ readAndParseBlob: ReadAndParseBlob,
236
+ correlatedSummaryLogger: ITelemetryLogger,
237
+ ): Promise<RefreshSummaryResult> {
238
+ this.defaultLogger.sendTelemetryEvent({
239
+ eventName: "refreshLatestSummary_start",
240
+ proposalHandle,
241
+ referenceSequenceNumber: this.referenceSequenceNumber,
242
+ summaryRefSeq,
243
+ });
244
+
245
+ if (proposalHandle !== undefined) {
246
+ const maybeSummaryNode = this.pendingSummaries.get(proposalHandle);
247
+
248
+ if (maybeSummaryNode !== undefined) {
249
+ this.refreshLatestSummaryFromPending(
250
+ proposalHandle,
251
+ maybeSummaryNode.referenceSequenceNumber,
252
+ );
253
+ return { latestSummaryUpdated: true, wasSummaryTracked: true, summaryRefSeq };
254
+ }
255
+
256
+ const props = {
257
+ summaryRefSeq,
258
+ pendingSize: this.pendingSummaries.size ?? undefined,
259
+ };
260
+ this.defaultLogger.sendTelemetryEvent({
261
+ eventName: "PendingSummaryNotFound",
262
+ proposalHandle,
263
+ referenceSequenceNumber: this.referenceSequenceNumber,
264
+ details: JSON.stringify(props),
265
+ });
266
+ }
267
+
268
+ // If the summary for which refresh is called is older than the latest tracked summary, ignore it.
269
+ if (this.referenceSequenceNumber >= summaryRefSeq) {
270
+ return { latestSummaryUpdated: false };
271
+ }
272
+
273
+ // Fetch the latest snapshot and refresh state from it. Note that we need to use the reference sequence number
274
+ // of the fetched snapshot and not the "summaryRefSeq" that was passed in.
275
+ const { snapshotTree, snapshotRefSeq: fetchedSnapshotRefSeq } = await fetchLatestSnapshot();
276
+
277
+ // Possible re-entrancy. We may have updated latest summary state while fetching the snapshot. If the fetched
278
+ // snapshot is older than the latest tracked summary, ignore it.
279
+ if (this.referenceSequenceNumber >= fetchedSnapshotRefSeq) {
280
+ return { latestSummaryUpdated: false };
281
+ }
282
+
283
+ await this.refreshLatestSummaryFromSnapshot(
284
+ fetchedSnapshotRefSeq,
285
+ snapshotTree,
286
+ undefined,
287
+ EscapedPath.create(""),
288
+ correlatedSummaryLogger,
289
+ readAndParseBlob,
290
+ );
291
+
292
+ return {
293
+ latestSummaryUpdated: true,
294
+ wasSummaryTracked: false,
295
+ snapshotTree,
296
+ summaryRefSeq: fetchedSnapshotRefSeq,
297
+ };
298
+ }
299
+ /**
300
+ * Called when we get an ack from the server for a summary we've just sent. Updates the reference state of this node
301
+ * from the state in the pending summary queue.
302
+ * @param proposalHandle - Handle for the current proposal.
303
+ * @param referenceSequenceNumber - reference sequence number of sent summary.
304
+ */
305
+ protected refreshLatestSummaryFromPending(
306
+ proposalHandle: string,
307
+ referenceSequenceNumber: number,
308
+ ): void {
309
+ const summaryNode = this.pendingSummaries.get(proposalHandle);
310
+ if (summaryNode === undefined) {
311
+ // This should only happen if parent skipped recursion AND no prior summary existed.
312
+ assert(
313
+ this._latestSummary === undefined,
314
+ 0x1a6 /* "Not found pending summary, but this node has previously completed a summary" */,
315
+ );
316
+ return;
317
+ } else {
318
+ assert(
319
+ referenceSequenceNumber === summaryNode.referenceSequenceNumber,
320
+ 0x1a7 /* Pending summary reference sequence number should be consistent */,
321
+ );
322
+
323
+ // Clear earlier pending summaries
324
+ this.pendingSummaries.delete(proposalHandle);
325
+ }
326
+
327
+ this.refreshLatestSummaryCore(referenceSequenceNumber);
328
+
329
+ this._latestSummary = summaryNode;
330
+ // Propagate update to all child nodes
331
+ for (const child of this.children.values()) {
332
+ child.refreshLatestSummaryFromPending(proposalHandle, referenceSequenceNumber);
333
+ }
334
+ }
335
+
336
+ protected async refreshLatestSummaryFromSnapshot(
337
+ referenceSequenceNumber: number,
338
+ snapshotTree: ISnapshotTree,
339
+ basePath: EscapedPath | undefined,
340
+ localPath: EscapedPath,
341
+ correlatedSummaryLogger: ITelemetryLogger,
342
+ readAndParseBlob: ReadAndParseBlob,
343
+ ): Promise<void> {
344
+ // Possible re-entrancy. If we have already seen a summary later than this one, ignore it.
345
+ if (this.referenceSequenceNumber >= referenceSequenceNumber) {
346
+ return;
347
+ }
348
+
349
+ this.refreshLatestSummaryCore(referenceSequenceNumber);
350
+
351
+ this._latestSummary = new SummaryNode({
352
+ referenceSequenceNumber,
353
+ basePath,
354
+ localPath,
355
+ });
356
+
357
+ const pathParts: string[] = [];
358
+ const { childrenTree, childrenPathPart } = parseSummaryForSubtrees(snapshotTree);
359
+ if (childrenPathPart !== undefined) {
360
+ pathParts.push(childrenPathPart);
361
+ }
362
+
363
+ if (pathParts.length > 0) {
364
+ this._latestSummary.additionalPath = EscapedPath.createAndConcat(pathParts);
365
+ }
366
+
367
+ // Propagate update to all child nodes
368
+ const pathForChildren = this._latestSummary.fullPathForChildren;
369
+ await Promise.all(
370
+ Array.from(this.children)
371
+ .filter(([id]) => {
372
+ // Assuming subtrees missing from snapshot are newer than the snapshot,
373
+ // but might be nice to assert this using earliest seq for node.
374
+ return childrenTree.trees[id] !== undefined;
375
+ })
376
+ .map(async ([id, child]) => {
377
+ return child.refreshLatestSummaryFromSnapshot(
378
+ referenceSequenceNumber,
379
+ childrenTree.trees[id],
380
+ pathForChildren,
381
+ EscapedPath.create(id),
382
+ correlatedSummaryLogger,
383
+ readAndParseBlob,
384
+ );
385
+ }),
386
+ );
387
+ }
388
+
389
+ private refreshLatestSummaryCore(referenceSequenceNumber: number): void {
390
+ for (const [key, value] of this.pendingSummaries) {
391
+ if (value.referenceSequenceNumber < referenceSequenceNumber) {
392
+ this.pendingSummaries.delete(key);
393
+ }
394
+ }
395
+ }
396
+
397
+ public updateBaseSummaryState(snapshot: ISnapshotTree) {
398
+ // Check base summary to see if it has any additional path parts
399
+ // separating child SummarizerNodes. Checks for .channels subtrees.
400
+ const { childrenPathPart } = parseSummaryForSubtrees(snapshot);
401
+ if (childrenPathPart !== undefined && this._latestSummary !== undefined) {
402
+ this._latestSummary.additionalPath = EscapedPath.create(childrenPathPart);
403
+ }
404
+ }
405
+
406
+ public recordChange(op: ISequencedDocumentMessage): void {
407
+ this.invalidate(op.sequenceNumber);
408
+ }
409
+
410
+ public invalidate(sequenceNumber: number): void {
411
+ if (sequenceNumber > this._changeSequenceNumber) {
412
+ this._changeSequenceNumber = sequenceNumber;
413
+ }
414
+ }
415
+
416
+ /**
417
+ * True if a change has been recorded with sequence number exceeding
418
+ * the latest successfully acked summary reference sequence number.
419
+ * False implies that the previous summary can be reused.
420
+ */
421
+ protected hasChanged(): boolean {
422
+ return this._changeSequenceNumber > this.referenceSequenceNumber;
423
+ }
424
+
425
+ public get latestSummary(): Readonly<SummaryNode> | undefined {
426
+ return this._latestSummary;
427
+ }
428
+
429
+ protected readonly canReuseHandle: boolean;
430
+
431
+ /**
432
+ * Do not call constructor directly.
433
+ * Use createRootSummarizerNode to create root node, or createChild to create child nodes.
434
+ */
435
+ public constructor(
436
+ protected readonly defaultLogger: ITelemetryLogger,
437
+ private readonly summarizeInternalFn: SummarizeInternalFn,
438
+ config: ISummarizerNodeConfig,
439
+ private _changeSequenceNumber: number,
440
+ /** Undefined means created without summary */
441
+ private _latestSummary?: SummaryNode,
442
+ private readonly initialSummary?: IInitialSummary,
443
+ protected wipSummaryLogger?: ITelemetryLogger,
444
+ ) {
445
+ this.canReuseHandle = config.canReuseHandle ?? true;
446
+ }
447
+
448
+ public createChild(
449
+ /** Summarize function */
450
+ summarizeInternalFn: SummarizeInternalFn,
451
+ /** Initial id or path part of this node */
452
+ id: string,
453
+ /**
454
+ * Information needed to create the node.
455
+ * If it is from a base summary, it will assert that a summary has been seen.
456
+ * Attach information if it is created from an attach op.
457
+ */
458
+ createParam: CreateChildSummarizerNodeParam,
459
+ config: ISummarizerNodeConfig = {},
460
+ ): ISummarizerNode {
461
+ assert(!this.children.has(id), 0x1ab /* "Create SummarizerNode child already exists" */);
462
+
463
+ const createDetails: ICreateChildDetails = this.getCreateDetailsForChild(id, createParam);
464
+ const child = new SummarizerNode(
465
+ this.defaultLogger,
466
+ summarizeInternalFn,
467
+ config,
468
+ createDetails.changeSequenceNumber,
469
+ createDetails.latestSummary,
470
+ createDetails.initialSummary,
471
+ this.wipSummaryLogger,
472
+ );
473
+
474
+ // There may be additional state that has to be updated in this child. For example, if a summary is being
475
+ // tracked, the child's summary tracking state needs to be updated too. Same goes for pendingSummaries we might
476
+ // have outstanding on the parent in case we realize nodes in between Summary Op and Summary Ack.
477
+ this.maybeUpdateChildState(child);
478
+
479
+ this.children.set(id, child);
480
+ return child;
481
+ }
482
+
483
+ public getChild(id: string): ISummarizerNode | undefined {
484
+ return this.children.get(id);
485
+ }
486
+
487
+ /**
488
+ * Returns the details needed to create a child node.
489
+ * @param id - Initial id or path part of the child node.
490
+ * @param createParam - Information needed to create the node.
491
+ * @returns the details needed to create the child node.
492
+ */
493
+ protected getCreateDetailsForChild(
494
+ id: string,
495
+ createParam: CreateChildSummarizerNodeParam,
496
+ ): ICreateChildDetails {
497
+ let initialSummary: IInitialSummary | undefined;
498
+ let latestSummary: SummaryNode | undefined;
499
+ let changeSequenceNumber: number;
500
+
501
+ const parentLatestSummary = this._latestSummary;
502
+ switch (createParam.type) {
503
+ case CreateSummarizerNodeSource.FromAttach: {
504
+ if (
505
+ parentLatestSummary !== undefined &&
506
+ createParam.sequenceNumber <= parentLatestSummary.referenceSequenceNumber
507
+ ) {
508
+ // Prioritize latest summary if it was after this node was attached.
509
+ latestSummary = parentLatestSummary.createForChild(id);
510
+ } else {
511
+ const summary = convertToSummaryTree(
512
+ createParam.snapshot,
513
+ ) as ISummaryTreeWithStats;
514
+ initialSummary = {
515
+ sequenceNumber: createParam.sequenceNumber,
516
+ id,
517
+ summary,
518
+ };
519
+ }
520
+ changeSequenceNumber = createParam.sequenceNumber;
521
+ break;
522
+ }
523
+ case CreateSummarizerNodeSource.FromSummary: {
524
+ if (this.initialSummary === undefined) {
525
+ assert(
526
+ !!parentLatestSummary,
527
+ 0x1ac /* "Cannot create child from summary if parent does not have latest summary" */,
528
+ );
529
+ }
530
+ // fallthrough to local
531
+ }
532
+ case CreateSummarizerNodeSource.Local: {
533
+ const parentInitialSummary = this.initialSummary;
534
+ if (parentInitialSummary !== undefined) {
535
+ let childSummary: SummaryObject | undefined;
536
+ if (parentInitialSummary.summary !== undefined) {
537
+ const { childrenTree } = parseSummaryTreeForSubtrees(
538
+ parentInitialSummary.summary.summary,
539
+ );
540
+ assert(
541
+ childrenTree.type === SummaryType.Tree,
542
+ 0x1d6 /* "Parent summary object is not a tree" */,
543
+ );
544
+ childSummary = childrenTree.tree[id];
545
+ }
546
+ if (createParam.type === CreateSummarizerNodeSource.FromSummary) {
547
+ // Locally created would not have differential subtree.
548
+ assert(!!childSummary, 0x1ad /* "Missing child summary tree" */);
549
+ }
550
+ let childSummaryWithStats: ISummaryTreeWithStats | undefined;
551
+ if (childSummary !== undefined) {
552
+ assert(
553
+ childSummary.type === SummaryType.Tree,
554
+ 0x1ae /* "Child summary object is not a tree" */,
555
+ );
556
+ childSummaryWithStats = {
557
+ summary: childSummary,
558
+ stats: calculateStats(childSummary),
559
+ };
560
+ }
561
+ initialSummary = {
562
+ sequenceNumber: parentInitialSummary.sequenceNumber,
563
+ id,
564
+ summary: childSummaryWithStats,
565
+ };
566
+ }
567
+ latestSummary = parentLatestSummary?.createForChild(id);
568
+ changeSequenceNumber = parentLatestSummary?.referenceSequenceNumber ?? -1;
569
+ break;
570
+ }
571
+ default: {
572
+ const type = (createParam as unknown as CreateChildSummarizerNodeParam).type;
573
+ unreachableCase(createParam, `Unexpected CreateSummarizerNodeSource: ${type}`);
574
+ }
575
+ }
576
+
577
+ return {
578
+ initialSummary,
579
+ latestSummary,
580
+ changeSequenceNumber,
581
+ };
582
+ }
583
+
584
+ /**
585
+ * Updates the state of the child if required. For example, if a summary is currently being tracked, the child's
586
+ * summary tracking state needs to be updated too.
587
+ * Also, in case a child node gets realized in between Summary Op and Summary Ack, let's initialize the child's
588
+ * pending summary as well.
589
+ * @param child - The child node whose state is to be updated.
590
+ */
591
+ protected maybeUpdateChildState(child: SummarizerNode) {
592
+ // If we are tracking a summary, this child was created after the tracking started. So, we need to update the
593
+ // child's tracking state as well.
594
+ if (this.isTrackingInProgress()) {
595
+ child.wipReferenceSequenceNumber = this.wipReferenceSequenceNumber;
596
+ }
597
+ // In case we have pending summaries on the parent, let's initialize it on the child.
598
+ if (child._latestSummary !== undefined) {
599
+ for (const [key, value] of this.pendingSummaries.entries()) {
600
+ const newLatestSummaryNode = new SummaryNode({
601
+ referenceSequenceNumber: value.referenceSequenceNumber,
602
+ basePath: child._latestSummary.basePath,
603
+ localPath: child._latestSummary.localPath,
604
+ });
605
+
606
+ child.addPendingSummary(key, newLatestSummaryNode);
607
+ }
608
+ }
609
+ }
610
+
611
+ protected addPendingSummary(key: string, summary: SummaryNode) {
612
+ this.pendingSummaries.set(key, summary);
613
+ }
614
+ /**
615
+ * Tells whether summary tracking is in progress. True if "startSummary" API is called before summarize.
616
+ */
617
+ protected isTrackingInProgress(): boolean {
618
+ return this.wipReferenceSequenceNumber !== undefined;
619
+ }
570
620
  }
571
621
 
572
622
  /**
@@ -579,15 +629,18 @@ export class SummarizerNode implements IRootSummarizerNode {
579
629
  * @param config - Configure behavior of summarizer node
580
630
  */
581
631
  export const createRootSummarizerNode = (
582
- logger: ITelemetryLogger,
583
- summarizeInternalFn: SummarizeInternalFn,
584
- changeSequenceNumber: number,
585
- referenceSequenceNumber: number | undefined,
586
- config: ISummarizerNodeConfig = {},
587
- ): IRootSummarizerNode => new SummarizerNode(
588
- logger,
589
- summarizeInternalFn,
590
- config,
591
- changeSequenceNumber,
592
- referenceSequenceNumber === undefined ? undefined : SummaryNode.createForRoot(referenceSequenceNumber),
593
- );
632
+ logger: ITelemetryLogger,
633
+ summarizeInternalFn: SummarizeInternalFn,
634
+ changeSequenceNumber: number,
635
+ referenceSequenceNumber: number | undefined,
636
+ config: ISummarizerNodeConfig = {},
637
+ ): IRootSummarizerNode =>
638
+ new SummarizerNode(
639
+ logger,
640
+ summarizeInternalFn,
641
+ config,
642
+ changeSequenceNumber,
643
+ referenceSequenceNumber === undefined
644
+ ? undefined
645
+ : SummaryNode.createForRoot(referenceSequenceNumber),
646
+ );