@fluidframework/container-runtime 2.0.0-internal.1.0.0.82693 → 2.0.0-internal.1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/.mocharc.js +12 -0
  2. package/dist/batchTracker.js +1 -1
  3. package/dist/batchTracker.js.map +1 -1
  4. package/dist/blobManager.d.ts +7 -1
  5. package/dist/blobManager.d.ts.map +1 -1
  6. package/dist/blobManager.js +34 -17
  7. package/dist/blobManager.js.map +1 -1
  8. package/dist/containerRuntime.d.ts +3 -104
  9. package/dist/containerRuntime.d.ts.map +1 -1
  10. package/dist/containerRuntime.js +83 -395
  11. package/dist/containerRuntime.js.map +1 -1
  12. package/dist/dataStore.d.ts +1 -1
  13. package/dist/dataStore.d.ts.map +1 -1
  14. package/dist/dataStore.js +2 -3
  15. package/dist/dataStore.js.map +1 -1
  16. package/dist/dataStoreContext.d.ts +3 -5
  17. package/dist/dataStoreContext.d.ts.map +1 -1
  18. package/dist/dataStoreContext.js +13 -23
  19. package/dist/dataStoreContext.js.map +1 -1
  20. package/dist/dataStores.d.ts +1 -1
  21. package/dist/dataStores.d.ts.map +1 -1
  22. package/dist/dataStores.js +3 -8
  23. package/dist/dataStores.js.map +1 -1
  24. package/dist/garbageCollection.d.ts +37 -6
  25. package/dist/garbageCollection.d.ts.map +1 -1
  26. package/dist/garbageCollection.js +61 -65
  27. package/dist/garbageCollection.js.map +1 -1
  28. package/dist/index.d.ts +2 -1
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +3 -2
  31. package/dist/index.js.map +1 -1
  32. package/dist/packageVersion.d.ts +1 -1
  33. package/dist/packageVersion.d.ts.map +1 -1
  34. package/dist/packageVersion.js +1 -1
  35. package/dist/packageVersion.js.map +1 -1
  36. package/dist/pendingStateManager.d.ts.map +1 -1
  37. package/dist/pendingStateManager.js +15 -2
  38. package/dist/pendingStateManager.js.map +1 -1
  39. package/dist/runningSummarizer.d.ts +14 -0
  40. package/dist/runningSummarizer.d.ts.map +1 -1
  41. package/dist/runningSummarizer.js +25 -0
  42. package/dist/runningSummarizer.js.map +1 -1
  43. package/dist/scheduleManager.d.ts +28 -0
  44. package/dist/scheduleManager.d.ts.map +1 -0
  45. package/dist/scheduleManager.js +235 -0
  46. package/dist/scheduleManager.js.map +1 -0
  47. package/dist/summarizer.d.ts.map +1 -1
  48. package/dist/summarizer.js +33 -3
  49. package/dist/summarizer.js.map +1 -1
  50. package/dist/summaryCollection.js +1 -1
  51. package/dist/summaryCollection.js.map +1 -1
  52. package/dist/summaryGenerator.js +1 -1
  53. package/dist/summaryGenerator.js.map +1 -1
  54. package/dist/summaryManager.d.ts.map +1 -1
  55. package/dist/summaryManager.js +20 -5
  56. package/dist/summaryManager.js.map +1 -1
  57. package/lib/batchTracker.js +1 -1
  58. package/lib/batchTracker.js.map +1 -1
  59. package/lib/blobManager.d.ts +7 -1
  60. package/lib/blobManager.d.ts.map +1 -1
  61. package/lib/blobManager.js +35 -18
  62. package/lib/blobManager.js.map +1 -1
  63. package/lib/containerRuntime.d.ts +3 -104
  64. package/lib/containerRuntime.d.ts.map +1 -1
  65. package/lib/containerRuntime.js +84 -395
  66. package/lib/containerRuntime.js.map +1 -1
  67. package/lib/dataStore.d.ts +1 -1
  68. package/lib/dataStore.d.ts.map +1 -1
  69. package/lib/dataStore.js +2 -3
  70. package/lib/dataStore.js.map +1 -1
  71. package/lib/dataStoreContext.d.ts +3 -5
  72. package/lib/dataStoreContext.d.ts.map +1 -1
  73. package/lib/dataStoreContext.js +13 -23
  74. package/lib/dataStoreContext.js.map +1 -1
  75. package/lib/dataStores.d.ts +1 -1
  76. package/lib/dataStores.d.ts.map +1 -1
  77. package/lib/dataStores.js +3 -8
  78. package/lib/dataStores.js.map +1 -1
  79. package/lib/garbageCollection.d.ts +37 -6
  80. package/lib/garbageCollection.d.ts.map +1 -1
  81. package/lib/garbageCollection.js +47 -52
  82. package/lib/garbageCollection.js.map +1 -1
  83. package/lib/index.d.ts +2 -1
  84. package/lib/index.d.ts.map +1 -1
  85. package/lib/index.js +2 -1
  86. package/lib/index.js.map +1 -1
  87. package/lib/packageVersion.d.ts +1 -1
  88. package/lib/packageVersion.d.ts.map +1 -1
  89. package/lib/packageVersion.js +1 -1
  90. package/lib/packageVersion.js.map +1 -1
  91. package/lib/pendingStateManager.d.ts.map +1 -1
  92. package/lib/pendingStateManager.js +15 -2
  93. package/lib/pendingStateManager.js.map +1 -1
  94. package/lib/runningSummarizer.d.ts +14 -0
  95. package/lib/runningSummarizer.d.ts.map +1 -1
  96. package/lib/runningSummarizer.js +25 -0
  97. package/lib/runningSummarizer.js.map +1 -1
  98. package/lib/scheduleManager.d.ts +28 -0
  99. package/lib/scheduleManager.d.ts.map +1 -0
  100. package/lib/scheduleManager.js +231 -0
  101. package/lib/scheduleManager.js.map +1 -0
  102. package/lib/summarizer.d.ts.map +1 -1
  103. package/lib/summarizer.js +35 -5
  104. package/lib/summarizer.js.map +1 -1
  105. package/lib/summaryCollection.js +1 -1
  106. package/lib/summaryCollection.js.map +1 -1
  107. package/lib/summaryGenerator.js +1 -1
  108. package/lib/summaryGenerator.js.map +1 -1
  109. package/lib/summaryManager.d.ts.map +1 -1
  110. package/lib/summaryManager.js +20 -5
  111. package/lib/summaryManager.js.map +1 -1
  112. package/package.json +32 -19
  113. package/src/batchTracker.ts +1 -1
  114. package/src/blobManager.ts +43 -17
  115. package/src/containerRuntime.ts +113 -547
  116. package/src/dataStore.ts +1 -4
  117. package/src/dataStoreContext.ts +10 -25
  118. package/src/dataStores.ts +13 -19
  119. package/src/garbageCollection.ts +64 -69
  120. package/src/index.ts +1 -2
  121. package/src/packageVersion.ts +1 -1
  122. package/src/pendingStateManager.ts +18 -2
  123. package/src/runningSummarizer.ts +33 -1
  124. package/src/scheduleManager.ts +294 -0
  125. package/src/summarizer.ts +46 -10
  126. package/src/summaryCollection.ts +1 -1
  127. package/src/summaryGenerator.ts +1 -1
  128. package/src/summaryManager.ts +20 -5
@@ -7,6 +7,7 @@ import { DataProcessingError } from "@fluidframework/container-utils";
7
7
  import { FlushMode } from "@fluidframework/runtime-definitions";
8
8
  import { wrapError } from "@fluidframework/telemetry-utils";
9
9
  import Deque from "double-ended-queue";
10
+ import { pkgVersion } from "./packageVersion";
10
11
  /**
11
12
  * PendingStateManager is responsible for maintaining the messages that have not been sent or have not yet been
12
13
  * acknowledged by the server. It also maintains the batch information for both automatically and manually flushed
@@ -234,8 +235,20 @@ export class PendingStateManager {
234
235
  else {
235
236
  // Get the batch metadata from the last message in the batch.
236
237
  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" */);
238
+ if (batchBeginMetadata !== true || batchEndMetadata !== false) {
239
+ this.stateHandler.close(DataProcessingError.create("Pending batch inconsistency", // Formerly known as asserts 0x16f and 0x170
240
+ "processPendingLocalMessage", message, {
241
+ runtimeVersion: pkgVersion,
242
+ batchClientId: this.pendingBatchBeginMessage.clientId,
243
+ clientId: this.stateHandler.clientId(),
244
+ hasBatchStart: batchBeginMetadata === true,
245
+ hasBatchEnd: batchEndMetadata === false,
246
+ messageType: message.type,
247
+ batchStartSequenceNumber: this.pendingBatchBeginMessage.clientSequenceNumber,
248
+ pendingMessagesCount: this.pendingMessagesCount,
249
+ nextPendingState: nextPendingState.type,
250
+ }));
251
+ }
239
252
  }
240
253
  // Clear the pending batch state now that we have processed the entire batch.
241
254
  this.pendingBatchBeginMessage = undefined;
@@ -1 +1 @@
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,OA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,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,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AAC5D,OAAO,KAAK,MAAM,oBAAoB,CAAC;AAEvC,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AA6D9C;;;;;;;;GAQG;AACH,MAAM,OAAO,mBAAmB;IAkD5B,YAC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AAG,CAAC,CAAC;QAE/B,uFAAuF;QACvF,MAAM,cAAc,GAAG,IAAI,CAAC,YAAY,CAAC,SAAS,EAAE,CAAC;QAErD,+GAA+G;QAC/G,2CAA2C;QAC3C,IAAI,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","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\";\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 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 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 * 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"]}
@@ -30,6 +30,7 @@ export declare class RunningSummarizer implements IDisposable {
30
30
  private stopping;
31
31
  private _disposed;
32
32
  private summarizingLock;
33
+ private refreshSummaryAckLock;
33
34
  private tryWhileSummarizing;
34
35
  private readonly pendingAckTimer;
35
36
  private heuristicRunner?;
@@ -60,6 +61,19 @@ export declare class RunningSummarizer implements IDisposable {
60
61
  private opCanTriggerSummary;
61
62
  waitStop(allowLastSummary: boolean): Promise<void>;
62
63
  private waitStart;
64
+ /**
65
+ * Blocks a new summarizer from running in case RefreshSummaryAck is being processed.
66
+ * Assumes that caller checked upfront for lack of concurrent action (this.refreshSummaryAckLock)
67
+ * before calling this API. I.e. caller is responsible for either erroring out or waiting on this promise.
68
+ * Note: The refreshSummaryAckLock makes sure no summarizer gets enqueued or processed
69
+ * until the refresh has completed. One can't rely uniquely on the summarizingLock as the
70
+ * refreshLatestSummaryAck also happens during the time summarizingLock !== undefined.
71
+ * Ex. Summarizer submits a summay + op and then waits for the Summary Ack to proceed
72
+ * with the refreshLatestSummaryAck and complete the summary.
73
+ * @param action - action to perform.
74
+ * @returns - result of action.
75
+ */
76
+ lockedRefreshSummaryAckAction<T>(action: () => Promise<T>): Promise<T>;
63
77
  /**
64
78
  * Runs single summary action that prevents any other concurrent actions.
65
79
  * Assumes that caller checked upfront for lack of concurrent action (this.summarizingLock)
@@ -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;AAInF,OAAO,EACH,yBAAyB,EAE5B,MAAM,sCAAsC,CAAC;AAE9C,OAAO,EACH,qBAAqB,EACxB,MAAM,oBAAoB,CAAC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QAAgB,EAChB,GAAG,OAAO,EACb,EAAE,wBAAwB,GAAG,sBAAsB;IA8BpD,OAAO,CAAC,qBAAqB;IAwB7B,OAAO,CAAC,sBAAsB;CAMjC"}
@@ -220,6 +220,27 @@ export class RunningSummarizer {
220
220
  }
221
221
  this.initialized = true;
222
222
  }
223
+ /**
224
+ * Blocks a new summarizer from running in case RefreshSummaryAck is being processed.
225
+ * Assumes that caller checked upfront for lack of concurrent action (this.refreshSummaryAckLock)
226
+ * before calling this API. I.e. caller is responsible for either erroring out or waiting on this promise.
227
+ * Note: The refreshSummaryAckLock makes sure no summarizer gets enqueued or processed
228
+ * until the refresh has completed. One can't rely uniquely on the summarizingLock as the
229
+ * refreshLatestSummaryAck also happens during the time summarizingLock !== undefined.
230
+ * Ex. Summarizer submits a summay + op and then waits for the Summary Ack to proceed
231
+ * with the refreshLatestSummaryAck and complete the summary.
232
+ * @param action - action to perform.
233
+ * @returns - result of action.
234
+ */
235
+ async lockedRefreshSummaryAckAction(action) {
236
+ assert(this.refreshSummaryAckLock === undefined, 0x396 /* Refresh Summary Ack - Caller is responsible for checking lock */);
237
+ const refreshSummaryAckLock = new Deferred();
238
+ this.refreshSummaryAckLock = refreshSummaryAckLock.promise;
239
+ return action().finally(() => {
240
+ refreshSummaryAckLock.resolve();
241
+ this.refreshSummaryAckLock = undefined;
242
+ });
243
+ }
223
244
  /**
224
245
  * Runs single summary action that prevents any other concurrent actions.
225
246
  * Assumes that caller checked upfront for lack of concurrent action (this.summarizingLock)
@@ -232,6 +253,8 @@ export class RunningSummarizer {
232
253
  const summarizingLock = new Deferred();
233
254
  this.summarizingLock = summarizingLock.promise;
234
255
  this.summarizeCount++;
256
+ // Make sure the RefreshLatestSummaryAck is not being executed.
257
+ await this.refreshSummaryAckLock;
235
258
  return action().finally(() => {
236
259
  var _a;
237
260
  summarizingLock.resolve();
@@ -303,6 +326,8 @@ export class RunningSummarizer {
303
326
  this.logger.sendPerformanceEvent(Object.assign({ eventName: "SummarizeAttemptDelay", duration: delaySeconds, summaryNackDelay: overrideDelaySeconds !== undefined }, summarizeProps));
304
327
  await delay(delaySeconds * 1000);
305
328
  }
329
+ // Make sure the refresh Summary Ack is not being executed.
330
+ await this.refreshSummaryAckLock;
306
331
  // Note: no need to account for cancellationToken.waitCancelled here, as
307
332
  // this is accounted SummaryGenerator.summarizeCore that controls receivedSummaryAckOrNack.
308
333
  const resultSummarize = this.generator.summarize(summarizeProps, options, cancellationToken);
@@ -1 +1 @@
1
- {"version":3,"file":"runningSummarizer.js","sourceRoot":"","sources":["../src/runningSummarizer.ts"],"names":[],"mappings":"AAAA;;;GAGG;;;;;;;;;;;;AAGH,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AACrF,OAAO,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,EAEH,WAAW,GACd,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAI9D,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAkBlE,OAAO,EACH,SAAS,EAET,sBAAsB,EACtB,gBAAgB,GACnB,MAAM,oBAAoB,CAAC;AAE5B,MAAM,uBAAuB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,aAAa;AAE7D;;;;;;GAMG;AACH,MAAM,OAAO,iBAAiB;IA2E1B,YACI,UAA4B,EACX,cAAqC,EACrC,aAAoC,EACpC,qBAAuF,EACvF,aAAsC,EACtC,qBAAqD,EACrD,iBAAoC,EACpC,iBAA4C,EAC5C,sBAA8D,EAC9D,OAA2B;QAR3B,mBAAc,GAAd,cAAc,CAAuB;QACrC,kBAAa,GAAb,aAAa,CAAuB;QACpC,0BAAqB,GAAr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O;YACP,cAAc,EAAE,IAAI,sBAAsB,EAAE;SAC/C,CAAC;QACF,MAAM,OAAO,GAAG,IAAI,CAAC,eAAe,CAAC,cAAc,CAAC,KAAK,EAAE,CAAC;QAC5D,IAAI,CAAC,qBAAqB,EAAE,CAAC;QAC7B,OAAO,UAAU,CAAC,CAAC,iCACZ,OAAO,KACV,eAAe,EAAE,IAAI,EACrB,UAAU,EAAE,IAAI,IAClB,CAAC,CAAC,OAAO,CAAC;IAChB,CAAC;IAEO,qBAAqB;QACzB,IAAI,IAAI,CAAC,QAAQ,EAAE;YACf,IAAI,CAAC,sBAAsB,EAAE,CAAC;YAC9B,OAAO,KAAK,CAAC;SAChB;QACD,IACI,IAAI,CAAC,eAAe,KAAK,SAAS;eAC/B,IAAI,CAAC,aAAa,CAAC,oBAAoB,GAAG,IAAI,CAAC,eAAe,CAAC,mBAAmB;eAClF,IAAI,CAAC,eAAe,KAAK,SAAS,EACvC;YACE,uFAAuF;YACvF,OAAO,KAAK,CAAC;SAChB;QACD,MAAM,EAAE,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC,eAAe,CAAC;QACjE,+FAA+F;QAC/F,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QACjC,IAAI,CAAC,gBAAgB,CACjB,EAAE,MAAM,EAAE,mBAAmB,MAAM,EAAE,EAAE,EACvC,OAAO,EACP,IAAI,CAAC,iBAAiB,EACtB,cAAc,CAAC,CAAC;QACpB,OAAO,IAAI,CAAC;IAChB,CAAC;IAEO,sBAAsB;QAC1B,IAAI,IAAI,CAAC,eAAe,KAAK,SAAS,EAAE;YACpC,IAAI,CAAC,eAAe,CAAC,cAAc,CAAC,IAAI,CAAC,uCAAuC,EAAE,SAAS,CAAC,CAAC;YAC7F,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;SACpC;IACL,CAAC;CACJ","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { IDisposable, ITelemetryLogger } from \"@fluidframework/common-definitions\";\nimport { assert, delay, Deferred, PromiseTimer } from \"@fluidframework/common-utils\";\nimport { UsageError } from \"@fluidframework/container-utils\";\nimport { isRuntimeMessage } from \"@fluidframework/driver-utils\";\nimport {\n ISequencedDocumentMessage,\n MessageType,\n} from \"@fluidframework/protocol-definitions\";\nimport { ChildLogger } from \"@fluidframework/telemetry-utils\";\nimport {\n ISummaryConfiguration,\n} from \"./containerRuntime\";\nimport { opSize } from \"./opProperties\";\nimport { SummarizeHeuristicRunner } from \"./summarizerHeuristics\";\nimport {\n IEnqueueSummarizeOptions,\n ISummarizeOptions,\n ISummarizeHeuristicData,\n ISummarizeHeuristicRunner,\n IOnDemandSummarizeOptions,\n EnqueueSummarizeResult,\n SummarizerStopReason,\n ISubmitSummaryOptions,\n SubmitSummaryResult,\n ISummaryCancellationToken,\n ISummarizeResults,\n ISummarizeTelemetryProperties,\n ISummarizerRuntime,\n ISummarizeRunnerTelemetry,\n} from \"./summarizerTypes\";\nimport { IClientSummaryWatcher, SummaryCollection } from \"./summaryCollection\";\nimport {\n raceTimer,\n SummarizeReason,\n SummarizeResultBuilder,\n SummaryGenerator,\n} from \"./summaryGenerator\";\n\nconst maxSummarizeAckWaitTime = 10 * 60 * 1000; // 10 minutes\n\n/**\n * An instance of RunningSummarizer manages the heuristics for summarizing.\n * Until disposed, the instance of RunningSummarizer can assume that it is\n * in a state of running, meaning it is connected and initialized. It keeps\n * track of summaries that it is generating as they are broadcast and acked/nacked.\n * This object is created and controlled by Summarizer object.\n */\nexport class RunningSummarizer implements IDisposable {\n public static async start(\n logger: ITelemetryLogger,\n summaryWatcher: IClientSummaryWatcher,\n configuration: ISummaryConfiguration,\n submitSummaryCallback: (options: ISubmitSummaryOptions) => Promise<SubmitSummaryResult>,\n heuristicData: ISummarizeHeuristicData,\n raiseSummarizingError: (errorMessage: string) => void,\n summaryCollection: SummaryCollection,\n cancellationToken: ISummaryCancellationToken,\n stopSummarizerCallback: (reason: SummarizerStopReason) => void,\n runtime: ISummarizerRuntime,\n ): Promise<RunningSummarizer> {\n const summarizer = new RunningSummarizer(\n logger,\n summaryWatcher,\n configuration,\n submitSummaryCallback,\n heuristicData,\n raiseSummarizingError,\n summaryCollection,\n cancellationToken,\n stopSummarizerCallback,\n runtime);\n\n await summarizer.waitStart();\n\n // Update heuristic counts\n // By the time we get here, there are potentially ops missing from the heuristic summary counts\n // Examples of where this could happen:\n // 1. Op is processed during the time that we are initiating the RunningSummarizer instance but before we\n // listen for the op events (will get missed by the handlers in the current workflow)\n // 2. Op was sequenced after the last time we summarized (op sequence number > summarize ref sequence number)\n const diff = runtime.deltaManager.lastSequenceNumber - (\n heuristicData.lastSuccessfulSummary.refSequenceNumber\n + heuristicData.numNonRuntimeOps\n + heuristicData.numRuntimeOps);\n heuristicData.hasMissingOpData = diff > 0;\n\n if (heuristicData.hasMissingOpData) {\n // Split the diff 50-50 and increment the counts appropriately\n heuristicData.numNonRuntimeOps += Math.ceil(diff / 2);\n heuristicData.numRuntimeOps += Math.floor(diff / 2);\n }\n\n // Update last seq number (in case the handlers haven't processed anything yet)\n heuristicData.lastOpSequenceNumber = runtime.deltaManager.lastSequenceNumber;\n\n // Start heuristics\n summarizer.heuristicRunner?.start();\n summarizer.heuristicRunner?.run();\n\n return summarizer;\n }\n\n public get disposed() { return this._disposed; }\n\n private stopping = false;\n private _disposed = false;\n private summarizingLock: Promise<void> | undefined;\n private tryWhileSummarizing = false;\n private readonly pendingAckTimer: PromiseTimer;\n private heuristicRunner?: ISummarizeHeuristicRunner;\n private readonly generator: SummaryGenerator;\n private readonly logger: ITelemetryLogger;\n private enqueuedSummary: {\n reason: SummarizeReason;\n afterSequenceNumber: number;\n options: ISummarizeOptions;\n readonly resultsBuilder: SummarizeResultBuilder;\n } | undefined;\n private summarizeCount = 0;\n private totalSuccessfulAttempts = 0;\n private initialized = false;\n\n private constructor(\n baseLogger: ITelemetryLogger,\n private readonly summaryWatcher: IClientSummaryWatcher,\n private readonly configuration: ISummaryConfiguration,\n private readonly submitSummaryCallback: (options: ISubmitSummaryOptions) => Promise<SubmitSummaryResult>,\n private readonly heuristicData: ISummarizeHeuristicData,\n private readonly raiseSummarizingError: (errorMessage: string) => void,\n private readonly summaryCollection: SummaryCollection,\n private readonly cancellationToken: ISummaryCancellationToken,\n private readonly stopSummarizerCallback: (reason: SummarizerStopReason) => void,\n private readonly runtime: ISummarizerRuntime,\n ) {\n const telemetryProps: ISummarizeRunnerTelemetry = {\n summarizeCount: () => this.summarizeCount,\n summarizerSuccessfulAttempts: () => this.totalSuccessfulAttempts,\n };\n\n this.logger = ChildLogger.create(\n baseLogger, \"Running\",\n {\n all: telemetryProps,\n },\n );\n\n if (configuration.state !== \"disableHeuristics\") {\n assert(this.configuration.state === \"enabled\", 0x2ea /* \"Configuration state should be enabled\" */);\n this.heuristicRunner = new SummarizeHeuristicRunner(\n heuristicData,\n this.configuration,\n (reason) => this.trySummarize(reason),\n this.logger);\n }\n\n assert(\n this.configuration.state !== \"disabled\",\n 0x2eb /* \"Summary not supported with configuration disabled\" */,\n );\n\n // Cap the maximum amount of time client will wait for a summarize op ack to maxSummarizeAckWaitTime\n // configuration.maxAckWaitTime is composed from defaults, server values, and runtime overrides\n\n const maxAckWaitTime = Math.min(this.configuration.maxAckWaitTime, maxSummarizeAckWaitTime);\n\n this.pendingAckTimer = new PromiseTimer(\n maxAckWaitTime,\n () => {\n // pre-0.58 error message: summaryAckWaitTimeout\n this.raiseSummarizingError(\"Pending summary ack not received in time\");\n // Note: summarizeCount (from ChildLogger definition) may be 0,\n // since this code path is hit when RunningSummarizer first starts up,\n // before this instance has kicked off a new summarize run.\n this.logger.sendErrorEvent({\n eventName: \"SummaryAckWaitTimeout\",\n maxAckWaitTime,\n referenceSequenceNumber: this.heuristicData.lastAttempt.refSequenceNumber,\n summarySequenceNumber: this.heuristicData.lastAttempt.summarySequenceNumber,\n timePending: Date.now() - this.heuristicData.lastAttempt.summaryTime,\n });\n });\n // Set up pending ack timeout by op timestamp differences for previous summaries.\n summaryCollection.setPendingAckTimerTimeoutCallback(maxAckWaitTime, () => {\n if (this.pendingAckTimer.hasTimer) {\n this.logger.sendTelemetryEvent({\n eventName: \"MissingSummaryAckFoundByOps\",\n referenceSequenceNumber: this.heuristicData.lastAttempt.refSequenceNumber,\n summarySequenceNumber: this.heuristicData.lastAttempt.summarySequenceNumber,\n });\n this.pendingAckTimer.clear();\n }\n });\n\n this.generator = new SummaryGenerator(\n this.pendingAckTimer,\n this.heuristicData,\n this.submitSummaryCallback,\n this.raiseSummarizingError,\n () => { this.totalSuccessfulAttempts++; },\n this.summaryWatcher,\n this.logger,\n );\n\n // Listen for ops\n this.runtime.deltaManager.on(\"op\", (op) => { this.handleOp(op); });\n }\n\n public dispose(): void {\n this.runtime.deltaManager.off(\"op\", (op) => { this.handleOp(op); });\n this.summaryWatcher.dispose();\n this.heuristicRunner?.dispose();\n this.heuristicRunner = undefined;\n this.generator.dispose();\n this.pendingAckTimer.clear();\n this.disposeEnqueuedSummary();\n this._disposed = true;\n this.stopping = true;\n }\n\n /**\n * RunningSummarizer's logger includes the sequenced index of the current summary on each event.\n * If some other Summarizer code wants that event on their logs they can get it here,\n * but only if they're logging about that same summary.\n * @param summaryOpRefSeq - RefSeq number of the summary op, to ensure the log correlation will be correct\n */\n public tryGetCorrelatedLogger = (summaryOpRefSeq) =>\n this.heuristicData.lastAttempt.refSequenceNumber === summaryOpRefSeq\n ? this.logger\n : undefined;\n\n /** We only want a single heuristic runner micro-task (will provide better optimized grouping of ops) */\n private heuristicRunnerMicroTaskExists = false;\n\n public handleOp(op: ISequencedDocumentMessage) {\n this.heuristicData.lastOpSequenceNumber = op.sequenceNumber;\n\n if (op.type !== MessageType.Summarize && isRuntimeMessage(op)) {\n this.heuristicData.numRuntimeOps++;\n } else {\n this.heuristicData.numNonRuntimeOps++;\n }\n\n this.heuristicData.totalOpsSize += opSize(op);\n\n // Check for enqueued on-demand summaries; Intentionally do nothing otherwise\n if (this.initialized\n && this.opCanTriggerSummary(op)\n && !this.tryRunEnqueuedSummary()\n && !this.heuristicRunnerMicroTaskExists) {\n this.heuristicRunnerMicroTaskExists = true;\n Promise.resolve().then(() => {\n this.heuristicRunner?.run();\n }).finally(() => {\n this.heuristicRunnerMicroTaskExists = false;\n });\n }\n }\n\n /**\n * Can the given op trigger a summary?\n * # Currently only prevents summaries for Summarize and SummaryAck ops\n * @param op - op to check\n * @returns true if this type of op can trigger a summary\n */\n private opCanTriggerSummary(op: ISequencedDocumentMessage): boolean {\n switch (op.type) {\n case MessageType.Summarize:\n case MessageType.SummaryAck:\n case MessageType.SummaryNack:\n return false;\n default:\n return true;\n }\n }\n\n public async waitStop(allowLastSummary: boolean): Promise<void> {\n if (this.stopping) {\n return;\n }\n\n this.stopping = true;\n\n this.disposeEnqueuedSummary();\n\n // This will try to run lastSummary if needed.\n if (allowLastSummary && this.heuristicRunner?.shouldRunLastSummary()) {\n if (this.summarizingLock === undefined) {\n this.trySummarizeOnce(\n // summarizeProps\n { reason: \"lastSummary\" },\n // ISummarizeOptions, using defaults: { refreshLatestAck: false, fullTree: false }\n {});\n }\n }\n\n // Note that trySummarizeOnce() call above returns right away, without waiting.\n // So we need to wait for its completion, otherwise it would be destroyed right away.\n // That said, if summary lock was taken upfront, this wait might wait on multiple retries to\n // submit summary. We should reconsider this flow and make summarizer move to exit faster.\n // This resolves when the current pending summary gets an ack or fails.\n await this.summarizingLock;\n }\n\n private async waitStart() {\n // Wait no longer than ack timeout for all pending\n const waitStartResult = await raceTimer(\n this.summaryWatcher.waitFlushed(),\n this.pendingAckTimer.start(),\n );\n this.pendingAckTimer.clear();\n\n // Remove pending ack wait timeout by op timestamp comparison, because\n // it has race conditions with summaries submitted by this same client.\n this.summaryCollection.unsetPendingAckTimerTimeoutCallback();\n\n if (waitStartResult.result === \"done\" && waitStartResult.value !== undefined) {\n this.heuristicData.updateWithLastSummaryAckInfo({\n refSequenceNumber: waitStartResult.value.summaryOp.referenceSequenceNumber,\n // This will be the Summarizer starting point so only use timestamps from client's machine.\n summaryTime: Date.now(),\n summarySequenceNumber: waitStartResult.value.summaryOp.sequenceNumber,\n });\n }\n this.initialized = true;\n }\n\n /**\n * Runs single summary action that prevents any other concurrent actions.\n * Assumes that caller checked upfront for lack of concurrent action (this.summarizingLock)\n * before calling this API. I.e. caller is responsible for either erroring out or waiting on this promise.\n * @param action - action to perform.\n * @returns - result of action.\n */\n private async lockedSummaryAction<T>(action: () => Promise<T>) {\n assert(this.summarizingLock === undefined, 0x25b /* \"Caller is responsible for checking lock\" */);\n\n const summarizingLock = new Deferred<void>();\n this.summarizingLock = summarizingLock.promise;\n\n this.summarizeCount++;\n\n return action().finally(() => {\n summarizingLock.resolve();\n this.summarizingLock = undefined;\n\n const retry = this.tryWhileSummarizing;\n this.tryWhileSummarizing = false;\n\n // After summarizing, we should check to see if we need to summarize again.\n // Rerun the heuristics and check for enqueued summaries.\n if (!this.stopping && !this.tryRunEnqueuedSummary() && retry) {\n this.heuristicRunner?.run();\n }\n });\n }\n\n /**\n * Runs single summarize attempt\n * @param summarizeProps - props to log with each telemetry event associated with this attempt\n * @param options - summary options\n * @param cancellationToken - cancellation token to use to be able to cancel this summary, if needed\n * @param resultsBuilder - optional, result builder to use.\n * @returns ISummarizeResult - result of running a summary.\n */\n private trySummarizeOnce(\n summarizeProps: ISummarizeTelemetryProperties,\n options: ISummarizeOptions,\n cancellationToken = this.cancellationToken,\n resultsBuilder = new SummarizeResultBuilder()): ISummarizeResults {\n this.lockedSummaryAction(async () => {\n const summarizeResult = this.generator.summarize(\n summarizeProps,\n options,\n cancellationToken,\n resultsBuilder);\n // ensure we wait till the end of the process\n return summarizeResult.receivedSummaryAckOrNack;\n }).catch((error) => {\n // SummaryGenerator.summarize() does not throw exceptions - it converts them to failed result\n // on resultsBuilder\n // We do not care about exceptions on receivedSummaryAckOrNack - caller should check results\n // and take a appropriate action.\n });\n\n return resultsBuilder.build();\n }\n\n /** Heuristics summarize attempt. */\n private trySummarize(\n reason: SummarizeReason,\n cancellationToken = this.cancellationToken): void {\n if (this.summarizingLock !== undefined) {\n // lockedSummaryAction() will retry heuristic-based summary at the end of current attempt\n // if it's still needed\n this.tryWhileSummarizing = true;\n return;\n }\n\n this.lockedSummaryAction(async () => {\n const attempts: (ISummarizeOptions & { delaySeconds?: number; })[] = [\n { refreshLatestAck: false, fullTree: false },\n { refreshLatestAck: true, fullTree: false },\n { refreshLatestAck: true, fullTree: false, delaySeconds: 2 * 60 },\n { refreshLatestAck: true, fullTree: true, delaySeconds: 10 * 60 },\n ];\n let overrideDelaySeconds: number | undefined;\n let summaryAttempts = 0;\n let summaryAttemptsPerPhase = 0;\n\n let lastResult: { message: string; error: any; } | undefined;\n\n for (let summaryAttemptPhase = 0; summaryAttemptPhase < attempts.length;) {\n if (this.cancellationToken.cancelled) {\n return;\n }\n\n // We only want to attempt 1 summary when reason is \"lastSummary\"\n if (++summaryAttempts > 1 && reason === \"lastSummary\") {\n return;\n }\n\n summaryAttemptsPerPhase++;\n\n const { delaySeconds: regularDelaySeconds = 0, ...options } = attempts[summaryAttemptPhase];\n const delaySeconds = overrideDelaySeconds ?? regularDelaySeconds;\n\n const summarizeProps: ISummarizeTelemetryProperties = {\n reason,\n summaryAttempts,\n summaryAttemptsPerPhase,\n summaryAttemptPhase: summaryAttemptPhase + 1, // make everything 1-based\n ...options,\n };\n\n if (delaySeconds > 0) {\n this.logger.sendPerformanceEvent({\n eventName: \"SummarizeAttemptDelay\",\n duration: delaySeconds,\n summaryNackDelay: overrideDelaySeconds !== undefined,\n ...summarizeProps,\n });\n await delay(delaySeconds * 1000);\n }\n // Note: no need to account for cancellationToken.waitCancelled here, as\n // this is accounted SummaryGenerator.summarizeCore that controls receivedSummaryAckOrNack.\n const resultSummarize = this.generator.summarize(summarizeProps, options, cancellationToken);\n const result = await resultSummarize.receivedSummaryAckOrNack;\n\n if (result.success) {\n return;\n }\n // Check for retryDelay that can come from summaryNack or upload summary flow.\n // Retry the same step only once per retryAfter response.\n overrideDelaySeconds = result.retryAfterSeconds;\n if (overrideDelaySeconds === undefined || summaryAttemptsPerPhase > 1) {\n summaryAttemptPhase++;\n summaryAttemptsPerPhase = 0;\n }\n lastResult = result;\n }\n\n // If all attempts failed, log error (with last attempt info) and close the summarizer container\n this.logger.sendErrorEvent({\n eventName: \"FailToSummarize\",\n reason,\n message: lastResult?.message,\n }, lastResult?.error);\n\n this.stopSummarizerCallback(\"failToSummarize\");\n }).catch((error) => {\n this.logger.sendErrorEvent({ eventName: \"UnexpectedSummarizeError\" }, error);\n });\n }\n\n /** {@inheritdoc (ISummarizer:interface).summarizeOnDemand} */\n public summarizeOnDemand(\n resultsBuilder: SummarizeResultBuilder = new SummarizeResultBuilder(),\n {\n reason,\n ...options\n }: IOnDemandSummarizeOptions): ISummarizeResults {\n if (this.stopping) {\n resultsBuilder.fail(\"RunningSummarizer stopped or disposed\", undefined);\n return resultsBuilder.build();\n }\n // Check for concurrent summary attempts. If one is found,\n // return a promise that caller can await before trying again.\n if (this.summarizingLock !== undefined) {\n // The heuristics are blocking concurrent summarize attempts.\n throw new UsageError(\"Attempted to run an already-running summarizer on demand\");\n }\n const result = this.trySummarizeOnce(\n { reason: `onDemand/${reason}` },\n options,\n this.cancellationToken,\n resultsBuilder);\n return result;\n }\n\n /** {@inheritdoc (ISummarizer:interface).enqueueSummarize} */\n public enqueueSummarize({\n reason,\n afterSequenceNumber = 0,\n override = false,\n ...options\n }: IEnqueueSummarizeOptions): EnqueueSummarizeResult {\n const onDemandReason = `enqueue;${reason}` as const;\n let overridden = false;\n if (this.enqueuedSummary !== undefined) {\n if (!override) {\n return { alreadyEnqueued: true };\n }\n // Override existing enqueued summarize attempt.\n this.enqueuedSummary.resultsBuilder.fail(\n \"Aborted; overridden by another enqueue summarize attempt\",\n undefined,\n );\n this.enqueuedSummary = undefined;\n overridden = true;\n }\n this.enqueuedSummary = {\n reason: onDemandReason,\n afterSequenceNumber,\n options,\n resultsBuilder: new SummarizeResultBuilder(),\n };\n const results = this.enqueuedSummary.resultsBuilder.build();\n this.tryRunEnqueuedSummary();\n return overridden ? {\n ...results,\n alreadyEnqueued: true,\n overridden: true,\n } : results;\n }\n\n private tryRunEnqueuedSummary() {\n if (this.stopping) {\n this.disposeEnqueuedSummary();\n return false;\n }\n if (\n this.enqueuedSummary === undefined\n || this.heuristicData.lastOpSequenceNumber < this.enqueuedSummary.afterSequenceNumber\n || this.summarizingLock !== undefined\n ) {\n // If no enqueued summary is ready or a summary is already in progress, take no action.\n return false;\n }\n const { reason, resultsBuilder, options } = this.enqueuedSummary;\n // Set to undefined first, so that subsequent enqueue attempt while summarize will occur later.\n this.enqueuedSummary = undefined;\n this.trySummarizeOnce(\n { reason: `enqueuedSummary/${reason}` },\n options,\n this.cancellationToken,\n resultsBuilder);\n return true;\n }\n\n private disposeEnqueuedSummary() {\n if (this.enqueuedSummary !== undefined) {\n this.enqueuedSummary.resultsBuilder.fail(\"RunningSummarizer stopped or disposed\", undefined);\n this.enqueuedSummary = undefined;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"runningSummarizer.js","sourceRoot":"","sources":["../src/runningSummarizer.ts"],"names":[],"mappings":"AAAA;;;GAGG;;;;;;;;;;;;AAGH,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AACrF,OAAO,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,EAEH,WAAW,GACd,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAI9D,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAkBlE,OAAO,EACH,SAAS,EAET,sBAAsB,EACtB,gBAAgB,GACnB,MAAM,oBAAo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zB,IAAI,IAAI,CAAC,QAAQ,EAAE;YACf,IAAI,CAAC,sBAAsB,EAAE,CAAC;YAC9B,OAAO,KAAK,CAAC;SAChB;QACD,IACI,IAAI,CAAC,eAAe,KAAK,SAAS;eAC/B,IAAI,CAAC,aAAa,CAAC,oBAAoB,GAAG,IAAI,CAAC,eAAe,CAAC,mBAAmB;eAClF,IAAI,CAAC,eAAe,KAAK,SAAS,EACvC;YACE,uFAAuF;YACvF,OAAO,KAAK,CAAC;SAChB;QACD,MAAM,EAAE,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC,eAAe,CAAC;QACjE,+FAA+F;QAC/F,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QACjC,IAAI,CAAC,gBAAgB,CACjB,EAAE,MAAM,EAAE,mBAAmB,MAAM,EAAE,EAAE,EACvC,OAAO,EACP,IAAI,CAAC,iBAAiB,EACtB,cAAc,CAAC,CAAC;QACpB,OAAO,IAAI,CAAC;IAChB,CAAC;IAEO,sBAAsB;QAC1B,IAAI,IAAI,CAAC,eAAe,KAAK,SAAS,EAAE;YACpC,IAAI,CAAC,eAAe,CAAC,cAAc,CAAC,IAAI,CAAC,uCAAuC,EAAE,SAAS,CAAC,CAAC;YAC7F,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;SACpC;IACL,CAAC;CACJ","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { IDisposable, ITelemetryLogger } from \"@fluidframework/common-definitions\";\nimport { assert, delay, Deferred, PromiseTimer } from \"@fluidframework/common-utils\";\nimport { UsageError } from \"@fluidframework/container-utils\";\nimport { isRuntimeMessage } from \"@fluidframework/driver-utils\";\nimport {\n ISequencedDocumentMessage,\n MessageType,\n} from \"@fluidframework/protocol-definitions\";\nimport { ChildLogger } from \"@fluidframework/telemetry-utils\";\nimport {\n ISummaryConfiguration,\n} from \"./containerRuntime\";\nimport { opSize } from \"./opProperties\";\nimport { SummarizeHeuristicRunner } from \"./summarizerHeuristics\";\nimport {\n IEnqueueSummarizeOptions,\n ISummarizeOptions,\n ISummarizeHeuristicData,\n ISummarizeHeuristicRunner,\n IOnDemandSummarizeOptions,\n EnqueueSummarizeResult,\n SummarizerStopReason,\n ISubmitSummaryOptions,\n SubmitSummaryResult,\n ISummaryCancellationToken,\n ISummarizeResults,\n ISummarizeTelemetryProperties,\n ISummarizerRuntime,\n ISummarizeRunnerTelemetry,\n} from \"./summarizerTypes\";\nimport { IClientSummaryWatcher, SummaryCollection } from \"./summaryCollection\";\nimport {\n raceTimer,\n SummarizeReason,\n SummarizeResultBuilder,\n SummaryGenerator,\n} from \"./summaryGenerator\";\n\nconst maxSummarizeAckWaitTime = 10 * 60 * 1000; // 10 minutes\n\n/**\n * An instance of RunningSummarizer manages the heuristics for summarizing.\n * Until disposed, the instance of RunningSummarizer can assume that it is\n * in a state of running, meaning it is connected and initialized. It keeps\n * track of summaries that it is generating as they are broadcast and acked/nacked.\n * This object is created and controlled by Summarizer object.\n */\nexport class RunningSummarizer implements IDisposable {\n public static async start(\n logger: ITelemetryLogger,\n summaryWatcher: IClientSummaryWatcher,\n configuration: ISummaryConfiguration,\n submitSummaryCallback: (options: ISubmitSummaryOptions) => Promise<SubmitSummaryResult>,\n heuristicData: ISummarizeHeuristicData,\n raiseSummarizingError: (errorMessage: string) => void,\n summaryCollection: SummaryCollection,\n cancellationToken: ISummaryCancellationToken,\n stopSummarizerCallback: (reason: SummarizerStopReason) => void,\n runtime: ISummarizerRuntime,\n ): Promise<RunningSummarizer> {\n const summarizer = new RunningSummarizer(\n logger,\n summaryWatcher,\n configuration,\n submitSummaryCallback,\n heuristicData,\n raiseSummarizingError,\n summaryCollection,\n cancellationToken,\n stopSummarizerCallback,\n runtime);\n\n await summarizer.waitStart();\n\n // Update heuristic counts\n // By the time we get here, there are potentially ops missing from the heuristic summary counts\n // Examples of where this could happen:\n // 1. Op is processed during the time that we are initiating the RunningSummarizer instance but before we\n // listen for the op events (will get missed by the handlers in the current workflow)\n // 2. Op was sequenced after the last time we summarized (op sequence number > summarize ref sequence number)\n const diff = runtime.deltaManager.lastSequenceNumber - (\n heuristicData.lastSuccessfulSummary.refSequenceNumber\n + heuristicData.numNonRuntimeOps\n + heuristicData.numRuntimeOps);\n heuristicData.hasMissingOpData = diff > 0;\n\n if (heuristicData.hasMissingOpData) {\n // Split the diff 50-50 and increment the counts appropriately\n heuristicData.numNonRuntimeOps += Math.ceil(diff / 2);\n heuristicData.numRuntimeOps += Math.floor(diff / 2);\n }\n\n // Update last seq number (in case the handlers haven't processed anything yet)\n heuristicData.lastOpSequenceNumber = runtime.deltaManager.lastSequenceNumber;\n\n // Start heuristics\n summarizer.heuristicRunner?.start();\n summarizer.heuristicRunner?.run();\n\n return summarizer;\n }\n\n public get disposed() { return this._disposed; }\n private stopping = false;\n private _disposed = false;\n private summarizingLock: Promise<void> | undefined;\n private refreshSummaryAckLock: Promise<void> | undefined;\n private tryWhileSummarizing = false;\n private readonly pendingAckTimer: PromiseTimer;\n private heuristicRunner?: ISummarizeHeuristicRunner;\n private readonly generator: SummaryGenerator;\n private readonly logger: ITelemetryLogger;\n private enqueuedSummary: {\n reason: SummarizeReason;\n afterSequenceNumber: number;\n options: ISummarizeOptions;\n readonly resultsBuilder: SummarizeResultBuilder;\n } | undefined;\n private summarizeCount = 0;\n private totalSuccessfulAttempts = 0;\n private initialized = false;\n\n private constructor(\n baseLogger: ITelemetryLogger,\n private readonly summaryWatcher: IClientSummaryWatcher,\n private readonly configuration: ISummaryConfiguration,\n private readonly submitSummaryCallback: (options: ISubmitSummaryOptions) => Promise<SubmitSummaryResult>,\n private readonly heuristicData: ISummarizeHeuristicData,\n private readonly raiseSummarizingError: (errorMessage: string) => void,\n private readonly summaryCollection: SummaryCollection,\n private readonly cancellationToken: ISummaryCancellationToken,\n private readonly stopSummarizerCallback: (reason: SummarizerStopReason) => void,\n private readonly runtime: ISummarizerRuntime,\n ) {\n const telemetryProps: ISummarizeRunnerTelemetry = {\n summarizeCount: () => this.summarizeCount,\n summarizerSuccessfulAttempts: () => this.totalSuccessfulAttempts,\n };\n\n this.logger = ChildLogger.create(\n baseLogger, \"Running\",\n {\n all: telemetryProps,\n },\n );\n\n if (configuration.state !== \"disableHeuristics\") {\n assert(this.configuration.state === \"enabled\", 0x2ea /* \"Configuration state should be enabled\" */);\n this.heuristicRunner = new SummarizeHeuristicRunner(\n heuristicData,\n this.configuration,\n (reason) => this.trySummarize(reason),\n this.logger);\n }\n\n assert(\n this.configuration.state !== \"disabled\",\n 0x2eb /* \"Summary not supported with configuration disabled\" */,\n );\n\n // Cap the maximum amount of time client will wait for a summarize op ack to maxSummarizeAckWaitTime\n // configuration.maxAckWaitTime is composed from defaults, server values, and runtime overrides\n\n const maxAckWaitTime = Math.min(this.configuration.maxAckWaitTime, maxSummarizeAckWaitTime);\n\n this.pendingAckTimer = new PromiseTimer(\n maxAckWaitTime,\n () => {\n // pre-0.58 error message: summaryAckWaitTimeout\n this.raiseSummarizingError(\"Pending summary ack not received in time\");\n // Note: summarizeCount (from ChildLogger definition) may be 0,\n // since this code path is hit when RunningSummarizer first starts up,\n // before this instance has kicked off a new summarize run.\n this.logger.sendErrorEvent({\n eventName: \"SummaryAckWaitTimeout\",\n maxAckWaitTime,\n referenceSequenceNumber: this.heuristicData.lastAttempt.refSequenceNumber,\n summarySequenceNumber: this.heuristicData.lastAttempt.summarySequenceNumber,\n timePending: Date.now() - this.heuristicData.lastAttempt.summaryTime,\n });\n });\n // Set up pending ack timeout by op timestamp differences for previous summaries.\n summaryCollection.setPendingAckTimerTimeoutCallback(maxAckWaitTime, () => {\n if (this.pendingAckTimer.hasTimer) {\n this.logger.sendTelemetryEvent({\n eventName: \"MissingSummaryAckFoundByOps\",\n referenceSequenceNumber: this.heuristicData.lastAttempt.refSequenceNumber,\n summarySequenceNumber: this.heuristicData.lastAttempt.summarySequenceNumber,\n });\n this.pendingAckTimer.clear();\n }\n });\n\n this.generator = new SummaryGenerator(\n this.pendingAckTimer,\n this.heuristicData,\n this.submitSummaryCallback,\n this.raiseSummarizingError,\n () => { this.totalSuccessfulAttempts++; },\n this.summaryWatcher,\n this.logger,\n );\n\n // Listen for ops\n this.runtime.deltaManager.on(\"op\", (op) => { this.handleOp(op); });\n }\n\n public dispose(): void {\n this.runtime.deltaManager.off(\"op\", (op) => { this.handleOp(op); });\n this.summaryWatcher.dispose();\n this.heuristicRunner?.dispose();\n this.heuristicRunner = undefined;\n this.generator.dispose();\n this.pendingAckTimer.clear();\n this.disposeEnqueuedSummary();\n this._disposed = true;\n this.stopping = true;\n }\n\n /**\n * RunningSummarizer's logger includes the sequenced index of the current summary on each event.\n * If some other Summarizer code wants that event on their logs they can get it here,\n * but only if they're logging about that same summary.\n * @param summaryOpRefSeq - RefSeq number of the summary op, to ensure the log correlation will be correct\n */\n public tryGetCorrelatedLogger = (summaryOpRefSeq) =>\n this.heuristicData.lastAttempt.refSequenceNumber === summaryOpRefSeq\n ? this.logger\n : undefined;\n\n /** We only want a single heuristic runner micro-task (will provide better optimized grouping of ops) */\n private heuristicRunnerMicroTaskExists = false;\n\n public handleOp(op: ISequencedDocumentMessage) {\n this.heuristicData.lastOpSequenceNumber = op.sequenceNumber;\n\n if (op.type !== MessageType.Summarize && isRuntimeMessage(op)) {\n this.heuristicData.numRuntimeOps++;\n } else {\n this.heuristicData.numNonRuntimeOps++;\n }\n\n this.heuristicData.totalOpsSize += opSize(op);\n\n // Check for enqueued on-demand summaries; Intentionally do nothing otherwise\n if (this.initialized\n && this.opCanTriggerSummary(op)\n && !this.tryRunEnqueuedSummary()\n && !this.heuristicRunnerMicroTaskExists) {\n this.heuristicRunnerMicroTaskExists = true;\n Promise.resolve().then(() => {\n this.heuristicRunner?.run();\n }).finally(() => {\n this.heuristicRunnerMicroTaskExists = false;\n });\n }\n }\n\n /**\n * Can the given op trigger a summary?\n * # Currently only prevents summaries for Summarize and SummaryAck ops\n * @param op - op to check\n * @returns true if this type of op can trigger a summary\n */\n private opCanTriggerSummary(op: ISequencedDocumentMessage): boolean {\n switch (op.type) {\n case MessageType.Summarize:\n case MessageType.SummaryAck:\n case MessageType.SummaryNack:\n return false;\n default:\n return true;\n }\n }\n\n public async waitStop(allowLastSummary: boolean): Promise<void> {\n if (this.stopping) {\n return;\n }\n\n this.stopping = true;\n\n this.disposeEnqueuedSummary();\n\n // This will try to run lastSummary if needed.\n if (allowLastSummary && this.heuristicRunner?.shouldRunLastSummary()) {\n if (this.summarizingLock === undefined) {\n this.trySummarizeOnce(\n // summarizeProps\n { reason: \"lastSummary\" },\n // ISummarizeOptions, using defaults: { refreshLatestAck: false, fullTree: false }\n {});\n }\n }\n\n // Note that trySummarizeOnce() call above returns right away, without waiting.\n // So we need to wait for its completion, otherwise it would be destroyed right away.\n // That said, if summary lock was taken upfront, this wait might wait on multiple retries to\n // submit summary. We should reconsider this flow and make summarizer move to exit faster.\n // This resolves when the current pending summary gets an ack or fails.\n await this.summarizingLock;\n }\n\n private async waitStart() {\n // Wait no longer than ack timeout for all pending\n const waitStartResult = await raceTimer(\n this.summaryWatcher.waitFlushed(),\n this.pendingAckTimer.start(),\n );\n this.pendingAckTimer.clear();\n\n // Remove pending ack wait timeout by op timestamp comparison, because\n // it has race conditions with summaries submitted by this same client.\n this.summaryCollection.unsetPendingAckTimerTimeoutCallback();\n\n if (waitStartResult.result === \"done\" && waitStartResult.value !== undefined) {\n this.heuristicData.updateWithLastSummaryAckInfo({\n refSequenceNumber: waitStartResult.value.summaryOp.referenceSequenceNumber,\n // This will be the Summarizer starting point so only use timestamps from client's machine.\n summaryTime: Date.now(),\n summarySequenceNumber: waitStartResult.value.summaryOp.sequenceNumber,\n });\n }\n this.initialized = true;\n }\n\n /**\n * Blocks a new summarizer from running in case RefreshSummaryAck is being processed.\n * Assumes that caller checked upfront for lack of concurrent action (this.refreshSummaryAckLock)\n * before calling this API. I.e. caller is responsible for either erroring out or waiting on this promise.\n * Note: The refreshSummaryAckLock makes sure no summarizer gets enqueued or processed\n * until the refresh has completed. One can't rely uniquely on the summarizingLock as the\n * refreshLatestSummaryAck also happens during the time summarizingLock !== undefined.\n * Ex. Summarizer submits a summay + op and then waits for the Summary Ack to proceed\n * with the refreshLatestSummaryAck and complete the summary.\n * @param action - action to perform.\n * @returns - result of action.\n */\n public async lockedRefreshSummaryAckAction<T>(action: () => Promise<T>) {\n assert(this.refreshSummaryAckLock === undefined,\n 0x396 /* Refresh Summary Ack - Caller is responsible for checking lock */);\n\n const refreshSummaryAckLock = new Deferred<void>();\n this.refreshSummaryAckLock = refreshSummaryAckLock.promise;\n\n return action().finally(() => {\n refreshSummaryAckLock.resolve();\n this.refreshSummaryAckLock = undefined;\n });\n }\n\n /**\n * Runs single summary action that prevents any other concurrent actions.\n * Assumes that caller checked upfront for lack of concurrent action (this.summarizingLock)\n * before calling this API. I.e. caller is responsible for either erroring out or waiting on this promise.\n * @param action - action to perform.\n * @returns - result of action.\n */\n private async lockedSummaryAction<T>(action: () => Promise<T>) {\n assert(this.summarizingLock === undefined, 0x25b /* \"Caller is responsible for checking lock\" */);\n\n const summarizingLock = new Deferred<void>();\n this.summarizingLock = summarizingLock.promise;\n\n this.summarizeCount++;\n // Make sure the RefreshLatestSummaryAck is not being executed.\n await this.refreshSummaryAckLock;\n\n return action().finally(() => {\n summarizingLock.resolve();\n this.summarizingLock = undefined;\n\n const retry = this.tryWhileSummarizing;\n this.tryWhileSummarizing = false;\n\n // After summarizing, we should check to see if we need to summarize again.\n // Rerun the heuristics and check for enqueued summaries.\n if (!this.stopping && !this.tryRunEnqueuedSummary() && retry) {\n this.heuristicRunner?.run();\n }\n });\n }\n\n /**\n * Runs single summarize attempt\n * @param summarizeProps - props to log with each telemetry event associated with this attempt\n * @param options - summary options\n * @param cancellationToken - cancellation token to use to be able to cancel this summary, if needed\n * @param resultsBuilder - optional, result builder to use.\n * @returns ISummarizeResult - result of running a summary.\n */\n private trySummarizeOnce(\n summarizeProps: ISummarizeTelemetryProperties,\n options: ISummarizeOptions,\n cancellationToken = this.cancellationToken,\n resultsBuilder = new SummarizeResultBuilder()): ISummarizeResults {\n this.lockedSummaryAction(async () => {\n const summarizeResult = this.generator.summarize(\n summarizeProps,\n options,\n cancellationToken,\n resultsBuilder);\n // ensure we wait till the end of the process\n return summarizeResult.receivedSummaryAckOrNack;\n }).catch((error) => {\n // SummaryGenerator.summarize() does not throw exceptions - it converts them to failed result\n // on resultsBuilder\n // We do not care about exceptions on receivedSummaryAckOrNack - caller should check results\n // and take a appropriate action.\n });\n\n return resultsBuilder.build();\n }\n\n /** Heuristics summarize attempt. */\n private trySummarize(\n reason: SummarizeReason,\n cancellationToken = this.cancellationToken): void {\n if (this.summarizingLock !== undefined) {\n // lockedSummaryAction() will retry heuristic-based summary at the end of current attempt\n // if it's still needed\n this.tryWhileSummarizing = true;\n return;\n }\n\n this.lockedSummaryAction(async () => {\n const attempts: (ISummarizeOptions & { delaySeconds?: number; })[] = [\n { refreshLatestAck: false, fullTree: false },\n { refreshLatestAck: true, fullTree: false },\n { refreshLatestAck: true, fullTree: false, delaySeconds: 2 * 60 },\n { refreshLatestAck: true, fullTree: true, delaySeconds: 10 * 60 },\n ];\n let overrideDelaySeconds: number | undefined;\n let summaryAttempts = 0;\n let summaryAttemptsPerPhase = 0;\n\n let lastResult: { message: string; error: any; } | undefined;\n\n for (let summaryAttemptPhase = 0; summaryAttemptPhase < attempts.length;) {\n if (this.cancellationToken.cancelled) {\n return;\n }\n\n // We only want to attempt 1 summary when reason is \"lastSummary\"\n if (++summaryAttempts > 1 && reason === \"lastSummary\") {\n return;\n }\n\n summaryAttemptsPerPhase++;\n\n const { delaySeconds: regularDelaySeconds = 0, ...options } = attempts[summaryAttemptPhase];\n const delaySeconds = overrideDelaySeconds ?? regularDelaySeconds;\n\n const summarizeProps: ISummarizeTelemetryProperties = {\n reason,\n summaryAttempts,\n summaryAttemptsPerPhase,\n summaryAttemptPhase: summaryAttemptPhase + 1, // make everything 1-based\n ...options,\n };\n\n if (delaySeconds > 0) {\n this.logger.sendPerformanceEvent({\n eventName: \"SummarizeAttemptDelay\",\n duration: delaySeconds,\n summaryNackDelay: overrideDelaySeconds !== undefined,\n ...summarizeProps,\n });\n await delay(delaySeconds * 1000);\n }\n\n // Make sure the refresh Summary Ack is not being executed.\n await this.refreshSummaryAckLock;\n\n // Note: no need to account for cancellationToken.waitCancelled here, as\n // this is accounted SummaryGenerator.summarizeCore that controls receivedSummaryAckOrNack.\n const resultSummarize = this.generator.summarize(summarizeProps, options, cancellationToken);\n const result = await resultSummarize.receivedSummaryAckOrNack;\n\n if (result.success) {\n return;\n }\n // Check for retryDelay that can come from summaryNack or upload summary flow.\n // Retry the same step only once per retryAfter response.\n overrideDelaySeconds = result.retryAfterSeconds;\n if (overrideDelaySeconds === undefined || summaryAttemptsPerPhase > 1) {\n summaryAttemptPhase++;\n summaryAttemptsPerPhase = 0;\n }\n lastResult = result;\n }\n\n // If all attempts failed, log error (with last attempt info) and close the summarizer container\n this.logger.sendErrorEvent({\n eventName: \"FailToSummarize\",\n reason,\n message: lastResult?.message,\n }, lastResult?.error);\n\n this.stopSummarizerCallback(\"failToSummarize\");\n }).catch((error) => {\n this.logger.sendErrorEvent({ eventName: \"UnexpectedSummarizeError\" }, error);\n });\n }\n\n /** {@inheritdoc (ISummarizer:interface).summarizeOnDemand} */\n public summarizeOnDemand(\n resultsBuilder: SummarizeResultBuilder = new SummarizeResultBuilder(),\n {\n reason,\n ...options\n }: IOnDemandSummarizeOptions): ISummarizeResults {\n if (this.stopping) {\n resultsBuilder.fail(\"RunningSummarizer stopped or disposed\", undefined);\n return resultsBuilder.build();\n }\n // Check for concurrent summary attempts. If one is found,\n // return a promise that caller can await before trying again.\n if (this.summarizingLock !== undefined) {\n // The heuristics are blocking concurrent summarize attempts.\n throw new UsageError(\"Attempted to run an already-running summarizer on demand\");\n }\n\n const result = this.trySummarizeOnce(\n { reason: `onDemand/${reason}` },\n options,\n this.cancellationToken,\n resultsBuilder);\n return result;\n }\n\n /** {@inheritdoc (ISummarizer:interface).enqueueSummarize} */\n public enqueueSummarize({\n reason,\n afterSequenceNumber = 0,\n override = false,\n ...options\n }: IEnqueueSummarizeOptions): EnqueueSummarizeResult {\n const onDemandReason = `enqueue;${reason}` as const;\n let overridden = false;\n if (this.enqueuedSummary !== undefined) {\n if (!override) {\n return { alreadyEnqueued: true };\n }\n // Override existing enqueued summarize attempt.\n this.enqueuedSummary.resultsBuilder.fail(\n \"Aborted; overridden by another enqueue summarize attempt\",\n undefined,\n );\n this.enqueuedSummary = undefined;\n overridden = true;\n }\n this.enqueuedSummary = {\n reason: onDemandReason,\n afterSequenceNumber,\n options,\n resultsBuilder: new SummarizeResultBuilder(),\n };\n const results = this.enqueuedSummary.resultsBuilder.build();\n this.tryRunEnqueuedSummary();\n return overridden ? {\n ...results,\n alreadyEnqueued: true,\n overridden: true,\n } : results;\n }\n\n private tryRunEnqueuedSummary() {\n if (this.stopping) {\n this.disposeEnqueuedSummary();\n return false;\n }\n if (\n this.enqueuedSummary === undefined\n || this.heuristicData.lastOpSequenceNumber < this.enqueuedSummary.afterSequenceNumber\n || this.summarizingLock !== undefined\n ) {\n // If no enqueued summary is ready or a summary is already in progress, take no action.\n return false;\n }\n const { reason, resultsBuilder, options } = this.enqueuedSummary;\n // Set to undefined first, so that subsequent enqueue attempt while summarize will occur later.\n this.enqueuedSummary = undefined;\n this.trySummarizeOnce(\n { reason: `enqueuedSummary/${reason}` },\n options,\n this.cancellationToken,\n resultsBuilder);\n return true;\n }\n\n private disposeEnqueuedSummary() {\n if (this.enqueuedSummary !== undefined) {\n this.enqueuedSummary.resultsBuilder.fail(\"RunningSummarizer stopped or disposed\", undefined);\n this.enqueuedSummary = undefined;\n }\n }\n}\n"]}
@@ -0,0 +1,28 @@
1
+ /// <reference types="node" />
2
+ /*!
3
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
4
+ * Licensed under the MIT License.
5
+ */
6
+ import { EventEmitter } from "events";
7
+ import { IDeltaManager } from "@fluidframework/container-definitions";
8
+ import { IDocumentMessage, ISequencedDocumentMessage } from "@fluidframework/protocol-definitions";
9
+ import { ITelemetryLogger } from "@fluidframework/common-definitions";
10
+ /**
11
+ * This class has the following responsibilities:
12
+ * 1. It tracks batches as we process ops and raises "batchBegin" and "batchEnd" events.
13
+ * As part of it, it validates batch correctness (i.e. no system ops in the middle of batch)
14
+ * 2. It creates instance of ScheduleManagerCore that ensures we never start processing ops from batch
15
+ * unless all ops of the batch are in.
16
+ */
17
+ export declare class ScheduleManager {
18
+ private readonly deltaManager;
19
+ private readonly emitter;
20
+ private readonly logger;
21
+ private readonly deltaScheduler;
22
+ private batchClientId;
23
+ private hitError;
24
+ constructor(deltaManager: IDeltaManager<ISequencedDocumentMessage, IDocumentMessage>, emitter: EventEmitter, logger: ITelemetryLogger);
25
+ beforeOpProcessing(message: ISequencedDocumentMessage): void;
26
+ afterOpProcessing(error: any | undefined, message: ISequencedDocumentMessage): void;
27
+ }
28
+ //# sourceMappingURL=scheduleManager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scheduleManager.d.ts","sourceRoot":"","sources":["../src/scheduleManager.ts"],"names":[],"mappings":";AAAA;;;GAGG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,EAAE,aAAa,EAAE,MAAM,uCAAuC,CAAC;AACtE,OAAO,EAAE,gBAAgB,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AACnG,OAAO,EAAE,gBAAgB,EAAE,MAAM,oCAAoC,CAAC;AAatE;;;;;;GAMG;AACH,qBAAa,eAAe;IAMpB,OAAO,CAAC,QAAQ,CAAC,YAAY;IAC7B,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,MAAM;IAP3B,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAiB;IAChD,OAAO,CAAC,aAAa,CAAqB;IAC1C,OAAO,CAAC,QAAQ,CAAS;gBAGJ,YAAY,EAAE,aAAa,CAAC,yBAAyB,EAAE,gBAAgB,CAAC,EACxE,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,gBAAgB;IAStC,kBAAkB,CAAC,OAAO,EAAE,yBAAyB;IAkBrD,iBAAiB,CAAC,KAAK,EAAE,GAAG,GAAG,SAAS,EAAE,OAAO,EAAE,yBAAyB;CAwBtF"}