@fluidframework/container-loader 2.0.0-internal.3.0.1 → 2.0.0-internal.3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/.eslintrc.js +18 -21
  2. package/.mocharc.js +2 -2
  3. package/README.md +45 -43
  4. package/api-extractor.json +2 -2
  5. package/closeAndGetPendingLocalState.md +51 -0
  6. package/dist/audience.d.ts.map +1 -1
  7. package/dist/audience.js.map +1 -1
  8. package/dist/catchUpMonitor.d.ts.map +1 -1
  9. package/dist/catchUpMonitor.js.map +1 -1
  10. package/dist/collabWindowTracker.d.ts.map +1 -1
  11. package/dist/collabWindowTracker.js.map +1 -1
  12. package/dist/connectionManager.d.ts +2 -2
  13. package/dist/connectionManager.d.ts.map +1 -1
  14. package/dist/connectionManager.js +50 -23
  15. package/dist/connectionManager.js.map +1 -1
  16. package/dist/connectionState.d.ts.map +1 -1
  17. package/dist/connectionState.js.map +1 -1
  18. package/dist/connectionStateHandler.d.ts.map +1 -1
  19. package/dist/connectionStateHandler.js +35 -16
  20. package/dist/connectionStateHandler.js.map +1 -1
  21. package/dist/container.d.ts.map +1 -1
  22. package/dist/container.js +96 -46
  23. package/dist/container.js.map +1 -1
  24. package/dist/containerContext.d.ts.map +1 -1
  25. package/dist/containerContext.js +6 -2
  26. package/dist/containerContext.js.map +1 -1
  27. package/dist/containerStorageAdapter.d.ts.map +1 -1
  28. package/dist/containerStorageAdapter.js +2 -4
  29. package/dist/containerStorageAdapter.js.map +1 -1
  30. package/dist/contracts.d.ts.map +1 -1
  31. package/dist/contracts.js.map +1 -1
  32. package/dist/deltaManager.d.ts +3 -3
  33. package/dist/deltaManager.d.ts.map +1 -1
  34. package/dist/deltaManager.js +56 -27
  35. package/dist/deltaManager.js.map +1 -1
  36. package/dist/deltaManagerProxy.d.ts.map +1 -1
  37. package/dist/deltaManagerProxy.js.map +1 -1
  38. package/dist/deltaQueue.d.ts.map +1 -1
  39. package/dist/deltaQueue.js +4 -2
  40. package/dist/deltaQueue.js.map +1 -1
  41. package/dist/index.d.ts +1 -1
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js.map +1 -1
  44. package/dist/loader.d.ts +3 -3
  45. package/dist/loader.d.ts.map +1 -1
  46. package/dist/loader.js +16 -8
  47. package/dist/loader.js.map +1 -1
  48. package/dist/packageVersion.d.ts +1 -1
  49. package/dist/packageVersion.js +1 -1
  50. package/dist/packageVersion.js.map +1 -1
  51. package/dist/protocol.d.ts.map +1 -1
  52. package/dist/protocol.js +2 -1
  53. package/dist/protocol.js.map +1 -1
  54. package/dist/protocolTreeDocumentStorageService.d.ts.map +1 -1
  55. package/dist/protocolTreeDocumentStorageService.js.map +1 -1
  56. package/dist/quorum.d.ts.map +1 -1
  57. package/dist/quorum.js.map +1 -1
  58. package/dist/retriableDocumentStorageService.d.ts.map +1 -1
  59. package/dist/retriableDocumentStorageService.js +6 -2
  60. package/dist/retriableDocumentStorageService.js.map +1 -1
  61. package/dist/utils.d.ts.map +1 -1
  62. package/dist/utils.js +6 -4
  63. package/dist/utils.js.map +1 -1
  64. package/lib/audience.d.ts.map +1 -1
  65. package/lib/audience.js.map +1 -1
  66. package/lib/catchUpMonitor.d.ts.map +1 -1
  67. package/lib/catchUpMonitor.js.map +1 -1
  68. package/lib/collabWindowTracker.d.ts.map +1 -1
  69. package/lib/collabWindowTracker.js.map +1 -1
  70. package/lib/connectionManager.d.ts +2 -2
  71. package/lib/connectionManager.d.ts.map +1 -1
  72. package/lib/connectionManager.js +52 -25
  73. package/lib/connectionManager.js.map +1 -1
  74. package/lib/connectionState.d.ts.map +1 -1
  75. package/lib/connectionState.js.map +1 -1
  76. package/lib/connectionStateHandler.d.ts.map +1 -1
  77. package/lib/connectionStateHandler.js +35 -16
  78. package/lib/connectionStateHandler.js.map +1 -1
  79. package/lib/container.d.ts.map +1 -1
  80. package/lib/container.js +100 -50
  81. package/lib/container.js.map +1 -1
  82. package/lib/containerContext.d.ts.map +1 -1
  83. package/lib/containerContext.js +6 -2
  84. package/lib/containerContext.js.map +1 -1
  85. package/lib/containerStorageAdapter.d.ts.map +1 -1
  86. package/lib/containerStorageAdapter.js +2 -4
  87. package/lib/containerStorageAdapter.js.map +1 -1
  88. package/lib/contracts.d.ts.map +1 -1
  89. package/lib/contracts.js.map +1 -1
  90. package/lib/deltaManager.d.ts +3 -3
  91. package/lib/deltaManager.d.ts.map +1 -1
  92. package/lib/deltaManager.js +58 -29
  93. package/lib/deltaManager.js.map +1 -1
  94. package/lib/deltaManagerProxy.d.ts.map +1 -1
  95. package/lib/deltaManagerProxy.js.map +1 -1
  96. package/lib/deltaQueue.d.ts.map +1 -1
  97. package/lib/deltaQueue.js +4 -2
  98. package/lib/deltaQueue.js.map +1 -1
  99. package/lib/index.d.ts +1 -1
  100. package/lib/index.d.ts.map +1 -1
  101. package/lib/index.js.map +1 -1
  102. package/lib/loader.d.ts +3 -3
  103. package/lib/loader.d.ts.map +1 -1
  104. package/lib/loader.js +16 -8
  105. package/lib/loader.js.map +1 -1
  106. package/lib/packageVersion.d.ts +1 -1
  107. package/lib/packageVersion.js +1 -1
  108. package/lib/packageVersion.js.map +1 -1
  109. package/lib/protocol.d.ts.map +1 -1
  110. package/lib/protocol.js +2 -1
  111. package/lib/protocol.js.map +1 -1
  112. package/lib/protocolTreeDocumentStorageService.d.ts.map +1 -1
  113. package/lib/protocolTreeDocumentStorageService.js.map +1 -1
  114. package/lib/quorum.d.ts.map +1 -1
  115. package/lib/quorum.js.map +1 -1
  116. package/lib/retriableDocumentStorageService.d.ts.map +1 -1
  117. package/lib/retriableDocumentStorageService.js +6 -2
  118. package/lib/retriableDocumentStorageService.js.map +1 -1
  119. package/lib/utils.d.ts.map +1 -1
  120. package/lib/utils.js +6 -4
  121. package/lib/utils.js.map +1 -1
  122. package/package.json +115 -114
  123. package/prettier.config.cjs +1 -1
  124. package/src/audience.ts +51 -46
  125. package/src/catchUpMonitor.ts +39 -37
  126. package/src/collabWindowTracker.ts +75 -70
  127. package/src/connectionManager.ts +1006 -943
  128. package/src/connectionState.ts +19 -19
  129. package/src/connectionStateHandler.ts +544 -465
  130. package/src/container.ts +2056 -1895
  131. package/src/containerContext.ts +350 -340
  132. package/src/containerStorageAdapter.ts +163 -153
  133. package/src/contracts.ts +155 -153
  134. package/src/deltaManager.ts +1069 -992
  135. package/src/deltaManagerProxy.ts +143 -137
  136. package/src/deltaQueue.ts +155 -151
  137. package/src/index.ts +14 -17
  138. package/src/loader.ts +408 -403
  139. package/src/packageVersion.ts +1 -1
  140. package/src/protocol.ts +93 -87
  141. package/src/protocolTreeDocumentStorageService.ts +30 -33
  142. package/src/quorum.ts +34 -34
  143. package/src/retriableDocumentStorageService.ts +118 -102
  144. package/src/utils.ts +89 -82
  145. package/tsconfig.esnext.json +6 -6
  146. package/tsconfig.json +8 -12
@@ -1 +1 @@
1
- {"version":3,"file":"collabWindowTracker.js","sourceRoot":"","sources":["../src/collabWindowTracker.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAC7D,OAAO,EAA6B,WAAW,EAAE,MAAM,sCAAsC,CAAC;AAC9F,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAE9E,MAAM,wBAAwB,GAAG,IAAI,CAAC;AACtC,MAAM,yBAAyB,GAAG,EAAE,CAAC;AAErC,6FAA6F;AAC7F,4GAA4G;AAC5G,yGAAyG;AACzG,2CAA2C;AAC3C,oHAAoH;AACpH,2FAA2F;AAC3F,kHAAkH;AAClH,+CAA+C;AAC/C,gHAAgH;AAChH,yFAAyF;AACzF,qHAAqH;AACrH,oDAAoD;AACpD,EAAE;AACF,kDAAkD;AAClD,oGAAoG;AACpG,iHAAiH;AACjH,sEAAsE;AACtE,4GAA4G;AAC5G,qGAAqG;AACrG,MAAM,OAAO,mBAAmB;IAI5B,YACqB,MAAmC,EACpD,o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EAAE;YAC1B,IAAI,IAAI,CAAC,iBAAiB,KAAK,CAAC,EAAE;gBAC9B,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;aACxB;YAED,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,iBAAiB,CAAC,CAAC;SACxD;IACL,CAAC;IAEO,UAAU,CAAC,SAAkB;QACjC,6CAA6C;QAC7C,8EAA8E;QAC9E,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAE,YAAY,CAAC,MAAiC,CAAC,CAAC,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;QAC5F,MAAM,CAAC,IAAI,CAAC,iBAAiB,KAAK,CAAC,EAC/B,KAAK,CAAC,8EAA8E,CAAC,CAAC;IAC9F,CAAC;IAEM,wBAAwB;QAC3B,IAAI,CAAC,iBAAiB,GAAG,CAAC,CAAC;QAC3B,kGAAkG;QAClG,wGAAwG;QACxG,oDAAoD;QACpD,qGAAqG;QACrG,yFAAyF;QACzF,sBAAsB;IAC1B,CAAC;CACJ","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { assert, Timer } from \"@fluidframework/common-utils\";\nimport { ISequencedDocumentMessage, MessageType } from \"@fluidframework/protocol-definitions\";\nimport { isRuntimeMessage, MessageType2 } from \"@fluidframework/driver-utils\";\n\nconst defaultNoopTimeFrequency = 2000;\nconst defaultNoopCountFrequency = 50;\n\n// Here are key considerations when deciding conditions for when to send non-immediate noops:\n// 1. Sending them too often results in increase in file size and bandwidth, as well as catch up performance\n// 2. Sending too infrequently ensures that collab window is large, and as result Sequence DDS would have\n// large catchUp blobs - see Issue #6364\n// 3. Similarly, processes that rely on \"core\" snapshot (and can't parse trailing ops, including above), like search\n// parser in SPO, will result in non-accurate results due to presence of catch up blobs.\n// 4. Ordering service used 250ms timeout to coalesce non-immediate noops. It was changed to 2000 ms to allow more\n// aggressive noop sending from client side.\n// 5. Number of ops sent by all clients is proportional to number of \"write\" clients (every client sends noops),\n// but number of sequenced noops is a function of time (one op per 2 seconds at most).\n// We should consider impact to both outbound traffic (might be huge, depends on number of clients) and file size.\n// Please also see Issue #5629 for more discussions.\n//\n// With that, the current algorithm is as follows:\n// 1. Sent noop 2000 ms of receiving an op if no ops were sent by this client within this timeframe.\n// This will ensure that MSN moves forward with reasonable speed. If that results in too many sequenced noops,\n// server timeout of 2000ms should be reconsidered to be increased.\n// 2. If there are more than 50 ops received without sending any ops, send noop to keep collab window small.\n// Note that system ops (including noops themselves) are excluded, so it's 1 noop per 50 real ops.\nexport class CollabWindowTracker {\n private opsCountSinceNoop = 0;\n private readonly timer: Timer | undefined;\n\n constructor(\n private readonly submit: (type: MessageType) => void,\n NoopTimeFrequency: number = defaultNoopTimeFrequency,\n private readonly NoopCountFrequency: number = defaultNoopCountFrequency,\n ) {\n if (NoopTimeFrequency !== Infinity) {\n this.timer = new Timer(NoopTimeFrequency, () => {\n // Can get here due to this.stopSequenceNumberUpdate() not resetting timer.\n // Also timer callback can fire even after timer cancellation if it was queued before cancellation.\n if (this.opsCountSinceNoop !== 0) {\n this.submitNoop(false /* immediate */);\n }\n });\n }\n }\n\n /**\n * Schedules as ack to the server to update the reference sequence number\n */\n public scheduleSequenceNumberUpdate(message: ISequencedDocumentMessage, immediateNoOp: boolean): void {\n // While processing a message, an immediate no-op can be requested.\n // i.e. to expedite approve or commit phase of quorum.\n if (immediateNoOp) {\n this.submitNoop(true /* immediate */);\n return;\n }\n\n // We don't acknowledge no-ops to avoid acknowledgement cycles (i.e. ack the MSN\n // update, which updates the MSN, then ack the update, etc...).\n // Intent here is for runtime (and DDSes) not to keep too much tracking state / memory\n // due to runtime ops from other clients.\n if (!isRuntimeMessage(message)) {\n return;\n }\n\n this.opsCountSinceNoop++;\n if (this.opsCountSinceNoop === this.NoopCountFrequency) {\n // Ensure we only send noop after a batch of many ops is processed\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n Promise.resolve().then(() => {\n if (this.opsCountSinceNoop >= this.NoopCountFrequency) {\n this.submitNoop(false /* immediate */);\n // reset count now that all ops are processed\n this.opsCountSinceNoop = 0;\n }\n return;\n });\n }\n\n if (this.timer !== undefined) {\n if (this.opsCountSinceNoop === 1) {\n this.timer.restart();\n }\n\n assert(this.timer.hasTimer, 0x242 /* \"has timer\" */);\n }\n }\n\n private submitNoop(immediate: boolean) {\n // Anything other than null is immediate noop\n // ADO:1385: Remove cast and use MessageType once definition changes propagate\n this.submit(immediate ? (MessageType2.Accept as unknown as MessageType) : MessageType.NoOp);\n assert(this.opsCountSinceNoop === 0,\n 0x243 /* \"stopSequenceNumberUpdate should be called as result of sending any op!\" */);\n }\n\n public stopSequenceNumberUpdate(): void {\n this.opsCountSinceNoop = 0;\n // Ideally, we cancel timer here. But that will result in too often set/reset cycle if this client\n // keeps sending ops. In most cases it's actually better to let it expire (at most - 4 times per second)\n // for nothing, then have a ton of set/reset cycles.\n // Note that Timer.restart() is smart and will not change timer expiration if we keep extending timer\n // expiration - it will restart the timer instead when it fires with adjusted expiration.\n // this.timer.clear();\n }\n}\n"]}
1
+ {"version":3,"file":"collabWindowTracker.js","sourceRoot":"","sources":["../src/collabWindowTracker.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAC7D,OAAO,EAA6B,WAAW,EAAE,MAAM,sCAAsC,CAAC;AAC9F,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAE9E,MAAM,wBAAwB,GAAG,IAAI,CAAC;AACtC,MAAM,yBAAyB,GAAG,EAAE,CAAC;AAErC,6FAA6F;AAC7F,4GAA4G;AAC5G,yGAAyG;AACzG,2CAA2C;AAC3C,oHAAoH;AACpH,2FAA2F;AAC3F,kHAAkH;AAClH,+CAA+C;AAC/C,gHAAgH;AAChH,yFAAyF;AACzF,qHAAqH;AACrH,oDAA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AAC;oBACvC,6CAA6C;oBAC7C,IAAI,CAAC,iBAAiB,GAAG,CAAC,CAAC;iBAC3B;gBACD,OAAO;YACR,CAAC,CAAC,CAAC;SACH;QAED,IAAI,IAAI,CAAC,KAAK,KAAK,SAAS,EAAE;YAC7B,IAAI,IAAI,CAAC,iBAAiB,KAAK,CAAC,EAAE;gBACjC,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;aACrB;YAED,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,iBAAiB,CAAC,CAAC;SACrD;IACF,CAAC;IAEO,UAAU,CAAC,SAAkB;QACpC,6CAA6C;QAC7C,8EAA8E;QAC9E,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAE,YAAY,CAAC,MAAiC,CAAC,CAAC,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;QAC5F,MAAM,CACL,IAAI,CAAC,iBAAiB,KAAK,CAAC,EAC5B,KAAK,CAAC,8EAA8E,CACpF,CAAC;IACH,CAAC;IAEM,wBAAwB;QAC9B,IAAI,CAAC,iBAAiB,GAAG,CAAC,CAAC;QAC3B,kGAAkG;QAClG,wGAAwG;QACxG,oDAAoD;QACpD,qGAAqG;QACrG,yFAAyF;QACzF,sBAAsB;IACvB,CAAC;CACD","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { assert, Timer } from \"@fluidframework/common-utils\";\nimport { ISequencedDocumentMessage, MessageType } from \"@fluidframework/protocol-definitions\";\nimport { isRuntimeMessage, MessageType2 } from \"@fluidframework/driver-utils\";\n\nconst defaultNoopTimeFrequency = 2000;\nconst defaultNoopCountFrequency = 50;\n\n// Here are key considerations when deciding conditions for when to send non-immediate noops:\n// 1. Sending them too often results in increase in file size and bandwidth, as well as catch up performance\n// 2. Sending too infrequently ensures that collab window is large, and as result Sequence DDS would have\n// large catchUp blobs - see Issue #6364\n// 3. Similarly, processes that rely on \"core\" snapshot (and can't parse trailing ops, including above), like search\n// parser in SPO, will result in non-accurate results due to presence of catch up blobs.\n// 4. Ordering service used 250ms timeout to coalesce non-immediate noops. It was changed to 2000 ms to allow more\n// aggressive noop sending from client side.\n// 5. Number of ops sent by all clients is proportional to number of \"write\" clients (every client sends noops),\n// but number of sequenced noops is a function of time (one op per 2 seconds at most).\n// We should consider impact to both outbound traffic (might be huge, depends on number of clients) and file size.\n// Please also see Issue #5629 for more discussions.\n//\n// With that, the current algorithm is as follows:\n// 1. Sent noop 2000 ms of receiving an op if no ops were sent by this client within this timeframe.\n// This will ensure that MSN moves forward with reasonable speed. If that results in too many sequenced noops,\n// server timeout of 2000ms should be reconsidered to be increased.\n// 2. If there are more than 50 ops received without sending any ops, send noop to keep collab window small.\n// Note that system ops (including noops themselves) are excluded, so it's 1 noop per 50 real ops.\nexport class CollabWindowTracker {\n\tprivate opsCountSinceNoop = 0;\n\tprivate readonly timer: Timer | undefined;\n\n\tconstructor(\n\t\tprivate readonly submit: (type: MessageType) => void,\n\t\tNoopTimeFrequency: number = defaultNoopTimeFrequency,\n\t\tprivate readonly NoopCountFrequency: number = defaultNoopCountFrequency,\n\t) {\n\t\tif (NoopTimeFrequency !== Infinity) {\n\t\t\tthis.timer = new Timer(NoopTimeFrequency, () => {\n\t\t\t\t// Can get here due to this.stopSequenceNumberUpdate() not resetting timer.\n\t\t\t\t// Also timer callback can fire even after timer cancellation if it was queued before cancellation.\n\t\t\t\tif (this.opsCountSinceNoop !== 0) {\n\t\t\t\t\tthis.submitNoop(false /* immediate */);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Schedules as ack to the server to update the reference sequence number\n\t */\n\tpublic scheduleSequenceNumberUpdate(\n\t\tmessage: ISequencedDocumentMessage,\n\t\timmediateNoOp: boolean,\n\t): void {\n\t\t// While processing a message, an immediate no-op can be requested.\n\t\t// i.e. to expedite approve or commit phase of quorum.\n\t\tif (immediateNoOp) {\n\t\t\tthis.submitNoop(true /* immediate */);\n\t\t\treturn;\n\t\t}\n\n\t\t// We don't acknowledge no-ops to avoid acknowledgement cycles (i.e. ack the MSN\n\t\t// update, which updates the MSN, then ack the update, etc...).\n\t\t// Intent here is for runtime (and DDSes) not to keep too much tracking state / memory\n\t\t// due to runtime ops from other clients.\n\t\tif (!isRuntimeMessage(message)) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.opsCountSinceNoop++;\n\t\tif (this.opsCountSinceNoop === this.NoopCountFrequency) {\n\t\t\t// Ensure we only send noop after a batch of many ops is processed\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-floating-promises\n\t\t\tPromise.resolve().then(() => {\n\t\t\t\tif (this.opsCountSinceNoop >= this.NoopCountFrequency) {\n\t\t\t\t\tthis.submitNoop(false /* immediate */);\n\t\t\t\t\t// reset count now that all ops are processed\n\t\t\t\t\tthis.opsCountSinceNoop = 0;\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t});\n\t\t}\n\n\t\tif (this.timer !== undefined) {\n\t\t\tif (this.opsCountSinceNoop === 1) {\n\t\t\t\tthis.timer.restart();\n\t\t\t}\n\n\t\t\tassert(this.timer.hasTimer, 0x242 /* \"has timer\" */);\n\t\t}\n\t}\n\n\tprivate submitNoop(immediate: boolean) {\n\t\t// Anything other than null is immediate noop\n\t\t// ADO:1385: Remove cast and use MessageType once definition changes propagate\n\t\tthis.submit(immediate ? (MessageType2.Accept as unknown as MessageType) : MessageType.NoOp);\n\t\tassert(\n\t\t\tthis.opsCountSinceNoop === 0,\n\t\t\t0x243 /* \"stopSequenceNumberUpdate should be called as result of sending any op!\" */,\n\t\t);\n\t}\n\n\tpublic stopSequenceNumberUpdate(): void {\n\t\tthis.opsCountSinceNoop = 0;\n\t\t// Ideally, we cancel timer here. But that will result in too often set/reset cycle if this client\n\t\t// keeps sending ops. In most cases it's actually better to let it expire (at most - 4 times per second)\n\t\t// for nothing, then have a ton of set/reset cycles.\n\t\t// Note that Timer.restart() is smart and will not change timer expiration if we keep extending timer\n\t\t// expiration - it will restart the timer instead when it fires with adjusted expiration.\n\t\t// this.timer.clear();\n\t}\n}\n"]}
@@ -68,7 +68,7 @@ export declare class ConnectionManager implements IConnectionManager {
68
68
  /**
69
69
  * Returns set of props that can be logged in telemetry that provide some insights / statistics
70
70
  * about current or last connection (if there is no connection at the moment)
71
- */
71
+ */
72
72
  get connectionProps(): ITelemetryProperties;
73
73
  shouldJoinWrite(): boolean;
74
74
  /**
@@ -88,7 +88,7 @@ export declare class ConnectionManager implements IConnectionManager {
88
88
  /**
89
89
  * Enables or disables automatic reconnecting.
90
90
  * Will throw an error if reconnectMode set to Never.
91
- */
91
+ */
92
92
  setAutoReconnect(mode: ReconnectMode): void;
93
93
  /**
94
94
  * Sends signal to runtime (and data stores) to be read-only.
@@ -1 +1 @@
1
- {"version":3,"file":"connectionManager.d.ts","sourceRoot":"","sources":["../src/connectionManager.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAEH,gBAAgB,EAChB,oBAAoB,EACvB,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EACH,WAAW,EACX,YAAY,EAEZ,uBAAuB,EAC1B,MAAM,uCAAuC,CAAC;AAE/C,OAAO,EAEH,gBAAgB,EAGnB,MAAM,oCAAoC,CAAC;AAW5C,OAAO,EACH,cAAc,EACd,OAAO,EACP,oBAAoB,EACpB,cAAc,EACd,gBAAgB,EAGhB,yBAAyB,EAO5B,MAAM,sCAAsC,CAAC;AAK9C,OAAO,EACH,aAAa,EACb,kBAAkB,EAClB,6BAA6B,EAChC,MAAM,aAAa,CAAC;AAuFrB;;;;GAIG;AACH,qBAAa,iBAAkB,YAAW,kBAAkB;IAyJpD,OAAO,CAAC,QAAQ,CAAC,eAAe;IAChC,OAAO,CAAC,MAAM;IAEd,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,KAAK;IA5J1B,qEAAqE;IACrE,OAAO,CAAC,QAAQ,CAA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B;IAwCjC;;OAEG;IACH,OAAO,CAAC,gBAAgB;IAUxB;;;;OAIG;IACH,OAAO,CAAC,4BAA4B;IA8IpC;;;;;;OAMG;IACH,OAAO,CAAC,gBAAgB;IAIxB;;;;;;OAMG;YACW,SAAS;IA8ChB,oBAAoB,CAC1B,OAAO,EAAE,IAAI,CAAC,gBAAgB,EAAE,sBAAsB,CAAC,GACrD,gBAAgB,GAAG,SAAS;IAsCxB,YAAY,CAAC,OAAO,EAAE,GAAG;IAQzB,YAAY,CAAC,QAAQ,EAAE,gBAAgB,EAAE;IA+BzC,0BAA0B,CAAC,OAAO,EAAE,yBAAyB;IAgDpE,OAAO,CAAC,QAAQ,CAAC,SAAS,CAGxB;IAGF,OAAO,CAAC,QAAQ,CAAC,WAAW,CAkB1B;IAGF,OAAO,CAAC,QAAQ,CAAC,yBAAyB,CAIxC;IAEF,OAAO,CAAC,QAAQ,CAAC,YAAY,CAE3B;CACF"}
@@ -7,8 +7,8 @@ import { assert, performance, TypedEventEmitter } from "@fluidframework/common-u
7
7
  import { GenericError, UsageError } from "@fluidframework/container-utils";
8
8
  import { canRetryOnError, createWriteError, createGenericNetworkError, getRetryDelayFromError, waitForConnectedState, DeltaStreamConnectionForbiddenError, logNetworkFailure, isRuntimeMessage, } from "@fluidframework/driver-utils";
9
9
  import { MessageType, ScopeType, } from "@fluidframework/protocol-definitions";
10
- import { TelemetryLogger, normalizeError, } from "@fluidframework/telemetry-utils";
11
- import { ReconnectMode, } from "./contracts";
10
+ import { TelemetryLogger, normalizeError } from "@fluidframework/telemetry-utils";
11
+ import { ReconnectMode } from "./contracts";
12
12
  import { DeltaQueue } from "./deltaQueue";
13
13
  import { SignalType } from "./protocol";
14
14
  const MaxReconnectDelayInMs = 8000;
@@ -46,7 +46,9 @@ class NoDeltaStream extends TypedEventEmitter {
46
46
  this.version = "";
47
47
  this.initialMessages = [];
48
48
  this.initialSignals = [];
49
- this.initialClients = [{ client: clientNoDeltaStream, clientId: clientIdNoDeltaStream }];
49
+ this.initialClients = [
50
+ { client: clientNoDeltaStream, clientId: clientIdNoDeltaStream },
51
+ ];
50
52
  this.serviceConfiguration = {
51
53
  maxMessageSize: 0,
52
54
  blockSize: 0,
@@ -68,8 +70,12 @@ class NoDeltaStream extends TypedEventEmitter {
68
70
  content: { message: "Cannot submit signal with storage-only connection", code: 403 },
69
71
  });
70
72
  }
71
- get disposed() { return this._disposed; }
72
- dispose() { this._disposed = true; }
73
+ get disposed() {
74
+ return this._disposed;
75
+ }
76
+ dispose() {
77
+ this._disposed = true;
78
+ }
73
79
  }
74
80
  /**
75
81
  * Implementation of IConnectionManager, used by Container class
@@ -137,7 +143,9 @@ export class ConnectionManager {
137
143
  this.props.closeHandler(normalizeError(error));
138
144
  });
139
145
  }
140
- get connectionVerboseProps() { return this._connectionVerboseProps; }
146
+ get connectionVerboseProps() {
147
+ return this._connectionVerboseProps;
148
+ }
141
149
  /**
142
150
  * The current connection mode, initially read.
143
151
  */
@@ -145,8 +153,13 @@ export class ConnectionManager {
145
153
  var _a, _b;
146
154
  return (_b = (_a = this.connection) === null || _a === void 0 ? void 0 : _a.mode) !== null && _b !== void 0 ? _b : "read";
147
155
  }
148
- get connected() { return this.connection !== undefined; }
149
- get clientId() { var _a; return (_a = this.connection) === null || _a === void 0 ? void 0 : _a.clientId; }
156
+ get connected() {
157
+ return this.connection !== undefined;
158
+ }
159
+ get clientId() {
160
+ var _a;
161
+ return (_a = this.connection) === null || _a === void 0 ? void 0 : _a.clientId;
162
+ }
150
163
  /**
151
164
  * Automatic reconnecting enabled or disabled.
152
165
  * If set to Never, then reconnecting will never be allowed.
@@ -178,7 +191,7 @@ export class ConnectionManager {
178
191
  /**
179
192
  * Returns set of props that can be logged in telemetry that provide some insights / statistics
180
193
  * about current or last connection (if there is no connection at the moment)
181
- */
194
+ */
182
195
  get connectionProps() {
183
196
  return this.connection !== undefined
184
197
  ? this._connectionProps
@@ -188,7 +201,7 @@ export class ConnectionManager {
188
201
  }
189
202
  shouldJoinWrite() {
190
203
  // We don't have to wait for ack for topmost NoOps. So subtract those.
191
- return this.clientSequenceNumberObserved < (this.clientSequenceNumber - this.localOpsToIgnore);
204
+ return (this.clientSequenceNumberObserved < this.clientSequenceNumber - this.localOpsToIgnore);
192
205
  }
193
206
  /**
194
207
  * Tells if container is in read-only mode.
@@ -223,7 +236,9 @@ export class ConnectionManager {
223
236
  clientId: connection.clientId,
224
237
  existing: connection.existing,
225
238
  checkpointSequenceNumber: connection.checkpointSequenceNumber,
226
- get initialClients() { return connection.initialClients; },
239
+ get initialClients() {
240
+ return connection.initialClients;
241
+ },
227
242
  mode: connection.mode,
228
243
  serviceConfiguration: connection.serviceConfiguration,
229
244
  version: connection.version,
@@ -238,9 +253,7 @@ export class ConnectionManager {
238
253
  // Ensure that things like triggerConnect() will short circuit
239
254
  this._reconnectMode = ReconnectMode.Never;
240
255
  this._outbound.clear();
241
- const disconnectReason = error !== undefined
242
- ? `Closing DeltaManager (${error.message})`
243
- : "Closing DeltaManager";
256
+ const disconnectReason = "Closing DeltaManager";
244
257
  // This raises "disconnect" event if we have active connection.
245
258
  this.disconnectFromDeltaStream(disconnectReason);
246
259
  if (switchToReadonly) {
@@ -253,7 +266,7 @@ export class ConnectionManager {
253
266
  /**
254
267
  * Enables or disables automatic reconnecting.
255
268
  * Will throw an error if reconnectMode set to Never.
256
- */
269
+ */
257
270
  setAutoReconnect(mode) {
258
271
  assert(mode !== ReconnectMode.Never && this._reconnectMode !== ReconnectMode.Never, 0x278 /* "API is not supported for non-connecting or closed container" */);
259
272
  this._reconnectMode = mode;
@@ -361,7 +374,12 @@ export class ConnectionManager {
361
374
  let lastError;
362
375
  const abortController = new AbortController();
363
376
  const abortSignal = abortController.signal;
364
- this.pendingConnection = { abort: () => { abortController.abort(); }, connectionMode: requestedMode };
377
+ this.pendingConnection = {
378
+ abort: () => {
379
+ abortController.abort();
380
+ },
381
+ connectionMode: requestedMode,
382
+ };
365
383
  // This loop will keep trying to connect until successful, with a delay between each iteration.
366
384
  while (connection === undefined) {
367
385
  if (this._disposed) {
@@ -387,7 +405,8 @@ export class ConnectionManager {
387
405
  }
388
406
  }
389
407
  catch (origError) {
390
- if (typeof origError === "object" && origError !== null &&
408
+ if (typeof origError === "object" &&
409
+ origError !== null &&
391
410
  (origError === null || origError === void 0 ? void 0 : origError.errorType) === DeltaStreamConnectionForbiddenError.errorType) {
392
411
  connection = new NoDeltaStream();
393
412
  requestedMode = "read";
@@ -512,7 +531,11 @@ export class ConnectionManager {
512
531
  // But if we ask read, server can still give us write.
513
532
  const readonly = !connection.claims.scopes.includes(ScopeType.DocWrite);
514
533
  if (connection.mode !== requestedMode) {
515
- this.logger.sendTelemetryEvent({ eventName: "ConnectionModeMismatch", requestedMode, mode: connection.mode });
534
+ this.logger.sendTelemetryEvent({
535
+ eventName: "ConnectionModeMismatch",
536
+ requestedMode,
537
+ mode: connection.mode,
538
+ });
516
539
  }
517
540
  // This connection mode validation logic is moving to the driver layer in 0.44. These two asserts can be
518
541
  // removed after those packages have released and become ubiquitous.
@@ -552,7 +575,8 @@ export class ConnectionManager {
552
575
  this._connectionProps.connectionMode = connection.mode;
553
576
  let last = -1;
554
577
  if (initialMessages.length !== 0) {
555
- this._connectionVerboseProps.connectionInitialOpsFrom = initialMessages[0].sequenceNumber;
578
+ this._connectionVerboseProps.connectionInitialOpsFrom =
579
+ initialMessages[0].sequenceNumber;
556
580
  last = initialMessages[initialMessages.length - 1].sequenceNumber;
557
581
  this._connectionVerboseProps.connectionInitialOpsTo = last + 1;
558
582
  // Update knowledge of how far we are behind, before raising "connect" event
@@ -605,8 +629,7 @@ export class ConnectionManager {
605
629
  * @returns A promise that resolves when the connection is reestablished or we stop trying
606
630
  */
607
631
  reconnectOnError(requestedMode, error) {
608
- this.reconnect(requestedMode, error.message, error)
609
- .catch(this.props.closeHandler);
632
+ this.reconnect(requestedMode, error.message, error).catch(this.props.closeHandler);
610
633
  }
611
634
  /**
612
635
  * Disconnect the current connection and reconnect.
@@ -696,12 +719,15 @@ export class ConnectionManager {
696
719
  if (this.connectionMode === "read") {
697
720
  if (!this.pendingReconnect) {
698
721
  this.pendingReconnect = true;
699
- Promise.resolve().then(async () => {
700
- if (this.pendingReconnect) { // still valid?
722
+ Promise.resolve()
723
+ .then(async () => {
724
+ if (this.pendingReconnect) {
725
+ // still valid?
701
726
  await this.reconnect("write", // connectionMode
702
727
  "Switch to write");
703
728
  }
704
- }).catch(() => { });
729
+ })
730
+ .catch(() => { });
705
731
  }
706
732
  return;
707
733
  }
@@ -711,7 +737,8 @@ export class ConnectionManager {
711
737
  beforeProcessingIncomingOp(message) {
712
738
  // if we have connection, and message is local, then we better treat is as local!
713
739
  assert(this.clientId !== message.clientId || this.lastSubmittedClientId === message.clientId, 0x0ee /* "Not accounting local messages correctly" */);
714
- if (this.lastSubmittedClientId !== undefined && this.lastSubmittedClientId === message.clientId) {
740
+ if (this.lastSubmittedClientId !== undefined &&
741
+ this.lastSubmittedClientId === message.clientId) {
715
742
  const clientSequenceNumber = message.clientSequenceNumber;
716
743
  assert(this.clientSequenceNumberObserved < clientSequenceNumber, 0x0ef /* "client seq# not growing" */);
717
744
  assert(clientSequenceNumber <= this.clientSequenceNumber, 0x0f0 /* "Incoming local client seq# > generated by this client" */);
@@ -1 +1 @@
1
- {"version":3,"file":"connectionManager.js","sourceRoot":"","sources":["../src/connectionManager.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAM9D,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAOtF,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAO3E,OAAO,EACH,eAAe,EACf,gBAAgB,EAChB,yBAAyB,EACzB,sBAAsB,EACtB,qBAAqB,EACrB,mCAAmC,EACnC,iBAAiB,EACjB,gBAAgB,GACnB,MAAM,8BAA8B,CAAC;A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BAAkB,CAAC,IAAI,CAAW,CAAC;YAC/D,IAAI,QAAQ,KAAK,IAAI,CAAC,QAAQ,EAAE;gBAC5B,sCAAsC;gBACtC,IAAI,CAAC,MAAM,CAAC,oBAAoB,CAAC,EAAE,SAAS,EAAE,0BAA0B,EAAE,CAAC,CAAC;gBAE5E,gGAAgG;gBAChG,sGAAsG;gBACtG,mGAAmG;gBACnG,mGAAmG;gBACnG,uFAAuF;gBACvF,mCAAmC;gBACnC,IAAI,CAAC,SAAS,CACV,MAAM,EAAE,iBAAiB;gBACzB,gBAAgB,CACnB,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;oBACd,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,EAAE,SAAS,EAAE,wBAAwB,EAAE,EAAE,KAAK,CAAC,CAAC;gBAC/E,CAAC,CAAC,CAAC;aACN;SACJ;IACL,CAAC;CA6CJ","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { default as AbortController } from \"abort-controller\";\nimport {\n IDisposable,\n ITelemetryLogger,\n ITelemetryProperties,\n} from \"@fluidframework/common-definitions\";\nimport { assert, performance, TypedEventEmitter } from \"@fluidframework/common-utils\";\nimport {\n IDeltaQueue,\n ReadOnlyInfo,\n IConnectionDetails,\n ICriticalContainerError,\n} from \"@fluidframework/container-definitions\";\nimport { GenericError, UsageError } from \"@fluidframework/container-utils\";\nimport {\n IAnyDriverError,\n IDocumentService,\n IDocumentDeltaConnection,\n IDocumentDeltaConnectionEvents,\n} from \"@fluidframework/driver-definitions\";\nimport {\n canRetryOnError,\n createWriteError,\n createGenericNetworkError,\n getRetryDelayFromError,\n waitForConnectedState,\n DeltaStreamConnectionForbiddenError,\n logNetworkFailure,\n isRuntimeMessage,\n} from \"@fluidframework/driver-utils\";\nimport {\n ConnectionMode,\n IClient,\n IClientConfiguration,\n IClientDetails,\n IDocumentMessage,\n INack,\n INackContent,\n ISequencedDocumentMessage,\n ISignalClient,\n ISignalMessage,\n ITokenClaims,\n MessageType,\n ScopeType,\n ISequencedDocumentSystemMessage,\n} from \"@fluidframework/protocol-definitions\";\nimport {\n TelemetryLogger,\n normalizeError,\n} from \"@fluidframework/telemetry-utils\";\nimport {\n ReconnectMode,\n IConnectionManager,\n IConnectionManagerFactoryArgs,\n} from \"./contracts\";\nimport { DeltaQueue } from \"./deltaQueue\";\nimport { SignalType } from \"./protocol\";\n\nconst MaxReconnectDelayInMs = 8000;\nconst InitialReconnectDelayInMs = 1000;\nconst DefaultChunkSize = 16 * 1024;\n\nconst fatalConnectErrorProp = { fatalConnectError: true };\n\nfunction getNackReconnectInfo(nackContent: INackContent) {\n const message = `Nack (${nackContent.type}): ${nackContent.message}`;\n const canRetry = nackContent.code !== 403;\n const retryAfterMs = nackContent.retryAfter !== undefined ? nackContent.retryAfter * 1000 : undefined;\n return createGenericNetworkError(\n message,\n { canRetry, retryAfterMs },\n { statusCode: nackContent.code, driverVersion: undefined });\n}\n\n/**\n * Implementation of IDocumentDeltaConnection that does not support submitting\n * or receiving ops. Used in storage-only mode.\n */\nconst clientNoDeltaStream: IClient = {\n mode: \"read\",\n details: { capabilities: { interactive: true } },\n permission: [],\n user: { id: \"storage-only client\" }, // we need some \"fake\" ID here.\n scopes: [],\n};\nconst clientIdNoDeltaStream: string = \"storage-only client\";\n\nclass NoDeltaStream\n extends TypedEventEmitter<IDocumentDeltaConnectionEvents>\n implements IDocumentDeltaConnection, IDisposable {\n clientId = clientIdNoDeltaStream;\n claims: ITokenClaims = {\n scopes: [ScopeType.DocRead],\n } as any;\n mode: ConnectionMode = \"read\";\n existing: boolean = true;\n maxMessageSize: number = 0;\n version: string = \"\";\n initialMessages: ISequencedDocumentMessage[] = [];\n initialSignals: ISignalMessage[] = [];\n initialClients: ISignalClient[] = [{ client: clientNoDeltaStream, clientId: clientIdNoDeltaStream }];\n serviceConfiguration: IClientConfiguration = {\n maxMessageSize: 0,\n blockSize: 0,\n };\n checkpointSequenceNumber?: number | undefined = undefined;\n submit(messages: IDocumentMessage[]): void {\n this.emit(\"nack\", this.clientId, messages.map((operation) => {\n return {\n operation,\n content: { message: \"Cannot submit with storage-only connection\", code: 403 },\n };\n }));\n }\n submitSignal(message: any): void {\n this.emit(\"nack\", this.clientId, {\n operation: message,\n content: { message: \"Cannot submit signal with storage-only connection\", code: 403 },\n });\n }\n\n private _disposed = false;\n public get disposed() { return this._disposed; }\n public dispose() { this._disposed = true; }\n}\n\n/**\n * Interface to track the current in-progress connection attempt.\n */\ninterface IPendingConnection {\n /**\n * Used to cancel an in-progress connection attempt.\n */\n abort(): void;\n\n /**\n * Desired ConnectionMode of this in-progress connection attempt.\n */\n connectionMode: ConnectionMode;\n}\n\n/**\n * Implementation of IConnectionManager, used by Container class\n * Implements constant connectivity to relay service, by reconnecting in case of lost connection or error.\n * Exposes various controls to influence this process, including manual reconnects, forced read-only mode, etc.\n */\nexport class ConnectionManager implements IConnectionManager {\n /** Connection mode used when reconnecting on error or disconnect. */\n private readonly defaultReconnectionMode: ConnectionMode;\n\n /**\n * Tracks the current in-progress connection attempt. Undefined if there is none.\n * Note: Once the connection attempt fires and the code becomes asynchronous, its possible that a new connection\n * attempt was fired and this.pendingConnection was overwritten to reflect the new attempt.\n */\n private pendingConnection: IPendingConnection | undefined;\n private connection: IDocumentDeltaConnection | undefined;\n\n /** file ACL - whether user has only read-only access to a file */\n private _readonlyPermissions: boolean | undefined;\n\n /** tracks host requiring read-only mode. */\n private _forceReadonly = false;\n\n /**\n * Controls whether the DeltaManager will automatically reconnect to the delta stream after receiving a disconnect.\n */\n private _reconnectMode: ReconnectMode;\n\n /** True if there is pending (async) reconnection from \"read\" to \"write\" */\n private pendingReconnect = false;\n\n private clientSequenceNumber = 0;\n private clientSequenceNumberObserved = 0;\n /** Counts the number of non-runtime ops sent by the client which may not be acked. */\n private localOpsToIgnore = 0;\n\n /** track clientId used last time when we sent any ops */\n private lastSubmittedClientId: string | undefined;\n\n private connectFirstConnection = true;\n\n private _connectionVerboseProps: Record<string, string | number> = {};\n\n private _connectionProps: ITelemetryProperties = {};\n\n private _disposed = false;\n\n private readonly _outbound: DeltaQueue<IDocumentMessage[]>;\n\n public get connectionVerboseProps() { return this._connectionVerboseProps; }\n\n public readonly clientDetails: IClientDetails;\n\n /**\n * The current connection mode, initially read.\n */\n public get connectionMode(): ConnectionMode {\n return this.connection?.mode ?? \"read\";\n }\n\n public get connected() { return this.connection !== undefined; }\n\n public get clientId() { return this.connection?.clientId; }\n /**\n * Automatic reconnecting enabled or disabled.\n * If set to Never, then reconnecting will never be allowed.\n */\n public get reconnectMode(): ReconnectMode {\n return this._reconnectMode;\n }\n\n public get maxMessageSize(): number {\n return this.connection?.serviceConfiguration?.maxMessageSize\n ?? DefaultChunkSize;\n }\n\n public get version(): string {\n if (this.connection === undefined) {\n throw new Error(\"Cannot check version without a connection\");\n }\n return this.connection.version;\n }\n\n public get serviceConfiguration(): IClientConfiguration | undefined {\n return this.connection?.serviceConfiguration;\n }\n\n public get scopes(): string[] | undefined {\n return this.connection?.claims.scopes;\n }\n\n public get outbound(): IDeltaQueue<IDocumentMessage[]> {\n return this._outbound;\n }\n\n /**\n * Returns set of props that can be logged in telemetry that provide some insights / statistics\n * about current or last connection (if there is no connection at the moment)\n */\n public get connectionProps(): ITelemetryProperties {\n return this.connection !== undefined\n ? this._connectionProps\n : {\n ...this._connectionProps,\n // Report how many ops this client sent in last disconnected session\n sentOps: this.clientSequenceNumber,\n };\n }\n\n public shouldJoinWrite(): boolean {\n // We don't have to wait for ack for topmost NoOps. So subtract those.\n return this.clientSequenceNumberObserved < (this.clientSequenceNumber - this.localOpsToIgnore);\n }\n\n /**\n * Tells if container is in read-only mode.\n * Data stores should listen for \"readonly\" notifications and disallow user\n * making changes to data stores.\n * Readonly state can be because of no storage write permission,\n * or due to host forcing readonly mode for container.\n * It is undefined if we have not yet established websocket connection\n * and do not know if user has write access to a file.\n */\n private get readonly(): boolean | undefined {\n if (this._forceReadonly) {\n return true;\n }\n return this._readonlyPermissions;\n }\n\n public get readOnlyInfo(): ReadOnlyInfo {\n const storageOnly = this.connection !== undefined && this.connection instanceof NoDeltaStream;\n if (storageOnly || this._forceReadonly || this._readonlyPermissions === true) {\n return {\n readonly: true,\n forced: this._forceReadonly,\n permissions: this._readonlyPermissions,\n storageOnly,\n };\n }\n\n return { readonly: this._readonlyPermissions };\n }\n\n private static detailsFromConnection(connection: IDocumentDeltaConnection): IConnectionDetails {\n return {\n claims: connection.claims,\n clientId: connection.clientId,\n existing: connection.existing,\n checkpointSequenceNumber: connection.checkpointSequenceNumber,\n get initialClients() { return connection.initialClients; },\n mode: connection.mode,\n serviceConfiguration: connection.serviceConfiguration,\n version: connection.version,\n };\n }\n\n constructor(\n private readonly serviceProvider: () => IDocumentService | undefined,\n private client: IClient,\n reconnectAllowed: boolean,\n private readonly logger: ITelemetryLogger,\n private readonly props: IConnectionManagerFactoryArgs,\n ) {\n this.clientDetails = this.client.details;\n this.defaultReconnectionMode = this.client.mode;\n this._reconnectMode = reconnectAllowed ? ReconnectMode.Enabled : ReconnectMode.Never;\n\n // Outbound message queue. The outbound queue is represented as a queue of an array of ops. Ops contained\n // within an array *must* fit within the maxMessageSize and are guaranteed to be ordered sequentially.\n this._outbound = new DeltaQueue<IDocumentMessage[]>(\n (messages) => {\n if (this.connection === undefined) {\n throw new Error(\"Attempted to submit an outbound message without connection\");\n }\n this.connection.submit(messages);\n });\n\n this._outbound.on(\"error\", (error) => {\n this.props.closeHandler(normalizeError(error));\n });\n }\n\n public dispose(error?: ICriticalContainerError, switchToReadonly: boolean = true) {\n if (this._disposed) {\n return;\n }\n this._disposed = true;\n\n this.pendingConnection = undefined;\n\n // Ensure that things like triggerConnect() will short circuit\n this._reconnectMode = ReconnectMode.Never;\n\n this._outbound.clear();\n\n const disconnectReason = error !== undefined\n ? `Closing DeltaManager (${error.message})`\n : \"Closing DeltaManager\";\n\n // This raises \"disconnect\" event if we have active connection.\n this.disconnectFromDeltaStream(disconnectReason);\n\n if (switchToReadonly) {\n // Notify everyone we are in read-only state.\n // Useful for data stores in case we hit some critical error,\n // to switch to a mode where user edits are not accepted\n this.set_readonlyPermissions(true);\n }\n }\n\n /**\n * Enables or disables automatic reconnecting.\n * Will throw an error if reconnectMode set to Never.\n */\n public setAutoReconnect(mode: ReconnectMode): void {\n assert(mode !== ReconnectMode.Never && this._reconnectMode !== ReconnectMode.Never,\n 0x278 /* \"API is not supported for non-connecting or closed container\" */);\n\n this._reconnectMode = mode;\n\n if (mode !== ReconnectMode.Enabled) {\n // immediately disconnect - do not rely on service eventually dropping connection.\n this.disconnectFromDeltaStream(\"setAutoReconnect\");\n }\n }\n\n /**\n * Sends signal to runtime (and data stores) to be read-only.\n * Hosts may have read only views, indicating to data stores that no edits are allowed.\n * This is independent from this._readonlyPermissions (permissions) and this.connectionMode\n * (server can return \"write\" mode even when asked for \"read\")\n * Leveraging same \"readonly\" event as runtime & data stores should behave the same in such case\n * as in read-only permissions.\n * But this.active can be used by some DDSes to figure out if ops can be sent\n * (for example, read-only view still participates in code proposals / upgrades decisions)\n *\n * Forcing Readonly does not prevent DDS from generating ops. It is up to user code to honour\n * the readonly flag. If ops are generated, they will accumulate locally and not be sent. If\n * there are pending in the outbound queue, it will stop sending until force readonly is\n * cleared.\n *\n * @param readonly - set or clear force readonly.\n */\n public forceReadonly(readonly: boolean) {\n if (readonly !== this._forceReadonly) {\n this.logger.sendTelemetryEvent({\n eventName: \"ForceReadOnly\",\n value: readonly,\n });\n }\n const oldValue = this.readonly;\n this._forceReadonly = readonly;\n\n if (oldValue !== this.readonly) {\n if (this._reconnectMode === ReconnectMode.Never) {\n throw new UsageError(\"API is not supported for non-connecting or closed container\");\n }\n let reconnect = false;\n if (this.readonly === true) {\n // If we switch to readonly while connected, we should disconnect first\n // See comment in the \"readonly\" event handler to deltaManager set up by\n // the ContainerRuntime constructor\n\n if (this.shouldJoinWrite()) {\n // If we have pending changes, then we will never send them - it smells like\n // host logic error.\n this.logger.sendErrorEvent({ eventName: \"ForceReadonlyPendingChanged\" });\n }\n\n reconnect = this.disconnectFromDeltaStream(\"Force readonly\");\n }\n this.props.readonlyChangeHandler(this.readonly);\n if (reconnect) {\n // reconnect if we disconnected from before.\n this.triggerConnect(\"read\");\n }\n }\n }\n\n private set_readonlyPermissions(readonly: boolean) {\n const oldValue = this.readonly;\n this._readonlyPermissions = readonly;\n if (oldValue !== this.readonly) {\n this.props.readonlyChangeHandler(this.readonly);\n }\n }\n\n public connect(connectionMode?: ConnectionMode) {\n this.connectCore(connectionMode).catch((error) => {\n const normalizedError = normalizeError(error, { props: fatalConnectErrorProp });\n this.props.closeHandler(normalizedError);\n });\n }\n\n private async connectCore(connectionMode?: ConnectionMode): Promise<void> {\n assert(!this._disposed, 0x26a /* \"not closed\" */);\n\n if (this.connection !== undefined) {\n return; // Connection attempt already completed successfully\n }\n\n let pendingConnectionMode;\n if (this.pendingConnection !== undefined) {\n pendingConnectionMode = this.pendingConnection.connectionMode;\n this.cancelConnection(); // Throw out in-progress connection attempt in favor of new attempt\n assert(this.pendingConnection === undefined, 0x344 /* this.pendingConnection should be undefined */);\n }\n // If there is no specified ConnectionMode, try the previous mode, if there is no previous mode use default\n let requestedMode = connectionMode ?? pendingConnectionMode ?? this.defaultReconnectionMode;\n\n // if we have any non-acked ops from last connection, reconnect as \"write\".\n // without that we would connect in view-only mode, which will result in immediate\n // firing of \"connected\" event from Container and switch of current clientId (as tracked\n // by all DDSes). This will make it impossible to figure out if ops actually made it through,\n // so DDSes will immediately resubmit all pending ops, and some of them will be duplicates, corrupting document\n if (this.shouldJoinWrite()) {\n requestedMode = \"write\";\n }\n\n const docService = this.serviceProvider();\n assert(docService !== undefined, 0x2a7 /* \"Container is not attached\" */);\n\n let connection: IDocumentDeltaConnection | undefined;\n\n if (docService.policies?.storageOnly === true) {\n connection = new NoDeltaStream();\n this.setupNewSuccessfulConnection(connection, \"read\");\n assert(this.pendingConnection === undefined, 0x2b3 /* \"logic error\" */);\n return;\n }\n\n let delayMs = InitialReconnectDelayInMs;\n let connectRepeatCount = 0;\n const connectStartTime = performance.now();\n let lastError: any;\n\n const abortController = new AbortController();\n const abortSignal = abortController.signal;\n this.pendingConnection = { abort: () => { abortController.abort(); }, connectionMode: requestedMode };\n\n // This loop will keep trying to connect until successful, with a delay between each iteration.\n while (connection === undefined) {\n if (this._disposed) {\n throw new Error(\"Attempting to connect a closed DeltaManager\");\n }\n if (abortSignal.aborted === true) {\n this.logger.sendTelemetryEvent({\n eventName: \"ConnectionAttemptCancelled\",\n attempts: connectRepeatCount,\n duration: TelemetryLogger.formatTick(performance.now() - connectStartTime),\n connectionEstablished: false,\n });\n return;\n }\n connectRepeatCount++;\n\n try {\n this.client.mode = requestedMode;\n connection = await docService.connectToDeltaStream({ ...this.client, mode: requestedMode });\n\n if (connection.disposed) {\n // Nobody observed this connection, so drop it on the floor and retry.\n this.logger.sendTelemetryEvent({ eventName: \"ReceivedClosedConnection\" });\n connection = undefined;\n }\n } catch (origError: any) {\n if (typeof origError === \"object\" && origError !== null &&\n origError?.errorType === DeltaStreamConnectionForbiddenError.errorType) {\n connection = new NoDeltaStream();\n requestedMode = \"read\";\n break;\n }\n\n // Socket.io error when we connect to wrong socket, or hit some multiplexing bug\n if (!canRetryOnError(origError)) {\n const error = normalizeError(origError, { props: fatalConnectErrorProp });\n this.props.closeHandler(error);\n throw error;\n }\n\n // Since the error is retryable this will not log to the error table\n logNetworkFailure(\n this.logger,\n {\n attempts: connectRepeatCount,\n delay: delayMs, // milliseconds\n eventName: \"DeltaConnectionFailureToConnect\",\n duration: TelemetryLogger.formatTick(performance.now() - connectStartTime),\n },\n origError);\n\n lastError = origError;\n\n const retryDelayFromError = getRetryDelayFromError(origError);\n delayMs = retryDelayFromError ?? Math.min(delayMs * 2, MaxReconnectDelayInMs);\n\n if (retryDelayFromError !== undefined) {\n this.props.reconnectionDelayHandler(retryDelayFromError, origError);\n }\n await waitForConnectedState(delayMs);\n }\n }\n\n // If we retried more than once, log an event about how long it took (this will not log to error table)\n if (connectRepeatCount > 1) {\n logNetworkFailure(\n this.logger,\n {\n eventName: \"MultipleDeltaConnectionFailures\",\n attempts: connectRepeatCount,\n duration: TelemetryLogger.formatTick(performance.now() - connectStartTime),\n },\n lastError,\n );\n }\n\n // Check for abort signal after while loop as well\n if (abortSignal.aborted === true) {\n connection.dispose();\n this.logger.sendTelemetryEvent({\n eventName: \"ConnectionAttemptCancelled\",\n attempts: connectRepeatCount,\n duration: TelemetryLogger.formatTick(performance.now() - connectStartTime),\n connectionEstablished: true,\n });\n return;\n }\n\n this.setupNewSuccessfulConnection(connection, requestedMode);\n }\n\n /**\n * Start the connection. Any error should result in container being closed.\n * And report the error if it escapes for any reason.\n * @param args - The connection arguments\n */\n private triggerConnect(connectionMode: ConnectionMode) {\n // reconnect() has async await of waitForConnectedState(), and that causes potential race conditions\n // where we might already have a connection. If it were to happen, it's possible that we will connect\n // with different mode to `connectionMode`. Glancing through the caller chains, it looks like code should be\n // fine (if needed, reconnect flow will get triggered again). Places where new mode matters should encode it\n // directly in connectCore - see this.shouldJoinWrite() test as an example.\n // assert(this.connection === undefined, 0x239 /* \"called only in disconnected state\" */);\n\n if (this.reconnectMode !== ReconnectMode.Enabled) {\n return;\n }\n this.connect(connectionMode);\n }\n\n /**\n * Disconnect the current connection.\n * @param reason - Text description of disconnect reason to emit with disconnect event\n * @returns A boolean that indicates if there was an existing connection (or pending connection) to disconnect\n */\n private disconnectFromDeltaStream(reason: string): boolean {\n this.pendingReconnect = false;\n\n if (this.connection === undefined) {\n if (this.pendingConnection !== undefined) {\n this.cancelConnection();\n return true;\n }\n return false;\n }\n\n assert(this.pendingConnection === undefined, 0x27b /* \"reentrancy may result in incorrect behavior\" */);\n\n const connection = this.connection;\n // Avoid any re-entrancy - clear object reference\n this.connection = undefined;\n\n // Remove listeners first so we don't try to retrigger this flow accidentally through reconnectOnError\n connection.off(\"op\", this.opHandler);\n connection.off(\"signal\", this.props.signalHandler);\n connection.off(\"nack\", this.nackHandler);\n connection.off(\"disconnect\", this.disconnectHandlerInternal);\n connection.off(\"error\", this.errorHandler);\n connection.off(\"pong\", this.props.pongHandler);\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._outbound.pause();\n this._outbound.clear();\n this.props.disconnectHandler(reason);\n\n connection.dispose();\n\n this._connectionVerboseProps = {};\n\n return true;\n }\n\n /**\n * Cancel in-progress connection attempt.\n */\n private cancelConnection() {\n assert(this.pendingConnection !== undefined,\n 0x345 /* this.pendingConnection is undefined when trying to cancel */);\n this.pendingConnection.abort();\n this.pendingConnection = undefined;\n this.logger.sendTelemetryEvent({ eventName: \"ConnectionCancelReceived\" });\n }\n\n /**\n * Once we've successfully gotten a connection, we need to set up state, attach event listeners, and process\n * initial messages.\n * @param connection - The newly established connection\n */\n private setupNewSuccessfulConnection(connection: IDocumentDeltaConnection, requestedMode: ConnectionMode) {\n // Old connection should have been cleaned up before establishing a new one\n assert(this.connection === undefined, 0x0e6 /* \"old connection exists on new connection setup\" */);\n assert(!connection.disposed, 0x28a /* \"can't be disposed - Callers need to ensure that!\" */);\n\n this.pendingConnection = undefined;\n\n this.connection = connection;\n\n // Does information in scopes & mode matches?\n // If we asked for \"write\" and got \"read\", then file is read-only\n // But if we ask read, server can still give us write.\n const readonly = !connection.claims.scopes.includes(ScopeType.DocWrite);\n\n if (connection.mode !== requestedMode) {\n this.logger.sendTelemetryEvent({ eventName: \"ConnectionModeMismatch\", requestedMode, mode: connection.mode });\n }\n // This connection mode validation logic is moving to the driver layer in 0.44. These two asserts can be\n // removed after those packages have released and become ubiquitous.\n assert(requestedMode === \"read\" || readonly === (this.connectionMode === \"read\"),\n 0x0e7 /* \"claims/connectionMode mismatch\" */);\n assert(!readonly || this.connectionMode === \"read\", 0x0e8 /* \"readonly perf with write connection\" */);\n\n this.set_readonlyPermissions(readonly);\n\n if (this._disposed) {\n // Raise proper events, Log telemetry event and close connection.\n this.disconnectFromDeltaStream(\"ConnectionManager already closed\");\n return;\n }\n\n this._outbound.resume();\n\n connection.on(\"op\", this.opHandler);\n connection.on(\"signal\", this.props.signalHandler);\n connection.on(\"nack\", this.nackHandler);\n connection.on(\"disconnect\", this.disconnectHandlerInternal);\n connection.on(\"error\", this.errorHandler);\n connection.on(\"pong\", this.props.pongHandler);\n\n // Initial messages are always sorted. However, due to early op handler installed by drivers and appending those\n // ops to initialMessages, resulting set is no longer sorted, which would result in client hitting storage to\n // fill in gap. We will recover by cancelling this request once we process remaining ops, but it's a waste that\n // we could avoid\n const initialMessages = connection.initialMessages.sort((a, b) => a.sequenceNumber - b.sequenceNumber);\n\n // Some storages may provide checkpointSequenceNumber to identify how far client is behind.\n let checkpointSequenceNumber = connection.checkpointSequenceNumber;\n\n this._connectionVerboseProps = {\n clientId: connection.clientId,\n mode: connection.mode,\n };\n\n // reset connection props\n this._connectionProps = {};\n\n if (connection.relayServiceAgent !== undefined) {\n this._connectionVerboseProps.relayServiceAgent = connection.relayServiceAgent;\n this._connectionProps.relayServiceAgent = connection.relayServiceAgent;\n }\n this._connectionProps.socketDocumentId = connection.claims.documentId;\n this._connectionProps.connectionMode = connection.mode;\n\n let last = -1;\n if (initialMessages.length !== 0) {\n this._connectionVerboseProps.connectionInitialOpsFrom = initialMessages[0].sequenceNumber;\n last = initialMessages[initialMessages.length - 1].sequenceNumber;\n this._connectionVerboseProps.connectionInitialOpsTo = last + 1;\n // Update knowledge of how far we are behind, before raising \"connect\" event\n // This is duplication of what incomingOpHandler() does, but we have to raise event before we get there,\n // so duplicating update logic here as well.\n if (checkpointSequenceNumber === undefined || checkpointSequenceNumber < last) {\n checkpointSequenceNumber = last;\n }\n }\n\n this.props.incomingOpHandler(\n initialMessages,\n this.connectFirstConnection ? \"InitialOps\" : \"ReconnectOps\");\n\n const details = ConnectionManager.detailsFromConnection(connection);\n details.checkpointSequenceNumber = checkpointSequenceNumber;\n this.props.connectHandler(details);\n\n this.connectFirstConnection = false;\n\n // Synthesize clear & join signals out of initialClients state.\n // This allows us to have single way to process signals, and makes it simpler to initialize\n // protocol in Container.\n const clearSignal: ISignalMessage = {\n clientId: null, // system message\n content: JSON.stringify({\n type: SignalType.Clear,\n }),\n };\n this.props.signalHandler(clearSignal);\n\n for (const priorClient of connection.initialClients ?? []) {\n const joinSignal: ISignalMessage = {\n clientId: null, // system signal\n content: JSON.stringify({\n type: SignalType.ClientJoin,\n content: priorClient, // ISignalClient\n }),\n };\n this.props.signalHandler(joinSignal);\n }\n\n // Unfortunately, there is no defined order between initialSignals (including join & leave signals)\n // and connection.initialClients. In practice, connection.initialSignals quite often contains join signal\n // for \"self\" and connection.initialClients does not contain \"self\", so we have to process them after\n // \"clear\" signal above.\n if (connection.initialSignals !== undefined) {\n for (const signal of connection.initialSignals) {\n this.props.signalHandler(signal);\n }\n }\n }\n\n /**\n * Disconnect the current connection and reconnect. Closes the container if it fails.\n * @param connection - The connection that wants to reconnect - no-op if it's different from this.connection\n * @param requestedMode - Read or write\n * @param error - Error reconnect information including whether or not to reconnect\n * @returns A promise that resolves when the connection is reestablished or we stop trying\n */\n private reconnectOnError(\n requestedMode: ConnectionMode,\n error: IAnyDriverError,\n ) {\n this.reconnect(\n requestedMode,\n error.message,\n error)\n .catch(this.props.closeHandler);\n }\n\n /**\n * Disconnect the current connection and reconnect.\n * @param connection - The connection that wants to reconnect - no-op if it's different from this.connection\n * @param requestedMode - Read or write\n * @param error - Error reconnect information including whether or not to reconnect\n * @returns A promise that resolves when the connection is reestablished or we stop trying\n */\n private async reconnect(\n requestedMode: ConnectionMode,\n disconnectMessage: string,\n error?: IAnyDriverError,\n ) {\n // We quite often get protocol errors before / after observing nack/disconnect\n // we do not want to run through same sequence twice.\n // If we're already disconnected/disconnecting it's not appropriate to call this again.\n assert(this.connection !== undefined, 0x0eb /* \"Missing connection for reconnect\" */);\n\n this.disconnectFromDeltaStream(disconnectMessage);\n\n // We will always trigger reconnect, even if canRetry is false.\n // Any truly fatal error state will result in container close upon attempted reconnect,\n // which is a preferable to closing abruptly when a live connection fails.\n if (error !== undefined && !error.canRetry) {\n this.logger.sendTelemetryEvent({\n eventName: \"reconnectingDespiteFatalError\",\n reconnectMode: this.reconnectMode,\n }, error);\n }\n\n if (this.reconnectMode === ReconnectMode.Never) {\n // Do not raise container error if we are closing just because we lost connection.\n // Those errors (like IdleDisconnect) would show up in telemetry dashboards and\n // are very misleading, as first initial reaction - some logic is broken.\n this.props.closeHandler();\n }\n\n // If closed then we can't reconnect\n if (this._disposed || this.reconnectMode !== ReconnectMode.Enabled) {\n return;\n }\n\n const delayMs = getRetryDelayFromError(error);\n if (error !== undefined && delayMs !== undefined) {\n this.props.reconnectionDelayHandler(delayMs, error);\n await waitForConnectedState(delayMs);\n }\n\n this.triggerConnect(requestedMode);\n }\n\n public prepareMessageToSend(message: Omit<IDocumentMessage, \"clientSequenceNumber\">): IDocumentMessage | undefined {\n if (this.readonly === true) {\n assert(this.readOnlyInfo.readonly === true, 0x1f0 /* \"Unexpected mismatch in readonly\" */);\n const error = new GenericError(\"deltaManagerReadonlySubmit\", undefined /* error */, {\n readonly: this.readOnlyInfo.readonly,\n forcedReadonly: this.readOnlyInfo.forced,\n readonlyPermissions: this.readOnlyInfo.permissions,\n storageOnly: this.readOnlyInfo.storageOnly,\n });\n this.props.closeHandler(error);\n return undefined;\n }\n\n // reset clientSequenceNumber if we are using new clientId.\n // we keep info about old connection as long as possible to be able to account for all non-acked ops\n // that we pick up on next connection.\n assert(!!this.connection, 0x0e4 /* \"Lost old connection!\" */);\n if (this.lastSubmittedClientId !== this.connection?.clientId) {\n this.lastSubmittedClientId = this.connection?.clientId;\n this.clientSequenceNumber = 0;\n this.clientSequenceNumberObserved = 0;\n }\n\n if (!isRuntimeMessage(message)) {\n this.localOpsToIgnore++;\n } else {\n this.localOpsToIgnore = 0;\n }\n\n return {\n ...message,\n clientSequenceNumber: ++this.clientSequenceNumber,\n };\n }\n\n public submitSignal(content: any) {\n if (this.connection !== undefined) {\n this.connection.submitSignal(content);\n } else {\n this.logger.sendErrorEvent({ eventName: \"submitSignalDisconnected\" });\n }\n }\n\n public sendMessages(messages: IDocumentMessage[]) {\n assert(this.connected, 0x2b4 /* \"not connected on sending ops!\" */);\n // If connection is \"read\" or implicit \"read\" (got leave op for \"write\" connection),\n // then op can't make it through - we will get a nack if op is sent.\n // We can short-circuit this process.\n // Note that we also want nacks to be rare and be treated as catastrophic failures.\n // Be careful with reentrancy though - disconnected event should not be be raised in the\n // middle of the current workflow, but rather on clean stack!\n if (this.connectionMode === \"read\") {\n if (!this.pendingReconnect) {\n this.pendingReconnect = true;\n Promise.resolve().then(async () => {\n if (this.pendingReconnect) { // still valid?\n await this.reconnect(\n \"write\", // connectionMode\n \"Switch to write\", // message\n );\n }\n }).catch(() => { });\n }\n return;\n }\n\n assert(!this.pendingReconnect, 0x2b5 /* \"logic error\" */);\n\n this._outbound.push(messages);\n }\n\n public beforeProcessingIncomingOp(message: ISequencedDocumentMessage) {\n // if we have connection, and message is local, then we better treat is as local!\n assert(this.clientId !== message.clientId || this.lastSubmittedClientId === message.clientId,\n 0x0ee /* \"Not accounting local messages correctly\" */,\n );\n\n if (this.lastSubmittedClientId !== undefined && this.lastSubmittedClientId === message.clientId) {\n const clientSequenceNumber = message.clientSequenceNumber;\n\n assert(this.clientSequenceNumberObserved < clientSequenceNumber, 0x0ef /* \"client seq# not growing\" */);\n assert(clientSequenceNumber <= this.clientSequenceNumber,\n 0x0f0 /* \"Incoming local client seq# > generated by this client\" */);\n\n this.clientSequenceNumberObserved = clientSequenceNumber;\n }\n\n if (message.type === MessageType.ClientLeave) {\n const systemLeaveMessage = message as ISequencedDocumentSystemMessage;\n const clientId = JSON.parse(systemLeaveMessage.data) as string;\n if (clientId === this.clientId) {\n // We have been kicked out from quorum\n this.logger.sendPerformanceEvent({ eventName: \"ReadConnectionTransition\" });\n\n // Please see #8483 for more details on why maintaining connection further as is would not work.\n // Short story - connection properties are immutable, and many processes (consensus DDSes, summarizer)\n // assume that connection stays \"write\" connection until disconnect, and act accordingly, which may\n // not work well with de-facto \"read\" connection we are in after receiving own leave op on timeout.\n // Clients need to be able to transition to \"read\" state after some time of inactivity!\n // Note - this may close container!\n this.reconnect(\n \"read\", // connectionMode\n \"Switch to read\", // message\n ).catch((error) => {\n this.logger.sendErrorEvent({ eventName: \"SwitchToReadConnection\" }, error);\n });\n }\n }\n }\n\n private readonly opHandler = (documentId: string, messagesArg: ISequencedDocumentMessage[]) => {\n const messages = Array.isArray(messagesArg) ? messagesArg : [messagesArg];\n this.props.incomingOpHandler(messages, \"opHandler\");\n };\n\n // Always connect in write mode after getting nacked.\n private readonly nackHandler = (documentId: string, messages: INack[]) => {\n const message = messages[0];\n if (this._readonlyPermissions === true) {\n this.props.closeHandler(createWriteError(\"writeOnReadOnlyDocument\", { driverVersion: undefined }));\n return;\n }\n\n const reconnectInfo = getNackReconnectInfo(message.content);\n\n // If the nack indicates we cannot retry, then close the container outright\n if (!reconnectInfo.canRetry) {\n this.props.closeHandler(reconnectInfo);\n return;\n }\n\n this.reconnectOnError(\n \"write\",\n reconnectInfo,\n );\n };\n\n // Connection mode is always read on disconnect/error unless the system mode was write.\n private readonly disconnectHandlerInternal = (disconnectReason: IAnyDriverError) => {\n // Note: we might get multiple disconnect calls on same socket, as early disconnect notification\n // (\"server_disconnect\", ODSP-specific) is mapped to \"disconnect\"\n this.reconnectOnError(\n this.defaultReconnectionMode,\n disconnectReason,\n );\n };\n\n private readonly errorHandler = (error: IAnyDriverError) => {\n this.reconnectOnError(\n this.defaultReconnectionMode,\n error,\n );\n };\n}\n"]}
1
+ {"version":3,"file":"connectionManager.js","sourceRoot":"","sources":["../src/connectionManager.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAM9D,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAOtF,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,iCAA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AAQ,GAAG,IAAI,CAAC,KAAK,CAAC,kBAAkB,CAAC,IAAI,CAAW,CAAC;YAC/D,IAAI,QAAQ,KAAK,IAAI,CAAC,QAAQ,EAAE;gBAC/B,sCAAsC;gBACtC,IAAI,CAAC,MAAM,CAAC,oBAAoB,CAAC,EAAE,SAAS,EAAE,0BAA0B,EAAE,CAAC,CAAC;gBAE5E,gGAAgG;gBAChG,sGAAsG;gBACtG,mGAAmG;gBACnG,mGAAmG;gBACnG,uFAAuF;gBACvF,mCAAmC;gBACnC,IAAI,CAAC,SAAS,CACb,MAAM,EAAE,iBAAiB;gBACzB,gBAAgB,CAChB,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;oBACjB,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,EAAE,SAAS,EAAE,wBAAwB,EAAE,EAAE,KAAK,CAAC,CAAC;gBAC5E,CAAC,CAAC,CAAC;aACH;SACD;IACF,CAAC;CAsCD","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { default as AbortController } from \"abort-controller\";\nimport {\n\tIDisposable,\n\tITelemetryLogger,\n\tITelemetryProperties,\n} from \"@fluidframework/common-definitions\";\nimport { assert, performance, TypedEventEmitter } from \"@fluidframework/common-utils\";\nimport {\n\tIDeltaQueue,\n\tReadOnlyInfo,\n\tIConnectionDetails,\n\tICriticalContainerError,\n} from \"@fluidframework/container-definitions\";\nimport { GenericError, UsageError } from \"@fluidframework/container-utils\";\nimport {\n\tIAnyDriverError,\n\tIDocumentService,\n\tIDocumentDeltaConnection,\n\tIDocumentDeltaConnectionEvents,\n} from \"@fluidframework/driver-definitions\";\nimport {\n\tcanRetryOnError,\n\tcreateWriteError,\n\tcreateGenericNetworkError,\n\tgetRetryDelayFromError,\n\twaitForConnectedState,\n\tDeltaStreamConnectionForbiddenError,\n\tlogNetworkFailure,\n\tisRuntimeMessage,\n} from \"@fluidframework/driver-utils\";\nimport {\n\tConnectionMode,\n\tIClient,\n\tIClientConfiguration,\n\tIClientDetails,\n\tIDocumentMessage,\n\tINack,\n\tINackContent,\n\tISequencedDocumentMessage,\n\tISignalClient,\n\tISignalMessage,\n\tITokenClaims,\n\tMessageType,\n\tScopeType,\n\tISequencedDocumentSystemMessage,\n} from \"@fluidframework/protocol-definitions\";\nimport { TelemetryLogger, normalizeError } from \"@fluidframework/telemetry-utils\";\nimport { ReconnectMode, IConnectionManager, IConnectionManagerFactoryArgs } from \"./contracts\";\nimport { DeltaQueue } from \"./deltaQueue\";\nimport { SignalType } from \"./protocol\";\n\nconst MaxReconnectDelayInMs = 8000;\nconst InitialReconnectDelayInMs = 1000;\nconst DefaultChunkSize = 16 * 1024;\n\nconst fatalConnectErrorProp = { fatalConnectError: true };\n\nfunction getNackReconnectInfo(nackContent: INackContent) {\n\tconst message = `Nack (${nackContent.type}): ${nackContent.message}`;\n\tconst canRetry = nackContent.code !== 403;\n\tconst retryAfterMs =\n\t\tnackContent.retryAfter !== undefined ? nackContent.retryAfter * 1000 : undefined;\n\treturn createGenericNetworkError(\n\t\tmessage,\n\t\t{ canRetry, retryAfterMs },\n\t\t{ statusCode: nackContent.code, driverVersion: undefined },\n\t);\n}\n\n/**\n * Implementation of IDocumentDeltaConnection that does not support submitting\n * or receiving ops. Used in storage-only mode.\n */\nconst clientNoDeltaStream: IClient = {\n\tmode: \"read\",\n\tdetails: { capabilities: { interactive: true } },\n\tpermission: [],\n\tuser: { id: \"storage-only client\" }, // we need some \"fake\" ID here.\n\tscopes: [],\n};\nconst clientIdNoDeltaStream: string = \"storage-only client\";\n\nclass NoDeltaStream\n\textends TypedEventEmitter<IDocumentDeltaConnectionEvents>\n\timplements IDocumentDeltaConnection, IDisposable\n{\n\tclientId = clientIdNoDeltaStream;\n\tclaims: ITokenClaims = {\n\t\tscopes: [ScopeType.DocRead],\n\t} as any;\n\tmode: ConnectionMode = \"read\";\n\texisting: boolean = true;\n\tmaxMessageSize: number = 0;\n\tversion: string = \"\";\n\tinitialMessages: ISequencedDocumentMessage[] = [];\n\tinitialSignals: ISignalMessage[] = [];\n\tinitialClients: ISignalClient[] = [\n\t\t{ client: clientNoDeltaStream, clientId: clientIdNoDeltaStream },\n\t];\n\tserviceConfiguration: IClientConfiguration = {\n\t\tmaxMessageSize: 0,\n\t\tblockSize: 0,\n\t};\n\tcheckpointSequenceNumber?: number | undefined = undefined;\n\tsubmit(messages: IDocumentMessage[]): void {\n\t\tthis.emit(\n\t\t\t\"nack\",\n\t\t\tthis.clientId,\n\t\t\tmessages.map((operation) => {\n\t\t\t\treturn {\n\t\t\t\t\toperation,\n\t\t\t\t\tcontent: { message: \"Cannot submit with storage-only connection\", code: 403 },\n\t\t\t\t};\n\t\t\t}),\n\t\t);\n\t}\n\tsubmitSignal(message: any): void {\n\t\tthis.emit(\"nack\", this.clientId, {\n\t\t\toperation: message,\n\t\t\tcontent: { message: \"Cannot submit signal with storage-only connection\", code: 403 },\n\t\t});\n\t}\n\n\tprivate _disposed = false;\n\tpublic get disposed() {\n\t\treturn this._disposed;\n\t}\n\tpublic dispose() {\n\t\tthis._disposed = true;\n\t}\n}\n\n/**\n * Interface to track the current in-progress connection attempt.\n */\ninterface IPendingConnection {\n\t/**\n\t * Used to cancel an in-progress connection attempt.\n\t */\n\tabort(): void;\n\n\t/**\n\t * Desired ConnectionMode of this in-progress connection attempt.\n\t */\n\tconnectionMode: ConnectionMode;\n}\n\n/**\n * Implementation of IConnectionManager, used by Container class\n * Implements constant connectivity to relay service, by reconnecting in case of lost connection or error.\n * Exposes various controls to influence this process, including manual reconnects, forced read-only mode, etc.\n */\nexport class ConnectionManager implements IConnectionManager {\n\t/** Connection mode used when reconnecting on error or disconnect. */\n\tprivate readonly defaultReconnectionMode: ConnectionMode;\n\n\t/**\n\t * Tracks the current in-progress connection attempt. Undefined if there is none.\n\t * Note: Once the connection attempt fires and the code becomes asynchronous, its possible that a new connection\n\t * attempt was fired and this.pendingConnection was overwritten to reflect the new attempt.\n\t */\n\tprivate pendingConnection: IPendingConnection | undefined;\n\tprivate connection: IDocumentDeltaConnection | undefined;\n\n\t/** file ACL - whether user has only read-only access to a file */\n\tprivate _readonlyPermissions: boolean | undefined;\n\n\t/** tracks host requiring read-only mode. */\n\tprivate _forceReadonly = false;\n\n\t/**\n\t * Controls whether the DeltaManager will automatically reconnect to the delta stream after receiving a disconnect.\n\t */\n\tprivate _reconnectMode: ReconnectMode;\n\n\t/** True if there is pending (async) reconnection from \"read\" to \"write\" */\n\tprivate pendingReconnect = false;\n\n\tprivate clientSequenceNumber = 0;\n\tprivate clientSequenceNumberObserved = 0;\n\t/** Counts the number of non-runtime ops sent by the client which may not be acked. */\n\tprivate localOpsToIgnore = 0;\n\n\t/** track clientId used last time when we sent any ops */\n\tprivate lastSubmittedClientId: string | undefined;\n\n\tprivate connectFirstConnection = true;\n\n\tprivate _connectionVerboseProps: Record<string, string | number> = {};\n\n\tprivate _connectionProps: ITelemetryProperties = {};\n\n\tprivate _disposed = false;\n\n\tprivate readonly _outbound: DeltaQueue<IDocumentMessage[]>;\n\n\tpublic get connectionVerboseProps() {\n\t\treturn this._connectionVerboseProps;\n\t}\n\n\tpublic readonly clientDetails: IClientDetails;\n\n\t/**\n\t * The current connection mode, initially read.\n\t */\n\tpublic get connectionMode(): ConnectionMode {\n\t\treturn this.connection?.mode ?? \"read\";\n\t}\n\n\tpublic get connected() {\n\t\treturn this.connection !== undefined;\n\t}\n\n\tpublic get clientId() {\n\t\treturn this.connection?.clientId;\n\t}\n\t/**\n\t * Automatic reconnecting enabled or disabled.\n\t * If set to Never, then reconnecting will never be allowed.\n\t */\n\tpublic get reconnectMode(): ReconnectMode {\n\t\treturn this._reconnectMode;\n\t}\n\n\tpublic get maxMessageSize(): number {\n\t\treturn this.connection?.serviceConfiguration?.maxMessageSize ?? DefaultChunkSize;\n\t}\n\n\tpublic get version(): string {\n\t\tif (this.connection === undefined) {\n\t\t\tthrow new Error(\"Cannot check version without a connection\");\n\t\t}\n\t\treturn this.connection.version;\n\t}\n\n\tpublic get serviceConfiguration(): IClientConfiguration | undefined {\n\t\treturn this.connection?.serviceConfiguration;\n\t}\n\n\tpublic get scopes(): string[] | undefined {\n\t\treturn this.connection?.claims.scopes;\n\t}\n\n\tpublic get outbound(): IDeltaQueue<IDocumentMessage[]> {\n\t\treturn this._outbound;\n\t}\n\n\t/**\n\t * Returns set of props that can be logged in telemetry that provide some insights / statistics\n\t * about current or last connection (if there is no connection at the moment)\n\t */\n\tpublic get connectionProps(): ITelemetryProperties {\n\t\treturn this.connection !== undefined\n\t\t\t? this._connectionProps\n\t\t\t: {\n\t\t\t\t\t...this._connectionProps,\n\t\t\t\t\t// Report how many ops this client sent in last disconnected session\n\t\t\t\t\tsentOps: this.clientSequenceNumber,\n\t\t\t };\n\t}\n\n\tpublic shouldJoinWrite(): boolean {\n\t\t// We don't have to wait for ack for topmost NoOps. So subtract those.\n\t\treturn (\n\t\t\tthis.clientSequenceNumberObserved < this.clientSequenceNumber - this.localOpsToIgnore\n\t\t);\n\t}\n\n\t/**\n\t * Tells if container is in read-only mode.\n\t * Data stores should listen for \"readonly\" notifications and disallow user\n\t * making changes to data stores.\n\t * Readonly state can be because of no storage write permission,\n\t * or due to host forcing readonly mode for container.\n\t * It is undefined if we have not yet established websocket connection\n\t * and do not know if user has write access to a file.\n\t */\n\tprivate get readonly(): boolean | undefined {\n\t\tif (this._forceReadonly) {\n\t\t\treturn true;\n\t\t}\n\t\treturn this._readonlyPermissions;\n\t}\n\n\tpublic get readOnlyInfo(): ReadOnlyInfo {\n\t\tconst storageOnly =\n\t\t\tthis.connection !== undefined && this.connection instanceof NoDeltaStream;\n\t\tif (storageOnly || this._forceReadonly || this._readonlyPermissions === true) {\n\t\t\treturn {\n\t\t\t\treadonly: true,\n\t\t\t\tforced: this._forceReadonly,\n\t\t\t\tpermissions: this._readonlyPermissions,\n\t\t\t\tstorageOnly,\n\t\t\t};\n\t\t}\n\n\t\treturn { readonly: this._readonlyPermissions };\n\t}\n\n\tprivate static detailsFromConnection(connection: IDocumentDeltaConnection): IConnectionDetails {\n\t\treturn {\n\t\t\tclaims: connection.claims,\n\t\t\tclientId: connection.clientId,\n\t\t\texisting: connection.existing,\n\t\t\tcheckpointSequenceNumber: connection.checkpointSequenceNumber,\n\t\t\tget initialClients() {\n\t\t\t\treturn connection.initialClients;\n\t\t\t},\n\t\t\tmode: connection.mode,\n\t\t\tserviceConfiguration: connection.serviceConfiguration,\n\t\t\tversion: connection.version,\n\t\t};\n\t}\n\n\tconstructor(\n\t\tprivate readonly serviceProvider: () => IDocumentService | undefined,\n\t\tprivate client: IClient,\n\t\treconnectAllowed: boolean,\n\t\tprivate readonly logger: ITelemetryLogger,\n\t\tprivate readonly props: IConnectionManagerFactoryArgs,\n\t) {\n\t\tthis.clientDetails = this.client.details;\n\t\tthis.defaultReconnectionMode = this.client.mode;\n\t\tthis._reconnectMode = reconnectAllowed ? ReconnectMode.Enabled : ReconnectMode.Never;\n\n\t\t// Outbound message queue. The outbound queue is represented as a queue of an array of ops. Ops contained\n\t\t// within an array *must* fit within the maxMessageSize and are guaranteed to be ordered sequentially.\n\t\tthis._outbound = new DeltaQueue<IDocumentMessage[]>((messages) => {\n\t\t\tif (this.connection === undefined) {\n\t\t\t\tthrow new Error(\"Attempted to submit an outbound message without connection\");\n\t\t\t}\n\t\t\tthis.connection.submit(messages);\n\t\t});\n\n\t\tthis._outbound.on(\"error\", (error) => {\n\t\t\tthis.props.closeHandler(normalizeError(error));\n\t\t});\n\t}\n\n\tpublic dispose(error?: ICriticalContainerError, switchToReadonly: boolean = true) {\n\t\tif (this._disposed) {\n\t\t\treturn;\n\t\t}\n\t\tthis._disposed = true;\n\n\t\tthis.pendingConnection = undefined;\n\n\t\t// Ensure that things like triggerConnect() will short circuit\n\t\tthis._reconnectMode = ReconnectMode.Never;\n\n\t\tthis._outbound.clear();\n\n\t\tconst disconnectReason = \"Closing DeltaManager\";\n\n\t\t// This raises \"disconnect\" event if we have active connection.\n\t\tthis.disconnectFromDeltaStream(disconnectReason);\n\n\t\tif (switchToReadonly) {\n\t\t\t// Notify everyone we are in read-only state.\n\t\t\t// Useful for data stores in case we hit some critical error,\n\t\t\t// to switch to a mode where user edits are not accepted\n\t\t\tthis.set_readonlyPermissions(true);\n\t\t}\n\t}\n\n\t/**\n\t * Enables or disables automatic reconnecting.\n\t * Will throw an error if reconnectMode set to Never.\n\t */\n\tpublic setAutoReconnect(mode: ReconnectMode): void {\n\t\tassert(\n\t\t\tmode !== ReconnectMode.Never && this._reconnectMode !== ReconnectMode.Never,\n\t\t\t0x278 /* \"API is not supported for non-connecting or closed container\" */,\n\t\t);\n\n\t\tthis._reconnectMode = mode;\n\n\t\tif (mode !== ReconnectMode.Enabled) {\n\t\t\t// immediately disconnect - do not rely on service eventually dropping connection.\n\t\t\tthis.disconnectFromDeltaStream(\"setAutoReconnect\");\n\t\t}\n\t}\n\n\t/**\n\t * Sends signal to runtime (and data stores) to be read-only.\n\t * Hosts may have read only views, indicating to data stores that no edits are allowed.\n\t * This is independent from this._readonlyPermissions (permissions) and this.connectionMode\n\t * (server can return \"write\" mode even when asked for \"read\")\n\t * Leveraging same \"readonly\" event as runtime & data stores should behave the same in such case\n\t * as in read-only permissions.\n\t * But this.active can be used by some DDSes to figure out if ops can be sent\n\t * (for example, read-only view still participates in code proposals / upgrades decisions)\n\t *\n\t * Forcing Readonly does not prevent DDS from generating ops. It is up to user code to honour\n\t * the readonly flag. If ops are generated, they will accumulate locally and not be sent. If\n\t * there are pending in the outbound queue, it will stop sending until force readonly is\n\t * cleared.\n\t *\n\t * @param readonly - set or clear force readonly.\n\t */\n\tpublic forceReadonly(readonly: boolean) {\n\t\tif (readonly !== this._forceReadonly) {\n\t\t\tthis.logger.sendTelemetryEvent({\n\t\t\t\teventName: \"ForceReadOnly\",\n\t\t\t\tvalue: readonly,\n\t\t\t});\n\t\t}\n\t\tconst oldValue = this.readonly;\n\t\tthis._forceReadonly = readonly;\n\n\t\tif (oldValue !== this.readonly) {\n\t\t\tif (this._reconnectMode === ReconnectMode.Never) {\n\t\t\t\tthrow new UsageError(\"API is not supported for non-connecting or closed container\");\n\t\t\t}\n\t\t\tlet reconnect = false;\n\t\t\tif (this.readonly === true) {\n\t\t\t\t// If we switch to readonly while connected, we should disconnect first\n\t\t\t\t// See comment in the \"readonly\" event handler to deltaManager set up by\n\t\t\t\t// the ContainerRuntime constructor\n\n\t\t\t\tif (this.shouldJoinWrite()) {\n\t\t\t\t\t// If we have pending changes, then we will never send them - it smells like\n\t\t\t\t\t// host logic error.\n\t\t\t\t\tthis.logger.sendErrorEvent({ eventName: \"ForceReadonlyPendingChanged\" });\n\t\t\t\t}\n\n\t\t\t\treconnect = this.disconnectFromDeltaStream(\"Force readonly\");\n\t\t\t}\n\t\t\tthis.props.readonlyChangeHandler(this.readonly);\n\t\t\tif (reconnect) {\n\t\t\t\t// reconnect if we disconnected from before.\n\t\t\t\tthis.triggerConnect(\"read\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate set_readonlyPermissions(readonly: boolean) {\n\t\tconst oldValue = this.readonly;\n\t\tthis._readonlyPermissions = readonly;\n\t\tif (oldValue !== this.readonly) {\n\t\t\tthis.props.readonlyChangeHandler(this.readonly);\n\t\t}\n\t}\n\n\tpublic connect(connectionMode?: ConnectionMode) {\n\t\tthis.connectCore(connectionMode).catch((error) => {\n\t\t\tconst normalizedError = normalizeError(error, { props: fatalConnectErrorProp });\n\t\t\tthis.props.closeHandler(normalizedError);\n\t\t});\n\t}\n\n\tprivate async connectCore(connectionMode?: ConnectionMode): Promise<void> {\n\t\tassert(!this._disposed, 0x26a /* \"not closed\" */);\n\n\t\tif (this.connection !== undefined) {\n\t\t\treturn; // Connection attempt already completed successfully\n\t\t}\n\n\t\tlet pendingConnectionMode;\n\t\tif (this.pendingConnection !== undefined) {\n\t\t\tpendingConnectionMode = this.pendingConnection.connectionMode;\n\t\t\tthis.cancelConnection(); // Throw out in-progress connection attempt in favor of new attempt\n\t\t\tassert(\n\t\t\t\tthis.pendingConnection === undefined,\n\t\t\t\t0x344 /* this.pendingConnection should be undefined */,\n\t\t\t);\n\t\t}\n\t\t// If there is no specified ConnectionMode, try the previous mode, if there is no previous mode use default\n\t\tlet requestedMode = connectionMode ?? pendingConnectionMode ?? this.defaultReconnectionMode;\n\n\t\t// if we have any non-acked ops from last connection, reconnect as \"write\".\n\t\t// without that we would connect in view-only mode, which will result in immediate\n\t\t// firing of \"connected\" event from Container and switch of current clientId (as tracked\n\t\t// by all DDSes). This will make it impossible to figure out if ops actually made it through,\n\t\t// so DDSes will immediately resubmit all pending ops, and some of them will be duplicates, corrupting document\n\t\tif (this.shouldJoinWrite()) {\n\t\t\trequestedMode = \"write\";\n\t\t}\n\n\t\tconst docService = this.serviceProvider();\n\t\tassert(docService !== undefined, 0x2a7 /* \"Container is not attached\" */);\n\n\t\tlet connection: IDocumentDeltaConnection | undefined;\n\n\t\tif (docService.policies?.storageOnly === true) {\n\t\t\tconnection = new NoDeltaStream();\n\t\t\tthis.setupNewSuccessfulConnection(connection, \"read\");\n\t\t\tassert(this.pendingConnection === undefined, 0x2b3 /* \"logic error\" */);\n\t\t\treturn;\n\t\t}\n\n\t\tlet delayMs = InitialReconnectDelayInMs;\n\t\tlet connectRepeatCount = 0;\n\t\tconst connectStartTime = performance.now();\n\t\tlet lastError: any;\n\n\t\tconst abortController = new AbortController();\n\t\tconst abortSignal = abortController.signal;\n\t\tthis.pendingConnection = {\n\t\t\tabort: () => {\n\t\t\t\tabortController.abort();\n\t\t\t},\n\t\t\tconnectionMode: requestedMode,\n\t\t};\n\n\t\t// This loop will keep trying to connect until successful, with a delay between each iteration.\n\t\twhile (connection === undefined) {\n\t\t\tif (this._disposed) {\n\t\t\t\tthrow new Error(\"Attempting to connect a closed DeltaManager\");\n\t\t\t}\n\t\t\tif (abortSignal.aborted === true) {\n\t\t\t\tthis.logger.sendTelemetryEvent({\n\t\t\t\t\teventName: \"ConnectionAttemptCancelled\",\n\t\t\t\t\tattempts: connectRepeatCount,\n\t\t\t\t\tduration: TelemetryLogger.formatTick(performance.now() - connectStartTime),\n\t\t\t\t\tconnectionEstablished: false,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconnectRepeatCount++;\n\n\t\t\ttry {\n\t\t\t\tthis.client.mode = requestedMode;\n\t\t\t\tconnection = await docService.connectToDeltaStream({\n\t\t\t\t\t...this.client,\n\t\t\t\t\tmode: requestedMode,\n\t\t\t\t});\n\n\t\t\t\tif (connection.disposed) {\n\t\t\t\t\t// Nobody observed this connection, so drop it on the floor and retry.\n\t\t\t\t\tthis.logger.sendTelemetryEvent({ eventName: \"ReceivedClosedConnection\" });\n\t\t\t\t\tconnection = undefined;\n\t\t\t\t}\n\t\t\t} catch (origError: any) {\n\t\t\t\tif (\n\t\t\t\t\ttypeof origError === \"object\" &&\n\t\t\t\t\torigError !== null &&\n\t\t\t\t\torigError?.errorType === DeltaStreamConnectionForbiddenError.errorType\n\t\t\t\t) {\n\t\t\t\t\tconnection = new NoDeltaStream();\n\t\t\t\t\trequestedMode = \"read\";\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t// Socket.io error when we connect to wrong socket, or hit some multiplexing bug\n\t\t\t\tif (!canRetryOnError(origError)) {\n\t\t\t\t\tconst error = normalizeError(origError, { props: fatalConnectErrorProp });\n\t\t\t\t\tthis.props.closeHandler(error);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\n\t\t\t\t// Since the error is retryable this will not log to the error table\n\t\t\t\tlogNetworkFailure(\n\t\t\t\t\tthis.logger,\n\t\t\t\t\t{\n\t\t\t\t\t\tattempts: connectRepeatCount,\n\t\t\t\t\t\tdelay: delayMs, // milliseconds\n\t\t\t\t\t\teventName: \"DeltaConnectionFailureToConnect\",\n\t\t\t\t\t\tduration: TelemetryLogger.formatTick(performance.now() - connectStartTime),\n\t\t\t\t\t},\n\t\t\t\t\torigError,\n\t\t\t\t);\n\n\t\t\t\tlastError = origError;\n\n\t\t\t\tconst retryDelayFromError = getRetryDelayFromError(origError);\n\t\t\t\tdelayMs = retryDelayFromError ?? Math.min(delayMs * 2, MaxReconnectDelayInMs);\n\n\t\t\t\tif (retryDelayFromError !== undefined) {\n\t\t\t\t\tthis.props.reconnectionDelayHandler(retryDelayFromError, origError);\n\t\t\t\t}\n\t\t\t\tawait waitForConnectedState(delayMs);\n\t\t\t}\n\t\t}\n\n\t\t// If we retried more than once, log an event about how long it took (this will not log to error table)\n\t\tif (connectRepeatCount > 1) {\n\t\t\tlogNetworkFailure(\n\t\t\t\tthis.logger,\n\t\t\t\t{\n\t\t\t\t\teventName: \"MultipleDeltaConnectionFailures\",\n\t\t\t\t\tattempts: connectRepeatCount,\n\t\t\t\t\tduration: TelemetryLogger.formatTick(performance.now() - connectStartTime),\n\t\t\t\t},\n\t\t\t\tlastError,\n\t\t\t);\n\t\t}\n\n\t\t// Check for abort signal after while loop as well\n\t\tif (abortSignal.aborted === true) {\n\t\t\tconnection.dispose();\n\t\t\tthis.logger.sendTelemetryEvent({\n\t\t\t\teventName: \"ConnectionAttemptCancelled\",\n\t\t\t\tattempts: connectRepeatCount,\n\t\t\t\tduration: TelemetryLogger.formatTick(performance.now() - connectStartTime),\n\t\t\t\tconnectionEstablished: true,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tthis.setupNewSuccessfulConnection(connection, requestedMode);\n\t}\n\n\t/**\n\t * Start the connection. Any error should result in container being closed.\n\t * And report the error if it escapes for any reason.\n\t * @param args - The connection arguments\n\t */\n\tprivate triggerConnect(connectionMode: ConnectionMode) {\n\t\t// reconnect() has async await of waitForConnectedState(), and that causes potential race conditions\n\t\t// where we might already have a connection. If it were to happen, it's possible that we will connect\n\t\t// with different mode to `connectionMode`. Glancing through the caller chains, it looks like code should be\n\t\t// fine (if needed, reconnect flow will get triggered again). Places where new mode matters should encode it\n\t\t// directly in connectCore - see this.shouldJoinWrite() test as an example.\n\t\t// assert(this.connection === undefined, 0x239 /* \"called only in disconnected state\" */);\n\n\t\tif (this.reconnectMode !== ReconnectMode.Enabled) {\n\t\t\treturn;\n\t\t}\n\t\tthis.connect(connectionMode);\n\t}\n\n\t/**\n\t * Disconnect the current connection.\n\t * @param reason - Text description of disconnect reason to emit with disconnect event\n\t * @returns A boolean that indicates if there was an existing connection (or pending connection) to disconnect\n\t */\n\tprivate disconnectFromDeltaStream(reason: string): boolean {\n\t\tthis.pendingReconnect = false;\n\n\t\tif (this.connection === undefined) {\n\t\t\tif (this.pendingConnection !== undefined) {\n\t\t\t\tthis.cancelConnection();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tassert(\n\t\t\tthis.pendingConnection === undefined,\n\t\t\t0x27b /* \"reentrancy may result in incorrect behavior\" */,\n\t\t);\n\n\t\tconst connection = this.connection;\n\t\t// Avoid any re-entrancy - clear object reference\n\t\tthis.connection = undefined;\n\n\t\t// Remove listeners first so we don't try to retrigger this flow accidentally through reconnectOnError\n\t\tconnection.off(\"op\", this.opHandler);\n\t\tconnection.off(\"signal\", this.props.signalHandler);\n\t\tconnection.off(\"nack\", this.nackHandler);\n\t\tconnection.off(\"disconnect\", this.disconnectHandlerInternal);\n\t\tconnection.off(\"error\", this.errorHandler);\n\t\tconnection.off(\"pong\", this.props.pongHandler);\n\n\t\t// eslint-disable-next-line @typescript-eslint/no-floating-promises\n\t\tthis._outbound.pause();\n\t\tthis._outbound.clear();\n\t\tthis.props.disconnectHandler(reason);\n\n\t\tconnection.dispose();\n\n\t\tthis._connectionVerboseProps = {};\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Cancel in-progress connection attempt.\n\t */\n\tprivate cancelConnection() {\n\t\tassert(\n\t\t\tthis.pendingConnection !== undefined,\n\t\t\t0x345 /* this.pendingConnection is undefined when trying to cancel */,\n\t\t);\n\t\tthis.pendingConnection.abort();\n\t\tthis.pendingConnection = undefined;\n\t\tthis.logger.sendTelemetryEvent({ eventName: \"ConnectionCancelReceived\" });\n\t}\n\n\t/**\n\t * Once we've successfully gotten a connection, we need to set up state, attach event listeners, and process\n\t * initial messages.\n\t * @param connection - The newly established connection\n\t */\n\tprivate setupNewSuccessfulConnection(\n\t\tconnection: IDocumentDeltaConnection,\n\t\trequestedMode: ConnectionMode,\n\t) {\n\t\t// Old connection should have been cleaned up before establishing a new one\n\t\tassert(\n\t\t\tthis.connection === undefined,\n\t\t\t0x0e6 /* \"old connection exists on new connection setup\" */,\n\t\t);\n\t\tassert(\n\t\t\t!connection.disposed,\n\t\t\t0x28a /* \"can't be disposed - Callers need to ensure that!\" */,\n\t\t);\n\n\t\tthis.pendingConnection = undefined;\n\n\t\tthis.connection = connection;\n\n\t\t// Does information in scopes & mode matches?\n\t\t// If we asked for \"write\" and got \"read\", then file is read-only\n\t\t// But if we ask read, server can still give us write.\n\t\tconst readonly = !connection.claims.scopes.includes(ScopeType.DocWrite);\n\n\t\tif (connection.mode !== requestedMode) {\n\t\t\tthis.logger.sendTelemetryEvent({\n\t\t\t\teventName: \"ConnectionModeMismatch\",\n\t\t\t\trequestedMode,\n\t\t\t\tmode: connection.mode,\n\t\t\t});\n\t\t}\n\t\t// This connection mode validation logic is moving to the driver layer in 0.44. These two asserts can be\n\t\t// removed after those packages have released and become ubiquitous.\n\t\tassert(\n\t\t\trequestedMode === \"read\" || readonly === (this.connectionMode === \"read\"),\n\t\t\t0x0e7 /* \"claims/connectionMode mismatch\" */,\n\t\t);\n\t\tassert(\n\t\t\t!readonly || this.connectionMode === \"read\",\n\t\t\t0x0e8 /* \"readonly perf with write connection\" */,\n\t\t);\n\n\t\tthis.set_readonlyPermissions(readonly);\n\n\t\tif (this._disposed) {\n\t\t\t// Raise proper events, Log telemetry event and close connection.\n\t\t\tthis.disconnectFromDeltaStream(\"ConnectionManager already closed\");\n\t\t\treturn;\n\t\t}\n\n\t\tthis._outbound.resume();\n\n\t\tconnection.on(\"op\", this.opHandler);\n\t\tconnection.on(\"signal\", this.props.signalHandler);\n\t\tconnection.on(\"nack\", this.nackHandler);\n\t\tconnection.on(\"disconnect\", this.disconnectHandlerInternal);\n\t\tconnection.on(\"error\", this.errorHandler);\n\t\tconnection.on(\"pong\", this.props.pongHandler);\n\n\t\t// Initial messages are always sorted. However, due to early op handler installed by drivers and appending those\n\t\t// ops to initialMessages, resulting set is no longer sorted, which would result in client hitting storage to\n\t\t// fill in gap. We will recover by cancelling this request once we process remaining ops, but it's a waste that\n\t\t// we could avoid\n\t\tconst initialMessages = connection.initialMessages.sort(\n\t\t\t(a, b) => a.sequenceNumber - b.sequenceNumber,\n\t\t);\n\n\t\t// Some storages may provide checkpointSequenceNumber to identify how far client is behind.\n\t\tlet checkpointSequenceNumber = connection.checkpointSequenceNumber;\n\n\t\tthis._connectionVerboseProps = {\n\t\t\tclientId: connection.clientId,\n\t\t\tmode: connection.mode,\n\t\t};\n\n\t\t// reset connection props\n\t\tthis._connectionProps = {};\n\n\t\tif (connection.relayServiceAgent !== undefined) {\n\t\t\tthis._connectionVerboseProps.relayServiceAgent = connection.relayServiceAgent;\n\t\t\tthis._connectionProps.relayServiceAgent = connection.relayServiceAgent;\n\t\t}\n\t\tthis._connectionProps.socketDocumentId = connection.claims.documentId;\n\t\tthis._connectionProps.connectionMode = connection.mode;\n\n\t\tlet last = -1;\n\t\tif (initialMessages.length !== 0) {\n\t\t\tthis._connectionVerboseProps.connectionInitialOpsFrom =\n\t\t\t\tinitialMessages[0].sequenceNumber;\n\t\t\tlast = initialMessages[initialMessages.length - 1].sequenceNumber;\n\t\t\tthis._connectionVerboseProps.connectionInitialOpsTo = last + 1;\n\t\t\t// Update knowledge of how far we are behind, before raising \"connect\" event\n\t\t\t// This is duplication of what incomingOpHandler() does, but we have to raise event before we get there,\n\t\t\t// so duplicating update logic here as well.\n\t\t\tif (checkpointSequenceNumber === undefined || checkpointSequenceNumber < last) {\n\t\t\t\tcheckpointSequenceNumber = last;\n\t\t\t}\n\t\t}\n\n\t\tthis.props.incomingOpHandler(\n\t\t\tinitialMessages,\n\t\t\tthis.connectFirstConnection ? \"InitialOps\" : \"ReconnectOps\",\n\t\t);\n\n\t\tconst details = ConnectionManager.detailsFromConnection(connection);\n\t\tdetails.checkpointSequenceNumber = checkpointSequenceNumber;\n\t\tthis.props.connectHandler(details);\n\n\t\tthis.connectFirstConnection = false;\n\n\t\t// Synthesize clear & join signals out of initialClients state.\n\t\t// This allows us to have single way to process signals, and makes it simpler to initialize\n\t\t// protocol in Container.\n\t\tconst clearSignal: ISignalMessage = {\n\t\t\tclientId: null, // system message\n\t\t\tcontent: JSON.stringify({\n\t\t\t\ttype: SignalType.Clear,\n\t\t\t}),\n\t\t};\n\t\tthis.props.signalHandler(clearSignal);\n\n\t\tfor (const priorClient of connection.initialClients ?? []) {\n\t\t\tconst joinSignal: ISignalMessage = {\n\t\t\t\tclientId: null, // system signal\n\t\t\t\tcontent: JSON.stringify({\n\t\t\t\t\ttype: SignalType.ClientJoin,\n\t\t\t\t\tcontent: priorClient, // ISignalClient\n\t\t\t\t}),\n\t\t\t};\n\t\t\tthis.props.signalHandler(joinSignal);\n\t\t}\n\n\t\t// Unfortunately, there is no defined order between initialSignals (including join & leave signals)\n\t\t// and connection.initialClients. In practice, connection.initialSignals quite often contains join signal\n\t\t// for \"self\" and connection.initialClients does not contain \"self\", so we have to process them after\n\t\t// \"clear\" signal above.\n\t\tif (connection.initialSignals !== undefined) {\n\t\t\tfor (const signal of connection.initialSignals) {\n\t\t\t\tthis.props.signalHandler(signal);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Disconnect the current connection and reconnect. Closes the container if it fails.\n\t * @param connection - The connection that wants to reconnect - no-op if it's different from this.connection\n\t * @param requestedMode - Read or write\n\t * @param error - Error reconnect information including whether or not to reconnect\n\t * @returns A promise that resolves when the connection is reestablished or we stop trying\n\t */\n\tprivate reconnectOnError(requestedMode: ConnectionMode, error: IAnyDriverError) {\n\t\tthis.reconnect(requestedMode, error.message, error).catch(this.props.closeHandler);\n\t}\n\n\t/**\n\t * Disconnect the current connection and reconnect.\n\t * @param connection - The connection that wants to reconnect - no-op if it's different from this.connection\n\t * @param requestedMode - Read or write\n\t * @param error - Error reconnect information including whether or not to reconnect\n\t * @returns A promise that resolves when the connection is reestablished or we stop trying\n\t */\n\tprivate async reconnect(\n\t\trequestedMode: ConnectionMode,\n\t\tdisconnectMessage: string,\n\t\terror?: IAnyDriverError,\n\t) {\n\t\t// We quite often get protocol errors before / after observing nack/disconnect\n\t\t// we do not want to run through same sequence twice.\n\t\t// If we're already disconnected/disconnecting it's not appropriate to call this again.\n\t\tassert(this.connection !== undefined, 0x0eb /* \"Missing connection for reconnect\" */);\n\n\t\tthis.disconnectFromDeltaStream(disconnectMessage);\n\n\t\t// We will always trigger reconnect, even if canRetry is false.\n\t\t// Any truly fatal error state will result in container close upon attempted reconnect,\n\t\t// which is a preferable to closing abruptly when a live connection fails.\n\t\tif (error !== undefined && !error.canRetry) {\n\t\t\tthis.logger.sendTelemetryEvent(\n\t\t\t\t{\n\t\t\t\t\teventName: \"reconnectingDespiteFatalError\",\n\t\t\t\t\treconnectMode: this.reconnectMode,\n\t\t\t\t},\n\t\t\t\terror,\n\t\t\t);\n\t\t}\n\n\t\tif (this.reconnectMode === ReconnectMode.Never) {\n\t\t\t// Do not raise container error if we are closing just because we lost connection.\n\t\t\t// Those errors (like IdleDisconnect) would show up in telemetry dashboards and\n\t\t\t// are very misleading, as first initial reaction - some logic is broken.\n\t\t\tthis.props.closeHandler();\n\t\t}\n\n\t\t// If closed then we can't reconnect\n\t\tif (this._disposed || this.reconnectMode !== ReconnectMode.Enabled) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst delayMs = getRetryDelayFromError(error);\n\t\tif (error !== undefined && delayMs !== undefined) {\n\t\t\tthis.props.reconnectionDelayHandler(delayMs, error);\n\t\t\tawait waitForConnectedState(delayMs);\n\t\t}\n\n\t\tthis.triggerConnect(requestedMode);\n\t}\n\n\tpublic prepareMessageToSend(\n\t\tmessage: Omit<IDocumentMessage, \"clientSequenceNumber\">,\n\t): IDocumentMessage | undefined {\n\t\tif (this.readonly === true) {\n\t\t\tassert(\n\t\t\t\tthis.readOnlyInfo.readonly === true,\n\t\t\t\t0x1f0 /* \"Unexpected mismatch in readonly\" */,\n\t\t\t);\n\t\t\tconst error = new GenericError(\"deltaManagerReadonlySubmit\", undefined /* error */, {\n\t\t\t\treadonly: this.readOnlyInfo.readonly,\n\t\t\t\tforcedReadonly: this.readOnlyInfo.forced,\n\t\t\t\treadonlyPermissions: this.readOnlyInfo.permissions,\n\t\t\t\tstorageOnly: this.readOnlyInfo.storageOnly,\n\t\t\t});\n\t\t\tthis.props.closeHandler(error);\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// reset clientSequenceNumber if we are using new clientId.\n\t\t// we keep info about old connection as long as possible to be able to account for all non-acked ops\n\t\t// that we pick up on next connection.\n\t\tassert(!!this.connection, 0x0e4 /* \"Lost old connection!\" */);\n\t\tif (this.lastSubmittedClientId !== this.connection?.clientId) {\n\t\t\tthis.lastSubmittedClientId = this.connection?.clientId;\n\t\t\tthis.clientSequenceNumber = 0;\n\t\t\tthis.clientSequenceNumberObserved = 0;\n\t\t}\n\n\t\tif (!isRuntimeMessage(message)) {\n\t\t\tthis.localOpsToIgnore++;\n\t\t} else {\n\t\t\tthis.localOpsToIgnore = 0;\n\t\t}\n\n\t\treturn {\n\t\t\t...message,\n\t\t\tclientSequenceNumber: ++this.clientSequenceNumber,\n\t\t};\n\t}\n\n\tpublic submitSignal(content: any) {\n\t\tif (this.connection !== undefined) {\n\t\t\tthis.connection.submitSignal(content);\n\t\t} else {\n\t\t\tthis.logger.sendErrorEvent({ eventName: \"submitSignalDisconnected\" });\n\t\t}\n\t}\n\n\tpublic sendMessages(messages: IDocumentMessage[]) {\n\t\tassert(this.connected, 0x2b4 /* \"not connected on sending ops!\" */);\n\t\t// If connection is \"read\" or implicit \"read\" (got leave op for \"write\" connection),\n\t\t// then op can't make it through - we will get a nack if op is sent.\n\t\t// We can short-circuit this process.\n\t\t// Note that we also want nacks to be rare and be treated as catastrophic failures.\n\t\t// Be careful with reentrancy though - disconnected event should not be be raised in the\n\t\t// middle of the current workflow, but rather on clean stack!\n\t\tif (this.connectionMode === \"read\") {\n\t\t\tif (!this.pendingReconnect) {\n\t\t\t\tthis.pendingReconnect = true;\n\t\t\t\tPromise.resolve()\n\t\t\t\t\t.then(async () => {\n\t\t\t\t\t\tif (this.pendingReconnect) {\n\t\t\t\t\t\t\t// still valid?\n\t\t\t\t\t\t\tawait this.reconnect(\n\t\t\t\t\t\t\t\t\"write\", // connectionMode\n\t\t\t\t\t\t\t\t\"Switch to write\", // message\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.catch(() => {});\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tassert(!this.pendingReconnect, 0x2b5 /* \"logic error\" */);\n\n\t\tthis._outbound.push(messages);\n\t}\n\n\tpublic beforeProcessingIncomingOp(message: ISequencedDocumentMessage) {\n\t\t// if we have connection, and message is local, then we better treat is as local!\n\t\tassert(\n\t\t\tthis.clientId !== message.clientId || this.lastSubmittedClientId === message.clientId,\n\t\t\t0x0ee /* \"Not accounting local messages correctly\" */,\n\t\t);\n\n\t\tif (\n\t\t\tthis.lastSubmittedClientId !== undefined &&\n\t\t\tthis.lastSubmittedClientId === message.clientId\n\t\t) {\n\t\t\tconst clientSequenceNumber = message.clientSequenceNumber;\n\n\t\t\tassert(\n\t\t\t\tthis.clientSequenceNumberObserved < clientSequenceNumber,\n\t\t\t\t0x0ef /* \"client seq# not growing\" */,\n\t\t\t);\n\t\t\tassert(\n\t\t\t\tclientSequenceNumber <= this.clientSequenceNumber,\n\t\t\t\t0x0f0 /* \"Incoming local client seq# > generated by this client\" */,\n\t\t\t);\n\n\t\t\tthis.clientSequenceNumberObserved = clientSequenceNumber;\n\t\t}\n\n\t\tif (message.type === MessageType.ClientLeave) {\n\t\t\tconst systemLeaveMessage = message as ISequencedDocumentSystemMessage;\n\t\t\tconst clientId = JSON.parse(systemLeaveMessage.data) as string;\n\t\t\tif (clientId === this.clientId) {\n\t\t\t\t// We have been kicked out from quorum\n\t\t\t\tthis.logger.sendPerformanceEvent({ eventName: \"ReadConnectionTransition\" });\n\n\t\t\t\t// Please see #8483 for more details on why maintaining connection further as is would not work.\n\t\t\t\t// Short story - connection properties are immutable, and many processes (consensus DDSes, summarizer)\n\t\t\t\t// assume that connection stays \"write\" connection until disconnect, and act accordingly, which may\n\t\t\t\t// not work well with de-facto \"read\" connection we are in after receiving own leave op on timeout.\n\t\t\t\t// Clients need to be able to transition to \"read\" state after some time of inactivity!\n\t\t\t\t// Note - this may close container!\n\t\t\t\tthis.reconnect(\n\t\t\t\t\t\"read\", // connectionMode\n\t\t\t\t\t\"Switch to read\", // message\n\t\t\t\t).catch((error) => {\n\t\t\t\t\tthis.logger.sendErrorEvent({ eventName: \"SwitchToReadConnection\" }, error);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate readonly opHandler = (documentId: string, messagesArg: ISequencedDocumentMessage[]) => {\n\t\tconst messages = Array.isArray(messagesArg) ? messagesArg : [messagesArg];\n\t\tthis.props.incomingOpHandler(messages, \"opHandler\");\n\t};\n\n\t// Always connect in write mode after getting nacked.\n\tprivate readonly nackHandler = (documentId: string, messages: INack[]) => {\n\t\tconst message = messages[0];\n\t\tif (this._readonlyPermissions === true) {\n\t\t\tthis.props.closeHandler(\n\t\t\t\tcreateWriteError(\"writeOnReadOnlyDocument\", { driverVersion: undefined }),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst reconnectInfo = getNackReconnectInfo(message.content);\n\n\t\t// If the nack indicates we cannot retry, then close the container outright\n\t\tif (!reconnectInfo.canRetry) {\n\t\t\tthis.props.closeHandler(reconnectInfo);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.reconnectOnError(\"write\", reconnectInfo);\n\t};\n\n\t// Connection mode is always read on disconnect/error unless the system mode was write.\n\tprivate readonly disconnectHandlerInternal = (disconnectReason: IAnyDriverError) => {\n\t\t// Note: we might get multiple disconnect calls on same socket, as early disconnect notification\n\t\t// (\"server_disconnect\", ODSP-specific) is mapped to \"disconnect\"\n\t\tthis.reconnectOnError(this.defaultReconnectionMode, disconnectReason);\n\t};\n\n\tprivate readonly errorHandler = (error: IAnyDriverError) => {\n\t\tthis.reconnectOnError(this.defaultReconnectionMode, error);\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"connectionState.d.ts","sourceRoot":"","sources":["../src/connectionState.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,oBAAY,eAAe;IACvB;;;;OAIG;IACH,YAAY,IAAI;IAEhB;;;OAGG;IACH,sBAAsB,IAAI;IAE1B;;OAEG;IACH,UAAU,IAAI;IAEd;;OAEG;IACH,SAAS,IAAI;CAChB"}
1
+ {"version":3,"file":"connectionState.d.ts","sourceRoot":"","sources":["../src/connectionState.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,oBAAY,eAAe;IAC1B;;;;OAIG;IACH,YAAY,IAAI;IAEhB;;;OAGG;IACH,sBAAsB,IAAI;IAE1B;;OAEG;IACH,UAAU,IAAI;IAEd;;OAEG;IACH,SAAS,IAAI;CACb"}
@@ -1 +1 @@
1
- {"version":3,"file":"connectionState.js","sourceRoot":"","sources":["../src/connectionState.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,CAAN,IAAY,eAuBX;AAvBD,WAAY,eAAe;IACvB;;;;OAIG;IACH,qEAAgB,CAAA;IAEhB;;;OAGG;IACH,yFAA0B,CAAA;IAE1B;;OAEG;IACH,iEAAc,CAAA;IAEd;;OAEG;IACH,+DAAa,CAAA;AACjB,CAAC,EAvBW,eAAe,KAAf,eAAe,QAuB1B","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nexport enum ConnectionState {\n /**\n * The container is not connected to the ordering service\n * Note - When in this state the container may be about to reconnect,\n * or may remain disconnected until explicitly told to connect.\n */\n Disconnected = 0,\n\n /**\n * The container is disconnected but actively trying to establish a new connection\n * PLEASE NOTE that this numerical value falls out of the order you may expect for this state\n */\n EstablishingConnection = 3,\n\n /**\n * The container has an inbound connection only, and is catching up to the latest known state from the service.\n */\n CatchingUp = 1,\n\n /**\n * The container is fully connected and syncing\n */\n Connected = 2,\n}\n"]}
1
+ {"version":3,"file":"connectionState.js","sourceRoot":"","sources":["../src/connectionState.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,CAAN,IAAY,eAuBX;AAvBD,WAAY,eAAe;IAC1B;;;;OAIG;IACH,qEAAgB,CAAA;IAEhB;;;OAGG;IACH,yFAA0B,CAAA;IAE1B;;OAEG;IACH,iEAAc,CAAA;IAEd;;OAEG;IACH,+DAAa,CAAA;AACd,CAAC,EAvBW,eAAe,KAAf,eAAe,QAuB1B","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nexport enum ConnectionState {\n\t/**\n\t * The container is not connected to the ordering service\n\t * Note - When in this state the container may be about to reconnect,\n\t * or may remain disconnected until explicitly told to connect.\n\t */\n\tDisconnected = 0,\n\n\t/**\n\t * The container is disconnected but actively trying to establish a new connection\n\t * PLEASE NOTE that this numerical value falls out of the order you may expect for this state\n\t */\n\tEstablishingConnection = 3,\n\n\t/**\n\t * The container has an inbound connection only, and is catching up to the latest known state from the service.\n\t */\n\tCatchingUp = 1,\n\n\t/**\n\t * The container is fully connected and syncing\n\t */\n\tConnected = 2,\n}\n"]}