@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
@@ -1 +1 @@
1
- {"version":3,"file":"packageVersion.js","sourceRoot":"","sources":["../src/packageVersion.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEU,QAAA,OAAO,GAAG,mCAAmC,CAAC;AAC9C,QAAA,UAAU,GAAG,OAAO,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n *\n * THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY\n */\n\nexport const pkgName = \"@fluidframework/container-runtime\";\nexport const pkgVersion = \"1.2.6\";\n"]}
1
+ {"version":3,"file":"packageVersion.js","sourceRoot":"","sources":["../src/packageVersion.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEU,QAAA,OAAO,GAAG,mCAAmC,CAAC;AAC9C,QAAA,UAAU,GAAG,uBAAuB,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n *\n * THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY\n */\n\nexport const pkgName = \"@fluidframework/container-runtime\";\nexport const pkgVersion = \"2.0.0-dev.1.3.0.96595\";\n"]}
@@ -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,EAAE,uBAAuB,EAAE,MAAM,uCAAuC,CAAC;AAEhF,OAAO,EACH,yBAAyB,EAC5B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,qCAAqC,CAAC;AAGhE,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAE1D;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC5B,IAAI,EAAE,SAAS,CAAC;IAChB,WAAW,EAAE,oBAAoB,CAAC;IAClC,oBAAoB,EAAE,MAAM,CAAC;IAC7B,uBAAuB,EAAE,MAAM,CAAC;IAChC,OAAO,EAAE,GAAG,CAAC;IACb,eAAe,EAAE,OAAO,CAAC;IACzB,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CA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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"}
@@ -11,8 +11,8 @@ exports.PendingStateManager = void 0;
11
11
  const common_utils_1 = require("@fluidframework/common-utils");
12
12
  const container_utils_1 = require("@fluidframework/container-utils");
13
13
  const runtime_definitions_1 = require("@fluidframework/runtime-definitions");
14
- const telemetry_utils_1 = require("@fluidframework/telemetry-utils");
15
14
  const double_ended_queue_1 = __importDefault(require("double-ended-queue"));
15
+ const packageVersion_1 = require("./packageVersion");
16
16
  /**
17
17
  * PendingStateManager is responsible for maintaining the messages that have not been sent or have not yet been
18
18
  * acknowledged by the server. It also maintains the batch information for both automatically and manually flushed
@@ -131,7 +131,11 @@ class PendingStateManager {
131
131
  }
132
132
  // then we push onto pendingStates which will cause PendingStateManager to resubmit when we connect
133
133
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
134
- this.pendingStates.push(this.initialStates.shift());
134
+ const firstPendingState = this.initialStates.shift();
135
+ this.pendingStates.push(firstPendingState);
136
+ if (firstPendingState.type === "message") {
137
+ this._pendingMessagesCount++;
138
+ }
135
139
  }
136
140
  }
137
141
  /**
@@ -155,6 +159,7 @@ class PendingStateManager {
155
159
  return;
156
160
  }
157
161
  this._pendingMessagesCount--;
162
+ (0, common_utils_1.assert)(this._pendingMessagesCount >= 0, 0x3d6 /* positive */);
158
163
  // Post-processing part - If we are processing a batch then this could be the last message in the batch.
159
164
  this.maybeProcessBatchEnd(message);
160
165
  return pendingState.localOpMetadata;
@@ -170,9 +175,11 @@ class PendingStateManager {
170
175
  let pendingFlush = false;
171
176
  /**
172
177
  * We are checking if the next message is the start of a batch. It can happen in the following scenarios:
178
+ *
173
179
  * 1. The FlushMode was set to TurnBased before this message was sent.
180
+ *
174
181
  * 2. The FlushMode was already TurnBased and a flush was called before this message was sent. This essentially
175
- * means that the flush marked the end of a previous batch and beginning of a new batch.
182
+ * means that the flush marked the end of a previous batch and beginning of a new batch.
176
183
  *
177
184
  * Keep reading pending states from the queue until we encounter a message. It's possible that the FlushMode was
178
185
  * updated a bunch of times without sending any messages.
@@ -240,35 +247,25 @@ class PendingStateManager {
240
247
  else {
241
248
  // Get the batch metadata from the last message in the batch.
242
249
  const batchEndMetadata = (_b = message.metadata) === null || _b === void 0 ? void 0 : _b.batch;
243
- (0, common_utils_1.assert)(batchBeginMetadata === true, 0x16f /* "Did not receive batch begin metadata" */);
244
- (0, common_utils_1.assert)(batchEndMetadata === false, 0x170 /* "Did not receive batch end metadata" */);
250
+ if (batchBeginMetadata !== true || batchEndMetadata !== false) {
251
+ this.stateHandler.close(container_utils_1.DataProcessingError.create("Pending batch inconsistency", // Formerly known as asserts 0x16f and 0x170
252
+ "processPendingLocalMessage", message, {
253
+ runtimeVersion: packageVersion_1.pkgVersion,
254
+ batchClientId: this.pendingBatchBeginMessage.clientId,
255
+ clientId: this.stateHandler.clientId(),
256
+ hasBatchStart: batchBeginMetadata === true,
257
+ hasBatchEnd: batchEndMetadata === false,
258
+ messageType: message.type,
259
+ batchStartSequenceNumber: this.pendingBatchBeginMessage.clientSequenceNumber,
260
+ pendingMessagesCount: this.pendingMessagesCount,
261
+ nextPendingState: nextPendingState.type,
262
+ }));
263
+ }
245
264
  }
246
265
  // Clear the pending batch state now that we have processed the entire batch.
247
266
  this.pendingBatchBeginMessage = undefined;
248
267
  this.isProcessingBatch = false;
249
268
  }
250
- /**
251
- * Capture the pending state at this point
252
- */
253
- checkpoint() {
254
- const checkpointHead = this.pendingStates.peekBack();
255
- return {
256
- rollback: () => {
257
- try {
258
- while (this.pendingStates.peekBack() !== checkpointHead) {
259
- this.rollbackNextPendingState();
260
- }
261
- }
262
- catch (err) {
263
- const error = (0, telemetry_utils_1.wrapError)(err, (message) => {
264
- return container_utils_1.DataProcessingError.create(`RollbackError: ${message}`, "checkpointRollback", undefined);
265
- });
266
- this.stateHandler.close(error);
267
- throw error;
268
- }
269
- },
270
- };
271
- }
272
269
  /**
273
270
  * Returns the next pending state from the pending state queue.
274
271
  */
@@ -277,25 +274,6 @@ class PendingStateManager {
277
274
  (0, common_utils_1.assert)(!!nextPendingState, 0x171 /* "No pending state found for the remote message" */);
278
275
  return nextPendingState;
279
276
  }
280
- /**
281
- * Undo the last pending state
282
- */
283
- rollbackNextPendingState() {
284
- const pendingStatesCount = this.pendingStates.length;
285
- if (pendingStatesCount === 0) {
286
- return;
287
- }
288
- this._pendingMessagesCount--;
289
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
290
- const pendingState = this.pendingStates.pop();
291
- switch (pendingState.type) {
292
- case "message":
293
- this.stateHandler.rollback(pendingState.messageType, pendingState.content, pendingState.localOpMetadata);
294
- break;
295
- default:
296
- throw new Error(`Can't rollback state ${pendingState.type}`);
297
- }
298
- }
299
277
  /**
300
278
  * Called when the Container's connection state changes. If the Container gets connected, it replays all the pending
301
279
  * 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;;;;;;AAGH,+DAA4D;AAE5D,qEAAsE;AAItE,6EAAgE;AAChE,qEAA4D;AAC5D,4EAAuC;AA8DvC;;;;;;;;GAQG;AACH,MAAa,mBAAmB;IAkD5B,YACqB,YAAkC,EACnD,gBAA2B,EAC3B,iBAAiD;;QAFhC,iBAAY,GAAZ,YAAY,CAAsB;QAlDtC,kBAAa,GAAG,IAAI,4BAAK,EAAiB,CAAC;QAE3C,gBAAW,GAAG,IAAI,mBAAI,CAAO,GAAG,EAAE;YAC/C,IAAI,CAAC,aAAa,CAAC,KAA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C7B,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;AA3ZD,kDA2ZC","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,+DAA4D;AAE5D,qEAAsE;AAItE,6EAAgE;AAChE,4EAAuC;AAEvC,qDAA8C;AAyD9C;;;;;;;;GAQG;AACH,MAAa,mBAAmB;IAkD5B,YACqB,YAAkC,EACnD,gBAA2B,EAC3B,iBAAiD;;QAFhC,iBAAY,GAAZ,YAAY,CAAsB;QAlDtC,kBAAa,GAAG,IAAI,4BAAK,EAAiB,CAAC;QAE3C,gBAAW,GAAG,IAAI,mBAAI,CAAO,GAAG,EAAE;YAC/C,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE,CAAC;YAC3B,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE,CAAC;QAC/B,CAAC,CAAC,CAAC;QAEH,8DAA8D;QACtD,0BAAqB,GAAW,CAAC,CAAC;QAK1C,+CAA+C;QACvC,sBAAiB,GAAY,KAAK,CAAC;QA+C3B,YAAO,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC;QAPnD,IAAI,CAAC,aAAa,GAAG,IAAI,4BAAK,CAA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I,CAAC,YAAY,CAAC,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;AA/XD,kDA+XC","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,MAAM,oBAAoB,CAAC;AAI5B;;;;;;GAMG;AACH,qBAAa,iBAAkB,YAAW,WAAW;IAmD7C,OAAO,CAAC,QAAQ,CAAC,cAAc;IAC/B,OAAO,CAAC,QAAQ,CAAC,aAAa;IAC9B,OAAO,CAAC,QAAQ,CAAC,qBAAqB;IACtC,OAAO,CAAC,QAAQ,CAAC,aAAa;IAC9B,OAAO,CAAC,QAAQ,CAAC,qBAAqB;IACtC,OAAO,CAAC,QAAQ,CAAC,iBAAiB;IAClC,OAAO,CAAC,QAAQ,CAAC,iBAAiB;IAClC,OAAO,CAAC,QAAQ,CAAC,sBAAsB;WAzDvB,KAAK,CACrB,MAAM,EAAE,gBAAgB,EACxB,cAAc,EAAE,qBAAqB,EACrC,aAAa,EAAE,qBAAqB,EACpC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ACH,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"}
@@ -18,8 +18,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.RunningSummarizer = void 0;
19
19
  const common_utils_1 = require("@fluidframework/common-utils");
20
20
  const container_utils_1 = require("@fluidframework/container-utils");
21
+ const driver_utils_1 = require("@fluidframework/driver-utils");
21
22
  const protocol_definitions_1 = require("@fluidframework/protocol-definitions");
22
23
  const telemetry_utils_1 = require("@fluidframework/telemetry-utils");
24
+ const opProperties_1 = require("./opProperties");
23
25
  const summarizerHeuristics_1 = require("./summarizerHeuristics");
24
26
  const summaryGenerator_1 = require("./summaryGenerator");
25
27
  const maxSummarizeAckWaitTime = 10 * 60 * 1000; // 10 minutes
@@ -31,7 +33,7 @@ const maxSummarizeAckWaitTime = 10 * 60 * 1000; // 10 minutes
31
33
  * This object is created and controlled by Summarizer object.
32
34
  */
33
35
  class RunningSummarizer {
34
- constructor(baseLogger, summaryWatcher, configuration, submitSummaryCallback, heuristicData, raiseSummarizingError, summaryCollection, cancellationToken, stopSummarizerCallback) {
36
+ constructor(baseLogger, summaryWatcher, configuration, submitSummaryCallback, heuristicData, raiseSummarizingError, summaryCollection, cancellationToken, stopSummarizerCallback, runtime) {
35
37
  this.summaryWatcher = summaryWatcher;
36
38
  this.configuration = configuration;
37
39
  this.submitSummaryCallback = submitSummaryCallback;
@@ -40,11 +42,13 @@ class RunningSummarizer {
40
42
  this.summaryCollection = summaryCollection;
41
43
  this.cancellationToken = cancellationToken;
42
44
  this.stopSummarizerCallback = stopSummarizerCallback;
45
+ this.runtime = runtime;
43
46
  this.stopping = false;
44
47
  this._disposed = false;
45
48
  this.tryWhileSummarizing = false;
46
49
  this.summarizeCount = 0;
47
50
  this.totalSuccessfulAttempts = 0;
51
+ this.initialized = false;
48
52
  /**
49
53
  * RunningSummarizer's logger includes the sequenced index of the current summary on each event.
50
54
  * If some other Summarizer code wants that event on their logs they can get it here,
@@ -54,6 +58,8 @@ class RunningSummarizer {
54
58
  this.tryGetCorrelatedLogger = (summaryOpRefSeq) => this.heuristicData.lastAttempt.refSequenceNumber === summaryOpRefSeq
55
59
  ? this.logger
56
60
  : undefined;
61
+ /** We only want a single heuristic runner micro-task (will provide better optimized grouping of ops) */
62
+ this.heuristicRunnerMicroTaskExists = false;
57
63
  const telemetryProps = {
58
64
  summarizeCount: () => this.summarizeCount,
59
65
  summarizerSuccessfulAttempts: () => this.totalSuccessfulAttempts,
@@ -95,18 +101,39 @@ class RunningSummarizer {
95
101
  }
96
102
  });
97
103
  this.generator = new summaryGenerator_1.SummaryGenerator(this.pendingAckTimer, this.heuristicData, this.submitSummaryCallback, this.raiseSummarizingError, () => { this.totalSuccessfulAttempts++; }, this.summaryWatcher, this.logger);
104
+ // Listen for ops
105
+ this.runtime.deltaManager.on("op", (op) => { this.handleOp(op); });
98
106
  }
99
- static async start(logger, summaryWatcher, configuration, submitSummaryCallback, heuristicData, raiseSummarizingError, summaryCollection, cancellationToken, stopSummarizerCallback) {
100
- var _a;
101
- const summarizer = new RunningSummarizer(logger, summaryWatcher, configuration, submitSummaryCallback, heuristicData, raiseSummarizingError, summaryCollection, cancellationToken, stopSummarizerCallback);
107
+ static async start(logger, summaryWatcher, configuration, submitSummaryCallback, heuristicData, raiseSummarizingError, summaryCollection, cancellationToken, stopSummarizerCallback, runtime) {
108
+ var _a, _b;
109
+ const summarizer = new RunningSummarizer(logger, summaryWatcher, configuration, submitSummaryCallback, heuristicData, raiseSummarizingError, summaryCollection, cancellationToken, stopSummarizerCallback, runtime);
102
110
  await summarizer.waitStart();
103
- // Run the heuristics after starting
104
- (_a = summarizer.heuristicRunner) === null || _a === void 0 ? void 0 : _a.run();
111
+ // Update heuristic counts
112
+ // By the time we get here, there are potentially ops missing from the heuristic summary counts
113
+ // Examples of where this could happen:
114
+ // 1. Op is processed during the time that we are initiating the RunningSummarizer instance but before we
115
+ // listen for the op events (will get missed by the handlers in the current workflow)
116
+ // 2. Op was sequenced after the last time we summarized (op sequence number > summarize ref sequence number)
117
+ const diff = runtime.deltaManager.lastSequenceNumber - (heuristicData.lastSuccessfulSummary.refSequenceNumber
118
+ + heuristicData.numNonRuntimeOps
119
+ + heuristicData.numRuntimeOps);
120
+ heuristicData.hasMissingOpData = diff > 0;
121
+ if (heuristicData.hasMissingOpData) {
122
+ // Split the diff 50-50 and increment the counts appropriately
123
+ heuristicData.numNonRuntimeOps += Math.ceil(diff / 2);
124
+ heuristicData.numRuntimeOps += Math.floor(diff / 2);
125
+ }
126
+ // Update last seq number (in case the handlers haven't processed anything yet)
127
+ heuristicData.lastOpSequenceNumber = runtime.deltaManager.lastSequenceNumber;
128
+ // Start heuristics
129
+ (_a = summarizer.heuristicRunner) === null || _a === void 0 ? void 0 : _a.start();
130
+ (_b = summarizer.heuristicRunner) === null || _b === void 0 ? void 0 : _b.run();
105
131
  return summarizer;
106
132
  }
107
133
  get disposed() { return this._disposed; }
108
134
  dispose() {
109
135
  var _a;
136
+ this.runtime.deltaManager.off("op", (op) => { this.handleOp(op); });
110
137
  this.summaryWatcher.dispose();
111
138
  (_a = this.heuristicRunner) === null || _a === void 0 ? void 0 : _a.dispose();
112
139
  this.heuristicRunner = undefined;
@@ -116,29 +143,43 @@ class RunningSummarizer {
116
143
  this._disposed = true;
117
144
  this.stopping = true;
118
145
  }
119
- handleSystemOp(op) {
120
- switch (op.type) {
121
- case protocol_definitions_1.MessageType.ClientLeave:
122
- case protocol_definitions_1.MessageType.ClientJoin:
123
- case protocol_definitions_1.MessageType.Propose: {
124
- // Synchronously handle quorum ops like regular ops
125
- this.handleOp(undefined, op);
126
- return;
127
- }
128
- default: {
129
- return;
130
- }
146
+ handleOp(op) {
147
+ this.heuristicData.lastOpSequenceNumber = op.sequenceNumber;
148
+ if ((0, driver_utils_1.isRuntimeMessage)(op)) {
149
+ this.heuristicData.numRuntimeOps++;
131
150
  }
132
- }
133
- handleOp(error, { sequenceNumber, type, clientId, contents }) {
134
- var _a;
135
- if (error !== undefined) {
136
- return;
151
+ else {
152
+ this.heuristicData.numNonRuntimeOps++;
137
153
  }
138
- this.heuristicData.lastOpSequenceNumber = sequenceNumber;
154
+ this.heuristicData.totalOpsSize += (0, opProperties_1.opSize)(op);
139
155
  // Check for enqueued on-demand summaries; Intentionally do nothing otherwise
140
- if (!this.tryRunEnqueuedSummary()) {
141
- (_a = this.heuristicRunner) === null || _a === void 0 ? void 0 : _a.run();
156
+ if (this.initialized
157
+ && this.opCanTriggerSummary(op)
158
+ && !this.tryRunEnqueuedSummary()
159
+ && !this.heuristicRunnerMicroTaskExists) {
160
+ this.heuristicRunnerMicroTaskExists = true;
161
+ Promise.resolve().then(() => {
162
+ var _a;
163
+ (_a = this.heuristicRunner) === null || _a === void 0 ? void 0 : _a.run();
164
+ }).finally(() => {
165
+ this.heuristicRunnerMicroTaskExists = false;
166
+ });
167
+ }
168
+ }
169
+ /**
170
+ * Can the given op trigger a summary?
171
+ * # Currently only prevents summaries for Summarize and SummaryAck ops
172
+ * @param op - op to check
173
+ * @returns true if this type of op can trigger a summary
174
+ */
175
+ opCanTriggerSummary(op) {
176
+ switch (op.type) {
177
+ case protocol_definitions_1.MessageType.Summarize:
178
+ case protocol_definitions_1.MessageType.SummaryAck:
179
+ case protocol_definitions_1.MessageType.SummaryNack:
180
+ return false;
181
+ default:
182
+ return true;
142
183
  }
143
184
  }
144
185
  async waitStop(allowLastSummary) {
@@ -180,6 +221,7 @@ class RunningSummarizer {
180
221
  summarySequenceNumber: waitStartResult.value.summaryOp.sequenceNumber,
181
222
  });
182
223
  }
224
+ this.initialized = true;
183
225
  }
184
226
  /**
185
227
  * Blocks a new summarizer from running in case RefreshSummaryAck is being processed.