@fluidframework/container-runtime 1.2.6 → 2.0.0-dev.1.3.0.96595

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 (221) hide show
  1. package/.mocharc.js +12 -0
  2. package/dist/batchManager.d.ts +37 -0
  3. package/dist/batchManager.d.ts.map +1 -0
  4. package/dist/batchManager.js +73 -0
  5. package/dist/batchManager.js.map +1 -0
  6. package/dist/batchTracker.d.ts +1 -2
  7. package/dist/batchTracker.d.ts.map +1 -1
  8. package/dist/batchTracker.js +2 -3
  9. package/dist/batchTracker.js.map +1 -1
  10. package/dist/blobManager.d.ts +87 -25
  11. package/dist/blobManager.d.ts.map +1 -1
  12. package/dist/blobManager.js +317 -99
  13. package/dist/blobManager.js.map +1 -1
  14. package/dist/containerRuntime.d.ts +109 -124
  15. package/dist/containerRuntime.d.ts.map +1 -1
  16. package/dist/containerRuntime.js +349 -542
  17. package/dist/containerRuntime.js.map +1 -1
  18. package/dist/dataStore.js +29 -24
  19. package/dist/dataStore.js.map +1 -1
  20. package/dist/dataStoreContext.d.ts +20 -14
  21. package/dist/dataStoreContext.d.ts.map +1 -1
  22. package/dist/dataStoreContext.js +49 -58
  23. package/dist/dataStoreContext.js.map +1 -1
  24. package/dist/dataStores.d.ts +12 -5
  25. package/dist/dataStores.d.ts.map +1 -1
  26. package/dist/dataStores.js +21 -20
  27. package/dist/dataStores.js.map +1 -1
  28. package/dist/deltaScheduler.d.ts +6 -4
  29. package/dist/deltaScheduler.d.ts.map +1 -1
  30. package/dist/deltaScheduler.js +6 -4
  31. package/dist/deltaScheduler.js.map +1 -1
  32. package/dist/garbageCollection.d.ts +74 -14
  33. package/dist/garbageCollection.d.ts.map +1 -1
  34. package/dist/garbageCollection.js +249 -170
  35. package/dist/garbageCollection.js.map +1 -1
  36. package/dist/gcSweepReadyUsageDetection.d.ts +53 -0
  37. package/dist/gcSweepReadyUsageDetection.d.ts.map +1 -0
  38. package/dist/gcSweepReadyUsageDetection.js +126 -0
  39. package/dist/gcSweepReadyUsageDetection.js.map +1 -0
  40. package/dist/index.d.ts +2 -1
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +3 -2
  43. package/dist/index.js.map +1 -1
  44. package/dist/opProperties.d.ts +7 -0
  45. package/dist/opProperties.d.ts.map +1 -0
  46. package/dist/opProperties.js +20 -0
  47. package/dist/opProperties.js.map +1 -0
  48. package/dist/orderedClientElection.d.ts +28 -10
  49. package/dist/orderedClientElection.d.ts.map +1 -1
  50. package/dist/orderedClientElection.js +14 -4
  51. package/dist/orderedClientElection.js.map +1 -1
  52. package/dist/packageVersion.d.ts +1 -1
  53. package/dist/packageVersion.d.ts.map +1 -1
  54. package/dist/packageVersion.js +1 -1
  55. package/dist/packageVersion.js.map +1 -1
  56. package/dist/pendingStateManager.d.ts +0 -11
  57. package/dist/pendingStateManager.d.ts.map +1 -1
  58. package/dist/pendingStateManager.js +24 -46
  59. package/dist/pendingStateManager.js.map +1 -1
  60. package/dist/runningSummarizer.d.ts +14 -4
  61. package/dist/runningSummarizer.d.ts.map +1 -1
  62. package/dist/runningSummarizer.js +68 -26
  63. package/dist/runningSummarizer.js.map +1 -1
  64. package/dist/scheduleManager.d.ts +31 -0
  65. package/dist/scheduleManager.d.ts.map +1 -0
  66. package/dist/scheduleManager.js +243 -0
  67. package/dist/scheduleManager.js.map +1 -0
  68. package/dist/summarizer.d.ts +0 -2
  69. package/dist/summarizer.d.ts.map +1 -1
  70. package/dist/summarizer.js +1 -12
  71. package/dist/summarizer.js.map +1 -1
  72. package/dist/summarizerHeuristics.d.ts +26 -4
  73. package/dist/summarizerHeuristics.d.ts.map +1 -1
  74. package/dist/summarizerHeuristics.js +95 -18
  75. package/dist/summarizerHeuristics.js.map +1 -1
  76. package/dist/summarizerTypes.d.ts +45 -18
  77. package/dist/summarizerTypes.d.ts.map +1 -1
  78. package/dist/summarizerTypes.js +1 -1
  79. package/dist/summarizerTypes.js.map +1 -1
  80. package/dist/summaryCollection.d.ts +1 -0
  81. package/dist/summaryCollection.d.ts.map +1 -1
  82. package/dist/summaryCollection.js +31 -15
  83. package/dist/summaryCollection.js.map +1 -1
  84. package/dist/summaryFormat.d.ts +0 -5
  85. package/dist/summaryFormat.d.ts.map +1 -1
  86. package/dist/summaryFormat.js.map +1 -1
  87. package/dist/summaryGenerator.d.ts +1 -0
  88. package/dist/summaryGenerator.d.ts.map +1 -1
  89. package/dist/summaryGenerator.js +11 -9
  90. package/dist/summaryGenerator.js.map +1 -1
  91. package/dist/summaryManager.d.ts +2 -2
  92. package/dist/summaryManager.d.ts.map +1 -1
  93. package/dist/summaryManager.js +22 -7
  94. package/dist/summaryManager.js.map +1 -1
  95. package/lib/batchManager.d.ts +37 -0
  96. package/lib/batchManager.d.ts.map +1 -0
  97. package/lib/batchManager.js +69 -0
  98. package/lib/batchManager.js.map +1 -0
  99. package/lib/batchTracker.d.ts +1 -2
  100. package/lib/batchTracker.d.ts.map +1 -1
  101. package/lib/batchTracker.js +2 -3
  102. package/lib/batchTracker.js.map +1 -1
  103. package/lib/blobManager.d.ts +87 -25
  104. package/lib/blobManager.d.ts.map +1 -1
  105. package/lib/blobManager.js +319 -101
  106. package/lib/blobManager.js.map +1 -1
  107. package/lib/containerRuntime.d.ts +109 -124
  108. package/lib/containerRuntime.d.ts.map +1 -1
  109. package/lib/containerRuntime.js +355 -547
  110. package/lib/containerRuntime.js.map +1 -1
  111. package/lib/dataStore.js +29 -24
  112. package/lib/dataStore.js.map +1 -1
  113. package/lib/dataStoreContext.d.ts +20 -14
  114. package/lib/dataStoreContext.d.ts.map +1 -1
  115. package/lib/dataStoreContext.js +46 -55
  116. package/lib/dataStoreContext.js.map +1 -1
  117. package/lib/dataStores.d.ts +12 -5
  118. package/lib/dataStores.d.ts.map +1 -1
  119. package/lib/dataStores.js +21 -20
  120. package/lib/dataStores.js.map +1 -1
  121. package/lib/deltaScheduler.d.ts +6 -4
  122. package/lib/deltaScheduler.d.ts.map +1 -1
  123. package/lib/deltaScheduler.js +6 -4
  124. package/lib/deltaScheduler.js.map +1 -1
  125. package/lib/garbageCollection.d.ts +74 -14
  126. package/lib/garbageCollection.d.ts.map +1 -1
  127. package/lib/garbageCollection.js +238 -160
  128. package/lib/garbageCollection.js.map +1 -1
  129. package/lib/gcSweepReadyUsageDetection.d.ts +53 -0
  130. package/lib/gcSweepReadyUsageDetection.d.ts.map +1 -0
  131. package/lib/gcSweepReadyUsageDetection.js +121 -0
  132. package/lib/gcSweepReadyUsageDetection.js.map +1 -0
  133. package/lib/index.d.ts +2 -1
  134. package/lib/index.d.ts.map +1 -1
  135. package/lib/index.js +2 -1
  136. package/lib/index.js.map +1 -1
  137. package/lib/opProperties.d.ts +7 -0
  138. package/lib/opProperties.d.ts.map +1 -0
  139. package/lib/opProperties.js +16 -0
  140. package/lib/opProperties.js.map +1 -0
  141. package/lib/orderedClientElection.d.ts +28 -10
  142. package/lib/orderedClientElection.d.ts.map +1 -1
  143. package/lib/orderedClientElection.js +14 -4
  144. package/lib/orderedClientElection.js.map +1 -1
  145. package/lib/packageVersion.d.ts +1 -1
  146. package/lib/packageVersion.d.ts.map +1 -1
  147. package/lib/packageVersion.js +1 -1
  148. package/lib/packageVersion.js.map +1 -1
  149. package/lib/pendingStateManager.d.ts +0 -11
  150. package/lib/pendingStateManager.d.ts.map +1 -1
  151. package/lib/pendingStateManager.js +24 -46
  152. package/lib/pendingStateManager.js.map +1 -1
  153. package/lib/runningSummarizer.d.ts +14 -4
  154. package/lib/runningSummarizer.d.ts.map +1 -1
  155. package/lib/runningSummarizer.js +68 -26
  156. package/lib/runningSummarizer.js.map +1 -1
  157. package/lib/scheduleManager.d.ts +31 -0
  158. package/lib/scheduleManager.d.ts.map +1 -0
  159. package/lib/scheduleManager.js +239 -0
  160. package/lib/scheduleManager.js.map +1 -0
  161. package/lib/summarizer.d.ts +0 -2
  162. package/lib/summarizer.d.ts.map +1 -1
  163. package/lib/summarizer.js +1 -12
  164. package/lib/summarizer.js.map +1 -1
  165. package/lib/summarizerHeuristics.d.ts +26 -4
  166. package/lib/summarizerHeuristics.d.ts.map +1 -1
  167. package/lib/summarizerHeuristics.js +95 -18
  168. package/lib/summarizerHeuristics.js.map +1 -1
  169. package/lib/summarizerTypes.d.ts +45 -18
  170. package/lib/summarizerTypes.d.ts.map +1 -1
  171. package/lib/summarizerTypes.js +1 -1
  172. package/lib/summarizerTypes.js.map +1 -1
  173. package/lib/summaryCollection.d.ts +1 -0
  174. package/lib/summaryCollection.d.ts.map +1 -1
  175. package/lib/summaryCollection.js +31 -15
  176. package/lib/summaryCollection.js.map +1 -1
  177. package/lib/summaryFormat.d.ts +0 -5
  178. package/lib/summaryFormat.d.ts.map +1 -1
  179. package/lib/summaryFormat.js.map +1 -1
  180. package/lib/summaryGenerator.d.ts +1 -0
  181. package/lib/summaryGenerator.d.ts.map +1 -1
  182. package/lib/summaryGenerator.js +11 -9
  183. package/lib/summaryGenerator.js.map +1 -1
  184. package/lib/summaryManager.d.ts +2 -2
  185. package/lib/summaryManager.d.ts.map +1 -1
  186. package/lib/summaryManager.js +22 -7
  187. package/lib/summaryManager.js.map +1 -1
  188. package/package.json +65 -24
  189. package/src/batchManager.ts +91 -0
  190. package/src/batchTracker.ts +2 -3
  191. package/src/blobManager.ts +385 -118
  192. package/src/containerRuntime.ts +529 -740
  193. package/src/dataStore.ts +49 -37
  194. package/src/dataStoreContext.ts +44 -56
  195. package/src/dataStores.ts +34 -30
  196. package/src/deltaScheduler.ts +6 -4
  197. package/src/garbageCollection.ts +297 -206
  198. package/src/gcSweepReadyUsageDetection.ts +139 -0
  199. package/src/index.ts +1 -2
  200. package/src/opProperties.ts +19 -0
  201. package/src/orderedClientElection.ts +31 -10
  202. package/src/packageVersion.ts +1 -1
  203. package/src/pendingStateManager.ts +27 -59
  204. package/src/runningSummarizer.ts +75 -22
  205. package/src/scheduleManager.ts +314 -0
  206. package/src/summarizer.ts +1 -18
  207. package/src/summarizerHeuristics.ts +133 -19
  208. package/src/summarizerTypes.ts +53 -18
  209. package/src/summaryCollection.ts +33 -18
  210. package/src/summaryFormat.ts +0 -6
  211. package/src/summaryGenerator.ts +40 -22
  212. package/src/summaryManager.ts +22 -7
  213. package/dist/opTelemetry.d.ts +0 -22
  214. package/dist/opTelemetry.d.ts.map +0 -1
  215. package/dist/opTelemetry.js +0 -59
  216. package/dist/opTelemetry.js.map +0 -1
  217. package/lib/opTelemetry.d.ts +0 -22
  218. package/lib/opTelemetry.d.ts.map +0 -1
  219. package/lib/opTelemetry.js +0 -55
  220. package/lib/opTelemetry.js.map +0 -1
  221. package/src/opTelemetry.ts +0 -71
@@ -51,7 +51,6 @@ export interface IRuntimeStateHandler {
51
51
  applyStashedOp: (type: ContainerMessageType, content: ISequencedDocumentMessage) => Promise<unknown>;
52
52
  flush(): void;
53
53
  reSubmit(type: ContainerMessageType, content: any, localOpMetadata: unknown, opMetadata: Record<string, unknown> | undefined): void;
54
- rollback(type: ContainerMessageType, content: any, localOpMetadata: unknown): void;
55
54
  }
56
55
  /**
57
56
  * PendingStateManager is responsible for maintaining the messages that have not been sent or have not yet been
@@ -126,20 +125,10 @@ export declare class PendingStateManager implements IDisposable {
126
125
  * @param message - The message that is being processed.
127
126
  */
128
127
  private maybeProcessBatchEnd;
129
- /**
130
- * Capture the pending state at this point
131
- */
132
- checkpoint(): {
133
- rollback: () => void;
134
- };
135
128
  /**
136
129
  * Returns the next pending state from the pending state queue.
137
130
  */
138
131
  private peekNextPendingState;
139
- /**
140
- * Undo the last pending state
141
- */
142
- private rollbackNextPendingState;
143
132
  /**
144
133
  * Called when the Container's connection state changes. If the Container gets connected, it replays all the pending
145
134
  * states in its queue. This includes setting the FlushMode and triggering resubmission of unacked ops.
@@ -1 +1 @@
1
- {"version":3,"file":"pendingStateManager.d.ts","sourceRoot":"","sources":["../src/pendingStateManager.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,oCAAoC,CAAC;AAEjE,OAAO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AAG,SAAS;gBAajC,YAAY,EAAE,oBAAoB,EACnD,gBAAgB,EAAE,SAAS,EAC3B,iBAAiB,EAAE,kBAAkB,GAAG,SAAS;IAQrD,IAAW,QAAQ,YAAyC;IAC5D,SAAgB,OAAO,aAAgC;IAEvD;;;;;;;OAOG;IACI,eAAe,CAClB,IAAI,EAAE,oBAAoB,EAC1B,oBAAoB,EAAE,MAAM,EAC5B,uBAAuB,EAAE,MAAM,EAC/B,OAAO,EAAE,GAAG,EACZ,eAAe,EAAE,OAAO,EACxB,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS;IAiBnD;;;OAGG;IACI,kBAAkB,CAAC,SAAS,EAAE,SAAS;IAI9C;;OAEG;IACI,OAAO;IAiBd;;;OAGG;IACU,iBAAiB,CAAC,MAAM,CAAC,EAAE,MAAM;IA8B9C;;;;OAIG;IACI,0BAA0B,CAAC,OAAO,EAAE,yBAAyB,GAAG,OAAO;IAiC9E;;;OAGG;IACH,OAAO,CAAC,sBAAsB;IAuD9B;;;OAGG;IACH,OAAO,CAAC,oBAAoB;IA0D5B;;OAEG;IACH,OAAO,CAAC,oBAAoB;IAM5B;;;OAGG;IACI,mBAAmB;CAsD7B"}
@@ -5,8 +5,8 @@
5
5
  import { assert, Lazy } from "@fluidframework/common-utils";
6
6
  import { DataProcessingError } from "@fluidframework/container-utils";
7
7
  import { FlushMode } from "@fluidframework/runtime-definitions";
8
- import { wrapError } from "@fluidframework/telemetry-utils";
9
8
  import Deque from "double-ended-queue";
9
+ import { pkgVersion } from "./packageVersion";
10
10
  /**
11
11
  * PendingStateManager is responsible for maintaining the messages that have not been sent or have not yet been
12
12
  * acknowledged by the server. It also maintains the batch information for both automatically and manually flushed
@@ -125,7 +125,11 @@ export class PendingStateManager {
125
125
  }
126
126
  // then we push onto pendingStates which will cause PendingStateManager to resubmit when we connect
127
127
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
128
- this.pendingStates.push(this.initialStates.shift());
128
+ const firstPendingState = this.initialStates.shift();
129
+ this.pendingStates.push(firstPendingState);
130
+ if (firstPendingState.type === "message") {
131
+ this._pendingMessagesCount++;
132
+ }
129
133
  }
130
134
  }
131
135
  /**
@@ -149,6 +153,7 @@ export class PendingStateManager {
149
153
  return;
150
154
  }
151
155
  this._pendingMessagesCount--;
156
+ assert(this._pendingMessagesCount >= 0, 0x3d6 /* positive */);
152
157
  // Post-processing part - If we are processing a batch then this could be the last message in the batch.
153
158
  this.maybeProcessBatchEnd(message);
154
159
  return pendingState.localOpMetadata;
@@ -164,9 +169,11 @@ export class PendingStateManager {
164
169
  let pendingFlush = false;
165
170
  /**
166
171
  * We are checking if the next message is the start of a batch. It can happen in the following scenarios:
172
+ *
167
173
  * 1. The FlushMode was set to TurnBased before this message was sent.
174
+ *
168
175
  * 2. The FlushMode was already TurnBased and a flush was called before this message was sent. This essentially
169
- * means that the flush marked the end of a previous batch and beginning of a new batch.
176
+ * means that the flush marked the end of a previous batch and beginning of a new batch.
170
177
  *
171
178
  * Keep reading pending states from the queue until we encounter a message. It's possible that the FlushMode was
172
179
  * updated a bunch of times without sending any messages.
@@ -234,35 +241,25 @@ export class PendingStateManager {
234
241
  else {
235
242
  // Get the batch metadata from the last message in the batch.
236
243
  const batchEndMetadata = (_b = message.metadata) === null || _b === void 0 ? void 0 : _b.batch;
237
- assert(batchBeginMetadata === true, 0x16f /* "Did not receive batch begin metadata" */);
238
- assert(batchEndMetadata === false, 0x170 /* "Did not receive batch end metadata" */);
244
+ if (batchBeginMetadata !== true || batchEndMetadata !== false) {
245
+ this.stateHandler.close(DataProcessingError.create("Pending batch inconsistency", // Formerly known as asserts 0x16f and 0x170
246
+ "processPendingLocalMessage", message, {
247
+ runtimeVersion: pkgVersion,
248
+ batchClientId: this.pendingBatchBeginMessage.clientId,
249
+ clientId: this.stateHandler.clientId(),
250
+ hasBatchStart: batchBeginMetadata === true,
251
+ hasBatchEnd: batchEndMetadata === false,
252
+ messageType: message.type,
253
+ batchStartSequenceNumber: this.pendingBatchBeginMessage.clientSequenceNumber,
254
+ pendingMessagesCount: this.pendingMessagesCount,
255
+ nextPendingState: nextPendingState.type,
256
+ }));
257
+ }
239
258
  }
240
259
  // Clear the pending batch state now that we have processed the entire batch.
241
260
  this.pendingBatchBeginMessage = undefined;
242
261
  this.isProcessingBatch = false;
243
262
  }
244
- /**
245
- * Capture the pending state at this point
246
- */
247
- checkpoint() {
248
- const checkpointHead = this.pendingStates.peekBack();
249
- return {
250
- rollback: () => {
251
- try {
252
- while (this.pendingStates.peekBack() !== checkpointHead) {
253
- this.rollbackNextPendingState();
254
- }
255
- }
256
- catch (err) {
257
- const error = wrapError(err, (message) => {
258
- return DataProcessingError.create(`RollbackError: ${message}`, "checkpointRollback", undefined);
259
- });
260
- this.stateHandler.close(error);
261
- throw error;
262
- }
263
- },
264
- };
265
- }
266
263
  /**
267
264
  * Returns the next pending state from the pending state queue.
268
265
  */
@@ -271,25 +268,6 @@ export class PendingStateManager {
271
268
  assert(!!nextPendingState, 0x171 /* "No pending state found for the remote message" */);
272
269
  return nextPendingState;
273
270
  }
274
- /**
275
- * Undo the last pending state
276
- */
277
- rollbackNextPendingState() {
278
- const pendingStatesCount = this.pendingStates.length;
279
- if (pendingStatesCount === 0) {
280
- return;
281
- }
282
- this._pendingMessagesCount--;
283
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
284
- const pendingState = this.pendingStates.pop();
285
- switch (pendingState.type) {
286
- case "message":
287
- this.stateHandler.rollback(pendingState.messageType, pendingState.content, pendingState.localOpMetadata);
288
- break;
289
- default:
290
- throw new Error(`Can't rollback state ${pendingState.type}`);
291
- }
292
- }
293
271
  /**
294
272
  * Called when the Container's connection state changes. If the Container gets connected, it replays all the pending
295
273
  * states in its queue. This includes setting the FlushMode and triggering resubmission of unacked ops.
@@ -1 +1 @@
1
- {"version":3,"file":"pendingStateManager.js","sourceRoot":"","sources":["../src/pendingStateManager.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA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AAC,YAAY,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;QAE7D,0GAA0G;QAC1G,0GAA0G;QAC1G,8BAA8B;QAC9B,OAAO,kBAAkB,GAAG,CAAC,EAAE;YAC3B,oEAAoE;YACpE,MAAM,YAAY,GAAG,IAAI,CAAC,aAAa,CAAC,KAAK,EAAG,CAAC;YACjD,QAAQ,YAAY,CAAC,IAAI,EAAE;gBACvB,KAAK,SAAS;oBACV,IAAI,CAAC,YAAY,CAAC,QAAQ,CACtB,YAAY,CAAC,WAAW,EACxB,YAAY,CAAC,OAAO,EACpB,YAAY,CAAC,eAAe,EAC5B,YAAY,CAAC,UAAU,CAAC,CAAC;oBAC7B,MAAM;gBACV,KAAK,WAAW;oBACZ,IAAI,CAAC,YAAY,CAAC,YAAY,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;oBACvD,MAAM;gBACV,KAAK,OAAO;oBACR,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,CAAC;oBAC1B,MAAM;gBACV;oBACI,MAAM;aACb;YACD,kBAAkB,EAAE,CAAC;SACxB;QAED,wBAAwB;QACxB,IAAI,CAAC,YAAY,CAAC,YAAY,CAAC,cAAc,CAAC,CAAC;IACnD,CAAC;CACJ","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { IDisposable } from \"@fluidframework/common-definitions\";\nimport { assert, Lazy } from \"@fluidframework/common-utils\";\nimport { ICriticalContainerError } from \"@fluidframework/container-definitions\";\nimport { DataProcessingError } from \"@fluidframework/container-utils\";\nimport {\n ISequencedDocumentMessage,\n} from \"@fluidframework/protocol-definitions\";\nimport { FlushMode } from \"@fluidframework/runtime-definitions\";\nimport { wrapError } from \"@fluidframework/telemetry-utils\";\nimport Deque from \"double-ended-queue\";\nimport { ContainerMessageType } from \"./containerRuntime\";\n\n/**\n * This represents a message that has been submitted and is added to the pending queue when `submit` is called on the\n * ContainerRuntime. This message has either not been ack'd by the server or has not been submitted to the server yet.\n */\nexport interface IPendingMessage {\n type: \"message\";\n messageType: ContainerMessageType;\n clientSequenceNumber: number;\n referenceSequenceNumber: number;\n content: any;\n localOpMetadata: unknown;\n opMetadata: Record<string, unknown> | undefined;\n}\n\n/**\n * This represents a FlushMode update and is added to the pending queue when `setFlushMode` is called on the\n * ContainerRuntime and the FlushMode changes.\n */\nexport interface IPendingFlushMode {\n type: \"flushMode\";\n flushMode: FlushMode;\n}\n\n/**\n * This represents an explicit flush call and is added to the pending queue when flush is called on the ContainerRuntime\n * to flush pending messages.\n */\nexport interface IPendingFlush {\n type: \"flush\";\n}\n\nexport type IPendingState = IPendingMessage | IPendingFlushMode | IPendingFlush;\n\nexport interface IPendingLocalState {\n /**\n * list of pending states, including ops and batch information\n */\n pendingStates: IPendingState[];\n}\n\nexport interface IRuntimeStateHandler{\n connected(): boolean;\n clientId(): string | undefined;\n flushMode(): FlushMode;\n setFlushMode(mode: FlushMode): void;\n close(error?: ICriticalContainerError): void;\n applyStashedOp: (type: ContainerMessageType, content: ISequencedDocumentMessage) => Promise<unknown>;\n flush(): void;\n reSubmit(\n type: ContainerMessageType,\n content: any,\n localOpMetadata: unknown,\n opMetadata: Record<string, unknown> | undefined): void;\n rollback(\n type: ContainerMessageType,\n content: any,\n localOpMetadata: unknown): void;\n}\n\n/**\n * PendingStateManager is responsible for maintaining the messages that have not been sent or have not yet been\n * acknowledged by the server. It also maintains the batch information for both automatically and manually flushed\n * batches along with the messages.\n * When the Container reconnects, it replays the pending states, which includes setting the FlushMode, manual flushing\n * of messages and triggering resubmission of unacked ops.\n *\n * It verifies that all the ops are acked, are received in the right order and batch information is correct.\n */\nexport class PendingStateManager implements IDisposable {\n private readonly pendingStates = new Deque<IPendingState>();\n private readonly initialStates: Deque<IPendingState>;\n private readonly disposeOnce = new Lazy<void>(() => {\n this.initialStates.clear();\n this.pendingStates.clear();\n });\n\n // Maintains the count of messages that are currently unacked.\n private _pendingMessagesCount: number = 0;\n public get pendingMessagesCount(): number {\n return this._pendingMessagesCount;\n }\n\n // Indicates whether we are processing a batch.\n private isProcessingBatch: boolean = false;\n\n // This stores the first message in the batch that we are processing. This is used to verify that we get\n // the correct batch metadata.\n private pendingBatchBeginMessage: ISequencedDocumentMessage | undefined;\n\n /**\n * This tracks the flush mode for the next message in the pending state queue. When replaying messages, we need to\n * first set the flush mode to this value and then send ops. It is important to do this info because the flush\n * mode could have been updated.\n */\n private flushModeForNextMessage: FlushMode;\n\n private clientId: string | undefined;\n\n /**\n * Called to check if there are any pending messages in the pending state queue.\n * @returns A boolean indicating whether there are messages or not.\n */\n public hasPendingMessages(): boolean {\n return this._pendingMessagesCount !== 0 || !this.initialStates.isEmpty();\n }\n\n public getLocalState(): IPendingLocalState | undefined {\n assert(this.initialStates.isEmpty(), 0x2e9 /* \"Must call getLocalState() after applying initial states\" */);\n if (this.hasPendingMessages()) {\n return {\n pendingStates: this.pendingStates.toArray().map(\n // delete localOpMetadata since it may not be serializable\n // and will be regenerated by applyStashedOp()\n (state) => state.type === \"message\" ? { ...state, localOpMetadata: undefined } : state),\n };\n }\n }\n\n constructor(\n private readonly stateHandler: IRuntimeStateHandler,\n initialFlushMode: FlushMode,\n initialLocalState: IPendingLocalState | undefined,\n ) {\n this.initialStates = new Deque<IPendingState>(initialLocalState?.pendingStates ?? []);\n\n this.flushModeForNextMessage = initialFlushMode;\n this.onFlushModeUpdated(initialFlushMode);\n }\n\n public get disposed() { return this.disposeOnce.evaluated; }\n public readonly dispose = () => this.disposeOnce.value;\n\n /**\n * Called when a message is submitted locally. Adds the message and the associated details to the pending state\n * queue.\n * @param type - The container message type.\n * @param clientSequenceNumber - The clientSequenceNumber associated with the message.\n * @param content - The message content.\n * @param localOpMetadata - The local metadata associated with the message.\n */\n public onSubmitMessage(\n type: ContainerMessageType,\n clientSequenceNumber: number,\n referenceSequenceNumber: number,\n content: any,\n localOpMetadata: unknown,\n opMetadata: Record<string, unknown> | undefined,\n ) {\n const pendingMessage: IPendingMessage = {\n type: \"message\",\n messageType: type,\n clientSequenceNumber,\n referenceSequenceNumber,\n content,\n localOpMetadata,\n opMetadata,\n };\n\n this.pendingStates.push(pendingMessage);\n\n this._pendingMessagesCount++;\n }\n\n /**\n * Called when the FlushMode is updated. Adds the FlushMode to the pending state queue.\n * @param flushMode - The flushMode that was updated.\n */\n public onFlushModeUpdated(flushMode: FlushMode) {\n this.pendingStates.push({ type: \"flushMode\", flushMode });\n }\n\n /**\n * Called when flush() is called on the ContainerRuntime to manually flush messages.\n */\n public onFlush() {\n // If the FlushMode is Immediate, we don't need to track an explicit flush call because every message is\n // automatically flushed. So, flush is a no-op.\n if (this.stateHandler.flushMode() === FlushMode.Immediate) {\n return;\n }\n\n // If the previous state is not a message, flush is a no-op.\n const previousState = this.pendingStates.peekBack();\n if (previousState?.type !== \"message\") {\n return;\n }\n\n // An explicit flush is interesting and is tracked only if there are messages sent in TurnBased mode.\n this.pendingStates.push({ type: \"flush\" });\n }\n\n /**\n * Applies stashed ops at their reference sequence number so they are ready to be ACKed or resubmitted\n * @param seqNum - Sequence number at which to apply ops. Will apply all ops if seqNum is undefined.\n */\n public async applyStashedOpsAt(seqNum?: number) {\n // apply stashed ops at sequence number\n while (!this.initialStates.isEmpty()) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const nextState = this.initialStates.peekFront()!;\n if (nextState.type === \"message\") {\n if (seqNum !== undefined) {\n if (nextState.referenceSequenceNumber > seqNum) {\n break; // nothing left to do at this sequence number\n } else if (nextState.referenceSequenceNumber < seqNum) {\n throw new Error(\"loaded from snapshot too recent to apply stashed ops\");\n }\n }\n\n // applyStashedOp will cause the DDS to behave as if it has sent the op but not actually send it\n const localOpMetadata =\n await this.stateHandler.applyStashedOp(nextState.messageType, nextState.content);\n nextState.localOpMetadata = localOpMetadata;\n }\n\n // then we push onto pendingStates which will cause PendingStateManager to resubmit when we connect\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.pendingStates.push(this.initialStates.shift()!);\n }\n }\n\n /**\n * Processes a local message once its ack'd by the server. It verifies that there was no data corruption and that\n * the batch information was preserved for batch messages.\n * @param message - The message that got ack'd and needs to be processed.\n */\n public processPendingLocalMessage(message: ISequencedDocumentMessage): unknown {\n // Pre-processing part - This may be the start of a batch.\n this.maybeProcessBatchBegin(message);\n\n // Get the next state from the pending queue and verify that it is of type \"message\".\n const pendingState = this.peekNextPendingState();\n assert(pendingState.type === \"message\", 0x169 /* \"No pending message found for this remote message\" */);\n this.pendingStates.shift();\n\n // Processing part - Verify that there has been no data corruption.\n // The clientSequenceNumber of the incoming message must match that of the pending message.\n if (pendingState.clientSequenceNumber !== message.clientSequenceNumber) {\n // Close the container because this could indicate data corruption.\n const error = DataProcessingError.create(\n \"pending local message clientSequenceNumber mismatch\",\n \"unexpectedAckReceived\",\n message,\n { expectedClientSequenceNumber: pendingState.clientSequenceNumber },\n );\n\n this.stateHandler.close(error);\n return;\n }\n\n this._pendingMessagesCount--;\n\n // Post-processing part - If we are processing a batch then this could be the last message in the batch.\n this.maybeProcessBatchEnd(message);\n\n return pendingState.localOpMetadata;\n }\n\n /**\n * This message could be the first message in batch. If so, set batch state marking the beginning of a batch.\n * @param message - The message that is being processed.\n */\n private maybeProcessBatchBegin(message: ISequencedDocumentMessage) {\n // Tracks the last FlushMode that was set before this message was sent.\n let pendingFlushMode: FlushMode | undefined;\n // Tracks whether a flush was called before this message was sent.\n let pendingFlush: boolean = false;\n\n /**\n * We are checking if the next message is the start of a batch. It can happen in the following scenarios:\n * 1. The FlushMode was set to TurnBased before this message was sent.\n * 2. The FlushMode was already TurnBased and a flush was called before this message was sent. This essentially\n * means that the flush marked the end of a previous batch and beginning of a new batch.\n *\n * Keep reading pending states from the queue until we encounter a message. It's possible that the FlushMode was\n * updated a bunch of times without sending any messages.\n */\n let nextPendingState = this.peekNextPendingState();\n while (nextPendingState.type !== \"message\") {\n if (nextPendingState.type === \"flushMode\") {\n pendingFlushMode = nextPendingState.flushMode;\n }\n if (nextPendingState.type === \"flush\") {\n pendingFlush = true;\n }\n this.pendingStates.shift();\n nextPendingState = this.peekNextPendingState();\n }\n\n if (pendingFlushMode !== undefined) {\n this.flushModeForNextMessage = pendingFlushMode;\n }\n\n // If the FlushMode was set to Immediate before this message was sent, this message won't be a batch message\n // because in Immediate mode, every message is flushed individually.\n if (pendingFlushMode === FlushMode.Immediate) {\n return;\n }\n\n /**\n * This message is the first in a batch if before it was sent either the FlushMode was set to TurnBased or there\n * was an explicit flush call. Note that a flush call is tracked only in TurnBased mode and it indicates the end\n * of one batch and beginning of another.\n */\n if (pendingFlushMode === FlushMode.TurnBased || pendingFlush) {\n // We should not already be processing a batch and there should be no pending batch begin message.\n assert(!this.isProcessingBatch && this.pendingBatchBeginMessage === undefined,\n 0x16b /* \"The pending batch state indicates we are already processing a batch\" */);\n\n // Set the pending batch state indicating we have started processing a batch.\n this.pendingBatchBeginMessage = message;\n this.isProcessingBatch = true;\n }\n }\n\n /**\n * This message could be the last message in batch. If so, clear batch state since the batch is complete.\n * @param message - The message that is being processed.\n */\n private maybeProcessBatchEnd(message: ISequencedDocumentMessage) {\n if (!this.isProcessingBatch) {\n return;\n }\n\n const nextPendingState = this.peekNextPendingState();\n if (nextPendingState.type === \"message\") {\n return;\n }\n\n /**\n * We are in the middle of processing a batch. The batch ends when we see an explicit flush. We should never see\n * a FlushMode before flush. This is true because we track batches only when FlushMode is TurnBased and in this\n * mode, a batch ends either by calling flush or by changing the mode to Immediate which also triggers a flush.\n */\n assert(\n nextPendingState.type !== \"flushMode\",\n 0x2bd /* \"We should not see a pending FlushMode until we see a flush when processing a batch\" */,\n );\n\n // There should be a pending batch begin message.\n assert(this.pendingBatchBeginMessage !== undefined, 0x16d /* \"There is no pending batch begin message\" */);\n\n // Get the batch begin metadata from the first message in the batch.\n const batchBeginMetadata = this.pendingBatchBeginMessage.metadata?.batch;\n\n // There could be just a single message in the batch. If so, it should not have any batch metadata. If there\n // are multiple messages in the batch, verify that we got the correct batch begin and end metadata.\n if (this.pendingBatchBeginMessage === message) {\n assert(batchBeginMetadata === undefined,\n 0x16e /* \"Batch with single message should not have batch metadata\" */);\n } else {\n // Get the batch metadata from the last message in the batch.\n const batchEndMetadata = message.metadata?.batch;\n assert(batchBeginMetadata === true, 0x16f /* \"Did not receive batch begin metadata\" */);\n assert(batchEndMetadata === false, 0x170 /* \"Did not receive batch end metadata\" */);\n }\n\n // Clear the pending batch state now that we have processed the entire batch.\n this.pendingBatchBeginMessage = undefined;\n this.isProcessingBatch = false;\n }\n\n /**\n * Capture the pending state at this point\n */\n public checkpoint() {\n const checkpointHead = this.pendingStates.peekBack();\n return {\n rollback: () => {\n try {\n while (this.pendingStates.peekBack() !== checkpointHead) {\n this.rollbackNextPendingState();\n }\n } catch (err) {\n const error = wrapError(err, (message) => {\n return DataProcessingError.create(\n `RollbackError: ${message}`,\n \"checkpointRollback\",\n undefined) as DataProcessingError;\n });\n this.stateHandler.close(error);\n throw error;\n }\n },\n };\n }\n\n /**\n * Returns the next pending state from the pending state queue.\n */\n private peekNextPendingState(): IPendingState {\n const nextPendingState = this.pendingStates.peekFront();\n assert(!!nextPendingState, 0x171 /* \"No pending state found for the remote message\" */);\n return nextPendingState;\n }\n\n /**\n * Undo the last pending state\n */\n private rollbackNextPendingState() {\n const pendingStatesCount = this.pendingStates.length;\n if (pendingStatesCount === 0) {\n return;\n }\n\n this._pendingMessagesCount--;\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const pendingState = this.pendingStates.pop()!;\n switch (pendingState.type) {\n case \"message\":\n this.stateHandler.rollback(\n pendingState.messageType,\n pendingState.content,\n pendingState.localOpMetadata);\n break;\n default:\n throw new Error(`Can't rollback state ${pendingState.type}`);\n }\n }\n\n /**\n * Called when the Container's connection state changes. If the Container gets connected, it replays all the pending\n * states in its queue. This includes setting the FlushMode and triggering resubmission of unacked ops.\n */\n public replayPendingStates() {\n assert(this.stateHandler.connected(), 0x172 /* \"The connection state is not consistent with the runtime\" */);\n\n // This assert suggests we are about to send same ops twice, which will result in data loss.\n assert(this.clientId !== this.stateHandler.clientId(),\n 0x173 /* \"replayPendingStates called twice for same clientId!\" */);\n this.clientId = this.stateHandler.clientId();\n\n assert(this.initialStates.isEmpty(), 0x174 /* \"initial states should be empty before replaying pending\" */);\n\n let pendingStatesCount = this.pendingStates.length;\n if (pendingStatesCount === 0) {\n return;\n }\n\n // Reset the pending message count because all these messages will be removed from the queue.\n this._pendingMessagesCount = 0;\n\n // Save the current FlushMode so that we can revert it back after replaying the states.\n const savedFlushMode = this.stateHandler.flushMode();\n\n // Set the flush mode for the next message. This step is important because the flush mode may have been changed\n // after the next pending message was sent.\n this.stateHandler.setFlushMode(this.flushModeForNextMessage);\n\n // Process exactly `pendingStatesCount` items in the queue as it represents the number of states that were\n // pending when we connected. This is important because the `reSubmitFn` might add more items in the queue\n // which must not be replayed.\n while (pendingStatesCount > 0) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const pendingState = this.pendingStates.shift()!;\n switch (pendingState.type) {\n case \"message\":\n this.stateHandler.reSubmit(\n pendingState.messageType,\n pendingState.content,\n pendingState.localOpMetadata,\n pendingState.opMetadata);\n break;\n case \"flushMode\":\n this.stateHandler.setFlushMode(pendingState.flushMode);\n break;\n case \"flush\":\n this.stateHandler.flush();\n break;\n default:\n break;\n }\n pendingStatesCount--;\n }\n\n // Revert the FlushMode.\n this.stateHandler.setFlushMode(savedFlushMode);\n }\n}\n"]}
1
+ {"version":3,"file":"pendingStateManager.js","sourceRoot":"","sources":["../src/pendingStateManager.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,8BAA8B,CAAC;AAE5D,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AAItE,OAAO,EAAE,SAAS,EAAE,MAAM,qCAAqC,CAAC;AAChE,OAAO,KAAK,MAAM,oBAAoB,CAAC;AAEvC,OAAO,EAAE,UAAU,EAAE,MAAM,kB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AC,YAAY,CAAC,cAAc,CAAC,CAAC;IACnD,CAAC;CACJ","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { IDisposable } from \"@fluidframework/common-definitions\";\nimport { assert, Lazy } from \"@fluidframework/common-utils\";\nimport { ICriticalContainerError } from \"@fluidframework/container-definitions\";\nimport { DataProcessingError } from \"@fluidframework/container-utils\";\nimport {\n ISequencedDocumentMessage,\n} from \"@fluidframework/protocol-definitions\";\nimport { FlushMode } from \"@fluidframework/runtime-definitions\";\nimport Deque from \"double-ended-queue\";\nimport { ContainerMessageType } from \"./containerRuntime\";\nimport { pkgVersion } from \"./packageVersion\";\n\n/**\n * This represents a message that has been submitted and is added to the pending queue when `submit` is called on the\n * ContainerRuntime. This message has either not been ack'd by the server or has not been submitted to the server yet.\n */\nexport interface IPendingMessage {\n type: \"message\";\n messageType: ContainerMessageType;\n clientSequenceNumber: number;\n referenceSequenceNumber: number;\n content: any;\n localOpMetadata: unknown;\n opMetadata: Record<string, unknown> | undefined;\n}\n\n/**\n * This represents a FlushMode update and is added to the pending queue when `setFlushMode` is called on the\n * ContainerRuntime and the FlushMode changes.\n */\nexport interface IPendingFlushMode {\n type: \"flushMode\";\n flushMode: FlushMode;\n}\n\n/**\n * This represents an explicit flush call and is added to the pending queue when flush is called on the ContainerRuntime\n * to flush pending messages.\n */\nexport interface IPendingFlush {\n type: \"flush\";\n}\n\nexport type IPendingState = IPendingMessage | IPendingFlushMode | IPendingFlush;\n\nexport interface IPendingLocalState {\n /**\n * list of pending states, including ops and batch information\n */\n pendingStates: IPendingState[];\n}\n\nexport interface IRuntimeStateHandler{\n connected(): boolean;\n clientId(): string | undefined;\n flushMode(): FlushMode;\n setFlushMode(mode: FlushMode): void;\n close(error?: ICriticalContainerError): void;\n applyStashedOp: (type: ContainerMessageType, content: ISequencedDocumentMessage) => Promise<unknown>;\n flush(): void;\n reSubmit(\n type: ContainerMessageType,\n content: any,\n localOpMetadata: unknown,\n opMetadata: Record<string, unknown> | undefined): void;\n}\n\n/**\n * PendingStateManager is responsible for maintaining the messages that have not been sent or have not yet been\n * acknowledged by the server. It also maintains the batch information for both automatically and manually flushed\n * batches along with the messages.\n * When the Container reconnects, it replays the pending states, which includes setting the FlushMode, manual flushing\n * of messages and triggering resubmission of unacked ops.\n *\n * It verifies that all the ops are acked, are received in the right order and batch information is correct.\n */\nexport class PendingStateManager implements IDisposable {\n private readonly pendingStates = new Deque<IPendingState>();\n private readonly initialStates: Deque<IPendingState>;\n private readonly disposeOnce = new Lazy<void>(() => {\n this.initialStates.clear();\n this.pendingStates.clear();\n });\n\n // Maintains the count of messages that are currently unacked.\n private _pendingMessagesCount: number = 0;\n public get pendingMessagesCount(): number {\n return this._pendingMessagesCount;\n }\n\n // Indicates whether we are processing a batch.\n private isProcessingBatch: boolean = false;\n\n // This stores the first message in the batch that we are processing. This is used to verify that we get\n // the correct batch metadata.\n private pendingBatchBeginMessage: ISequencedDocumentMessage | undefined;\n\n /**\n * This tracks the flush mode for the next message in the pending state queue. When replaying messages, we need to\n * first set the flush mode to this value and then send ops. It is important to do this info because the flush\n * mode could have been updated.\n */\n private flushModeForNextMessage: FlushMode;\n\n private clientId: string | undefined;\n\n /**\n * Called to check if there are any pending messages in the pending state queue.\n * @returns A boolean indicating whether there are messages or not.\n */\n public hasPendingMessages(): boolean {\n return this._pendingMessagesCount !== 0 || !this.initialStates.isEmpty();\n }\n\n public getLocalState(): IPendingLocalState | undefined {\n assert(this.initialStates.isEmpty(), 0x2e9 /* \"Must call getLocalState() after applying initial states\" */);\n if (this.hasPendingMessages()) {\n return {\n pendingStates: this.pendingStates.toArray().map(\n // delete localOpMetadata since it may not be serializable\n // and will be regenerated by applyStashedOp()\n (state) => state.type === \"message\" ? { ...state, localOpMetadata: undefined } : state),\n };\n }\n }\n\n constructor(\n private readonly stateHandler: IRuntimeStateHandler,\n initialFlushMode: FlushMode,\n initialLocalState: IPendingLocalState | undefined,\n ) {\n this.initialStates = new Deque<IPendingState>(initialLocalState?.pendingStates ?? []);\n\n this.flushModeForNextMessage = initialFlushMode;\n this.onFlushModeUpdated(initialFlushMode);\n }\n\n public get disposed() { return this.disposeOnce.evaluated; }\n public readonly dispose = () => this.disposeOnce.value;\n\n /**\n * Called when a message is submitted locally. Adds the message and the associated details to the pending state\n * queue.\n * @param type - The container message type.\n * @param clientSequenceNumber - The clientSequenceNumber associated with the message.\n * @param content - The message content.\n * @param localOpMetadata - The local metadata associated with the message.\n */\n public onSubmitMessage(\n type: ContainerMessageType,\n clientSequenceNumber: number,\n referenceSequenceNumber: number,\n content: any,\n localOpMetadata: unknown,\n opMetadata: Record<string, unknown> | undefined,\n ) {\n const pendingMessage: IPendingMessage = {\n type: \"message\",\n messageType: type,\n clientSequenceNumber,\n referenceSequenceNumber,\n content,\n localOpMetadata,\n opMetadata,\n };\n\n this.pendingStates.push(pendingMessage);\n\n this._pendingMessagesCount++;\n }\n\n /**\n * Called when the FlushMode is updated. Adds the FlushMode to the pending state queue.\n * @param flushMode - The flushMode that was updated.\n */\n public onFlushModeUpdated(flushMode: FlushMode) {\n this.pendingStates.push({ type: \"flushMode\", flushMode });\n }\n\n /**\n * Called when flush() is called on the ContainerRuntime to manually flush messages.\n */\n public onFlush() {\n // If the FlushMode is Immediate, we don't need to track an explicit flush call because every message is\n // automatically flushed. So, flush is a no-op.\n if (this.stateHandler.flushMode() === FlushMode.Immediate) {\n return;\n }\n\n // If the previous state is not a message, flush is a no-op.\n const previousState = this.pendingStates.peekBack();\n if (previousState?.type !== \"message\") {\n return;\n }\n\n // An explicit flush is interesting and is tracked only if there are messages sent in TurnBased mode.\n this.pendingStates.push({ type: \"flush\" });\n }\n\n /**\n * Applies stashed ops at their reference sequence number so they are ready to be ACKed or resubmitted\n * @param seqNum - Sequence number at which to apply ops. Will apply all ops if seqNum is undefined.\n */\n public async applyStashedOpsAt(seqNum?: number) {\n // apply stashed ops at sequence number\n while (!this.initialStates.isEmpty()) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const nextState = this.initialStates.peekFront()!;\n if (nextState.type === \"message\") {\n if (seqNum !== undefined) {\n if (nextState.referenceSequenceNumber > seqNum) {\n break; // nothing left to do at this sequence number\n } else if (nextState.referenceSequenceNumber < seqNum) {\n throw new Error(\"loaded from snapshot too recent to apply stashed ops\");\n }\n }\n\n // applyStashedOp will cause the DDS to behave as if it has sent the op but not actually send it\n const localOpMetadata =\n await this.stateHandler.applyStashedOp(nextState.messageType, nextState.content);\n nextState.localOpMetadata = localOpMetadata;\n }\n\n // then we push onto pendingStates which will cause PendingStateManager to resubmit when we connect\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const firstPendingState = this.initialStates.shift()!;\n this.pendingStates.push(firstPendingState);\n if (firstPendingState.type === \"message\") {\n this._pendingMessagesCount++;\n }\n }\n }\n\n /**\n * Processes a local message once its ack'd by the server. It verifies that there was no data corruption and that\n * the batch information was preserved for batch messages.\n * @param message - The message that got ack'd and needs to be processed.\n */\n public processPendingLocalMessage(message: ISequencedDocumentMessage): unknown {\n // Pre-processing part - This may be the start of a batch.\n this.maybeProcessBatchBegin(message);\n\n // Get the next state from the pending queue and verify that it is of type \"message\".\n const pendingState = this.peekNextPendingState();\n assert(pendingState.type === \"message\", 0x169 /* \"No pending message found for this remote message\" */);\n this.pendingStates.shift();\n\n // Processing part - Verify that there has been no data corruption.\n // The clientSequenceNumber of the incoming message must match that of the pending message.\n if (pendingState.clientSequenceNumber !== message.clientSequenceNumber) {\n // Close the container because this could indicate data corruption.\n const error = DataProcessingError.create(\n \"pending local message clientSequenceNumber mismatch\",\n \"unexpectedAckReceived\",\n message,\n { expectedClientSequenceNumber: pendingState.clientSequenceNumber },\n );\n\n this.stateHandler.close(error);\n return;\n }\n\n this._pendingMessagesCount--;\n assert(this._pendingMessagesCount >= 0, 0x3d6 /* positive */);\n\n // Post-processing part - If we are processing a batch then this could be the last message in the batch.\n this.maybeProcessBatchEnd(message);\n\n return pendingState.localOpMetadata;\n }\n\n /**\n * This message could be the first message in batch. If so, set batch state marking the beginning of a batch.\n * @param message - The message that is being processed.\n */\n private maybeProcessBatchBegin(message: ISequencedDocumentMessage) {\n // Tracks the last FlushMode that was set before this message was sent.\n let pendingFlushMode: FlushMode | undefined;\n // Tracks whether a flush was called before this message was sent.\n let pendingFlush: boolean = false;\n\n /**\n * We are checking if the next message is the start of a batch. It can happen in the following scenarios:\n *\n * 1. The FlushMode was set to TurnBased before this message was sent.\n *\n * 2. The FlushMode was already TurnBased and a flush was called before this message was sent. This essentially\n * means that the flush marked the end of a previous batch and beginning of a new batch.\n *\n * Keep reading pending states from the queue until we encounter a message. It's possible that the FlushMode was\n * updated a bunch of times without sending any messages.\n */\n let nextPendingState = this.peekNextPendingState();\n while (nextPendingState.type !== \"message\") {\n if (nextPendingState.type === \"flushMode\") {\n pendingFlushMode = nextPendingState.flushMode;\n }\n if (nextPendingState.type === \"flush\") {\n pendingFlush = true;\n }\n this.pendingStates.shift();\n nextPendingState = this.peekNextPendingState();\n }\n\n if (pendingFlushMode !== undefined) {\n this.flushModeForNextMessage = pendingFlushMode;\n }\n\n // If the FlushMode was set to Immediate before this message was sent, this message won't be a batch message\n // because in Immediate mode, every message is flushed individually.\n if (pendingFlushMode === FlushMode.Immediate) {\n return;\n }\n\n /**\n * This message is the first in a batch if before it was sent either the FlushMode was set to TurnBased or there\n * was an explicit flush call. Note that a flush call is tracked only in TurnBased mode and it indicates the end\n * of one batch and beginning of another.\n */\n if (pendingFlushMode === FlushMode.TurnBased || pendingFlush) {\n // We should not already be processing a batch and there should be no pending batch begin message.\n assert(!this.isProcessingBatch && this.pendingBatchBeginMessage === undefined,\n 0x16b /* \"The pending batch state indicates we are already processing a batch\" */);\n\n // Set the pending batch state indicating we have started processing a batch.\n this.pendingBatchBeginMessage = message;\n this.isProcessingBatch = true;\n }\n }\n\n /**\n * This message could be the last message in batch. If so, clear batch state since the batch is complete.\n * @param message - The message that is being processed.\n */\n private maybeProcessBatchEnd(message: ISequencedDocumentMessage) {\n if (!this.isProcessingBatch) {\n return;\n }\n\n const nextPendingState = this.peekNextPendingState();\n if (nextPendingState.type === \"message\") {\n return;\n }\n\n /**\n * We are in the middle of processing a batch. The batch ends when we see an explicit flush. We should never see\n * a FlushMode before flush. This is true because we track batches only when FlushMode is TurnBased and in this\n * mode, a batch ends either by calling flush or by changing the mode to Immediate which also triggers a flush.\n */\n assert(\n nextPendingState.type !== \"flushMode\",\n 0x2bd /* \"We should not see a pending FlushMode until we see a flush when processing a batch\" */,\n );\n\n // There should be a pending batch begin message.\n assert(this.pendingBatchBeginMessage !== undefined, 0x16d /* \"There is no pending batch begin message\" */);\n\n // Get the batch begin metadata from the first message in the batch.\n const batchBeginMetadata = this.pendingBatchBeginMessage.metadata?.batch;\n\n // There could be just a single message in the batch. If so, it should not have any batch metadata. If there\n // are multiple messages in the batch, verify that we got the correct batch begin and end metadata.\n if (this.pendingBatchBeginMessage === message) {\n assert(batchBeginMetadata === undefined,\n 0x16e /* \"Batch with single message should not have batch metadata\" */);\n } else {\n // Get the batch metadata from the last message in the batch.\n const batchEndMetadata = message.metadata?.batch;\n if (batchBeginMetadata !== true || batchEndMetadata !== false) {\n this.stateHandler.close(DataProcessingError.create(\n \"Pending batch inconsistency\", // Formerly known as asserts 0x16f and 0x170\n \"processPendingLocalMessage\",\n message,\n {\n runtimeVersion: pkgVersion,\n batchClientId: this.pendingBatchBeginMessage.clientId,\n clientId: this.stateHandler.clientId(),\n hasBatchStart: batchBeginMetadata === true,\n hasBatchEnd: batchEndMetadata === false,\n messageType: message.type,\n batchStartSequenceNumber: this.pendingBatchBeginMessage.clientSequenceNumber,\n pendingMessagesCount: this.pendingMessagesCount,\n nextPendingState: nextPendingState.type,\n }));\n }\n }\n\n // Clear the pending batch state now that we have processed the entire batch.\n this.pendingBatchBeginMessage = undefined;\n this.isProcessingBatch = false;\n }\n\n /**\n * Returns the next pending state from the pending state queue.\n */\n private peekNextPendingState(): IPendingState {\n const nextPendingState = this.pendingStates.peekFront();\n assert(!!nextPendingState, 0x171 /* \"No pending state found for the remote message\" */);\n return nextPendingState;\n }\n\n /**\n * Called when the Container's connection state changes. If the Container gets connected, it replays all the pending\n * states in its queue. This includes setting the FlushMode and triggering resubmission of unacked ops.\n */\n public replayPendingStates() {\n assert(this.stateHandler.connected(), 0x172 /* \"The connection state is not consistent with the runtime\" */);\n\n // This assert suggests we are about to send same ops twice, which will result in data loss.\n assert(this.clientId !== this.stateHandler.clientId(),\n 0x173 /* \"replayPendingStates called twice for same clientId!\" */);\n this.clientId = this.stateHandler.clientId();\n\n assert(this.initialStates.isEmpty(), 0x174 /* \"initial states should be empty before replaying pending\" */);\n\n let pendingStatesCount = this.pendingStates.length;\n if (pendingStatesCount === 0) {\n return;\n }\n\n // Reset the pending message count because all these messages will be removed from the queue.\n this._pendingMessagesCount = 0;\n\n // Save the current FlushMode so that we can revert it back after replaying the states.\n const savedFlushMode = this.stateHandler.flushMode();\n\n // Set the flush mode for the next message. This step is important because the flush mode may have been changed\n // after the next pending message was sent.\n this.stateHandler.setFlushMode(this.flushModeForNextMessage);\n\n // Process exactly `pendingStatesCount` items in the queue as it represents the number of states that were\n // pending when we connected. This is important because the `reSubmitFn` might add more items in the queue\n // which must not be replayed.\n while (pendingStatesCount > 0) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const pendingState = this.pendingStates.shift()!;\n switch (pendingState.type) {\n case \"message\":\n this.stateHandler.reSubmit(\n pendingState.messageType,\n pendingState.content,\n pendingState.localOpMetadata,\n pendingState.opMetadata);\n break;\n case \"flushMode\":\n this.stateHandler.setFlushMode(pendingState.flushMode);\n break;\n case \"flush\":\n this.stateHandler.flush();\n break;\n default:\n break;\n }\n pendingStatesCount--;\n }\n\n // Revert the FlushMode.\n this.stateHandler.setFlushMode(savedFlushMode);\n }\n}\n"]}
@@ -5,7 +5,7 @@
5
5
  import { IDisposable, ITelemetryLogger } from "@fluidframework/common-definitions";
6
6
  import { ISequencedDocumentMessage } from "@fluidframework/protocol-definitions";
7
7
  import { ISummaryConfiguration } from "./containerRuntime";
8
- import { IEnqueueSummarizeOptions, ISummarizeHeuristicData, IOnDemandSummarizeOptions, EnqueueSummarizeResult, SummarizerStopReason, ISubmitSummaryOptions, SubmitSummaryResult, ISummaryCancellationToken, ISummarizeResults } from "./summarizerTypes";
8
+ import { IEnqueueSummarizeOptions, ISummarizeHeuristicData, IOnDemandSummarizeOptions, EnqueueSummarizeResult, SummarizerStopReason, ISubmitSummaryOptions, SubmitSummaryResult, ISummaryCancellationToken, ISummarizeResults, ISummarizerRuntime } from "./summarizerTypes";
9
9
  import { IClientSummaryWatcher, SummaryCollection } from "./summaryCollection";
10
10
  import { SummarizeResultBuilder } from "./summaryGenerator";
11
11
  /**
@@ -24,7 +24,8 @@ export declare class RunningSummarizer implements IDisposable {
24
24
  private readonly summaryCollection;
25
25
  private readonly cancellationToken;
26
26
  private readonly stopSummarizerCallback;
27
- static start(logger: ITelemetryLogger, summaryWatcher: IClientSummaryWatcher, configuration: ISummaryConfiguration, submitSummaryCallback: (options: ISubmitSummaryOptions) => Promise<SubmitSummaryResult>, heuristicData: ISummarizeHeuristicData, raiseSummarizingError: (errorMessage: string) => void, summaryCollection: SummaryCollection, cancellationToken: ISummaryCancellationToken, stopSummarizerCallback: (reason: SummarizerStopReason) => void): Promise<RunningSummarizer>;
27
+ private readonly runtime;
28
+ static start(logger: ITelemetryLogger, summaryWatcher: IClientSummaryWatcher, configuration: ISummaryConfiguration, submitSummaryCallback: (options: ISubmitSummaryOptions) => Promise<SubmitSummaryResult>, heuristicData: ISummarizeHeuristicData, raiseSummarizingError: (errorMessage: string) => void, summaryCollection: SummaryCollection, cancellationToken: ISummaryCancellationToken, stopSummarizerCallback: (reason: SummarizerStopReason) => void, runtime: ISummarizerRuntime): Promise<RunningSummarizer>;
28
29
  get disposed(): boolean;
29
30
  private stopping;
30
31
  private _disposed;
@@ -38,6 +39,7 @@ export declare class RunningSummarizer implements IDisposable {
38
39
  private enqueuedSummary;
39
40
  private summarizeCount;
40
41
  private totalSuccessfulAttempts;
42
+ private initialized;
41
43
  private constructor();
42
44
  dispose(): void;
43
45
  /**
@@ -47,8 +49,16 @@ export declare class RunningSummarizer implements IDisposable {
47
49
  * @param summaryOpRefSeq - RefSeq number of the summary op, to ensure the log correlation will be correct
48
50
  */
49
51
  tryGetCorrelatedLogger: (summaryOpRefSeq: any) => ITelemetryLogger | undefined;
50
- handleSystemOp(op: ISequencedDocumentMessage): void;
51
- handleOp(error: any, { sequenceNumber, type, clientId, contents }: ISequencedDocumentMessage): void;
52
+ /** We only want a single heuristic runner micro-task (will provide better optimized grouping of ops) */
53
+ private heuristicRunnerMicroTaskExists;
54
+ handleOp(op: ISequencedDocumentMessage): void;
55
+ /**
56
+ * Can the given op trigger a summary?
57
+ * # Currently only prevents summaries for Summarize and SummaryAck ops
58
+ * @param op - op to check
59
+ * @returns true if this type of op can trigger a summary
60
+ */
61
+ private opCanTriggerSummary;
52
62
  waitStop(allowLastSummary: boolean): Promise<void>;
53
63
  private waitStart;
54
64
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"runningSummarizer.d.ts","sourceRoot":"","sources":["../src/runningSummarizer.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,oCAAoC,CAAC;AAGnF,OAAO,EACH,yBAAyB,EAE5B,MAAM,sCAAsC,CAAC;AAE9C,OAAO,EACH,qBAAqB,EACxB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACH,wBAAwB,EAExB,uBAAuB,EAEvB,yBAAyB,EACzB,sBAAsB,EACtB,oBAAoB,EACpB,qBAAqB,EACrB,mBAAmB,EACnB,yBAAyB,EACzB,iBAAiB,EAGpB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAC/E,OAAO,EAGH,sBAAsB,EAEzB,M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AAS;IACpC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAe;IAC/C,OAAO,CAAC,eAAe,CAAC,CAA4B;IACpD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAmB;IAC7C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAmB;IAC1C,OAAO,CAAC,eAAe,CAKT;IACd,OAAO,CAAC,cAAc,CAAK;IAC3B,OAAO,CAAC,uBAAuB,CAAK;IACpC,OAAO,CAAC,WAAW,CAAS;IAE5B,OAAO;IAqFA,OAAO,IAAI,IAAI;IAYtB;;;;;OAKG;IACI,sBAAsB,yDAGT;IAEpB,wGAAwG;IACxG,OAAO,CAAC,8BAA8B,CAAS;IAExC,QAAQ,CAAC,EAAE,EAAE,yBAAyB;IAyB7C;;;;;OAKG;IACH,OAAO,CAAC,mBAAmB;IAWd,QAAQ,CAAC,gBAAgB,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;YA4BjD,SAAS;IAuBvB;;;;;;;;;;;OAWG;IACU,6BAA6B,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC;IAatE;;;;;;OAMG;YACW,mBAAmB;IAyBjC;;;;;;;OAOG;IACH,OAAO,CAAC,gBAAgB;IAuBxB,oCAAoC;IACpC,OAAO,CAAC,YAAY;IA0FpB,8DAA8D;IACvD,iBAAiB,CACpB,cAAc,oCAAuD,EACrE,EACI,MAAM,EACN,GAAG,OAAO,EACb,EAAE,yBAAyB,GAAG,iBAAiB;IAoBpD,6DAA6D;IACtD,gBAAgB,CAAC,EACpB,MAAM,EACN,mBAAuB,EACvB,QAAgB,EAChB,GAAG,OAAO,EACb,EAAE,wBAAwB,GAAG,sBAAsB;IA8BpD,OAAO,CAAC,qBAAqB;IAwB7B,OAAO,CAAC,sBAAsB;CAMjC"}
@@ -15,8 +15,10 @@ var __rest = (this && this.__rest) || function (s, e) {
15
15
  };
16
16
  import { assert, delay, Deferred, PromiseTimer } from "@fluidframework/common-utils";
17
17
  import { UsageError } from "@fluidframework/container-utils";
18
+ import { isRuntimeMessage } from "@fluidframework/driver-utils";
18
19
  import { MessageType, } from "@fluidframework/protocol-definitions";
19
20
  import { ChildLogger } from "@fluidframework/telemetry-utils";
21
+ import { opSize } from "./opProperties";
20
22
  import { SummarizeHeuristicRunner } from "./summarizerHeuristics";
21
23
  import { raceTimer, SummarizeResultBuilder, SummaryGenerator, } from "./summaryGenerator";
22
24
  const maxSummarizeAckWaitTime = 10 * 60 * 1000; // 10 minutes
@@ -28,7 +30,7 @@ const maxSummarizeAckWaitTime = 10 * 60 * 1000; // 10 minutes
28
30
  * This object is created and controlled by Summarizer object.
29
31
  */
30
32
  export class RunningSummarizer {
31
- constructor(baseLogger, summaryWatcher, configuration, submitSummaryCallback, heuristicData, raiseSummarizingError, summaryCollection, cancellationToken, stopSummarizerCallback) {
33
+ constructor(baseLogger, summaryWatcher, configuration, submitSummaryCallback, heuristicData, raiseSummarizingError, summaryCollection, cancellationToken, stopSummarizerCallback, runtime) {
32
34
  this.summaryWatcher = summaryWatcher;
33
35
  this.configuration = configuration;
34
36
  this.submitSummaryCallback = submitSummaryCallback;
@@ -37,11 +39,13 @@ export class RunningSummarizer {
37
39
  this.summaryCollection = summaryCollection;
38
40
  this.cancellationToken = cancellationToken;
39
41
  this.stopSummarizerCallback = stopSummarizerCallback;
42
+ this.runtime = runtime;
40
43
  this.stopping = false;
41
44
  this._disposed = false;
42
45
  this.tryWhileSummarizing = false;
43
46
  this.summarizeCount = 0;
44
47
  this.totalSuccessfulAttempts = 0;
48
+ this.initialized = false;
45
49
  /**
46
50
  * RunningSummarizer's logger includes the sequenced index of the current summary on each event.
47
51
  * If some other Summarizer code wants that event on their logs they can get it here,
@@ -51,6 +55,8 @@ export class RunningSummarizer {
51
55
  this.tryGetCorrelatedLogger = (summaryOpRefSeq) => this.heuristicData.lastAttempt.refSequenceNumber === summaryOpRefSeq
52
56
  ? this.logger
53
57
  : undefined;
58
+ /** We only want a single heuristic runner micro-task (will provide better optimized grouping of ops) */
59
+ this.heuristicRunnerMicroTaskExists = false;
54
60
  const telemetryProps = {
55
61
  summarizeCount: () => this.summarizeCount,
56
62
  summarizerSuccessfulAttempts: () => this.totalSuccessfulAttempts,
@@ -92,18 +98,39 @@ export class RunningSummarizer {
92
98
  }
93
99
  });
94
100
  this.generator = new SummaryGenerator(this.pendingAckTimer, this.heuristicData, this.submitSummaryCallback, this.raiseSummarizingError, () => { this.totalSuccessfulAttempts++; }, this.summaryWatcher, this.logger);
101
+ // Listen for ops
102
+ this.runtime.deltaManager.on("op", (op) => { this.handleOp(op); });
95
103
  }
96
- static async start(logger, summaryWatcher, configuration, submitSummaryCallback, heuristicData, raiseSummarizingError, summaryCollection, cancellationToken, stopSummarizerCallback) {
97
- var _a;
98
- const summarizer = new RunningSummarizer(logger, summaryWatcher, configuration, submitSummaryCallback, heuristicData, raiseSummarizingError, summaryCollection, cancellationToken, stopSummarizerCallback);
104
+ static async start(logger, summaryWatcher, configuration, submitSummaryCallback, heuristicData, raiseSummarizingError, summaryCollection, cancellationToken, stopSummarizerCallback, runtime) {
105
+ var _a, _b;
106
+ const summarizer = new RunningSummarizer(logger, summaryWatcher, configuration, submitSummaryCallback, heuristicData, raiseSummarizingError, summaryCollection, cancellationToken, stopSummarizerCallback, runtime);
99
107
  await summarizer.waitStart();
100
- // Run the heuristics after starting
101
- (_a = summarizer.heuristicRunner) === null || _a === void 0 ? void 0 : _a.run();
108
+ // Update heuristic counts
109
+ // By the time we get here, there are potentially ops missing from the heuristic summary counts
110
+ // Examples of where this could happen:
111
+ // 1. Op is processed during the time that we are initiating the RunningSummarizer instance but before we
112
+ // listen for the op events (will get missed by the handlers in the current workflow)
113
+ // 2. Op was sequenced after the last time we summarized (op sequence number > summarize ref sequence number)
114
+ const diff = runtime.deltaManager.lastSequenceNumber - (heuristicData.lastSuccessfulSummary.refSequenceNumber
115
+ + heuristicData.numNonRuntimeOps
116
+ + heuristicData.numRuntimeOps);
117
+ heuristicData.hasMissingOpData = diff > 0;
118
+ if (heuristicData.hasMissingOpData) {
119
+ // Split the diff 50-50 and increment the counts appropriately
120
+ heuristicData.numNonRuntimeOps += Math.ceil(diff / 2);
121
+ heuristicData.numRuntimeOps += Math.floor(diff / 2);
122
+ }
123
+ // Update last seq number (in case the handlers haven't processed anything yet)
124
+ heuristicData.lastOpSequenceNumber = runtime.deltaManager.lastSequenceNumber;
125
+ // Start heuristics
126
+ (_a = summarizer.heuristicRunner) === null || _a === void 0 ? void 0 : _a.start();
127
+ (_b = summarizer.heuristicRunner) === null || _b === void 0 ? void 0 : _b.run();
102
128
  return summarizer;
103
129
  }
104
130
  get disposed() { return this._disposed; }
105
131
  dispose() {
106
132
  var _a;
133
+ this.runtime.deltaManager.off("op", (op) => { this.handleOp(op); });
107
134
  this.summaryWatcher.dispose();
108
135
  (_a = this.heuristicRunner) === null || _a === void 0 ? void 0 : _a.dispose();
109
136
  this.heuristicRunner = undefined;
@@ -113,29 +140,43 @@ export class RunningSummarizer {
113
140
  this._disposed = true;
114
141
  this.stopping = true;
115
142
  }
116
- handleSystemOp(op) {
117
- switch (op.type) {
118
- case MessageType.ClientLeave:
119
- case MessageType.ClientJoin:
120
- case MessageType.Propose: {
121
- // Synchronously handle quorum ops like regular ops
122
- this.handleOp(undefined, op);
123
- return;
124
- }
125
- default: {
126
- return;
127
- }
143
+ handleOp(op) {
144
+ this.heuristicData.lastOpSequenceNumber = op.sequenceNumber;
145
+ if (isRuntimeMessage(op)) {
146
+ this.heuristicData.numRuntimeOps++;
128
147
  }
129
- }
130
- handleOp(error, { sequenceNumber, type, clientId, contents }) {
131
- var _a;
132
- if (error !== undefined) {
133
- return;
148
+ else {
149
+ this.heuristicData.numNonRuntimeOps++;
134
150
  }
135
- this.heuristicData.lastOpSequenceNumber = sequenceNumber;
151
+ this.heuristicData.totalOpsSize += opSize(op);
136
152
  // Check for enqueued on-demand summaries; Intentionally do nothing otherwise
137
- if (!this.tryRunEnqueuedSummary()) {
138
- (_a = this.heuristicRunner) === null || _a === void 0 ? void 0 : _a.run();
153
+ if (this.initialized
154
+ && this.opCanTriggerSummary(op)
155
+ && !this.tryRunEnqueuedSummary()
156
+ && !this.heuristicRunnerMicroTaskExists) {
157
+ this.heuristicRunnerMicroTaskExists = true;
158
+ Promise.resolve().then(() => {
159
+ var _a;
160
+ (_a = this.heuristicRunner) === null || _a === void 0 ? void 0 : _a.run();
161
+ }).finally(() => {
162
+ this.heuristicRunnerMicroTaskExists = false;
163
+ });
164
+ }
165
+ }
166
+ /**
167
+ * Can the given op trigger a summary?
168
+ * # Currently only prevents summaries for Summarize and SummaryAck ops
169
+ * @param op - op to check
170
+ * @returns true if this type of op can trigger a summary
171
+ */
172
+ opCanTriggerSummary(op) {
173
+ switch (op.type) {
174
+ case MessageType.Summarize:
175
+ case MessageType.SummaryAck:
176
+ case MessageType.SummaryNack:
177
+ return false;
178
+ default:
179
+ return true;
139
180
  }
140
181
  }
141
182
  async waitStop(allowLastSummary) {
@@ -177,6 +218,7 @@ export class RunningSummarizer {
177
218
  summarySequenceNumber: waitStartResult.value.summaryOp.sequenceNumber,
178
219
  });
179
220
  }
221
+ this.initialized = true;
180
222
  }
181
223
  /**
182
224
  * Blocks a new summarizer from running in case RefreshSummaryAck is being processed.