@fluidframework/container-loader 2.0.0-internal.5.4.0 → 2.0.0-internal.6.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 (102) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/dist/connectionManager.d.ts +4 -4
  3. package/dist/connectionManager.d.ts.map +1 -1
  4. package/dist/connectionManager.js +57 -49
  5. package/dist/connectionManager.js.map +1 -1
  6. package/dist/connectionStateHandler.d.ts +15 -14
  7. package/dist/connectionStateHandler.d.ts.map +1 -1
  8. package/dist/connectionStateHandler.js +26 -28
  9. package/dist/connectionStateHandler.js.map +1 -1
  10. package/dist/container.d.ts +10 -5
  11. package/dist/container.d.ts.map +1 -1
  12. package/dist/container.js +183 -134
  13. package/dist/container.js.map +1 -1
  14. package/dist/containerContext.d.ts +2 -12
  15. package/dist/containerContext.d.ts.map +1 -1
  16. package/dist/containerContext.js +1 -20
  17. package/dist/containerContext.js.map +1 -1
  18. package/dist/containerStorageAdapter.js +3 -5
  19. package/dist/containerStorageAdapter.js.map +1 -1
  20. package/dist/contracts.d.ts +20 -7
  21. package/dist/contracts.d.ts.map +1 -1
  22. package/dist/contracts.js +3 -3
  23. package/dist/contracts.js.map +1 -1
  24. package/dist/debugLogger.js +2 -3
  25. package/dist/debugLogger.js.map +1 -1
  26. package/dist/deltaManager.d.ts +19 -6
  27. package/dist/deltaManager.d.ts.map +1 -1
  28. package/dist/deltaManager.js +67 -28
  29. package/dist/deltaManager.js.map +1 -1
  30. package/dist/deltaQueue.js +1 -2
  31. package/dist/deltaQueue.js.map +1 -1
  32. package/dist/loader.d.ts +12 -0
  33. package/dist/loader.d.ts.map +1 -1
  34. package/dist/loader.js +57 -42
  35. package/dist/loader.js.map +1 -1
  36. package/dist/packageVersion.d.ts +1 -1
  37. package/dist/packageVersion.js +1 -1
  38. package/dist/packageVersion.js.map +1 -1
  39. package/dist/protocol.d.ts +4 -2
  40. package/dist/protocol.d.ts.map +1 -1
  41. package/dist/protocol.js +25 -4
  42. package/dist/protocol.js.map +1 -1
  43. package/dist/utils.d.ts +8 -1
  44. package/dist/utils.d.ts.map +1 -1
  45. package/dist/utils.js +24 -6
  46. package/dist/utils.js.map +1 -1
  47. package/lib/connectionManager.d.ts +4 -4
  48. package/lib/connectionManager.d.ts.map +1 -1
  49. package/lib/connectionManager.js +58 -50
  50. package/lib/connectionManager.js.map +1 -1
  51. package/lib/connectionStateHandler.d.ts +15 -14
  52. package/lib/connectionStateHandler.d.ts.map +1 -1
  53. package/lib/connectionStateHandler.js +26 -28
  54. package/lib/connectionStateHandler.js.map +1 -1
  55. package/lib/container.d.ts +10 -5
  56. package/lib/container.d.ts.map +1 -1
  57. package/lib/container.js +182 -133
  58. package/lib/container.js.map +1 -1
  59. package/lib/containerContext.d.ts +2 -12
  60. package/lib/containerContext.d.ts.map +1 -1
  61. package/lib/containerContext.js +1 -20
  62. package/lib/containerContext.js.map +1 -1
  63. package/lib/containerStorageAdapter.js +3 -5
  64. package/lib/containerStorageAdapter.js.map +1 -1
  65. package/lib/contracts.d.ts +20 -7
  66. package/lib/contracts.d.ts.map +1 -1
  67. package/lib/contracts.js +3 -3
  68. package/lib/contracts.js.map +1 -1
  69. package/lib/debugLogger.js +2 -3
  70. package/lib/debugLogger.js.map +1 -1
  71. package/lib/deltaManager.d.ts +19 -6
  72. package/lib/deltaManager.d.ts.map +1 -1
  73. package/lib/deltaManager.js +67 -28
  74. package/lib/deltaManager.js.map +1 -1
  75. package/lib/deltaQueue.js +1 -2
  76. package/lib/deltaQueue.js.map +1 -1
  77. package/lib/loader.d.ts +12 -0
  78. package/lib/loader.d.ts.map +1 -1
  79. package/lib/loader.js +57 -42
  80. package/lib/loader.js.map +1 -1
  81. package/lib/packageVersion.d.ts +1 -1
  82. package/lib/packageVersion.js +1 -1
  83. package/lib/packageVersion.js.map +1 -1
  84. package/lib/protocol.d.ts +4 -2
  85. package/lib/protocol.d.ts.map +1 -1
  86. package/lib/protocol.js +25 -4
  87. package/lib/protocol.js.map +1 -1
  88. package/lib/utils.d.ts +8 -1
  89. package/lib/utils.d.ts.map +1 -1
  90. package/lib/utils.js +22 -5
  91. package/lib/utils.js.map +1 -1
  92. package/package.json +15 -19
  93. package/src/connectionManager.ts +53 -34
  94. package/src/connectionStateHandler.ts +30 -37
  95. package/src/container.ts +156 -76
  96. package/src/containerContext.ts +0 -24
  97. package/src/contracts.ts +27 -10
  98. package/src/deltaManager.ts +41 -18
  99. package/src/loader.ts +37 -23
  100. package/src/packageVersion.ts +1 -1
  101. package/src/protocol.ts +33 -2
  102. package/src/utils.ts +29 -0
@@ -87,7 +87,7 @@ export class DeltaManager extends TypedEventEmitter {
87
87
  signalHandler: (message) => this._inboundSignal.push(message),
88
88
  reconnectionDelayHandler: (delayMs, error) => this.emitDelayInfo(this.deltaStreamDelayId, delayMs, error),
89
89
  closeHandler: (error) => this.close(error),
90
- disconnectHandler: (reason, error) => this.disconnectHandler(reason, error),
90
+ disconnectHandler: (reason) => this.disconnectHandler(reason),
91
91
  connectHandler: (connection) => this.connectHandler(connection),
92
92
  pongHandler: (latency) => this.emit("pong", latency),
93
93
  readonlyChangeHandler: (readonly) => safeRaiseEvent(this, this.logger, "readonly", readonly),
@@ -178,7 +178,7 @@ export class DeltaManager extends TypedEventEmitter {
178
178
  }
179
179
  submit(type, contents, batch = false, metadata, compression, referenceSequenceNumber) {
180
180
  // Back-compat ADO:3455
181
- const backCompatRefSeqNum = referenceSequenceNumber !== null && referenceSequenceNumber !== void 0 ? referenceSequenceNumber : this.lastProcessedSequenceNumber;
181
+ const backCompatRefSeqNum = referenceSequenceNumber ?? this.lastProcessedSequenceNumber;
182
182
  const messagePartial = {
183
183
  contents,
184
184
  metadata,
@@ -211,7 +211,6 @@ export class DeltaManager extends TypedEventEmitter {
211
211
  return this.connectionManager.submitSignal(content);
212
212
  }
213
213
  flush() {
214
- var _a, _b, _c;
215
214
  const batch = this.messageBuffer;
216
215
  if (batch.length === 0) {
217
216
  return;
@@ -220,17 +219,22 @@ export class DeltaManager extends TypedEventEmitter {
220
219
  // The prepareFlush event allows listeners to append metadata to the batch prior to submission.
221
220
  this.emit("prepareSend", batch);
222
221
  if (batch.length === 1) {
223
- assert(((_a = batch[0].metadata) === null || _a === void 0 ? void 0 : _a.batch) === undefined, 0x3c9 /* no batch markup on single message */);
222
+ assert(batch[0].metadata?.batch === undefined, 0x3c9 /* no batch markup on single message */);
224
223
  }
225
224
  else {
226
- assert(((_b = batch[0].metadata) === null || _b === void 0 ? void 0 : _b.batch) === true, 0x3ca /* no start batch markup */);
227
- assert(((_c = batch[batch.length - 1].metadata) === null || _c === void 0 ? void 0 : _c.batch) === false, 0x3cb /* no end batch markup */);
225
+ assert(batch[0].metadata?.batch === true, 0x3ca /* no start batch markup */);
226
+ assert(batch[batch.length - 1].metadata?.batch === false, 0x3cb /* no end batch markup */);
228
227
  }
229
228
  this.connectionManager.sendMessages(batch);
230
229
  assert(this.messageBuffer.length === 0, 0x3cc /* reentrancy */);
231
230
  }
232
231
  get connectionProps() {
233
- return Object.assign({ sequenceNumber: this.lastSequenceNumber, opsSize: this.opsSize > 0 ? this.opsSize : undefined }, this.connectionManager.connectionProps);
232
+ return {
233
+ sequenceNumber: this.lastSequenceNumber,
234
+ opsSize: this.opsSize > 0 ? this.opsSize : undefined,
235
+ deltaManagerState: this._disposed ? "disposed" : this._closed ? "closed" : "open",
236
+ ...this.connectionManager.connectionProps,
237
+ };
234
238
  }
235
239
  /**
236
240
  * Log error event with a bunch of internal to DeltaManager information about state of op processing
@@ -239,15 +243,25 @@ export class DeltaManager extends TypedEventEmitter {
239
243
  * @param event - Event to log.
240
244
  */
241
245
  logConnectionIssue(event) {
242
- var _a;
243
246
  assert(this.connectionManager.connected, 0x238 /* "called only in connected state" */);
244
247
  const pendingSorted = this.pending.sort((a, b) => a.sequenceNumber - b.sequenceNumber);
245
- this.logger.sendErrorEvent(Object.assign(Object.assign(Object.assign(Object.assign({}, event), {
248
+ this.logger.sendErrorEvent({
249
+ ...event,
246
250
  // This directly tells us if fetching ops is in flight, and thus likely the reason of
247
251
  // stalled op processing
248
- fetchReason: this.fetchReason,
252
+ fetchReason: this.fetchReason,
249
253
  // A bunch of useful sequence numbers to understand if we are holding some ops from processing
250
- lastQueuedSequenceNumber: this.lastQueuedSequenceNumber, lastProcessedSequenceNumber: this.lastProcessedSequenceNumber, lastObserved: this.lastObservedSeqNumber }), this.connectionManager.connectionVerboseProps), { pendingOps: this.pending.length, pendingFirst: (_a = pendingSorted[0]) === null || _a === void 0 ? void 0 : _a.sequenceNumber, haveHandler: this.handler !== undefined, inboundLength: this.inbound.length, inboundPaused: this.inbound.paused }));
254
+ lastQueuedSequenceNumber: this.lastQueuedSequenceNumber,
255
+ lastProcessedSequenceNumber: this.lastProcessedSequenceNumber,
256
+ lastObserved: this.lastObservedSeqNumber,
257
+ // connection info
258
+ ...this.connectionManager.connectionVerboseProps,
259
+ pendingOps: this.pending.length,
260
+ pendingFirst: pendingSorted[0]?.sequenceNumber,
261
+ haveHandler: this.handler !== undefined,
262
+ inboundLength: this.inbound.length,
263
+ inboundPaused: this.inbound.paused,
264
+ });
251
265
  }
252
266
  cancelEstablishingConnection(reason) {
253
267
  this.emit("cancelEstablishingConnection", reason);
@@ -332,8 +346,7 @@ export class DeltaManager extends TypedEventEmitter {
332
346
  assert(this.fetchReason !== undefined || this.pending.length === 0, 0x269 /* "pending ops are not dropped" */);
333
347
  }
334
348
  connect(args) {
335
- var _a;
336
- const fetchOpsFromStorage = (_a = args.fetchOpsFromStorage) !== null && _a !== void 0 ? _a : true;
349
+ const fetchOpsFromStorage = args.fetchOpsFromStorage ?? true;
337
350
  logIfFalse(this.handler !== undefined || !fetchOpsFromStorage, this.logger, "CantFetchWithoutBaseline"); // can't fetch if no baseline
338
351
  // Note: There is race condition here.
339
352
  // We want to issue request to storage as soon as possible, to
@@ -346,7 +359,7 @@ export class DeltaManager extends TypedEventEmitter {
346
359
  // on the wire, we might be always behind.
347
360
  // See comment at the end of "connect" handler
348
361
  if (fetchOpsFromStorage) {
349
- this.fetchMissingDeltas(args.reason);
362
+ this.fetchMissingDeltas(args.reason.text);
350
363
  }
351
364
  this.connectionManager.connect(args.reason, args.mode);
352
365
  }
@@ -366,8 +379,14 @@ export class DeltaManager extends TypedEventEmitter {
366
379
  // It is possible that due to asynchrony (including await above), required ops were already
367
380
  // received through delta stream. Validate that before moving forward.
368
381
  if (this.lastQueuedSequenceNumber >= lastExpectedOp) {
369
- this.logger.sendPerformanceEvent(Object.assign({ reason: fetchReason, eventName: "ExtraStorageCall", early: true, from,
370
- to }, this.connectionManager.connectionVerboseProps));
382
+ this.logger.sendPerformanceEvent({
383
+ reason: fetchReason,
384
+ eventName: "ExtraStorageCall",
385
+ early: true,
386
+ from,
387
+ to,
388
+ ...this.connectionManager.connectionVerboseProps,
389
+ });
371
390
  return;
372
391
  }
373
392
  // Be prepared for the case where webSocket would receive the ops that we are trying to fill through
@@ -494,9 +513,9 @@ export class DeltaManager extends TypedEventEmitter {
494
513
  this.timeTillThrottling = 0;
495
514
  }
496
515
  }
497
- disconnectHandler(reason, error) {
516
+ disconnectHandler(reason) {
498
517
  this.messageBuffer.length = 0;
499
- this.emit("disconnect", reason, error);
518
+ this.emit("disconnect", reason);
500
519
  }
501
520
  /**
502
521
  * Emit info about a delay in service communication on account of throttling.
@@ -524,7 +543,6 @@ export class DeltaManager extends TypedEventEmitter {
524
543
  return `${m.clientId}-${m.type}-${m.minimumSequenceNumber}-${m.referenceSequenceNumber}-${m.timestamp}`;
525
544
  }
526
545
  enqueueMessages(messages, reason, allowGaps = false) {
527
- var _a, _b;
528
546
  if (this.handler === undefined) {
529
547
  // We did not setup handler yet.
530
548
  // This happens when we connect to web socket faster than we get attributes for container
@@ -587,19 +605,32 @@ export class DeltaManager extends TypedEventEmitter {
587
605
  // Do not report when pending fetch is in progress, as such reporting will not
588
606
  // correctly take into account pending ops.
589
607
  if (eventName !== undefined) {
590
- this.logger.sendPerformanceEvent(Object.assign({ eventName,
591
- reason, previousReason: this.prevEnqueueMessagesReason, from, to: last + 1, length: messages.length, fetchReason: this.fetchReason, duplicate: duplicate > 0 ? duplicate : undefined, initialGap: initialGap !== 0 ? initialGap : undefined, gap: gap > 0 ? gap : undefined, firstMissing, dmInitialSeqNumber: this.initialSequenceNumber }, this.connectionManager.connectionVerboseProps));
608
+ this.logger.sendPerformanceEvent({
609
+ eventName,
610
+ reason,
611
+ previousReason: this.prevEnqueueMessagesReason,
612
+ from,
613
+ to: last + 1,
614
+ length: messages.length,
615
+ fetchReason: this.fetchReason,
616
+ duplicate: duplicate > 0 ? duplicate : undefined,
617
+ initialGap: initialGap !== 0 ? initialGap : undefined,
618
+ gap: gap > 0 ? gap : undefined,
619
+ firstMissing,
620
+ dmInitialSeqNumber: this.initialSequenceNumber,
621
+ ...this.connectionManager.connectionVerboseProps,
622
+ });
592
623
  }
593
624
  }
594
625
  this.updateLatestKnownOpSeqNumber(messages[messages.length - 1].sequenceNumber);
595
- const n = (_a = this.previouslyProcessedMessage) === null || _a === void 0 ? void 0 : _a.sequenceNumber;
626
+ const n = this.previouslyProcessedMessage?.sequenceNumber;
596
627
  assert(n === undefined || n === this.lastQueuedSequenceNumber, 0x0ec /* "Unexpected value for previously processed message's sequence number" */);
597
628
  for (const message of messages) {
598
629
  // Check that the messages are arriving in the expected order
599
630
  if (message.sequenceNumber <= this.lastQueuedSequenceNumber) {
600
631
  // Validate that we do not have data loss, i.e. sequencing is reset and started again
601
632
  // with numbers that this client already observed before.
602
- if (((_b = this.previouslyProcessedMessage) === null || _b === void 0 ? void 0 : _b.sequenceNumber) === message.sequenceNumber) {
633
+ if (this.previouslyProcessedMessage?.sequenceNumber === message.sequenceNumber) {
603
634
  const message1 = this.comparableMessagePayload(this.previouslyProcessedMessage);
604
635
  const message2 = this.comparableMessagePayload(message);
605
636
  if (message1 !== message2) {
@@ -650,7 +681,10 @@ export class DeltaManager extends TypedEventEmitter {
650
681
  // 1. (Legacy) We can see message.type === "attach" or "chunkedOp" for legacy files before RTM
651
682
  // 2. Non-immediate noops (contents: null) can be sent by service without clientId
652
683
  if (!isString && isClientMessage(message) && message.type !== MessageType.NoOp) {
653
- throw new DataCorruptionError("Mismatch in clientId", Object.assign(Object.assign({}, extractSafePropertiesFromMessage(message)), { messageType: message.type }));
684
+ throw new DataCorruptionError("Mismatch in clientId", {
685
+ ...extractSafePropertiesFromMessage(message),
686
+ messageType: message.type,
687
+ });
654
688
  }
655
689
  // TODO Remove after SPO picks up the latest build.
656
690
  if (typeof message.contents === "string" &&
@@ -676,7 +710,10 @@ export class DeltaManager extends TypedEventEmitter {
676
710
  // Watch the minimum sequence number and be ready to update as needed
677
711
  if (this.minSequenceNumber > message.minimumSequenceNumber) {
678
712
  // pre-0.58 error message: msnMovesBackwards
679
- throw new DataCorruptionError("Found a lower minimumSequenceNumber (msn) than previously recorded", Object.assign(Object.assign({}, extractSafePropertiesFromMessage(message)), { clientId: this.connectionManager.clientId }));
713
+ throw new DataCorruptionError("Found a lower minimumSequenceNumber (msn) than previously recorded", {
714
+ ...extractSafePropertiesFromMessage(message),
715
+ clientId: this.connectionManager.clientId,
716
+ });
680
717
  }
681
718
  // Client ops: MSN has to be lower than sequence #, as client can continue to send ops with same
682
719
  // reference sequence number as this op.
@@ -688,7 +725,10 @@ export class DeltaManager extends TypedEventEmitter {
688
725
  this.minSequenceNumber = message.minimumSequenceNumber;
689
726
  if (message.sequenceNumber !== this.lastProcessedSequenceNumber + 1) {
690
727
  // pre-0.58 error message: nonSequentialSequenceNumber
691
- throw new DataCorruptionError("Found a non-Sequential sequenceNumber", Object.assign(Object.assign({}, extractSafePropertiesFromMessage(message)), { clientId: this.connectionManager.clientId }));
728
+ throw new DataCorruptionError("Found a non-Sequential sequenceNumber", {
729
+ ...extractSafePropertiesFromMessage(message),
730
+ clientId: this.connectionManager.clientId,
731
+ });
692
732
  }
693
733
  this.lastProcessedSequenceNumber = message.sequenceNumber;
694
734
  // a bunch of code assumes that this is true
@@ -719,7 +759,6 @@ export class DeltaManager extends TypedEventEmitter {
719
759
  * Retrieves the missing deltas between the given sequence numbers
720
760
  */
721
761
  async fetchMissingDeltasCore(reason, cacheOnly, to) {
722
- var _a;
723
762
  // Exit out early if we're already fetching deltas
724
763
  if (this.fetchReason !== undefined) {
725
764
  return;
@@ -738,7 +777,7 @@ export class DeltaManager extends TypedEventEmitter {
738
777
  }
739
778
  try {
740
779
  let from = this.lastQueuedSequenceNumber + 1;
741
- const n = (_a = this.previouslyProcessedMessage) === null || _a === void 0 ? void 0 : _a.sequenceNumber;
780
+ const n = this.previouslyProcessedMessage?.sequenceNumber;
742
781
  if (n !== undefined) {
743
782
  // If we already processed at least one op, then we have this.previouslyProcessedMessage populated
744
783
  // and can use it to validate that we are operating on same file, i.e. it was not overwritten.
@@ -1 +1 @@
1
- {"version":3,"file":"deltaManager.js","sourceRoot":"","sources":["../src/deltaManager.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,EAAE,IAAI,IAAI,EAAE,MAAM,MAAM,CAAC;AAYlC,OAAO,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACzE,OAAO,EACN,cAAc,EACd,UAAU,EACV,cAAc,EACd,YAAY,GAEZ,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAGN,eAAe,GAEf,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAIN,WAAW,GAEX,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AACjG,OAAO,EACN,iBAAiB,EACjB,mBAAmB,EACnB,gCAAgC,EAChC,mBAAmB,EACnB,UAAU,GACV,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AA2BhD;;GAEG;AACH,SAAS,eAAe,C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I,CAAC,OAAO,GAAG,EAAE,CAAC;QAClB,+EAA+E;QAC/E,2CAA2C;QAC3C,IAAI,CAAC,eAAe,CAAC,aAAa,EAAE,GAAG,MAAM,UAAU,EAAE,IAAI,CAAC,eAAe,CAAC,CAAC;QAE/E,wFAAwF;QACxF,IAAI,IAAI,CAAC,WAAW,KAAK,SAAS,EAAE;YACnC,mCAAmC;YACnC,yFAAyF;YACzF,2EAA2E;YAC3E,gGAAgG;YAChG,iGAAiG;YACjG,qGAAqG;YACrG,wFAAwF;YACxF,uGAAuG;YACvG,kGAAkG;YAClG,iGAAiG;YACjG,YAAY;YACZ,IAAI,IAAI,CAAC,wBAAwB,GAAG,IAAI,CAAC,qBAAqB,EAAE;gBAC/D,IAAI,CAAC,kBAAkB,CAAC,WAAW,CAAC,CAAC;aACrC;SACD;IACF,CAAC;IAEO,4BAA4B,CAAC,GAAW;QAC/C,IAAI,IAAI,CAAC,qBAAqB,GAAG,GAAG,EAAE;YACrC,IAAI,CAAC,qBAAqB,GAAG,GAAG,CAAC;SACjC;IACF,CAAC;CACD","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { v4 as uuid } from \"uuid\";\nimport { IEventProvider } from \"@fluidframework/common-definitions\";\nimport { ITelemetryProperties, ITelemetryErrorEvent } from \"@fluidframework/core-interfaces\";\nimport {\n\tIDeltaHandlerStrategy,\n\tIDeltaManager,\n\tIDeltaManagerEvents,\n\tIDeltaQueue,\n\tICriticalContainerError,\n\tIThrottlingWarning,\n\tIConnectionDetailsInternal,\n} from \"@fluidframework/container-definitions\";\nimport { assert, TypedEventEmitter } from \"@fluidframework/common-utils\";\nimport {\n\tnormalizeError,\n\tlogIfFalse,\n\tsafeRaiseEvent,\n\tisFluidError,\n\tITelemetryLoggerExt,\n} from \"@fluidframework/telemetry-utils\";\nimport {\n\tIDocumentDeltaStorageService,\n\tIDocumentService,\n\tDriverErrorType,\n\tIAnyDriverError,\n} from \"@fluidframework/driver-definitions\";\nimport {\n\tIDocumentMessage,\n\tISequencedDocumentMessage,\n\tISignalMessage,\n\tMessageType,\n\tConnectionMode,\n} from \"@fluidframework/protocol-definitions\";\nimport { NonRetryableError, isRuntimeMessage, MessageType2 } from \"@fluidframework/driver-utils\";\nimport {\n\tThrottlingWarning,\n\tDataCorruptionError,\n\textractSafePropertiesFromMessage,\n\tDataProcessingError,\n\tUsageError,\n} from \"@fluidframework/container-utils\";\nimport { IConnectionManagerFactoryArgs, IConnectionManager } from \"./contracts\";\nimport { DeltaQueue } from \"./deltaQueue\";\nimport { OnlyValidTermValue } from \"./protocol\";\n\nexport interface IConnectionArgs {\n\tmode?: ConnectionMode;\n\tfetchOpsFromStorage?: boolean;\n\treason: string;\n}\n\n/**\n * Includes events emitted by the concrete implementation DeltaManager\n * but not exposed on the public interface IDeltaManager\n */\nexport interface IDeltaManagerInternalEvents extends IDeltaManagerEvents {\n\t(event: \"throttled\", listener: (error: IThrottlingWarning) => void);\n\t(event: \"closed\" | \"disposed\", listener: (error?: ICriticalContainerError) => void);\n\t(event: \"connect\", listener: (details: IConnectionDetailsInternal, opsBehind?: number) => void);\n\t(event: \"establishingConnection\", listener: (reason: string) => void);\n\t(event: \"cancelEstablishingConnection\", listener: (reason: string) => void);\n}\n\n/**\n * Batching makes assumptions about what might be on the metadata. This interface codifies those assumptions, but does not validate them.\n */\ninterface IBatchMetadata {\n\tbatch?: boolean;\n}\n\n/**\n * Determines if message was sent by client, not service\n */\nfunction isClientMessage(message: ISequencedDocumentMessage | IDocumentMessage): boolean {\n\tif (isRuntimeMessage(message)) {\n\t\treturn true;\n\t}\n\tswitch (message.type) {\n\t\tcase MessageType.Propose:\n\t\tcase MessageType.Reject:\n\t\tcase MessageType.NoOp:\n\t\tcase MessageType2.Accept:\n\t\tcase MessageType.Summarize:\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n/**\n * Type is used to cast AbortController to represent new version of DOM API and prevent build issues\n * TODO: Remove when typescript version of the repo contains the AbortSignal.reason property (AB#5045)\n */\ntype AbortControllerReal = AbortController & { abort(reason?: any): void };\n/**\n * Type is used to cast AbortSignal to represent new version of DOM API and prevent build issues\n * TODO: Remove when typescript version of the repo contains the AbortSignal.reason property (AB#5045)\n */\ntype AbortSignalReal = AbortSignal & { reason: any };\n\n/**\n * Manages the flow of both inbound and outbound messages. This class ensures that shared objects receive delta\n * messages in order regardless of possible network conditions or timings causing out of order delivery.\n */\nexport class DeltaManager<TConnectionManager extends IConnectionManager>\n\textends TypedEventEmitter<IDeltaManagerInternalEvents>\n\timplements\n\t\tIDeltaManager<ISequencedDocumentMessage, IDocumentMessage>,\n\t\tIEventProvider<IDeltaManagerInternalEvents>\n{\n\tpublic readonly connectionManager: TConnectionManager;\n\n\tpublic get active(): boolean {\n\t\treturn this._active();\n\t}\n\n\tpublic get disposed() {\n\t\treturn this._closed;\n\t}\n\n\tpublic get IDeltaSender() {\n\t\treturn this;\n\t}\n\n\tprivate pending: ISequencedDocumentMessage[] = [];\n\tprivate fetchReason: string | undefined;\n\n\t// A boolean used to assert that ops are not being sent while processing another op.\n\tprivate currentlyProcessingOps: boolean = false;\n\n\t// The minimum sequence number and last sequence number received from the server\n\tprivate minSequenceNumber: number = 0;\n\n\t// There are three numbers we track\n\t// * lastQueuedSequenceNumber is the last queued sequence number. If there are gaps in seq numbers, then this number\n\t// is not updated until we cover that gap, so it increases each time by 1.\n\t// * lastObservedSeqNumber is an estimation of last known sequence number for container in storage. It's initially\n\t// populated at web socket connection time (if storage provides that info) and is updated once ops shows up.\n\t// It's never less than lastQueuedSequenceNumber\n\t// * lastProcessedSequenceNumber - last processed sequence number\n\tprivate lastQueuedSequenceNumber: number = 0;\n\tprivate lastObservedSeqNumber: number = 0;\n\tprivate lastProcessedSequenceNumber: number = 0;\n\tprivate lastProcessedMessage: ISequencedDocumentMessage | undefined;\n\n\t/** count number of noops sent by the client which may not be acked */\n\tprivate noOpCount: number = 0;\n\t/** Track clientSequenceNumber of the last op */\n\tprivate lastClientSequenceNumber: number = 0;\n\n\t/**\n\t * Track down the ops size.\n\t */\n\tprivate opsSize: number = 0;\n\tprivate prevEnqueueMessagesReason: string | undefined;\n\tprivate previouslyProcessedMessage: ISequencedDocumentMessage | undefined;\n\n\t// The sequence number we initially loaded from\n\t// In case of reading from a snapshot or pending state, its value will be equal to\n\t// the last message that got serialized.\n\tprivate initSequenceNumber: number = 0;\n\n\tprivate readonly _inbound: DeltaQueue<ISequencedDocumentMessage>;\n\tprivate readonly _inboundSignal: DeltaQueue<ISignalMessage>;\n\n\tprivate _closed = false;\n\tprivate _disposed = false;\n\n\tprivate handler: IDeltaHandlerStrategy | undefined;\n\tprivate deltaStorage: IDocumentDeltaStorageService | undefined;\n\n\tprivate readonly throttlingIdSet = new Set<string>();\n\tprivate timeTillThrottling: number = 0;\n\n\tpublic readonly closeAbortController = new AbortController();\n\n\tprivate readonly deltaStorageDelayId = uuid();\n\tprivate readonly deltaStreamDelayId = uuid();\n\n\tprivate messageBuffer: IDocumentMessage[] = [];\n\n\tprivate _checkpointSequenceNumber: number | undefined;\n\n\tpublic get inbound(): IDeltaQueue<ISequencedDocumentMessage> {\n\t\treturn this._inbound;\n\t}\n\n\tpublic get inboundSignal(): IDeltaQueue<ISignalMessage> {\n\t\treturn this._inboundSignal;\n\t}\n\n\tpublic get initialSequenceNumber(): number {\n\t\treturn this.initSequenceNumber;\n\t}\n\n\tpublic get lastSequenceNumber(): number {\n\t\treturn this.lastProcessedSequenceNumber;\n\t}\n\n\tpublic get lastMessage() {\n\t\treturn this.lastProcessedMessage;\n\t}\n\n\tpublic get lastKnownSeqNumber() {\n\t\treturn this.lastObservedSeqNumber;\n\t}\n\n\tpublic get minimumSequenceNumber(): number {\n\t\treturn this.minSequenceNumber;\n\t}\n\n\t/**\n\t * Tells if current connection has checkpoint information.\n\t * I.e. we know how far behind the client was at the time of establishing connection\n\t */\n\tpublic get hasCheckpointSequenceNumber() {\n\t\t// Valid to be called only if we have active connection.\n\t\tassert(this.connectionManager.connected, 0x0df /* \"Missing active connection\" */);\n\t\treturn this._checkpointSequenceNumber !== undefined;\n\t}\n\n\t// Forwarding connection manager properties / IDeltaManager implementation\n\tpublic get maxMessageSize(): number {\n\t\treturn this.connectionManager.maxMessageSize;\n\t}\n\tpublic get version() {\n\t\treturn this.connectionManager.version;\n\t}\n\tpublic get serviceConfiguration() {\n\t\treturn this.connectionManager.serviceConfiguration;\n\t}\n\tpublic get outbound() {\n\t\treturn this.connectionManager.outbound;\n\t}\n\tpublic get readOnlyInfo() {\n\t\treturn this.connectionManager.readOnlyInfo;\n\t}\n\tpublic get clientDetails() {\n\t\treturn this.connectionManager.clientDetails;\n\t}\n\n\tpublic submit(\n\t\ttype: MessageType,\n\t\tcontents?: string,\n\t\tbatch = false,\n\t\tmetadata?: any,\n\t\tcompression?: string,\n\t\treferenceSequenceNumber?: number,\n\t) {\n\t\t// Back-compat ADO:3455\n\t\tconst backCompatRefSeqNum = referenceSequenceNumber ?? this.lastProcessedSequenceNumber;\n\t\tconst messagePartial: Omit<IDocumentMessage, \"clientSequenceNumber\"> = {\n\t\t\tcontents,\n\t\t\tmetadata,\n\t\t\treferenceSequenceNumber: backCompatRefSeqNum,\n\t\t\ttype,\n\t\t\tcompression,\n\t\t};\n\n\t\tif (!batch) {\n\t\t\tthis.flush();\n\t\t}\n\t\tconst message = this.connectionManager.prepareMessageToSend(messagePartial);\n\t\tif (message === undefined) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tassert(isClientMessage(message), 0x419 /* client sends non-client message */);\n\n\t\tif (contents !== undefined) {\n\t\t\tthis.opsSize += contents.length;\n\t\t}\n\n\t\tthis.messageBuffer.push(message);\n\n\t\tif (message.type === MessageType.NoOp) {\n\t\t\tthis.noOpCount++;\n\t\t}\n\n\t\tthis.emit(\"submitOp\", message);\n\n\t\tif (!batch) {\n\t\t\tthis.flush();\n\t\t}\n\t\treturn message.clientSequenceNumber;\n\t}\n\n\tpublic submitSignal(content: any) {\n\t\treturn this.connectionManager.submitSignal(content);\n\t}\n\n\tpublic flush() {\n\t\tconst batch = this.messageBuffer;\n\t\tif (batch.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.messageBuffer = [];\n\n\t\t// The prepareFlush event allows listeners to append metadata to the batch prior to submission.\n\t\tthis.emit(\"prepareSend\", batch);\n\n\t\tif (batch.length === 1) {\n\t\t\tassert(\n\t\t\t\t(batch[0].metadata as IBatchMetadata)?.batch === undefined,\n\t\t\t\t0x3c9 /* no batch markup on single message */,\n\t\t\t);\n\t\t} else {\n\t\t\tassert(\n\t\t\t\t(batch[0].metadata as IBatchMetadata)?.batch === true,\n\t\t\t\t0x3ca /* no start batch markup */,\n\t\t\t);\n\t\t\tassert(\n\t\t\t\t(batch[batch.length - 1].metadata as IBatchMetadata)?.batch === false,\n\t\t\t\t0x3cb /* no end batch markup */,\n\t\t\t);\n\t\t}\n\n\t\tthis.connectionManager.sendMessages(batch);\n\n\t\tassert(this.messageBuffer.length === 0, 0x3cc /* reentrancy */);\n\t}\n\n\tpublic get connectionProps(): ITelemetryProperties {\n\t\treturn {\n\t\t\tsequenceNumber: this.lastSequenceNumber,\n\t\t\topsSize: this.opsSize > 0 ? this.opsSize : undefined,\n\t\t\t...this.connectionManager.connectionProps,\n\t\t};\n\t}\n\n\t/**\n\t * Log error event with a bunch of internal to DeltaManager information about state of op processing\n\t * Used to diagnose connectivity issues related to op processing (i.e. cases where for some reason\n\t * we stop processing ops that results in no processing join op and thus moving to connected state)\n\t * @param event - Event to log.\n\t */\n\tpublic logConnectionIssue(event: ITelemetryErrorEvent) {\n\t\tassert(this.connectionManager.connected, 0x238 /* \"called only in connected state\" */);\n\n\t\tconst pendingSorted = this.pending.sort((a, b) => a.sequenceNumber - b.sequenceNumber);\n\t\tthis.logger.sendErrorEvent({\n\t\t\t...event,\n\t\t\t// This directly tells us if fetching ops is in flight, and thus likely the reason of\n\t\t\t// stalled op processing\n\t\t\tfetchReason: this.fetchReason,\n\t\t\t// A bunch of useful sequence numbers to understand if we are holding some ops from processing\n\t\t\tlastQueuedSequenceNumber: this.lastQueuedSequenceNumber, // last sequential op\n\t\t\tlastProcessedSequenceNumber: this.lastProcessedSequenceNumber, // same as above, but after processing\n\t\t\tlastObserved: this.lastObservedSeqNumber, // last sequence we ever saw; may have gaps with above.\n\t\t\t// connection info\n\t\t\t...this.connectionManager.connectionVerboseProps,\n\t\t\tpendingOps: this.pending.length, // Do we have any pending ops?\n\t\t\tpendingFirst: pendingSorted[0]?.sequenceNumber, // is the first pending op the one that we are missing?\n\t\t\thaveHandler: this.handler !== undefined, // do we have handler installed?\n\t\t\tinboundLength: this.inbound.length,\n\t\t\tinboundPaused: this.inbound.paused,\n\t\t});\n\t}\n\n\tconstructor(\n\t\tprivate readonly serviceProvider: () => IDocumentService | undefined,\n\t\tprivate readonly logger: ITelemetryLoggerExt,\n\t\tprivate readonly _active: () => boolean,\n\t\tcreateConnectionManager: (props: IConnectionManagerFactoryArgs) => TConnectionManager,\n\t) {\n\t\tsuper();\n\t\tconst props: IConnectionManagerFactoryArgs = {\n\t\t\tincomingOpHandler: (messages: ISequencedDocumentMessage[], reason: string) => {\n\t\t\t\ttry {\n\t\t\t\t\tthis.enqueueMessages(messages, reason);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.logger.sendErrorEvent({ eventName: \"EnqueueMessages_Exception\" }, error);\n\t\t\t\t\tthis.close(normalizeError(error));\n\t\t\t\t}\n\t\t\t},\n\t\t\tsignalHandler: (message: ISignalMessage) => this._inboundSignal.push(message),\n\t\t\treconnectionDelayHandler: (delayMs: number, error: unknown) =>\n\t\t\t\tthis.emitDelayInfo(this.deltaStreamDelayId, delayMs, error),\n\t\t\tcloseHandler: (error: any) => this.close(error),\n\t\t\tdisconnectHandler: (reason: string, error?: IAnyDriverError) =>\n\t\t\t\tthis.disconnectHandler(reason, error),\n\t\t\tconnectHandler: (connection: IConnectionDetailsInternal) =>\n\t\t\t\tthis.connectHandler(connection),\n\t\t\tpongHandler: (latency: number) => this.emit(\"pong\", latency),\n\t\t\treadonlyChangeHandler: (readonly?: boolean) =>\n\t\t\t\tsafeRaiseEvent(this, this.logger, \"readonly\", readonly),\n\t\t\testablishConnectionHandler: (reason: string) => this.establishingConnection(reason),\n\t\t\tcancelConnectionHandler: (reason: string) => this.cancelEstablishingConnection(reason),\n\t\t};\n\n\t\tthis.connectionManager = createConnectionManager(props);\n\t\tthis._inbound = new DeltaQueue<ISequencedDocumentMessage>((op) => {\n\t\t\tthis.processInboundMessage(op);\n\t\t});\n\n\t\tthis._inbound.on(\"error\", (error) => {\n\t\t\tthis.close(\n\t\t\t\tDataProcessingError.wrapIfUnrecognized(\n\t\t\t\t\terror,\n\t\t\t\t\t\"deltaManagerInboundErrorHandler\",\n\t\t\t\t\tthis.lastMessage,\n\t\t\t\t),\n\t\t\t);\n\t\t});\n\n\t\t// Inbound signal queue\n\t\tthis._inboundSignal = new DeltaQueue<ISignalMessage>((message) => {\n\t\t\tif (this.handler === undefined) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Attempted to process an inbound signal without a handler attached\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.handler.processSignal({\n\t\t\t\tclientId: message.clientId,\n\t\t\t\tcontent: JSON.parse(message.content as string),\n\t\t\t});\n\t\t});\n\n\t\tthis._inboundSignal.on(\"error\", (error) => {\n\t\t\tthis.close(normalizeError(error));\n\t\t});\n\n\t\t// Initially, all queues are created paused.\n\t\t// - outbound is flipped back and forth in setupNewSuccessfulConnection / disconnectFromDeltaStream\n\t\t// - inbound & inboundSignal are resumed in attachOpHandler() when we have handler setup\n\t}\n\n\tprivate cancelEstablishingConnection(reason: string) {\n\t\tthis.emit(\"cancelEstablishingConnection\", reason);\n\t}\n\n\tprivate establishingConnection(reason: string) {\n\t\tthis.emit(\"establishingConnection\", reason);\n\t}\n\n\tprivate connectHandler(connection: IConnectionDetailsInternal) {\n\t\tthis.refreshDelayInfo(this.deltaStreamDelayId);\n\n\t\tconst props = this.connectionManager.connectionVerboseProps;\n\t\tprops.connectionLastQueuedSequenceNumber = this.lastQueuedSequenceNumber;\n\t\tprops.connectionLastObservedSeqNumber = this.lastObservedSeqNumber;\n\n\t\tconst checkpointSequenceNumber = connection.checkpointSequenceNumber;\n\t\tthis._checkpointSequenceNumber = checkpointSequenceNumber;\n\t\tif (checkpointSequenceNumber !== undefined) {\n\t\t\tthis.updateLatestKnownOpSeqNumber(checkpointSequenceNumber);\n\t\t}\n\n\t\t// We cancel all ops on lost of connectivity, and rely on DDSes to resubmit them.\n\t\t// Semantics are not well defined for batches (and they are broken right now on disconnects anyway),\n\t\t// but it's safe to assume (until better design is put into place) that batches should not exist\n\t\t// across multiple connections. Right now we assume runtime will not submit any ops in disconnected\n\t\t// state. As requirements change, so should these checks.\n\t\tassert(\n\t\t\tthis.messageBuffer.length === 0,\n\t\t\t0x0e9 /* \"messageBuffer is not empty on new connection\" */,\n\t\t);\n\n\t\tthis.opsSize = 0;\n\t\tthis.noOpCount = 0;\n\n\t\tthis.emit(\n\t\t\t\"connect\",\n\t\t\tconnection,\n\t\t\tcheckpointSequenceNumber !== undefined\n\t\t\t\t? this.lastObservedSeqNumber - this.lastSequenceNumber\n\t\t\t\t: undefined,\n\t\t);\n\n\t\t// If we got some initial ops, then we know the gap and call above fetched ops to fill it.\n\t\t// Same is true for \"write\" mode even if we have no ops - we will get \"join\" own op very very soon.\n\t\t// However if we are connecting as view-only, then there is no good signal to realize if client is behind.\n\t\t// Thus we have to hit storage to see if any ops are there.\n\t\tif (checkpointSequenceNumber !== undefined) {\n\t\t\t// We know how far we are behind (roughly). If it's non-zero gap, fetch ops right away.\n\t\t\tif (checkpointSequenceNumber > this.lastQueuedSequenceNumber) {\n\t\t\t\tthis.fetchMissingDeltas(\"AfterConnection\");\n\t\t\t}\n\t\t\t// we do not know the gap, and we will not learn about it if socket is quite - have to ask.\n\t\t} else if (connection.mode === \"read\") {\n\t\t\tthis.fetchMissingDeltas(\"AfterReadConnection\");\n\t\t}\n\t}\n\n\t/**\n\t * Sets the sequence number from which inbound messages should be returned\n\t */\n\tpublic async attachOpHandler(\n\t\tminSequenceNumber: number,\n\t\tsequenceNumber: number,\n\t\thandler: IDeltaHandlerStrategy,\n\t\tprefetchType: \"cached\" | \"all\" | \"none\" = \"none\",\n\t) {\n\t\tthis.initSequenceNumber = sequenceNumber;\n\t\tthis.lastProcessedSequenceNumber = sequenceNumber;\n\t\tthis.minSequenceNumber = minSequenceNumber;\n\t\tthis.lastQueuedSequenceNumber = sequenceNumber;\n\t\tthis.lastObservedSeqNumber = sequenceNumber;\n\n\t\t// We will use same check in other places to make sure all the seq number above are set properly.\n\t\tassert(\n\t\t\tthis.handler === undefined,\n\t\t\t0x0e2 /* \"DeltaManager already has attached op handler!\" */,\n\t\t);\n\t\tthis.handler = handler;\n\t\t// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n\t\tassert(!!(this.handler as any), 0x0e3 /* \"Newly set op handler is null/undefined!\" */);\n\n\t\t// There should be no pending fetch!\n\t\t// This API is called right after attachOpHandler by Container.load().\n\t\t// We might have connection already and it might have called fetchMissingDeltas() from\n\t\t// setupNewSuccessfulConnection. But it should do nothing, because there is no way to fetch ops before\n\t\t// we know snapshot sequence number that is set in attachOpHandler. So all such calls should be noop.\n\t\tassert(\n\t\t\tthis.fetchReason === undefined,\n\t\t\t0x268 /* \"There can't be pending fetch that early in boot sequence!\" */,\n\t\t);\n\n\t\tif (this._closed) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._inbound.resume();\n\t\tthis._inboundSignal.resume();\n\n\t\tif (prefetchType !== \"none\") {\n\t\t\tconst cacheOnly = prefetchType === \"cached\";\n\t\t\tawait this.fetchMissingDeltasCore(`DocumentOpen_${prefetchType}`, cacheOnly);\n\n\t\t\t// Keep going with fetching ops from storage once we have all cached ops in.\n\t\t\t// But do not block load and make this request async / not blocking this api.\n\t\t\t// Ops processing will start once cached ops are in and and will stop when queue is empty\n\t\t\t// (which in most cases will happen when we are done processing cached ops)\n\t\t\tif (cacheOnly) {\n\t\t\t\t// fire and forget\n\t\t\t\tthis.fetchMissingDeltas(\"PostDocumentOpen\");\n\t\t\t}\n\t\t}\n\n\t\t// Ensure there is no need to call this.processPendingOps() at the end of boot sequence\n\t\tassert(\n\t\t\tthis.fetchReason !== undefined || this.pending.length === 0,\n\t\t\t0x269 /* \"pending ops are not dropped\" */,\n\t\t);\n\t}\n\n\tpublic connect(args: IConnectionArgs) {\n\t\tconst fetchOpsFromStorage = args.fetchOpsFromStorage ?? true;\n\t\tlogIfFalse(\n\t\t\tthis.handler !== undefined || !fetchOpsFromStorage,\n\t\t\tthis.logger,\n\t\t\t\"CantFetchWithoutBaseline\",\n\t\t); // can't fetch if no baseline\n\n\t\t// Note: There is race condition here.\n\t\t// We want to issue request to storage as soon as possible, to\n\t\t// reduce latency of becoming current, thus this code here.\n\t\t// But there is no ordering between fetching OPs and connection to delta stream\n\t\t// As result, we might be behind by the time we connect to delta stream\n\t\t// In case of r/w connection, that's not an issue, because we will hear our\n\t\t// own \"join\" message and realize any gap client has in ops.\n\t\t// But for view-only connection, we have no such signal, and with no traffic\n\t\t// on the wire, we might be always behind.\n\t\t// See comment at the end of \"connect\" handler\n\t\tif (fetchOpsFromStorage) {\n\t\t\tthis.fetchMissingDeltas(args.reason);\n\t\t}\n\n\t\tthis.connectionManager.connect(args.reason, args.mode);\n\t}\n\n\tprivate async getDeltas(\n\t\tfrom: number, // inclusive\n\t\tto: number | undefined, // exclusive\n\t\tfetchReason: string,\n\t\tcallback: (messages: ISequencedDocumentMessage[]) => void,\n\t\tcacheOnly: boolean,\n\t) {\n\t\tconst docService = this.serviceProvider();\n\t\tif (docService === undefined) {\n\t\t\tthrow new Error(\"Delta manager is not attached\");\n\t\t}\n\n\t\tif (this.deltaStorage === undefined) {\n\t\t\tthis.deltaStorage = await docService.connectToDeltaStorage();\n\t\t}\n\n\t\tlet cancelFetch: (op: ISequencedDocumentMessage) => boolean;\n\n\t\tif (to !== undefined) {\n\t\t\tconst lastExpectedOp = to - 1; // make it inclusive!\n\n\t\t\t// It is possible that due to asynchrony (including await above), required ops were already\n\t\t\t// received through delta stream. Validate that before moving forward.\n\t\t\tif (this.lastQueuedSequenceNumber >= lastExpectedOp) {\n\t\t\t\tthis.logger.sendPerformanceEvent({\n\t\t\t\t\treason: fetchReason,\n\t\t\t\t\teventName: \"ExtraStorageCall\",\n\t\t\t\t\tearly: true,\n\t\t\t\t\tfrom,\n\t\t\t\t\tto,\n\t\t\t\t\t...this.connectionManager.connectionVerboseProps,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Be prepared for the case where webSocket would receive the ops that we are trying to fill through\n\t\t\t// storage. Ideally it should never happen (i.e. ops on socket are always ordered, and thus once we\n\t\t\t// detected gap, this gap can't be filled in later on through websocket).\n\t\t\t// And in practice that does look like the case. The place where this code gets hit is if we lost\n\t\t\t// connection and reconnected (likely to another box), and new socket's initial ops contains these ops.\n\t\t\tcancelFetch = (op: ISequencedDocumentMessage) => op.sequenceNumber >= lastExpectedOp;\n\t\t} else {\n\t\t\t// Unbound requests are made to proactively fetch ops, but also get up to date in cases where socket\n\t\t\t// is silent (and connection is \"read\", thus we might not have any data on how far client is behind).\n\t\t\t// Once we have any op coming in from socket, we can cancel it as it's not needed any more.\n\t\t\t// That said, if we have socket connection, make sure we got ops up to checkpointSequenceNumber!\n\t\t\tcancelFetch = (op: ISequencedDocumentMessage) =>\n\t\t\t\top.sequenceNumber >= this.lastObservedSeqNumber;\n\t\t}\n\n\t\tconst controller = new AbortController();\n\t\tlet opsFromFetch = false;\n\n\t\tconst opListener = (op: ISequencedDocumentMessage) => {\n\t\t\tassert(op.sequenceNumber === this.lastQueuedSequenceNumber, 0x23a /* \"seq#'s\" */);\n\t\t\t// Ops that are coming from this request should not cancel itself.\n\t\t\t// This is useless for known ranges (to is defined) as it means request is over either way.\n\t\t\t// And it will cancel unbound request too early, not allowing us to learn where the end of the file is.\n\t\t\tif (!opsFromFetch && cancelFetch(op)) {\n\t\t\t\t// TODO: Remove when typescript version of the repo contains the AbortSignal.reason property (AB#5045)\n\t\t\t\t(controller as AbortControllerReal).abort(\"DeltaManager getDeltas fetch cancelled\");\n\t\t\t\tthis._inbound.off(\"push\", opListener);\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\tthis._inbound.on(\"push\", opListener);\n\t\t\tassert(this.closeAbortController.signal.onabort === null, 0x1e8 /* \"reentrancy\" */);\n\t\t\tthis.closeAbortController.signal.onabort = () =>\n\t\t\t\t// TODO: Remove when typescript version of the repo contains the AbortSignal.reason property (AB#5045)\n\t\t\t\t(controller as AbortControllerReal).abort(\n\t\t\t\t\t(this.closeAbortController.signal as AbortSignalReal).reason,\n\t\t\t\t);\n\n\t\t\tconst stream = this.deltaStorage.fetchMessages(\n\t\t\t\tfrom, // inclusive\n\t\t\t\tto, // exclusive\n\t\t\t\tcontroller.signal,\n\t\t\t\tcacheOnly,\n\t\t\t\tfetchReason,\n\t\t\t);\n\n\t\t\t// eslint-disable-next-line no-constant-condition\n\t\t\twhile (true) {\n\t\t\t\tconst result = await stream.read();\n\t\t\t\tif (result.done) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\topsFromFetch = true;\n\t\t\t\t\tcallback(result.value);\n\t\t\t\t} finally {\n\t\t\t\t\topsFromFetch = false;\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tif (controller.signal.aborted) {\n\t\t\t\tthis.logger.sendTelemetryEvent({\n\t\t\t\t\teventName: \"DeltaManager_GetDeltasAborted\",\n\t\t\t\t\tfetchReason,\n\t\t\t\t\t// TODO: Remove when typescript version of the repo contains the AbortSignal.reason property (AB#5045)\n\t\t\t\t\treason: (controller.signal as AbortSignalReal).reason,\n\t\t\t\t});\n\t\t\t}\n\t\t\tthis.closeAbortController.signal.onabort = null;\n\t\t\tthis._inbound.off(\"push\", opListener);\n\t\t\tassert(!opsFromFetch, 0x289 /* \"logic error\" */);\n\t\t}\n\t}\n\n\t/**\n\t * Closes the connection and clears inbound & outbound queues.\n\t *\n\t * Differences from dispose:\n\t * - close will trigger readonly notification\n\t * - close emits \"closed\"\n\t * - close cannot be called after dispose\n\t */\n\tpublic close(error?: ICriticalContainerError): void {\n\t\tif (this._closed) {\n\t\t\treturn;\n\t\t}\n\t\tthis._closed = true;\n\n\t\tthis.connectionManager.dispose(error, true /* switchToReadonly */);\n\t\tthis.clearQueues();\n\t\tthis.emit(\"closed\", error);\n\t}\n\n\t/**\n\t * Disposes the connection and clears the inbound & outbound queues.\n\t *\n\t * Differences from close:\n\t * - dispose will emit \"disposed\"\n\t * - dispose will remove all listeners\n\t * - dispose can be called after closure\n\t */\n\tpublic dispose(error?: Error | ICriticalContainerError): void {\n\t\tif (this._disposed) {\n\t\t\treturn;\n\t\t}\n\t\tif (error !== undefined && !isFluidError(error)) {\n\t\t\tthrow new UsageError(\"Error must be a Fluid error\");\n\t\t}\n\n\t\tthis._disposed = true;\n\t\tthis._closed = true; // We consider \"disposed\" as a further state than \"closed\"\n\n\t\tthis.connectionManager.dispose(error, false /* switchToReadonly */);\n\t\tthis.clearQueues();\n\n\t\t// This needs to be the last thing we do (before removing listeners), as it causes\n\t\t// Container to dispose context and break ability of data stores / runtime to \"hear\" from delta manager.\n\t\tthis.emit(\"disposed\", error);\n\t\tthis.removeAllListeners();\n\t}\n\n\tprivate clearQueues() {\n\t\t// TODO: Remove when typescript version of the repo contains the AbortSignal.reason property (AB#5045)\n\t\t(this.closeAbortController as AbortControllerReal).abort(\"DeltaManager is closed\");\n\n\t\tthis._inbound.clear();\n\t\tthis._inboundSignal.clear();\n\n\t\t// eslint-disable-next-line @typescript-eslint/no-floating-promises\n\t\tthis._inbound.pause();\n\t\t// eslint-disable-next-line @typescript-eslint/no-floating-promises\n\t\tthis._inboundSignal.pause();\n\n\t\t// Drop pending messages - this will ensure catchUp() does not go into infinite loop\n\t\tthis.pending = [];\n\t}\n\n\tpublic refreshDelayInfo(id: string) {\n\t\tthis.throttlingIdSet.delete(id);\n\t\tif (this.throttlingIdSet.size === 0) {\n\t\t\tthis.timeTillThrottling = 0;\n\t\t}\n\t}\n\n\tprivate disconnectHandler(reason: string, error?: IAnyDriverError) {\n\t\tthis.messageBuffer.length = 0;\n\t\tthis.emit(\"disconnect\", reason, error);\n\t}\n\n\t/**\n\t * Emit info about a delay in service communication on account of throttling.\n\t * @param id - Id of the connection that is delayed\n\t * @param delayMs - Duration of the delay\n\t * @param error - error object indicating the throttling\n\t */\n\tpublic emitDelayInfo(id: string, delayMs: number, error: unknown) {\n\t\tconst timeNow = Date.now();\n\t\tthis.throttlingIdSet.add(id);\n\t\tif (delayMs > 0 && timeNow + delayMs > this.timeTillThrottling) {\n\t\t\tthis.timeTillThrottling = timeNow + delayMs;\n\n\t\t\tconst throttlingWarning: IThrottlingWarning = ThrottlingWarning.wrap(\n\t\t\t\terror,\n\t\t\t\tdelayMs / 1000 /* retryAfterSeconds */,\n\t\t\t\tthis.logger,\n\t\t\t);\n\t\t\tthis.emit(\"throttled\", throttlingWarning);\n\t\t}\n\t}\n\n\t// returns parts of message (in string format) that should never change for a given message.\n\t// Used for message comparison. It attempts to avoid comparing fields that potentially may differ.\n\t// for example, it's not clear if serverMetadata or timestamp property is a property of message or server state.\n\t// We only extract the most obvious fields that are sufficient (with high probability) to detect sequence number\n\t// reuse.\n\t// Also payload goes to telemetry, so no content or anything else that shouldn't be logged for privacy reasons\n\t// Note: It's possible for a duplicate op to be broadcasted and have everything the same except the timestamp.\n\tprivate comparableMessagePayload(m: ISequencedDocumentMessage) {\n\t\treturn `${m.clientId}-${m.type}-${m.minimumSequenceNumber}-${m.referenceSequenceNumber}-${m.timestamp}`;\n\t}\n\n\tprivate enqueueMessages(\n\t\tmessages: ISequencedDocumentMessage[],\n\t\treason: string,\n\t\tallowGaps = false,\n\t): void {\n\t\tif (this.handler === undefined) {\n\t\t\t// We did not setup handler yet.\n\t\t\t// This happens when we connect to web socket faster than we get attributes for container\n\t\t\t// and thus faster than attachOpHandler() is called\n\t\t\t// this.lastProcessedSequenceNumber is still zero, so we can't rely on this.fetchMissingDeltas()\n\t\t\t// to do the right thing.\n\t\t\tthis.pending = this.pending.concat(messages);\n\t\t\treturn;\n\t\t}\n\n\t\t// Pending ops should never just hang around for nothing.\n\t\t// This invariant will stay true through this function execution,\n\t\t// so there is no need to process pending ops here.\n\t\t// It's responsibility of\n\t\t// - attachOpHandler()\n\t\t// - fetchMissingDeltas() after it's done with querying storage\n\t\tassert(\n\t\t\tthis.pending.length === 0 || this.fetchReason !== undefined,\n\t\t\t0x1e9 /* \"Pending ops\" */,\n\t\t);\n\n\t\tif (messages.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst from = messages[0].sequenceNumber;\n\t\tconst last = messages[messages.length - 1].sequenceNumber;\n\n\t\t// Report stats about missing and duplicate ops\n\t\t// This helps better understand why we fetch ops from storage, and thus may delay\n\t\t// getting current / sending ops\n\t\t// It's possible that this batch is already too late - do not bother\n\t\tif (last > this.lastQueuedSequenceNumber) {\n\t\t\tlet prev = from - 1;\n\t\t\tconst initialGap = prev - this.lastQueuedSequenceNumber;\n\t\t\tlet firstMissing: number | undefined;\n\t\t\tlet duplicate = 0;\n\t\t\tlet gap = 0;\n\n\t\t\t// Count all gaps and duplicates\n\t\t\tfor (const message of messages) {\n\t\t\t\tif (message.sequenceNumber === prev) {\n\t\t\t\t\tduplicate++;\n\t\t\t\t} else if (message.sequenceNumber !== prev + 1) {\n\t\t\t\t\tgap++;\n\t\t\t\t\tif (firstMissing === undefined) {\n\t\t\t\t\t\tfirstMissing = prev + 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tprev = message.sequenceNumber;\n\t\t\t}\n\n\t\t\tlet eventName: string | undefined;\n\n\t\t\t// Report if we found some issues\n\t\t\tif (\n\t\t\t\tduplicate !== 0 ||\n\t\t\t\t(gap !== 0 && !allowGaps) ||\n\t\t\t\t(initialGap > 0 && this.fetchReason === undefined)\n\t\t\t) {\n\t\t\t\teventName = \"enqueueMessages\";\n\t\t\t\t// Also report if we are fetching ops, and same range comes in, thus making this fetch obsolete.\n\t\t\t} else if (\n\t\t\t\tthis.fetchReason !== undefined &&\n\t\t\t\tthis.fetchReason !== reason &&\n\t\t\t\tfrom <= this.lastQueuedSequenceNumber + 1 &&\n\t\t\t\tlast > this.lastQueuedSequenceNumber\n\t\t\t) {\n\t\t\t\teventName = \"enqueueMessagesExtraFetch\";\n\t\t\t}\n\n\t\t\t// Report if there is something to report\n\t\t\t// Do not report when pending fetch is in progress, as such reporting will not\n\t\t\t// correctly take into account pending ops.\n\t\t\tif (eventName !== undefined) {\n\t\t\t\tthis.logger.sendPerformanceEvent({\n\t\t\t\t\teventName,\n\t\t\t\t\treason,\n\t\t\t\t\tpreviousReason: this.prevEnqueueMessagesReason,\n\t\t\t\t\tfrom,\n\t\t\t\t\tto: last + 1, // exclusive, being consistent with the other telemetry / APIs\n\t\t\t\t\tlength: messages.length,\n\t\t\t\t\tfetchReason: this.fetchReason,\n\t\t\t\t\tduplicate: duplicate > 0 ? duplicate : undefined,\n\t\t\t\t\tinitialGap: initialGap !== 0 ? initialGap : undefined,\n\t\t\t\t\tgap: gap > 0 ? gap : undefined,\n\t\t\t\t\tfirstMissing,\n\t\t\t\t\tdmInitialSeqNumber: this.initialSequenceNumber,\n\t\t\t\t\t...this.connectionManager.connectionVerboseProps,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tthis.updateLatestKnownOpSeqNumber(messages[messages.length - 1].sequenceNumber);\n\n\t\tconst n = this.previouslyProcessedMessage?.sequenceNumber;\n\t\tassert(\n\t\t\tn === undefined || n === this.lastQueuedSequenceNumber,\n\t\t\t0x0ec /* \"Unexpected value for previously processed message's sequence number\" */,\n\t\t);\n\n\t\tfor (const message of messages) {\n\t\t\t// Check that the messages are arriving in the expected order\n\t\t\tif (message.sequenceNumber <= this.lastQueuedSequenceNumber) {\n\t\t\t\t// Validate that we do not have data loss, i.e. sequencing is reset and started again\n\t\t\t\t// with numbers that this client already observed before.\n\t\t\t\tif (this.previouslyProcessedMessage?.sequenceNumber === message.sequenceNumber) {\n\t\t\t\t\tconst message1 = this.comparableMessagePayload(this.previouslyProcessedMessage);\n\t\t\t\t\tconst message2 = this.comparableMessagePayload(message);\n\t\t\t\t\tif (message1 !== message2) {\n\t\t\t\t\t\tconst error = new NonRetryableError(\n\t\t\t\t\t\t\t// This looks like a data corruption but the culprit was that the file was overwritten\n\t\t\t\t\t\t\t// in storage. See PR #5882.\n\t\t\t\t\t\t\t// Likely to be an issue with Fluid Services. Content does not match previous client\n\t\t\t\t\t\t\t// knowledge about this file. If the file is overwritten for any reason, this error can be\n\t\t\t\t\t\t\t// hit. One example is that some clients could be submitting ops to two different service\n\t\t\t\t\t\t\t// instances such that the same sequence number is reused for two different ops.\n\t\t\t\t\t\t\t// pre-0.58 error message: twoMessagesWithSameSeqNumAndDifferentPayload\n\t\t\t\t\t\t\t\"Found two messages with the same sequenceNumber but different payloads. Likely to be a \" +\n\t\t\t\t\t\t\t\t\"service issue\",\n\t\t\t\t\t\t\tDriverErrorType.fileOverwrittenInStorage,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tclientId: this.connectionManager.clientId,\n\t\t\t\t\t\t\t\tsequenceNumber: message.sequenceNumber,\n\t\t\t\t\t\t\t\tmessage1,\n\t\t\t\t\t\t\t\tmessage2,\n\t\t\t\t\t\t\t\tdriverVersion: undefined,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthis.close(error);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (message.sequenceNumber !== this.lastQueuedSequenceNumber + 1) {\n\t\t\t\tthis.pending.push(message);\n\t\t\t\tthis.fetchMissingDeltas(reason, message.sequenceNumber);\n\t\t\t} else {\n\t\t\t\tthis.lastQueuedSequenceNumber = message.sequenceNumber;\n\t\t\t\tthis.previouslyProcessedMessage = message;\n\t\t\t\tthis._inbound.push(message);\n\t\t\t}\n\t\t}\n\n\t\t// When / if we report a gap in ops in the future, we want telemetry to correctly reflect source\n\t\t// of prior ops. But if we have some out of order ops (this.pending), then reporting current reason\n\t\t// becomes not accurate, as the gap existed before current batch, so we should just report \"unknown\".\n\t\tthis.prevEnqueueMessagesReason = this.pending.length > 0 ? \"unknown\" : reason;\n\t}\n\n\tprivate processInboundMessage(message: ISequencedDocumentMessage): void {\n\t\tconst startTime = Date.now();\n\t\tassert(!this.currentlyProcessingOps, 0x3af /* Already processing ops. */);\n\t\tthis.currentlyProcessingOps = true;\n\t\tthis.lastProcessedMessage = message;\n\n\t\tconst isString = typeof message.clientId === \"string\";\n\t\tassert(message.clientId === null || isString, 0x41a /* undefined or string */);\n\t\t// All client messages are coming from some client, and should have clientId,\n\t\t// and non-client message should not have clientId. But, there are two exceptions:\n\t\t// 1. (Legacy) We can see message.type === \"attach\" or \"chunkedOp\" for legacy files before RTM\n\t\t// 2. Non-immediate noops (contents: null) can be sent by service without clientId\n\t\tif (!isString && isClientMessage(message) && message.type !== MessageType.NoOp) {\n\t\t\tthrow new DataCorruptionError(\"Mismatch in clientId\", {\n\t\t\t\t...extractSafePropertiesFromMessage(message),\n\t\t\t\tmessageType: message.type,\n\t\t\t});\n\t\t}\n\n\t\t// TODO Remove after SPO picks up the latest build.\n\t\tif (\n\t\t\ttypeof message.contents === \"string\" &&\n\t\t\tmessage.contents !== \"\" &&\n\t\t\tmessage.type !== MessageType.ClientLeave\n\t\t) {\n\t\t\tmessage.contents = JSON.parse(message.contents);\n\t\t}\n\n\t\t// Validate client sequence number has no gap. Decrement the noOpCount by gap\n\t\t// If the count ends up negative, that means we have a real gap and throw error\n\t\tif (\n\t\t\tthis.connectionManager.clientId !== undefined &&\n\t\t\tthis.connectionManager.clientId === message.clientId\n\t\t) {\n\t\t\tif (message.type === MessageType.NoOp) {\n\t\t\t\tthis.noOpCount--;\n\t\t\t}\n\t\t\tconst clientSeqNumGap =\n\t\t\t\tmessage.clientSequenceNumber - this.lastClientSequenceNumber - 1;\n\t\t\tthis.noOpCount -= clientSeqNumGap;\n\t\t\tif (this.noOpCount < 0) {\n\t\t\t\tthrow new Error(`gap in client sequence number: ${clientSeqNumGap}`);\n\t\t\t}\n\t\t\tthis.lastClientSequenceNumber = message.clientSequenceNumber;\n\t\t}\n\n\t\tthis.connectionManager.beforeProcessingIncomingOp(message);\n\n\t\t// Watch the minimum sequence number and be ready to update as needed\n\t\tif (this.minSequenceNumber > message.minimumSequenceNumber) {\n\t\t\t// pre-0.58 error message: msnMovesBackwards\n\t\t\tthrow new DataCorruptionError(\n\t\t\t\t\"Found a lower minimumSequenceNumber (msn) than previously recorded\",\n\t\t\t\t{\n\t\t\t\t\t...extractSafePropertiesFromMessage(message),\n\t\t\t\t\tclientId: this.connectionManager.clientId,\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\n\t\t// Client ops: MSN has to be lower than sequence #, as client can continue to send ops with same\n\t\t// reference sequence number as this op.\n\t\t// System ops (when no clients are connected) are the only ops where equation is possible.\n\t\tconst diff = message.sequenceNumber - message.minimumSequenceNumber;\n\t\tif (diff < 0 || (diff === 0 && message.clientId !== null)) {\n\t\t\tthrow new DataCorruptionError(\n\t\t\t\t\"MSN has to be lower than sequence #\",\n\t\t\t\textractSafePropertiesFromMessage(message),\n\t\t\t);\n\t\t}\n\n\t\tthis.minSequenceNumber = message.minimumSequenceNumber;\n\n\t\tif (message.sequenceNumber !== this.lastProcessedSequenceNumber + 1) {\n\t\t\t// pre-0.58 error message: nonSequentialSequenceNumber\n\t\t\tthrow new DataCorruptionError(\"Found a non-Sequential sequenceNumber\", {\n\t\t\t\t...extractSafePropertiesFromMessage(message),\n\t\t\t\tclientId: this.connectionManager.clientId,\n\t\t\t});\n\t\t}\n\t\tthis.lastProcessedSequenceNumber = message.sequenceNumber;\n\n\t\t// a bunch of code assumes that this is true\n\t\tassert(\n\t\t\tthis.lastProcessedSequenceNumber <= this.lastObservedSeqNumber,\n\t\t\t0x267 /* \"lastObservedSeqNumber should be updated first\" */,\n\t\t);\n\n\t\t// Back-compat for older server with no term\n\t\tif (message.term === undefined) {\n\t\t\tmessage.term = OnlyValidTermValue;\n\t\t}\n\n\t\tif (this.handler === undefined) {\n\t\t\tthrow new Error(\"Attempted to process an inbound message without a handler attached\");\n\t\t}\n\t\tthis.handler.process(message);\n\t\tthis.currentlyProcessingOps = false;\n\t\tconst endTime = Date.now();\n\n\t\t// Should be last, after changing this.lastProcessedSequenceNumber above, as many callers\n\t\t// test this.lastProcessedSequenceNumber instead of using op.sequenceNumber itself.\n\t\tthis.emit(\"op\", message, endTime - startTime);\n\t}\n\n\t/**\n\t * Retrieves the missing deltas between the given sequence numbers\n\t */\n\tprivate fetchMissingDeltas(reasonArg: string, to?: number) {\n\t\tthis.fetchMissingDeltasCore(reasonArg, false /* cacheOnly */, to).catch((error) => {\n\t\t\tthis.logger.sendErrorEvent({ eventName: \"fetchMissingDeltasException\" }, error);\n\t\t});\n\t}\n\n\t/**\n\t * Retrieves the missing deltas between the given sequence numbers\n\t */\n\tprivate async fetchMissingDeltasCore(reason: string, cacheOnly: boolean, to?: number) {\n\t\t// Exit out early if we're already fetching deltas\n\t\tif (this.fetchReason !== undefined) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._closed) {\n\t\t\tthis.logger.sendTelemetryEvent({\n\t\t\t\teventName: \"fetchMissingDeltasClosedConnection\",\n\t\t\t\treason,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.handler === undefined) {\n\t\t\t// We do not poses yet any information\n\t\t\tassert(this.lastQueuedSequenceNumber === 0, 0x26b /* \"initial state\" */);\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tlet from = this.lastQueuedSequenceNumber + 1;\n\n\t\t\tconst n = this.previouslyProcessedMessage?.sequenceNumber;\n\t\t\tif (n !== undefined) {\n\t\t\t\t// If we already processed at least one op, then we have this.previouslyProcessedMessage populated\n\t\t\t\t// and can use it to validate that we are operating on same file, i.e. it was not overwritten.\n\t\t\t\t// Knowing about this mechanism, we could ask for op we already observed to increase validation.\n\t\t\t\t// This is especially useful when coming out of offline mode or loading from\n\t\t\t\t// very old cached (by client / driver) snapshot.\n\t\t\t\tassert(\n\t\t\t\t\tn === this.lastQueuedSequenceNumber,\n\t\t\t\t\t0x0f2 /* \"previouslyProcessedMessage\" */,\n\t\t\t\t);\n\t\t\t\tassert(from > 1, 0x0f3 /* \"not positive\" */);\n\t\t\t\tfrom--;\n\t\t\t}\n\n\t\t\tconst fetchReason = `${reason}_fetch`;\n\t\t\tthis.fetchReason = fetchReason;\n\n\t\t\tawait this.getDeltas(\n\t\t\t\tfrom,\n\t\t\t\tto,\n\t\t\t\tfetchReason,\n\t\t\t\t(messages) => {\n\t\t\t\t\tthis.refreshDelayInfo(this.deltaStorageDelayId);\n\t\t\t\t\tthis.enqueueMessages(messages, fetchReason);\n\t\t\t\t},\n\t\t\t\tcacheOnly,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthis.logger.sendErrorEvent({ eventName: \"GetDeltas_Exception\" }, error);\n\t\t\tthis.close(normalizeError(error));\n\t\t} finally {\n\t\t\tthis.refreshDelayInfo(this.deltaStorageDelayId);\n\t\t\tthis.fetchReason = undefined;\n\t\t\tthis.processPendingOps(reason);\n\t\t}\n\t}\n\n\t/**\n\t * Sorts pending ops and attempts to apply them\n\t */\n\tprivate processPendingOps(reason?: string): void {\n\t\tif (this._closed) {\n\t\t\treturn;\n\t\t}\n\n\t\tassert(this.handler !== undefined, 0x26c /* \"handler should be installed\" */);\n\n\t\tconst pendingSorted = this.pending.sort((a, b) => a.sequenceNumber - b.sequenceNumber);\n\t\tthis.pending = [];\n\t\t// Given that we do not track where these ops came from any more, it's not very\n\t\t// actionably to report gaps in this range.\n\t\tthis.enqueueMessages(pendingSorted, `${reason}_pending`, true /* allowGaps */);\n\n\t\t// Re-entrancy is ignored by fetchMissingDeltas, execution will come here when it's over\n\t\tif (this.fetchReason === undefined) {\n\t\t\t// See issue #7312 for more details\n\t\t\t// We observe cases where client gets into situation where it is not aware of missing ops\n\t\t\t// (i.e. client being behind), and as such, does not attempt to fetch them.\n\t\t\t// In some cases client may not have enough signal (example - \"read\" connection that is silent -\n\t\t\t// there is no easy way for client to realize it's behind, see a bit of commentary / logic at the\n\t\t\t// end of setupNewSuccessfulConnection). In other cases it should be able to learn that info (\"write\"\n\t\t\t// connection, learn by receiving its own join op), but data suggest it does not happen.\n\t\t\t// In 50% of these cases we do know we are behind through checkpointSequenceNumber on connection object\n\t\t\t// and thus can leverage that to trigger recovery. But this is not going to solve all the problems\n\t\t\t// (the other 50%), and thus these errors below should be looked at even if code below results in\n\t\t\t// recovery.\n\t\t\tif (this.lastQueuedSequenceNumber < this.lastObservedSeqNumber) {\n\t\t\t\tthis.fetchMissingDeltas(\"OpsBehind\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate updateLatestKnownOpSeqNumber(seq: number) {\n\t\tif (this.lastObservedSeqNumber < seq) {\n\t\t\tthis.lastObservedSeqNumber = seq;\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"deltaManager.js","sourceRoot":"","sources":["../src/deltaManager.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,EAAE,IAAI,IAAI,EAAE,MAAM,MAAM,CAAC;AAUlC,OAAO,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACzE,OAAO,EACN,cAAc,EACd,UAAU,EACV,cAAc,EACd,YAAY,GAEZ,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAGN,eAAe,GACf,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAIN,WAAW,GAEX,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AACjG,OAAO,EACN,iBAAiB,EACjB,mBAAmB,EACnB,gCAAgC,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F,CAAC;IAED;;OAEG;IACK,iBAAiB,CAAC,MAAe;QACxC,IAAI,IAAI,CAAC,OAAO,EAAE;YACjB,OAAO;SACP;QAED,MAAM,CAAC,IAAI,CAAC,OAAO,KAAK,SAAS,EAAE,KAAK,CAAC,mCAAmC,CAAC,CAAC;QAE9E,MAAM,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,cAAc,GAAG,CAAC,CAAC,cAAc,CAAC,CAAC;QACvF,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;QAClB,+EAA+E;QAC/E,2CAA2C;QAC3C,IAAI,CAAC,eAAe,CAAC,aAAa,EAAE,GAAG,MAAM,UAAU,EAAE,IAAI,CAAC,eAAe,CAAC,CAAC;QAE/E,wFAAwF;QACxF,IAAI,IAAI,CAAC,WAAW,KAAK,SAAS,EAAE;YACnC,mCAAmC;YACnC,yFAAyF;YACzF,2EAA2E;YAC3E,gGAAgG;YAChG,iGAAiG;YACjG,qGAAqG;YACrG,wFAAwF;YACxF,uGAAuG;YACvG,kGAAkG;YAClG,iGAAiG;YACjG,YAAY;YACZ,IAAI,IAAI,CAAC,wBAAwB,GAAG,IAAI,CAAC,qBAAqB,EAAE;gBAC/D,IAAI,CAAC,kBAAkB,CAAC,WAAW,CAAC,CAAC;aACrC;SACD;IACF,CAAC;IAEO,4BAA4B,CAAC,GAAW;QAC/C,IAAI,IAAI,CAAC,qBAAqB,GAAG,GAAG,EAAE;YACrC,IAAI,CAAC,qBAAqB,GAAG,GAAG,CAAC;SACjC;IACF,CAAC;CACD","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { v4 as uuid } from \"uuid\";\nimport { IEventProvider } from \"@fluidframework/common-definitions\";\nimport { ITelemetryProperties, ITelemetryErrorEvent } from \"@fluidframework/core-interfaces\";\nimport {\n\tICriticalContainerError,\n\tIDeltaManager,\n\tIDeltaManagerEvents,\n\tIDeltaQueue,\n\tIThrottlingWarning,\n} from \"@fluidframework/container-definitions\";\nimport { assert, TypedEventEmitter } from \"@fluidframework/common-utils\";\nimport {\n\tnormalizeError,\n\tlogIfFalse,\n\tsafeRaiseEvent,\n\tisFluidError,\n\tITelemetryLoggerExt,\n} from \"@fluidframework/telemetry-utils\";\nimport {\n\tIDocumentDeltaStorageService,\n\tIDocumentService,\n\tDriverErrorType,\n} from \"@fluidframework/driver-definitions\";\nimport {\n\tIDocumentMessage,\n\tISequencedDocumentMessage,\n\tISignalMessage,\n\tMessageType,\n\tConnectionMode,\n} from \"@fluidframework/protocol-definitions\";\nimport { NonRetryableError, isRuntimeMessage, MessageType2 } from \"@fluidframework/driver-utils\";\nimport {\n\tThrottlingWarning,\n\tDataCorruptionError,\n\textractSafePropertiesFromMessage,\n\tDataProcessingError,\n\tUsageError,\n} from \"@fluidframework/container-utils\";\nimport {\n\tIConnectionDetailsInternal,\n\tIConnectionManager,\n\tIConnectionManagerFactoryArgs,\n\tIConnectionStateChangeReason,\n} from \"./contracts\";\nimport { DeltaQueue } from \"./deltaQueue\";\nimport { OnlyValidTermValue } from \"./protocol\";\n\nexport interface IConnectionArgs {\n\tmode?: ConnectionMode;\n\tfetchOpsFromStorage?: boolean;\n\treason: IConnectionStateChangeReason;\n}\n\n/**\n * Includes events emitted by the concrete implementation DeltaManager\n * but not exposed on the public interface IDeltaManager\n */\nexport interface IDeltaManagerInternalEvents extends IDeltaManagerEvents {\n\t(event: \"throttled\", listener: (error: IThrottlingWarning) => void);\n\t(event: \"closed\" | \"disposed\", listener: (error?: ICriticalContainerError) => void);\n\t(event: \"connect\", listener: (details: IConnectionDetailsInternal, opsBehind?: number) => void);\n\t(event: \"establishingConnection\", listener: (reason: IConnectionStateChangeReason) => void);\n\t(\n\t\tevent: \"cancelEstablishingConnection\",\n\t\tlistener: (reason: IConnectionStateChangeReason) => void,\n\t);\n}\n\n/**\n * Batching makes assumptions about what might be on the metadata. This interface codifies those assumptions, but does not validate them.\n */\ninterface IBatchMetadata {\n\tbatch?: boolean;\n}\n\n/**\n * Interface used to define a strategy for handling incoming delta messages\n */\nexport interface IDeltaHandlerStrategy {\n\t/**\n\t * Processes the message.\n\t */\n\tprocess: (message: ISequencedDocumentMessage) => void;\n\n\t/**\n\t * Processes the signal.\n\t */\n\tprocessSignal: (message: ISignalMessage) => void;\n}\n\n/**\n * Determines if message was sent by client, not service\n */\nfunction isClientMessage(message: ISequencedDocumentMessage | IDocumentMessage): boolean {\n\tif (isRuntimeMessage(message)) {\n\t\treturn true;\n\t}\n\tswitch (message.type) {\n\t\tcase MessageType.Propose:\n\t\tcase MessageType.Reject:\n\t\tcase MessageType.NoOp:\n\t\tcase MessageType2.Accept:\n\t\tcase MessageType.Summarize:\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n/**\n * Type is used to cast AbortController to represent new version of DOM API and prevent build issues\n * TODO: Remove when typescript version of the repo contains the AbortSignal.reason property (AB#5045)\n */\ntype AbortControllerReal = AbortController & { abort(reason?: any): void };\n/**\n * Type is used to cast AbortSignal to represent new version of DOM API and prevent build issues\n * TODO: Remove when typescript version of the repo contains the AbortSignal.reason property (AB#5045)\n */\ntype AbortSignalReal = AbortSignal & { reason: any };\n\n/**\n * Manages the flow of both inbound and outbound messages. This class ensures that shared objects receive delta\n * messages in order regardless of possible network conditions or timings causing out of order delivery.\n */\nexport class DeltaManager<TConnectionManager extends IConnectionManager>\n\textends TypedEventEmitter<IDeltaManagerInternalEvents>\n\timplements\n\t\tIDeltaManager<ISequencedDocumentMessage, IDocumentMessage>,\n\t\tIEventProvider<IDeltaManagerInternalEvents>\n{\n\tpublic readonly connectionManager: TConnectionManager;\n\n\tpublic get active(): boolean {\n\t\treturn this._active();\n\t}\n\n\tpublic get disposed() {\n\t\treturn this._closed;\n\t}\n\n\tpublic get IDeltaSender() {\n\t\treturn this;\n\t}\n\n\tprivate pending: ISequencedDocumentMessage[] = [];\n\tprivate fetchReason: string | undefined;\n\n\t// A boolean used to assert that ops are not being sent while processing another op.\n\tprivate currentlyProcessingOps: boolean = false;\n\n\t// The minimum sequence number and last sequence number received from the server\n\tprivate minSequenceNumber: number = 0;\n\n\t// There are three numbers we track\n\t// * lastQueuedSequenceNumber is the last queued sequence number. If there are gaps in seq numbers, then this number\n\t// is not updated until we cover that gap, so it increases each time by 1.\n\t// * lastObservedSeqNumber is an estimation of last known sequence number for container in storage. It's initially\n\t// populated at web socket connection time (if storage provides that info) and is updated once ops shows up.\n\t// It's never less than lastQueuedSequenceNumber\n\t// * lastProcessedSequenceNumber - last processed sequence number\n\tprivate lastQueuedSequenceNumber: number = 0;\n\tprivate lastObservedSeqNumber: number = 0;\n\tprivate lastProcessedSequenceNumber: number = 0;\n\tprivate lastProcessedMessage: ISequencedDocumentMessage | undefined;\n\n\t/** count number of noops sent by the client which may not be acked */\n\tprivate noOpCount: number = 0;\n\t/** Track clientSequenceNumber of the last op */\n\tprivate lastClientSequenceNumber: number = 0;\n\n\t/**\n\t * Track down the ops size.\n\t */\n\tprivate opsSize: number = 0;\n\tprivate prevEnqueueMessagesReason: string | undefined;\n\tprivate previouslyProcessedMessage: ISequencedDocumentMessage | undefined;\n\n\t// The sequence number we initially loaded from\n\t// In case of reading from a snapshot or pending state, its value will be equal to\n\t// the last message that got serialized.\n\tprivate initSequenceNumber: number = 0;\n\n\tprivate readonly _inbound: DeltaQueue<ISequencedDocumentMessage>;\n\tprivate readonly _inboundSignal: DeltaQueue<ISignalMessage>;\n\n\tprivate _closed = false;\n\tprivate _disposed = false;\n\n\tprivate handler: IDeltaHandlerStrategy | undefined;\n\tprivate deltaStorage: IDocumentDeltaStorageService | undefined;\n\n\tprivate readonly throttlingIdSet = new Set<string>();\n\tprivate timeTillThrottling: number = 0;\n\n\tpublic readonly closeAbortController = new AbortController();\n\n\tprivate readonly deltaStorageDelayId = uuid();\n\tprivate readonly deltaStreamDelayId = uuid();\n\n\tprivate messageBuffer: IDocumentMessage[] = [];\n\n\tprivate _checkpointSequenceNumber: number | undefined;\n\n\tpublic get inbound(): IDeltaQueue<ISequencedDocumentMessage> {\n\t\treturn this._inbound;\n\t}\n\n\tpublic get inboundSignal(): IDeltaQueue<ISignalMessage> {\n\t\treturn this._inboundSignal;\n\t}\n\n\tpublic get initialSequenceNumber(): number {\n\t\treturn this.initSequenceNumber;\n\t}\n\n\tpublic get lastSequenceNumber(): number {\n\t\treturn this.lastProcessedSequenceNumber;\n\t}\n\n\tpublic get lastMessage() {\n\t\treturn this.lastProcessedMessage;\n\t}\n\n\tpublic get lastKnownSeqNumber() {\n\t\treturn this.lastObservedSeqNumber;\n\t}\n\n\tpublic get minimumSequenceNumber(): number {\n\t\treturn this.minSequenceNumber;\n\t}\n\n\t/**\n\t * Tells if current connection has checkpoint information.\n\t * I.e. we know how far behind the client was at the time of establishing connection\n\t */\n\tpublic get hasCheckpointSequenceNumber() {\n\t\t// Valid to be called only if we have active connection.\n\t\tassert(this.connectionManager.connected, 0x0df /* \"Missing active connection\" */);\n\t\treturn this._checkpointSequenceNumber !== undefined;\n\t}\n\n\t// Forwarding connection manager properties / IDeltaManager implementation\n\tpublic get maxMessageSize(): number {\n\t\treturn this.connectionManager.maxMessageSize;\n\t}\n\tpublic get version() {\n\t\treturn this.connectionManager.version;\n\t}\n\tpublic get serviceConfiguration() {\n\t\treturn this.connectionManager.serviceConfiguration;\n\t}\n\tpublic get outbound() {\n\t\treturn this.connectionManager.outbound;\n\t}\n\tpublic get readOnlyInfo() {\n\t\treturn this.connectionManager.readOnlyInfo;\n\t}\n\tpublic get clientDetails() {\n\t\treturn this.connectionManager.clientDetails;\n\t}\n\n\tpublic submit(\n\t\ttype: MessageType,\n\t\tcontents?: string,\n\t\tbatch = false,\n\t\tmetadata?: any,\n\t\tcompression?: string,\n\t\treferenceSequenceNumber?: number,\n\t) {\n\t\t// Back-compat ADO:3455\n\t\tconst backCompatRefSeqNum = referenceSequenceNumber ?? this.lastProcessedSequenceNumber;\n\t\tconst messagePartial: Omit<IDocumentMessage, \"clientSequenceNumber\"> = {\n\t\t\tcontents,\n\t\t\tmetadata,\n\t\t\treferenceSequenceNumber: backCompatRefSeqNum,\n\t\t\ttype,\n\t\t\tcompression,\n\t\t};\n\n\t\tif (!batch) {\n\t\t\tthis.flush();\n\t\t}\n\t\tconst message = this.connectionManager.prepareMessageToSend(messagePartial);\n\t\tif (message === undefined) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tassert(isClientMessage(message), 0x419 /* client sends non-client message */);\n\n\t\tif (contents !== undefined) {\n\t\t\tthis.opsSize += contents.length;\n\t\t}\n\n\t\tthis.messageBuffer.push(message);\n\n\t\tif (message.type === MessageType.NoOp) {\n\t\t\tthis.noOpCount++;\n\t\t}\n\n\t\tthis.emit(\"submitOp\", message);\n\n\t\tif (!batch) {\n\t\t\tthis.flush();\n\t\t}\n\t\treturn message.clientSequenceNumber;\n\t}\n\n\tpublic submitSignal(content: any) {\n\t\treturn this.connectionManager.submitSignal(content);\n\t}\n\n\tpublic flush() {\n\t\tconst batch = this.messageBuffer;\n\t\tif (batch.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.messageBuffer = [];\n\n\t\t// The prepareFlush event allows listeners to append metadata to the batch prior to submission.\n\t\tthis.emit(\"prepareSend\", batch);\n\n\t\tif (batch.length === 1) {\n\t\t\tassert(\n\t\t\t\t(batch[0].metadata as IBatchMetadata)?.batch === undefined,\n\t\t\t\t0x3c9 /* no batch markup on single message */,\n\t\t\t);\n\t\t} else {\n\t\t\tassert(\n\t\t\t\t(batch[0].metadata as IBatchMetadata)?.batch === true,\n\t\t\t\t0x3ca /* no start batch markup */,\n\t\t\t);\n\t\t\tassert(\n\t\t\t\t(batch[batch.length - 1].metadata as IBatchMetadata)?.batch === false,\n\t\t\t\t0x3cb /* no end batch markup */,\n\t\t\t);\n\t\t}\n\n\t\tthis.connectionManager.sendMessages(batch);\n\n\t\tassert(this.messageBuffer.length === 0, 0x3cc /* reentrancy */);\n\t}\n\n\tpublic get connectionProps(): ITelemetryProperties {\n\t\treturn {\n\t\t\tsequenceNumber: this.lastSequenceNumber,\n\t\t\topsSize: this.opsSize > 0 ? this.opsSize : undefined,\n\t\t\tdeltaManagerState: this._disposed ? \"disposed\" : this._closed ? \"closed\" : \"open\",\n\t\t\t...this.connectionManager.connectionProps,\n\t\t};\n\t}\n\n\t/**\n\t * Log error event with a bunch of internal to DeltaManager information about state of op processing\n\t * Used to diagnose connectivity issues related to op processing (i.e. cases where for some reason\n\t * we stop processing ops that results in no processing join op and thus moving to connected state)\n\t * @param event - Event to log.\n\t */\n\tpublic logConnectionIssue(event: ITelemetryErrorEvent) {\n\t\tassert(this.connectionManager.connected, 0x238 /* \"called only in connected state\" */);\n\n\t\tconst pendingSorted = this.pending.sort((a, b) => a.sequenceNumber - b.sequenceNumber);\n\t\tthis.logger.sendErrorEvent({\n\t\t\t...event,\n\t\t\t// This directly tells us if fetching ops is in flight, and thus likely the reason of\n\t\t\t// stalled op processing\n\t\t\tfetchReason: this.fetchReason,\n\t\t\t// A bunch of useful sequence numbers to understand if we are holding some ops from processing\n\t\t\tlastQueuedSequenceNumber: this.lastQueuedSequenceNumber, // last sequential op\n\t\t\tlastProcessedSequenceNumber: this.lastProcessedSequenceNumber, // same as above, but after processing\n\t\t\tlastObserved: this.lastObservedSeqNumber, // last sequence we ever saw; may have gaps with above.\n\t\t\t// connection info\n\t\t\t...this.connectionManager.connectionVerboseProps,\n\t\t\tpendingOps: this.pending.length, // Do we have any pending ops?\n\t\t\tpendingFirst: pendingSorted[0]?.sequenceNumber, // is the first pending op the one that we are missing?\n\t\t\thaveHandler: this.handler !== undefined, // do we have handler installed?\n\t\t\tinboundLength: this.inbound.length,\n\t\t\tinboundPaused: this.inbound.paused,\n\t\t});\n\t}\n\n\tconstructor(\n\t\tprivate readonly serviceProvider: () => IDocumentService | undefined,\n\t\tprivate readonly logger: ITelemetryLoggerExt,\n\t\tprivate readonly _active: () => boolean,\n\t\tcreateConnectionManager: (props: IConnectionManagerFactoryArgs) => TConnectionManager,\n\t) {\n\t\tsuper();\n\t\tconst props: IConnectionManagerFactoryArgs = {\n\t\t\tincomingOpHandler: (messages: ISequencedDocumentMessage[], reason: string) => {\n\t\t\t\ttry {\n\t\t\t\t\tthis.enqueueMessages(messages, reason);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.logger.sendErrorEvent({ eventName: \"EnqueueMessages_Exception\" }, error);\n\t\t\t\t\tthis.close(normalizeError(error));\n\t\t\t\t}\n\t\t\t},\n\t\t\tsignalHandler: (message: ISignalMessage) => this._inboundSignal.push(message),\n\t\t\treconnectionDelayHandler: (delayMs: number, error: unknown) =>\n\t\t\t\tthis.emitDelayInfo(this.deltaStreamDelayId, delayMs, error),\n\t\t\tcloseHandler: (error: any) => this.close(error),\n\t\t\tdisconnectHandler: (reason: IConnectionStateChangeReason) =>\n\t\t\t\tthis.disconnectHandler(reason),\n\t\t\tconnectHandler: (connection: IConnectionDetailsInternal) =>\n\t\t\t\tthis.connectHandler(connection),\n\t\t\tpongHandler: (latency: number) => this.emit(\"pong\", latency),\n\t\t\treadonlyChangeHandler: (readonly?: boolean) =>\n\t\t\t\tsafeRaiseEvent(this, this.logger, \"readonly\", readonly),\n\t\t\testablishConnectionHandler: (reason: IConnectionStateChangeReason) =>\n\t\t\t\tthis.establishingConnection(reason),\n\t\t\tcancelConnectionHandler: (reason: IConnectionStateChangeReason) =>\n\t\t\t\tthis.cancelEstablishingConnection(reason),\n\t\t};\n\n\t\tthis.connectionManager = createConnectionManager(props);\n\t\tthis._inbound = new DeltaQueue<ISequencedDocumentMessage>((op) => {\n\t\t\tthis.processInboundMessage(op);\n\t\t});\n\n\t\tthis._inbound.on(\"error\", (error) => {\n\t\t\tthis.close(\n\t\t\t\tDataProcessingError.wrapIfUnrecognized(\n\t\t\t\t\terror,\n\t\t\t\t\t\"deltaManagerInboundErrorHandler\",\n\t\t\t\t\tthis.lastMessage,\n\t\t\t\t),\n\t\t\t);\n\t\t});\n\n\t\t// Inbound signal queue\n\t\tthis._inboundSignal = new DeltaQueue<ISignalMessage>((message) => {\n\t\t\tif (this.handler === undefined) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Attempted to process an inbound signal without a handler attached\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.handler.processSignal({\n\t\t\t\tclientId: message.clientId,\n\t\t\t\tcontent: JSON.parse(message.content as string),\n\t\t\t});\n\t\t});\n\n\t\tthis._inboundSignal.on(\"error\", (error) => {\n\t\t\tthis.close(normalizeError(error));\n\t\t});\n\n\t\t// Initially, all queues are created paused.\n\t\t// - outbound is flipped back and forth in setupNewSuccessfulConnection / disconnectFromDeltaStream\n\t\t// - inbound & inboundSignal are resumed in attachOpHandler() when we have handler setup\n\t}\n\n\tprivate cancelEstablishingConnection(reason: IConnectionStateChangeReason) {\n\t\tthis.emit(\"cancelEstablishingConnection\", reason);\n\t}\n\n\tprivate establishingConnection(reason: IConnectionStateChangeReason) {\n\t\tthis.emit(\"establishingConnection\", reason);\n\t}\n\n\tprivate connectHandler(connection: IConnectionDetailsInternal) {\n\t\tthis.refreshDelayInfo(this.deltaStreamDelayId);\n\n\t\tconst props = this.connectionManager.connectionVerboseProps;\n\t\tprops.connectionLastQueuedSequenceNumber = this.lastQueuedSequenceNumber;\n\t\tprops.connectionLastObservedSeqNumber = this.lastObservedSeqNumber;\n\n\t\tconst checkpointSequenceNumber = connection.checkpointSequenceNumber;\n\t\tthis._checkpointSequenceNumber = checkpointSequenceNumber;\n\t\tif (checkpointSequenceNumber !== undefined) {\n\t\t\tthis.updateLatestKnownOpSeqNumber(checkpointSequenceNumber);\n\t\t}\n\n\t\t// We cancel all ops on lost of connectivity, and rely on DDSes to resubmit them.\n\t\t// Semantics are not well defined for batches (and they are broken right now on disconnects anyway),\n\t\t// but it's safe to assume (until better design is put into place) that batches should not exist\n\t\t// across multiple connections. Right now we assume runtime will not submit any ops in disconnected\n\t\t// state. As requirements change, so should these checks.\n\t\tassert(\n\t\t\tthis.messageBuffer.length === 0,\n\t\t\t0x0e9 /* \"messageBuffer is not empty on new connection\" */,\n\t\t);\n\n\t\tthis.opsSize = 0;\n\t\tthis.noOpCount = 0;\n\n\t\tthis.emit(\n\t\t\t\"connect\",\n\t\t\tconnection,\n\t\t\tcheckpointSequenceNumber !== undefined\n\t\t\t\t? this.lastObservedSeqNumber - this.lastSequenceNumber\n\t\t\t\t: undefined,\n\t\t);\n\n\t\t// If we got some initial ops, then we know the gap and call above fetched ops to fill it.\n\t\t// Same is true for \"write\" mode even if we have no ops - we will get \"join\" own op very very soon.\n\t\t// However if we are connecting as view-only, then there is no good signal to realize if client is behind.\n\t\t// Thus we have to hit storage to see if any ops are there.\n\t\tif (checkpointSequenceNumber !== undefined) {\n\t\t\t// We know how far we are behind (roughly). If it's non-zero gap, fetch ops right away.\n\t\t\tif (checkpointSequenceNumber > this.lastQueuedSequenceNumber) {\n\t\t\t\tthis.fetchMissingDeltas(\"AfterConnection\");\n\t\t\t}\n\t\t\t// we do not know the gap, and we will not learn about it if socket is quite - have to ask.\n\t\t} else if (connection.mode === \"read\") {\n\t\t\tthis.fetchMissingDeltas(\"AfterReadConnection\");\n\t\t}\n\t}\n\n\t/**\n\t * Sets the sequence number from which inbound messages should be returned\n\t */\n\tpublic async attachOpHandler(\n\t\tminSequenceNumber: number,\n\t\tsequenceNumber: number,\n\t\thandler: IDeltaHandlerStrategy,\n\t\tprefetchType: \"sequenceNumber\" | \"cached\" | \"all\" | \"none\" = \"none\",\n\t) {\n\t\tthis.initSequenceNumber = sequenceNumber;\n\t\tthis.lastProcessedSequenceNumber = sequenceNumber;\n\t\tthis.minSequenceNumber = minSequenceNumber;\n\t\tthis.lastQueuedSequenceNumber = sequenceNumber;\n\t\tthis.lastObservedSeqNumber = sequenceNumber;\n\n\t\t// We will use same check in other places to make sure all the seq number above are set properly.\n\t\tassert(\n\t\t\tthis.handler === undefined,\n\t\t\t0x0e2 /* \"DeltaManager already has attached op handler!\" */,\n\t\t);\n\t\tthis.handler = handler;\n\t\t// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n\t\tassert(!!(this.handler as any), 0x0e3 /* \"Newly set op handler is null/undefined!\" */);\n\n\t\t// There should be no pending fetch!\n\t\t// This API is called right after attachOpHandler by Container.load().\n\t\t// We might have connection already and it might have called fetchMissingDeltas() from\n\t\t// setupNewSuccessfulConnection. But it should do nothing, because there is no way to fetch ops before\n\t\t// we know snapshot sequence number that is set in attachOpHandler. So all such calls should be noop.\n\t\tassert(\n\t\t\tthis.fetchReason === undefined,\n\t\t\t0x268 /* \"There can't be pending fetch that early in boot sequence!\" */,\n\t\t);\n\n\t\tif (this._closed) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._inbound.resume();\n\t\tthis._inboundSignal.resume();\n\n\t\tif (prefetchType !== \"none\") {\n\t\t\tconst cacheOnly = prefetchType === \"cached\";\n\t\t\tawait this.fetchMissingDeltasCore(`DocumentOpen_${prefetchType}`, cacheOnly);\n\n\t\t\t// Keep going with fetching ops from storage once we have all cached ops in.\n\t\t\t// But do not block load and make this request async / not blocking this api.\n\t\t\t// Ops processing will start once cached ops are in and and will stop when queue is empty\n\t\t\t// (which in most cases will happen when we are done processing cached ops)\n\t\t\tif (cacheOnly) {\n\t\t\t\t// fire and forget\n\t\t\t\tthis.fetchMissingDeltas(\"PostDocumentOpen\");\n\t\t\t}\n\t\t}\n\n\t\t// Ensure there is no need to call this.processPendingOps() at the end of boot sequence\n\t\tassert(\n\t\t\tthis.fetchReason !== undefined || this.pending.length === 0,\n\t\t\t0x269 /* \"pending ops are not dropped\" */,\n\t\t);\n\t}\n\n\tpublic connect(args: IConnectionArgs) {\n\t\tconst fetchOpsFromStorage = args.fetchOpsFromStorage ?? true;\n\t\tlogIfFalse(\n\t\t\tthis.handler !== undefined || !fetchOpsFromStorage,\n\t\t\tthis.logger,\n\t\t\t\"CantFetchWithoutBaseline\",\n\t\t); // can't fetch if no baseline\n\n\t\t// Note: There is race condition here.\n\t\t// We want to issue request to storage as soon as possible, to\n\t\t// reduce latency of becoming current, thus this code here.\n\t\t// But there is no ordering between fetching OPs and connection to delta stream\n\t\t// As result, we might be behind by the time we connect to delta stream\n\t\t// In case of r/w connection, that's not an issue, because we will hear our\n\t\t// own \"join\" message and realize any gap client has in ops.\n\t\t// But for view-only connection, we have no such signal, and with no traffic\n\t\t// on the wire, we might be always behind.\n\t\t// See comment at the end of \"connect\" handler\n\t\tif (fetchOpsFromStorage) {\n\t\t\tthis.fetchMissingDeltas(args.reason.text);\n\t\t}\n\n\t\tthis.connectionManager.connect(args.reason, args.mode);\n\t}\n\n\tprivate async getDeltas(\n\t\tfrom: number, // inclusive\n\t\tto: number | undefined, // exclusive\n\t\tfetchReason: string,\n\t\tcallback: (messages: ISequencedDocumentMessage[]) => void,\n\t\tcacheOnly: boolean,\n\t) {\n\t\tconst docService = this.serviceProvider();\n\t\tif (docService === undefined) {\n\t\t\tthrow new Error(\"Delta manager is not attached\");\n\t\t}\n\n\t\tif (this.deltaStorage === undefined) {\n\t\t\tthis.deltaStorage = await docService.connectToDeltaStorage();\n\t\t}\n\n\t\tlet cancelFetch: (op: ISequencedDocumentMessage) => boolean;\n\n\t\tif (to !== undefined) {\n\t\t\tconst lastExpectedOp = to - 1; // make it inclusive!\n\n\t\t\t// It is possible that due to asynchrony (including await above), required ops were already\n\t\t\t// received through delta stream. Validate that before moving forward.\n\t\t\tif (this.lastQueuedSequenceNumber >= lastExpectedOp) {\n\t\t\t\tthis.logger.sendPerformanceEvent({\n\t\t\t\t\treason: fetchReason,\n\t\t\t\t\teventName: \"ExtraStorageCall\",\n\t\t\t\t\tearly: true,\n\t\t\t\t\tfrom,\n\t\t\t\t\tto,\n\t\t\t\t\t...this.connectionManager.connectionVerboseProps,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Be prepared for the case where webSocket would receive the ops that we are trying to fill through\n\t\t\t// storage. Ideally it should never happen (i.e. ops on socket are always ordered, and thus once we\n\t\t\t// detected gap, this gap can't be filled in later on through websocket).\n\t\t\t// And in practice that does look like the case. The place where this code gets hit is if we lost\n\t\t\t// connection and reconnected (likely to another box), and new socket's initial ops contains these ops.\n\t\t\tcancelFetch = (op: ISequencedDocumentMessage) => op.sequenceNumber >= lastExpectedOp;\n\t\t} else {\n\t\t\t// Unbound requests are made to proactively fetch ops, but also get up to date in cases where socket\n\t\t\t// is silent (and connection is \"read\", thus we might not have any data on how far client is behind).\n\t\t\t// Once we have any op coming in from socket, we can cancel it as it's not needed any more.\n\t\t\t// That said, if we have socket connection, make sure we got ops up to checkpointSequenceNumber!\n\t\t\tcancelFetch = (op: ISequencedDocumentMessage) =>\n\t\t\t\top.sequenceNumber >= this.lastObservedSeqNumber;\n\t\t}\n\n\t\tconst controller = new AbortController();\n\t\tlet opsFromFetch = false;\n\n\t\tconst opListener = (op: ISequencedDocumentMessage) => {\n\t\t\tassert(op.sequenceNumber === this.lastQueuedSequenceNumber, 0x23a /* \"seq#'s\" */);\n\t\t\t// Ops that are coming from this request should not cancel itself.\n\t\t\t// This is useless for known ranges (to is defined) as it means request is over either way.\n\t\t\t// And it will cancel unbound request too early, not allowing us to learn where the end of the file is.\n\t\t\tif (!opsFromFetch && cancelFetch(op)) {\n\t\t\t\t// TODO: Remove when typescript version of the repo contains the AbortSignal.reason property (AB#5045)\n\t\t\t\t(controller as AbortControllerReal).abort(\"DeltaManager getDeltas fetch cancelled\");\n\t\t\t\tthis._inbound.off(\"push\", opListener);\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\tthis._inbound.on(\"push\", opListener);\n\t\t\tassert(this.closeAbortController.signal.onabort === null, 0x1e8 /* \"reentrancy\" */);\n\t\t\tthis.closeAbortController.signal.onabort = () =>\n\t\t\t\t// TODO: Remove when typescript version of the repo contains the AbortSignal.reason property (AB#5045)\n\t\t\t\t(controller as AbortControllerReal).abort(\n\t\t\t\t\t(this.closeAbortController.signal as AbortSignalReal).reason,\n\t\t\t\t);\n\n\t\t\tconst stream = this.deltaStorage.fetchMessages(\n\t\t\t\tfrom, // inclusive\n\t\t\t\tto, // exclusive\n\t\t\t\tcontroller.signal,\n\t\t\t\tcacheOnly,\n\t\t\t\tfetchReason,\n\t\t\t);\n\n\t\t\t// eslint-disable-next-line no-constant-condition\n\t\t\twhile (true) {\n\t\t\t\tconst result = await stream.read();\n\t\t\t\tif (result.done) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\topsFromFetch = true;\n\t\t\t\t\tcallback(result.value);\n\t\t\t\t} finally {\n\t\t\t\t\topsFromFetch = false;\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tif (controller.signal.aborted) {\n\t\t\t\tthis.logger.sendTelemetryEvent({\n\t\t\t\t\teventName: \"DeltaManager_GetDeltasAborted\",\n\t\t\t\t\tfetchReason,\n\t\t\t\t\t// TODO: Remove when typescript version of the repo contains the AbortSignal.reason property (AB#5045)\n\t\t\t\t\treason: (controller.signal as AbortSignalReal).reason,\n\t\t\t\t});\n\t\t\t}\n\t\t\tthis.closeAbortController.signal.onabort = null;\n\t\t\tthis._inbound.off(\"push\", opListener);\n\t\t\tassert(!opsFromFetch, 0x289 /* \"logic error\" */);\n\t\t}\n\t}\n\n\t/**\n\t * Closes the connection and clears inbound & outbound queues.\n\t *\n\t * Differences from dispose:\n\t * - close will trigger readonly notification\n\t * - close emits \"closed\"\n\t * - close cannot be called after dispose\n\t */\n\tpublic close(error?: ICriticalContainerError): void {\n\t\tif (this._closed) {\n\t\t\treturn;\n\t\t}\n\t\tthis._closed = true;\n\n\t\tthis.connectionManager.dispose(error, true /* switchToReadonly */);\n\t\tthis.clearQueues();\n\t\tthis.emit(\"closed\", error);\n\t}\n\n\t/**\n\t * Disposes the connection and clears the inbound & outbound queues.\n\t *\n\t * Differences from close:\n\t * - dispose will emit \"disposed\"\n\t * - dispose will remove all listeners\n\t * - dispose can be called after closure\n\t */\n\tpublic dispose(error?: Error | ICriticalContainerError): void {\n\t\tif (this._disposed) {\n\t\t\treturn;\n\t\t}\n\t\tif (error !== undefined && !isFluidError(error)) {\n\t\t\tthrow new UsageError(\"Error must be a Fluid error\");\n\t\t}\n\n\t\tthis._disposed = true;\n\t\tthis._closed = true; // We consider \"disposed\" as a further state than \"closed\"\n\n\t\tthis.connectionManager.dispose(error, false /* switchToReadonly */);\n\t\tthis.clearQueues();\n\n\t\t// This needs to be the last thing we do (before removing listeners), as it causes\n\t\t// Container to dispose context and break ability of data stores / runtime to \"hear\" from delta manager.\n\t\tthis.emit(\"disposed\", error);\n\t\tthis.removeAllListeners();\n\t}\n\n\tprivate clearQueues() {\n\t\t// TODO: Remove when typescript version of the repo contains the AbortSignal.reason property (AB#5045)\n\t\t(this.closeAbortController as AbortControllerReal).abort(\"DeltaManager is closed\");\n\n\t\tthis._inbound.clear();\n\t\tthis._inboundSignal.clear();\n\n\t\t// eslint-disable-next-line @typescript-eslint/no-floating-promises\n\t\tthis._inbound.pause();\n\t\t// eslint-disable-next-line @typescript-eslint/no-floating-promises\n\t\tthis._inboundSignal.pause();\n\n\t\t// Drop pending messages - this will ensure catchUp() does not go into infinite loop\n\t\tthis.pending = [];\n\t}\n\n\tpublic refreshDelayInfo(id: string) {\n\t\tthis.throttlingIdSet.delete(id);\n\t\tif (this.throttlingIdSet.size === 0) {\n\t\t\tthis.timeTillThrottling = 0;\n\t\t}\n\t}\n\n\tprivate disconnectHandler(reason: IConnectionStateChangeReason) {\n\t\tthis.messageBuffer.length = 0;\n\t\tthis.emit(\"disconnect\", reason);\n\t}\n\n\t/**\n\t * Emit info about a delay in service communication on account of throttling.\n\t * @param id - Id of the connection that is delayed\n\t * @param delayMs - Duration of the delay\n\t * @param error - error object indicating the throttling\n\t */\n\tpublic emitDelayInfo(id: string, delayMs: number, error: unknown) {\n\t\tconst timeNow = Date.now();\n\t\tthis.throttlingIdSet.add(id);\n\t\tif (delayMs > 0 && timeNow + delayMs > this.timeTillThrottling) {\n\t\t\tthis.timeTillThrottling = timeNow + delayMs;\n\n\t\t\tconst throttlingWarning: IThrottlingWarning = ThrottlingWarning.wrap(\n\t\t\t\terror,\n\t\t\t\tdelayMs / 1000 /* retryAfterSeconds */,\n\t\t\t\tthis.logger,\n\t\t\t);\n\t\t\tthis.emit(\"throttled\", throttlingWarning);\n\t\t}\n\t}\n\n\t// returns parts of message (in string format) that should never change for a given message.\n\t// Used for message comparison. It attempts to avoid comparing fields that potentially may differ.\n\t// for example, it's not clear if serverMetadata or timestamp property is a property of message or server state.\n\t// We only extract the most obvious fields that are sufficient (with high probability) to detect sequence number\n\t// reuse.\n\t// Also payload goes to telemetry, so no content or anything else that shouldn't be logged for privacy reasons\n\t// Note: It's possible for a duplicate op to be broadcasted and have everything the same except the timestamp.\n\tprivate comparableMessagePayload(m: ISequencedDocumentMessage) {\n\t\treturn `${m.clientId}-${m.type}-${m.minimumSequenceNumber}-${m.referenceSequenceNumber}-${m.timestamp}`;\n\t}\n\n\tprivate enqueueMessages(\n\t\tmessages: ISequencedDocumentMessage[],\n\t\treason: string,\n\t\tallowGaps = false,\n\t): void {\n\t\tif (this.handler === undefined) {\n\t\t\t// We did not setup handler yet.\n\t\t\t// This happens when we connect to web socket faster than we get attributes for container\n\t\t\t// and thus faster than attachOpHandler() is called\n\t\t\t// this.lastProcessedSequenceNumber is still zero, so we can't rely on this.fetchMissingDeltas()\n\t\t\t// to do the right thing.\n\t\t\tthis.pending = this.pending.concat(messages);\n\t\t\treturn;\n\t\t}\n\n\t\t// Pending ops should never just hang around for nothing.\n\t\t// This invariant will stay true through this function execution,\n\t\t// so there is no need to process pending ops here.\n\t\t// It's responsibility of\n\t\t// - attachOpHandler()\n\t\t// - fetchMissingDeltas() after it's done with querying storage\n\t\tassert(\n\t\t\tthis.pending.length === 0 || this.fetchReason !== undefined,\n\t\t\t0x1e9 /* \"Pending ops\" */,\n\t\t);\n\n\t\tif (messages.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst from = messages[0].sequenceNumber;\n\t\tconst last = messages[messages.length - 1].sequenceNumber;\n\n\t\t// Report stats about missing and duplicate ops\n\t\t// This helps better understand why we fetch ops from storage, and thus may delay\n\t\t// getting current / sending ops\n\t\t// It's possible that this batch is already too late - do not bother\n\t\tif (last > this.lastQueuedSequenceNumber) {\n\t\t\tlet prev = from - 1;\n\t\t\tconst initialGap = prev - this.lastQueuedSequenceNumber;\n\t\t\tlet firstMissing: number | undefined;\n\t\t\tlet duplicate = 0;\n\t\t\tlet gap = 0;\n\n\t\t\t// Count all gaps and duplicates\n\t\t\tfor (const message of messages) {\n\t\t\t\tif (message.sequenceNumber === prev) {\n\t\t\t\t\tduplicate++;\n\t\t\t\t} else if (message.sequenceNumber !== prev + 1) {\n\t\t\t\t\tgap++;\n\t\t\t\t\tif (firstMissing === undefined) {\n\t\t\t\t\t\tfirstMissing = prev + 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tprev = message.sequenceNumber;\n\t\t\t}\n\n\t\t\tlet eventName: string | undefined;\n\n\t\t\t// Report if we found some issues\n\t\t\tif (\n\t\t\t\tduplicate !== 0 ||\n\t\t\t\t(gap !== 0 && !allowGaps) ||\n\t\t\t\t(initialGap > 0 && this.fetchReason === undefined)\n\t\t\t) {\n\t\t\t\teventName = \"enqueueMessages\";\n\t\t\t\t// Also report if we are fetching ops, and same range comes in, thus making this fetch obsolete.\n\t\t\t} else if (\n\t\t\t\tthis.fetchReason !== undefined &&\n\t\t\t\tthis.fetchReason !== reason &&\n\t\t\t\tfrom <= this.lastQueuedSequenceNumber + 1 &&\n\t\t\t\tlast > this.lastQueuedSequenceNumber\n\t\t\t) {\n\t\t\t\teventName = \"enqueueMessagesExtraFetch\";\n\t\t\t}\n\n\t\t\t// Report if there is something to report\n\t\t\t// Do not report when pending fetch is in progress, as such reporting will not\n\t\t\t// correctly take into account pending ops.\n\t\t\tif (eventName !== undefined) {\n\t\t\t\tthis.logger.sendPerformanceEvent({\n\t\t\t\t\teventName,\n\t\t\t\t\treason,\n\t\t\t\t\tpreviousReason: this.prevEnqueueMessagesReason,\n\t\t\t\t\tfrom,\n\t\t\t\t\tto: last + 1, // exclusive, being consistent with the other telemetry / APIs\n\t\t\t\t\tlength: messages.length,\n\t\t\t\t\tfetchReason: this.fetchReason,\n\t\t\t\t\tduplicate: duplicate > 0 ? duplicate : undefined,\n\t\t\t\t\tinitialGap: initialGap !== 0 ? initialGap : undefined,\n\t\t\t\t\tgap: gap > 0 ? gap : undefined,\n\t\t\t\t\tfirstMissing,\n\t\t\t\t\tdmInitialSeqNumber: this.initialSequenceNumber,\n\t\t\t\t\t...this.connectionManager.connectionVerboseProps,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tthis.updateLatestKnownOpSeqNumber(messages[messages.length - 1].sequenceNumber);\n\n\t\tconst n = this.previouslyProcessedMessage?.sequenceNumber;\n\t\tassert(\n\t\t\tn === undefined || n === this.lastQueuedSequenceNumber,\n\t\t\t0x0ec /* \"Unexpected value for previously processed message's sequence number\" */,\n\t\t);\n\n\t\tfor (const message of messages) {\n\t\t\t// Check that the messages are arriving in the expected order\n\t\t\tif (message.sequenceNumber <= this.lastQueuedSequenceNumber) {\n\t\t\t\t// Validate that we do not have data loss, i.e. sequencing is reset and started again\n\t\t\t\t// with numbers that this client already observed before.\n\t\t\t\tif (this.previouslyProcessedMessage?.sequenceNumber === message.sequenceNumber) {\n\t\t\t\t\tconst message1 = this.comparableMessagePayload(this.previouslyProcessedMessage);\n\t\t\t\t\tconst message2 = this.comparableMessagePayload(message);\n\t\t\t\t\tif (message1 !== message2) {\n\t\t\t\t\t\tconst error = new NonRetryableError(\n\t\t\t\t\t\t\t// This looks like a data corruption but the culprit was that the file was overwritten\n\t\t\t\t\t\t\t// in storage. See PR #5882.\n\t\t\t\t\t\t\t// Likely to be an issue with Fluid Services. Content does not match previous client\n\t\t\t\t\t\t\t// knowledge about this file. If the file is overwritten for any reason, this error can be\n\t\t\t\t\t\t\t// hit. One example is that some clients could be submitting ops to two different service\n\t\t\t\t\t\t\t// instances such that the same sequence number is reused for two different ops.\n\t\t\t\t\t\t\t// pre-0.58 error message: twoMessagesWithSameSeqNumAndDifferentPayload\n\t\t\t\t\t\t\t\"Found two messages with the same sequenceNumber but different payloads. Likely to be a \" +\n\t\t\t\t\t\t\t\t\"service issue\",\n\t\t\t\t\t\t\tDriverErrorType.fileOverwrittenInStorage,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tclientId: this.connectionManager.clientId,\n\t\t\t\t\t\t\t\tsequenceNumber: message.sequenceNumber,\n\t\t\t\t\t\t\t\tmessage1,\n\t\t\t\t\t\t\t\tmessage2,\n\t\t\t\t\t\t\t\tdriverVersion: undefined,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthis.close(error);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (message.sequenceNumber !== this.lastQueuedSequenceNumber + 1) {\n\t\t\t\tthis.pending.push(message);\n\t\t\t\tthis.fetchMissingDeltas(reason, message.sequenceNumber);\n\t\t\t} else {\n\t\t\t\tthis.lastQueuedSequenceNumber = message.sequenceNumber;\n\t\t\t\tthis.previouslyProcessedMessage = message;\n\t\t\t\tthis._inbound.push(message);\n\t\t\t}\n\t\t}\n\n\t\t// When / if we report a gap in ops in the future, we want telemetry to correctly reflect source\n\t\t// of prior ops. But if we have some out of order ops (this.pending), then reporting current reason\n\t\t// becomes not accurate, as the gap existed before current batch, so we should just report \"unknown\".\n\t\tthis.prevEnqueueMessagesReason = this.pending.length > 0 ? \"unknown\" : reason;\n\t}\n\n\tprivate processInboundMessage(message: ISequencedDocumentMessage): void {\n\t\tconst startTime = Date.now();\n\t\tassert(!this.currentlyProcessingOps, 0x3af /* Already processing ops. */);\n\t\tthis.currentlyProcessingOps = true;\n\t\tthis.lastProcessedMessage = message;\n\n\t\tconst isString = typeof message.clientId === \"string\";\n\t\tassert(message.clientId === null || isString, 0x41a /* undefined or string */);\n\t\t// All client messages are coming from some client, and should have clientId,\n\t\t// and non-client message should not have clientId. But, there are two exceptions:\n\t\t// 1. (Legacy) We can see message.type === \"attach\" or \"chunkedOp\" for legacy files before RTM\n\t\t// 2. Non-immediate noops (contents: null) can be sent by service without clientId\n\t\tif (!isString && isClientMessage(message) && message.type !== MessageType.NoOp) {\n\t\t\tthrow new DataCorruptionError(\"Mismatch in clientId\", {\n\t\t\t\t...extractSafePropertiesFromMessage(message),\n\t\t\t\tmessageType: message.type,\n\t\t\t});\n\t\t}\n\n\t\t// TODO Remove after SPO picks up the latest build.\n\t\tif (\n\t\t\ttypeof message.contents === \"string\" &&\n\t\t\tmessage.contents !== \"\" &&\n\t\t\tmessage.type !== MessageType.ClientLeave\n\t\t) {\n\t\t\tmessage.contents = JSON.parse(message.contents);\n\t\t}\n\n\t\t// Validate client sequence number has no gap. Decrement the noOpCount by gap\n\t\t// If the count ends up negative, that means we have a real gap and throw error\n\t\tif (\n\t\t\tthis.connectionManager.clientId !== undefined &&\n\t\t\tthis.connectionManager.clientId === message.clientId\n\t\t) {\n\t\t\tif (message.type === MessageType.NoOp) {\n\t\t\t\tthis.noOpCount--;\n\t\t\t}\n\t\t\tconst clientSeqNumGap =\n\t\t\t\tmessage.clientSequenceNumber - this.lastClientSequenceNumber - 1;\n\t\t\tthis.noOpCount -= clientSeqNumGap;\n\t\t\tif (this.noOpCount < 0) {\n\t\t\t\tthrow new Error(`gap in client sequence number: ${clientSeqNumGap}`);\n\t\t\t}\n\t\t\tthis.lastClientSequenceNumber = message.clientSequenceNumber;\n\t\t}\n\n\t\tthis.connectionManager.beforeProcessingIncomingOp(message);\n\n\t\t// Watch the minimum sequence number and be ready to update as needed\n\t\tif (this.minSequenceNumber > message.minimumSequenceNumber) {\n\t\t\t// pre-0.58 error message: msnMovesBackwards\n\t\t\tthrow new DataCorruptionError(\n\t\t\t\t\"Found a lower minimumSequenceNumber (msn) than previously recorded\",\n\t\t\t\t{\n\t\t\t\t\t...extractSafePropertiesFromMessage(message),\n\t\t\t\t\tclientId: this.connectionManager.clientId,\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\n\t\t// Client ops: MSN has to be lower than sequence #, as client can continue to send ops with same\n\t\t// reference sequence number as this op.\n\t\t// System ops (when no clients are connected) are the only ops where equation is possible.\n\t\tconst diff = message.sequenceNumber - message.minimumSequenceNumber;\n\t\tif (diff < 0 || (diff === 0 && message.clientId !== null)) {\n\t\t\tthrow new DataCorruptionError(\n\t\t\t\t\"MSN has to be lower than sequence #\",\n\t\t\t\textractSafePropertiesFromMessage(message),\n\t\t\t);\n\t\t}\n\n\t\tthis.minSequenceNumber = message.minimumSequenceNumber;\n\n\t\tif (message.sequenceNumber !== this.lastProcessedSequenceNumber + 1) {\n\t\t\t// pre-0.58 error message: nonSequentialSequenceNumber\n\t\t\tthrow new DataCorruptionError(\"Found a non-Sequential sequenceNumber\", {\n\t\t\t\t...extractSafePropertiesFromMessage(message),\n\t\t\t\tclientId: this.connectionManager.clientId,\n\t\t\t});\n\t\t}\n\t\tthis.lastProcessedSequenceNumber = message.sequenceNumber;\n\n\t\t// a bunch of code assumes that this is true\n\t\tassert(\n\t\t\tthis.lastProcessedSequenceNumber <= this.lastObservedSeqNumber,\n\t\t\t0x267 /* \"lastObservedSeqNumber should be updated first\" */,\n\t\t);\n\n\t\t// Back-compat for older server with no term\n\t\tif (message.term === undefined) {\n\t\t\tmessage.term = OnlyValidTermValue;\n\t\t}\n\n\t\tif (this.handler === undefined) {\n\t\t\tthrow new Error(\"Attempted to process an inbound message without a handler attached\");\n\t\t}\n\t\tthis.handler.process(message);\n\t\tthis.currentlyProcessingOps = false;\n\t\tconst endTime = Date.now();\n\n\t\t// Should be last, after changing this.lastProcessedSequenceNumber above, as many callers\n\t\t// test this.lastProcessedSequenceNumber instead of using op.sequenceNumber itself.\n\t\tthis.emit(\"op\", message, endTime - startTime);\n\t}\n\n\t/**\n\t * Retrieves the missing deltas between the given sequence numbers\n\t */\n\tprivate fetchMissingDeltas(reasonArg: string, to?: number) {\n\t\tthis.fetchMissingDeltasCore(reasonArg, false /* cacheOnly */, to).catch((error) => {\n\t\t\tthis.logger.sendErrorEvent({ eventName: \"fetchMissingDeltasException\" }, error);\n\t\t});\n\t}\n\n\t/**\n\t * Retrieves the missing deltas between the given sequence numbers\n\t */\n\tprivate async fetchMissingDeltasCore(reason: string, cacheOnly: boolean, to?: number) {\n\t\t// Exit out early if we're already fetching deltas\n\t\tif (this.fetchReason !== undefined) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._closed) {\n\t\t\tthis.logger.sendTelemetryEvent({\n\t\t\t\teventName: \"fetchMissingDeltasClosedConnection\",\n\t\t\t\treason,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.handler === undefined) {\n\t\t\t// We do not poses yet any information\n\t\t\tassert(this.lastQueuedSequenceNumber === 0, 0x26b /* \"initial state\" */);\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tlet from = this.lastQueuedSequenceNumber + 1;\n\n\t\t\tconst n = this.previouslyProcessedMessage?.sequenceNumber;\n\t\t\tif (n !== undefined) {\n\t\t\t\t// If we already processed at least one op, then we have this.previouslyProcessedMessage populated\n\t\t\t\t// and can use it to validate that we are operating on same file, i.e. it was not overwritten.\n\t\t\t\t// Knowing about this mechanism, we could ask for op we already observed to increase validation.\n\t\t\t\t// This is especially useful when coming out of offline mode or loading from\n\t\t\t\t// very old cached (by client / driver) snapshot.\n\t\t\t\tassert(\n\t\t\t\t\tn === this.lastQueuedSequenceNumber,\n\t\t\t\t\t0x0f2 /* \"previouslyProcessedMessage\" */,\n\t\t\t\t);\n\t\t\t\tassert(from > 1, 0x0f3 /* \"not positive\" */);\n\t\t\t\tfrom--;\n\t\t\t}\n\n\t\t\tconst fetchReason = `${reason}_fetch`;\n\t\t\tthis.fetchReason = fetchReason;\n\n\t\t\tawait this.getDeltas(\n\t\t\t\tfrom,\n\t\t\t\tto,\n\t\t\t\tfetchReason,\n\t\t\t\t(messages) => {\n\t\t\t\t\tthis.refreshDelayInfo(this.deltaStorageDelayId);\n\t\t\t\t\tthis.enqueueMessages(messages, fetchReason);\n\t\t\t\t},\n\t\t\t\tcacheOnly,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthis.logger.sendErrorEvent({ eventName: \"GetDeltas_Exception\" }, error);\n\t\t\tthis.close(normalizeError(error));\n\t\t} finally {\n\t\t\tthis.refreshDelayInfo(this.deltaStorageDelayId);\n\t\t\tthis.fetchReason = undefined;\n\t\t\tthis.processPendingOps(reason);\n\t\t}\n\t}\n\n\t/**\n\t * Sorts pending ops and attempts to apply them\n\t */\n\tprivate processPendingOps(reason?: string): void {\n\t\tif (this._closed) {\n\t\t\treturn;\n\t\t}\n\n\t\tassert(this.handler !== undefined, 0x26c /* \"handler should be installed\" */);\n\n\t\tconst pendingSorted = this.pending.sort((a, b) => a.sequenceNumber - b.sequenceNumber);\n\t\tthis.pending = [];\n\t\t// Given that we do not track where these ops came from any more, it's not very\n\t\t// actionably to report gaps in this range.\n\t\tthis.enqueueMessages(pendingSorted, `${reason}_pending`, true /* allowGaps */);\n\n\t\t// Re-entrancy is ignored by fetchMissingDeltas, execution will come here when it's over\n\t\tif (this.fetchReason === undefined) {\n\t\t\t// See issue #7312 for more details\n\t\t\t// We observe cases where client gets into situation where it is not aware of missing ops\n\t\t\t// (i.e. client being behind), and as such, does not attempt to fetch them.\n\t\t\t// In some cases client may not have enough signal (example - \"read\" connection that is silent -\n\t\t\t// there is no easy way for client to realize it's behind, see a bit of commentary / logic at the\n\t\t\t// end of setupNewSuccessfulConnection). In other cases it should be able to learn that info (\"write\"\n\t\t\t// connection, learn by receiving its own join op), but data suggest it does not happen.\n\t\t\t// In 50% of these cases we do know we are behind through checkpointSequenceNumber on connection object\n\t\t\t// and thus can leverage that to trigger recovery. But this is not going to solve all the problems\n\t\t\t// (the other 50%), and thus these errors below should be looked at even if code below results in\n\t\t\t// recovery.\n\t\t\tif (this.lastQueuedSequenceNumber < this.lastObservedSeqNumber) {\n\t\t\t\tthis.fetchMissingDeltas(\"OpsBehind\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate updateLatestKnownOpSeqNumber(seq: number) {\n\t\tif (this.lastObservedSeqNumber < seq) {\n\t\t\tthis.lastObservedSeqNumber = seq;\n\t\t}\n\t}\n}\n"]}
package/lib/deltaQueue.js CHANGED
@@ -35,8 +35,7 @@ export class DeltaQueue extends TypedEventEmitter {
35
35
  return this.processingPromise === undefined && this.q.length === 0;
36
36
  }
37
37
  async waitTillProcessingDone() {
38
- var _a;
39
- return (_a = this.processingPromise) !== null && _a !== void 0 ? _a : { count: 0, duration: 0 };
38
+ return this.processingPromise ?? { count: 0, duration: 0 };
40
39
  }
41
40
  dispose() {
42
41
  throw new Error("Not implemented.");