@fluidframework/container-loader 1.4.0-121020 → 2.0.0-dev-rc.1.0.0.225277

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 (335) hide show
  1. package/.eslintrc.js +18 -21
  2. package/.mocharc.js +12 -0
  3. package/CHANGELOG.md +364 -0
  4. package/README.md +152 -56
  5. package/api-extractor-esm.json +4 -0
  6. package/api-extractor-lint.json +4 -0
  7. package/api-extractor.json +2 -2
  8. package/api-report/container-loader.api.md +143 -0
  9. package/dist/{audience.js → audience.cjs} +15 -13
  10. package/dist/audience.cjs.map +1 -0
  11. package/dist/audience.d.ts +4 -6
  12. package/dist/audience.d.ts.map +1 -1
  13. package/dist/catchUpMonitor.cjs +43 -0
  14. package/dist/catchUpMonitor.cjs.map +1 -0
  15. package/dist/catchUpMonitor.d.ts +29 -0
  16. package/dist/catchUpMonitor.d.ts.map +1 -0
  17. package/dist/{connectionManager.js → connectionManager.cjs} +397 -240
  18. package/dist/connectionManager.cjs.map +1 -0
  19. package/dist/connectionManager.d.ts +23 -33
  20. package/dist/connectionManager.d.ts.map +1 -1
  21. package/dist/{connectionState.js → connectionState.cjs} +5 -7
  22. package/dist/connectionState.cjs.map +1 -0
  23. package/dist/connectionState.d.ts +3 -5
  24. package/dist/connectionState.d.ts.map +1 -1
  25. package/dist/connectionStateHandler.cjs +474 -0
  26. package/dist/connectionStateHandler.cjs.map +1 -0
  27. package/dist/connectionStateHandler.d.ts +127 -29
  28. package/dist/connectionStateHandler.d.ts.map +1 -1
  29. package/dist/container-loader-alpha.d.ts +274 -0
  30. package/dist/container-loader-beta.d.ts +75 -0
  31. package/dist/container-loader-public.d.ts +75 -0
  32. package/dist/container-loader-untrimmed.d.ts +331 -0
  33. package/dist/container.cjs +1585 -0
  34. package/dist/container.cjs.map +1 -0
  35. package/dist/container.d.ts +227 -83
  36. package/dist/container.d.ts.map +1 -1
  37. package/dist/containerContext.cjs +74 -0
  38. package/dist/containerContext.cjs.map +1 -0
  39. package/dist/containerContext.d.ts +33 -59
  40. package/dist/containerContext.d.ts.map +1 -1
  41. package/dist/containerStorageAdapter.cjs +234 -0
  42. package/dist/containerStorageAdapter.cjs.map +1 -0
  43. package/dist/containerStorageAdapter.d.ts +48 -23
  44. package/dist/containerStorageAdapter.d.ts.map +1 -1
  45. package/dist/{contracts.js → contracts.cjs} +5 -5
  46. package/dist/contracts.cjs.map +1 -0
  47. package/dist/contracts.d.ts +45 -17
  48. package/dist/contracts.d.ts.map +1 -1
  49. package/dist/debugLogger.cjs +101 -0
  50. package/dist/debugLogger.cjs.map +1 -0
  51. package/dist/debugLogger.d.ts +30 -0
  52. package/dist/debugLogger.d.ts.map +1 -0
  53. package/dist/{deltaManager.js → deltaManager.cjs} +379 -186
  54. package/dist/deltaManager.cjs.map +1 -0
  55. package/dist/deltaManager.d.ts +54 -18
  56. package/dist/deltaManager.d.ts.map +1 -1
  57. package/dist/{deltaQueue.js → deltaQueue.cjs} +29 -28
  58. package/dist/deltaQueue.cjs.map +1 -0
  59. package/dist/deltaQueue.d.ts +3 -4
  60. package/dist/deltaQueue.d.ts.map +1 -1
  61. package/dist/disposal.cjs +25 -0
  62. package/dist/disposal.cjs.map +1 -0
  63. package/dist/disposal.d.ts +13 -0
  64. package/dist/disposal.d.ts.map +1 -0
  65. package/dist/error.cjs +32 -0
  66. package/dist/error.cjs.map +1 -0
  67. package/dist/error.d.ts +23 -0
  68. package/dist/error.d.ts.map +1 -0
  69. package/dist/index.cjs +19 -0
  70. package/dist/index.cjs.map +1 -0
  71. package/dist/index.d.ts +5 -2
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/loader.cjs +148 -0
  74. package/dist/loader.cjs.map +1 -0
  75. package/dist/loader.d.ts +38 -19
  76. package/dist/loader.d.ts.map +1 -1
  77. package/dist/location-redirection-utilities/index.cjs +11 -0
  78. package/dist/location-redirection-utilities/index.cjs.map +1 -0
  79. package/dist/location-redirection-utilities/index.d.ts +6 -0
  80. package/dist/location-redirection-utilities/index.d.ts.map +1 -0
  81. package/dist/location-redirection-utilities/resolveWithLocationRedirection.cjs +53 -0
  82. package/dist/location-redirection-utilities/resolveWithLocationRedirection.cjs.map +1 -0
  83. package/dist/location-redirection-utilities/resolveWithLocationRedirection.d.ts +24 -0
  84. package/dist/location-redirection-utilities/resolveWithLocationRedirection.d.ts.map +1 -0
  85. package/dist/{collabWindowTracker.js → noopHeuristic.cjs} +37 -39
  86. package/dist/noopHeuristic.cjs.map +1 -0
  87. package/dist/noopHeuristic.d.ts +23 -0
  88. package/dist/noopHeuristic.d.ts.map +1 -0
  89. package/dist/{packageVersion.js → packageVersion.cjs} +2 -2
  90. package/dist/packageVersion.cjs.map +1 -0
  91. package/dist/packageVersion.d.ts +1 -1
  92. package/dist/packageVersion.d.ts.map +1 -1
  93. package/dist/protocol.cjs +99 -0
  94. package/dist/protocol.cjs.map +1 -0
  95. package/dist/protocol.d.ts +38 -0
  96. package/dist/protocol.d.ts.map +1 -0
  97. package/dist/{protocolTreeDocumentStorageService.js → protocolTreeDocumentStorageService.cjs} +8 -5
  98. package/dist/protocolTreeDocumentStorageService.cjs.map +1 -0
  99. package/dist/protocolTreeDocumentStorageService.d.ts +8 -4
  100. package/dist/protocolTreeDocumentStorageService.d.ts.map +1 -1
  101. package/dist/quorum.cjs +16 -0
  102. package/dist/quorum.cjs.map +1 -0
  103. package/dist/quorum.d.ts +1 -14
  104. package/dist/quorum.d.ts.map +1 -1
  105. package/dist/{retriableDocumentStorageService.js → retriableDocumentStorageService.cjs} +36 -21
  106. package/dist/retriableDocumentStorageService.cjs.map +1 -0
  107. package/dist/retriableDocumentStorageService.d.ts +7 -5
  108. package/dist/retriableDocumentStorageService.d.ts.map +1 -1
  109. package/dist/tsdoc-metadata.json +11 -0
  110. package/dist/{utils.js → utils.cjs} +52 -14
  111. package/dist/utils.cjs.map +1 -0
  112. package/dist/utils.d.ts +34 -1
  113. package/dist/utils.d.ts.map +1 -1
  114. package/lib/{audience.d.ts → audience.d.mts} +5 -11
  115. package/lib/audience.d.mts.map +1 -0
  116. package/lib/{audience.js → audience.mjs} +15 -17
  117. package/lib/audience.mjs.map +1 -0
  118. package/lib/catchUpMonitor.d.mts +29 -0
  119. package/lib/catchUpMonitor.d.mts.map +1 -0
  120. package/lib/catchUpMonitor.mjs +39 -0
  121. package/lib/catchUpMonitor.mjs.map +1 -0
  122. package/lib/{connectionManager.d.ts → connectionManager.d.mts} +24 -34
  123. package/lib/connectionManager.d.mts.map +1 -0
  124. package/lib/{connectionManager.js → connectionManager.mjs} +378 -218
  125. package/lib/connectionManager.mjs.map +1 -0
  126. package/lib/{connectionState.d.ts → connectionState.d.mts} +4 -6
  127. package/lib/connectionState.d.mts.map +1 -0
  128. package/lib/{connectionState.js → connectionState.mjs} +4 -6
  129. package/lib/connectionState.mjs.map +1 -0
  130. package/lib/connectionStateHandler.d.mts +179 -0
  131. package/lib/connectionStateHandler.d.mts.map +1 -0
  132. package/lib/connectionStateHandler.mjs +469 -0
  133. package/lib/connectionStateHandler.mjs.map +1 -0
  134. package/lib/container-loader-alpha.d.mts +274 -0
  135. package/lib/container-loader-beta.d.mts +75 -0
  136. package/lib/container-loader-public.d.mts +75 -0
  137. package/lib/container-loader-untrimmed.d.mts +331 -0
  138. package/lib/container.d.mts +382 -0
  139. package/lib/container.d.mts.map +1 -0
  140. package/lib/container.mjs +1579 -0
  141. package/lib/container.mjs.map +1 -0
  142. package/lib/containerContext.d.mts +58 -0
  143. package/lib/containerContext.d.mts.map +1 -0
  144. package/lib/containerContext.mjs +70 -0
  145. package/lib/containerContext.mjs.map +1 -0
  146. package/lib/containerStorageAdapter.d.mts +73 -0
  147. package/lib/containerStorageAdapter.d.mts.map +1 -0
  148. package/lib/containerStorageAdapter.mjs +228 -0
  149. package/lib/containerStorageAdapter.mjs.map +1 -0
  150. package/lib/{contracts.d.ts → contracts.d.mts} +46 -18
  151. package/lib/contracts.d.mts.map +1 -0
  152. package/lib/{contracts.js → contracts.mjs} +4 -4
  153. package/lib/contracts.mjs.map +1 -0
  154. package/lib/debugLogger.d.mts +30 -0
  155. package/lib/debugLogger.d.mts.map +1 -0
  156. package/lib/debugLogger.mjs +93 -0
  157. package/lib/debugLogger.mjs.map +1 -0
  158. package/lib/{deltaManager.d.ts → deltaManager.d.mts} +55 -19
  159. package/lib/deltaManager.d.mts.map +1 -0
  160. package/lib/{deltaManager.js → deltaManager.mjs} +361 -165
  161. package/lib/deltaManager.mjs.map +1 -0
  162. package/lib/{deltaQueue.d.ts → deltaQueue.d.mts} +4 -5
  163. package/lib/deltaQueue.d.mts.map +1 -0
  164. package/lib/{deltaQueue.js → deltaQueue.mjs} +25 -24
  165. package/lib/deltaQueue.mjs.map +1 -0
  166. package/lib/disposal.d.mts +13 -0
  167. package/lib/disposal.d.mts.map +1 -0
  168. package/lib/disposal.mjs +21 -0
  169. package/lib/disposal.mjs.map +1 -0
  170. package/lib/error.d.mts +23 -0
  171. package/lib/error.d.mts.map +1 -0
  172. package/lib/error.mjs +28 -0
  173. package/lib/error.mjs.map +1 -0
  174. package/lib/index.d.mts +11 -0
  175. package/lib/index.d.mts.map +1 -0
  176. package/lib/index.mjs +10 -0
  177. package/lib/index.mjs.map +1 -0
  178. package/lib/{loader.d.ts → loader.d.mts} +40 -21
  179. package/lib/loader.d.mts.map +1 -0
  180. package/lib/loader.mjs +143 -0
  181. package/lib/loader.mjs.map +1 -0
  182. package/lib/location-redirection-utilities/index.d.mts +6 -0
  183. package/lib/location-redirection-utilities/index.d.mts.map +1 -0
  184. package/lib/location-redirection-utilities/index.mjs +6 -0
  185. package/lib/location-redirection-utilities/index.mjs.map +1 -0
  186. package/lib/location-redirection-utilities/resolveWithLocationRedirection.d.mts +24 -0
  187. package/lib/location-redirection-utilities/resolveWithLocationRedirection.d.mts.map +1 -0
  188. package/lib/location-redirection-utilities/resolveWithLocationRedirection.mjs +48 -0
  189. package/lib/location-redirection-utilities/resolveWithLocationRedirection.mjs.map +1 -0
  190. package/lib/noopHeuristic.d.mts +23 -0
  191. package/lib/noopHeuristic.d.mts.map +1 -0
  192. package/lib/{collabWindowTracker.js → noopHeuristic.mjs} +33 -35
  193. package/lib/noopHeuristic.mjs.map +1 -0
  194. package/lib/{packageVersion.d.ts → packageVersion.d.mts} +2 -2
  195. package/lib/packageVersion.d.mts.map +1 -0
  196. package/lib/{packageVersion.js → packageVersion.mjs} +2 -2
  197. package/lib/packageVersion.mjs.map +1 -0
  198. package/lib/protocol.d.mts +38 -0
  199. package/lib/protocol.d.mts.map +1 -0
  200. package/lib/protocol.mjs +94 -0
  201. package/lib/protocol.mjs.map +1 -0
  202. package/lib/{protocolTreeDocumentStorageService.d.ts → protocolTreeDocumentStorageService.d.mts} +9 -5
  203. package/lib/protocolTreeDocumentStorageService.d.mts.map +1 -0
  204. package/lib/{protocolTreeDocumentStorageService.js → protocolTreeDocumentStorageService.mjs} +8 -5
  205. package/lib/protocolTreeDocumentStorageService.mjs.map +1 -0
  206. package/lib/quorum.d.mts +4 -0
  207. package/lib/quorum.d.mts.map +1 -0
  208. package/lib/quorum.mjs +12 -0
  209. package/lib/quorum.mjs.map +1 -0
  210. package/lib/{retriableDocumentStorageService.d.ts → retriableDocumentStorageService.d.mts} +8 -6
  211. package/lib/retriableDocumentStorageService.d.mts.map +1 -0
  212. package/lib/{retriableDocumentStorageService.js → retriableDocumentStorageService.mjs} +35 -20
  213. package/lib/retriableDocumentStorageService.mjs.map +1 -0
  214. package/lib/utils.d.mts +67 -0
  215. package/lib/utils.d.mts.map +1 -0
  216. package/lib/{utils.js → utils.mjs} +47 -11
  217. package/lib/utils.mjs.map +1 -0
  218. package/package.json +189 -69
  219. package/prettier.config.cjs +8 -0
  220. package/src/audience.ts +59 -49
  221. package/src/catchUpMonitor.ts +61 -0
  222. package/src/connectionManager.ts +1154 -910
  223. package/src/connectionState.ts +22 -25
  224. package/src/connectionStateHandler.ts +689 -319
  225. package/src/container.ts +2476 -1792
  226. package/src/containerContext.ts +98 -330
  227. package/src/containerStorageAdapter.ts +301 -105
  228. package/src/contracts.ts +184 -146
  229. package/src/debugLogger.ts +123 -0
  230. package/src/deltaManager.ts +1165 -900
  231. package/src/deltaQueue.ts +156 -152
  232. package/src/disposal.ts +25 -0
  233. package/src/error.ts +44 -0
  234. package/src/index.ts +14 -15
  235. package/src/loader.ts +356 -427
  236. package/src/location-redirection-utilities/index.ts +9 -0
  237. package/src/location-redirection-utilities/resolveWithLocationRedirection.ts +61 -0
  238. package/src/noopHeuristic.ts +107 -0
  239. package/src/packageVersion.ts +1 -1
  240. package/src/protocol.ts +150 -0
  241. package/src/protocolTreeDocumentStorageService.ts +35 -35
  242. package/src/quorum.ts +11 -50
  243. package/src/retriableDocumentStorageService.ts +135 -95
  244. package/src/utils.ts +159 -86
  245. package/tsc-multi.test.json +4 -0
  246. package/tsconfig.json +10 -12
  247. package/dist/audience.js.map +0 -1
  248. package/dist/collabWindowTracker.d.ts +0 -19
  249. package/dist/collabWindowTracker.d.ts.map +0 -1
  250. package/dist/collabWindowTracker.js.map +0 -1
  251. package/dist/connectionManager.js.map +0 -1
  252. package/dist/connectionState.js.map +0 -1
  253. package/dist/connectionStateHandler.js +0 -280
  254. package/dist/connectionStateHandler.js.map +0 -1
  255. package/dist/container.js +0 -1284
  256. package/dist/container.js.map +0 -1
  257. package/dist/containerContext.js +0 -217
  258. package/dist/containerContext.js.map +0 -1
  259. package/dist/containerStorageAdapter.js +0 -104
  260. package/dist/containerStorageAdapter.js.map +0 -1
  261. package/dist/contracts.js.map +0 -1
  262. package/dist/deltaManager.js.map +0 -1
  263. package/dist/deltaManagerProxy.d.ts +0 -54
  264. package/dist/deltaManagerProxy.d.ts.map +0 -1
  265. package/dist/deltaManagerProxy.js +0 -115
  266. package/dist/deltaManagerProxy.js.map +0 -1
  267. package/dist/deltaQueue.js.map +0 -1
  268. package/dist/index.js +0 -16
  269. package/dist/index.js.map +0 -1
  270. package/dist/loader.js +0 -241
  271. package/dist/loader.js.map +0 -1
  272. package/dist/packageVersion.js.map +0 -1
  273. package/dist/protocolTreeDocumentStorageService.js.map +0 -1
  274. package/dist/quorum.js +0 -44
  275. package/dist/quorum.js.map +0 -1
  276. package/dist/retriableDocumentStorageService.js.map +0 -1
  277. package/dist/utils.js.map +0 -1
  278. package/lib/audience.d.ts.map +0 -1
  279. package/lib/audience.js.map +0 -1
  280. package/lib/collabWindowTracker.d.ts +0 -19
  281. package/lib/collabWindowTracker.d.ts.map +0 -1
  282. package/lib/collabWindowTracker.js.map +0 -1
  283. package/lib/connectionManager.d.ts.map +0 -1
  284. package/lib/connectionManager.js.map +0 -1
  285. package/lib/connectionState.d.ts.map +0 -1
  286. package/lib/connectionState.js.map +0 -1
  287. package/lib/connectionStateHandler.d.ts +0 -81
  288. package/lib/connectionStateHandler.d.ts.map +0 -1
  289. package/lib/connectionStateHandler.js +0 -276
  290. package/lib/connectionStateHandler.js.map +0 -1
  291. package/lib/container.d.ts +0 -238
  292. package/lib/container.d.ts.map +0 -1
  293. package/lib/container.js +0 -1276
  294. package/lib/container.js.map +0 -1
  295. package/lib/containerContext.d.ts +0 -84
  296. package/lib/containerContext.d.ts.map +0 -1
  297. package/lib/containerContext.js +0 -213
  298. package/lib/containerContext.js.map +0 -1
  299. package/lib/containerStorageAdapter.d.ts +0 -48
  300. package/lib/containerStorageAdapter.d.ts.map +0 -1
  301. package/lib/containerStorageAdapter.js +0 -99
  302. package/lib/containerStorageAdapter.js.map +0 -1
  303. package/lib/contracts.d.ts.map +0 -1
  304. package/lib/contracts.js.map +0 -1
  305. package/lib/deltaManager.d.ts.map +0 -1
  306. package/lib/deltaManager.js.map +0 -1
  307. package/lib/deltaManagerProxy.d.ts +0 -54
  308. package/lib/deltaManagerProxy.d.ts.map +0 -1
  309. package/lib/deltaManagerProxy.js +0 -110
  310. package/lib/deltaManagerProxy.js.map +0 -1
  311. package/lib/deltaQueue.d.ts.map +0 -1
  312. package/lib/deltaQueue.js.map +0 -1
  313. package/lib/index.d.ts +0 -8
  314. package/lib/index.d.ts.map +0 -1
  315. package/lib/index.js +0 -8
  316. package/lib/index.js.map +0 -1
  317. package/lib/loader.d.ts.map +0 -1
  318. package/lib/loader.js +0 -236
  319. package/lib/loader.js.map +0 -1
  320. package/lib/packageVersion.d.ts.map +0 -1
  321. package/lib/packageVersion.js.map +0 -1
  322. package/lib/protocolTreeDocumentStorageService.d.ts.map +0 -1
  323. package/lib/protocolTreeDocumentStorageService.js.map +0 -1
  324. package/lib/quorum.d.ts +0 -21
  325. package/lib/quorum.d.ts.map +0 -1
  326. package/lib/quorum.js +0 -38
  327. package/lib/quorum.js.map +0 -1
  328. package/lib/retriableDocumentStorageService.d.ts.map +0 -1
  329. package/lib/retriableDocumentStorageService.js.map +0 -1
  330. package/lib/utils.d.ts +0 -34
  331. package/lib/utils.d.ts.map +0 -1
  332. package/lib/utils.js.map +0 -1
  333. package/src/collabWindowTracker.ts +0 -102
  334. package/src/deltaManagerProxy.ts +0 -158
  335. package/tsconfig.esnext.json +0 -7
@@ -0,0 +1,1585 @@
1
+ "use strict";
2
+ /*!
3
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
4
+ * Licensed under the MIT License.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.Container = exports.ReportIfTooLong = exports.waitContainerToCatchUp = void 0;
8
+ const uuid_1 = require("uuid");
9
+ const core_utils_1 = require("@fluidframework/core-utils");
10
+ const client_utils_1 = require("@fluid-internal/client-utils");
11
+ const core_interfaces_1 = require("@fluidframework/core-interfaces");
12
+ const container_definitions_1 = require("@fluidframework/container-definitions");
13
+ const driver_utils_1 = require("@fluidframework/driver-utils");
14
+ const protocol_definitions_1 = require("@fluidframework/protocol-definitions");
15
+ const telemetry_utils_1 = require("@fluidframework/telemetry-utils");
16
+ const audience_1 = require("./audience.cjs");
17
+ const containerContext_1 = require("./containerContext.cjs");
18
+ const contracts_1 = require("./contracts.cjs");
19
+ const deltaManager_1 = require("./deltaManager.cjs");
20
+ const loader_1 = require("./loader.cjs");
21
+ const packageVersion_1 = require("./packageVersion.cjs");
22
+ const containerStorageAdapter_1 = require("./containerStorageAdapter.cjs");
23
+ const connectionStateHandler_1 = require("./connectionStateHandler.cjs");
24
+ const utils_1 = require("./utils.cjs");
25
+ const quorum_1 = require("./quorum.cjs");
26
+ const noopHeuristic_1 = require("./noopHeuristic.cjs");
27
+ const connectionManager_1 = require("./connectionManager.cjs");
28
+ const connectionState_1 = require("./connectionState.cjs");
29
+ const protocol_1 = require("./protocol.cjs");
30
+ const detachedContainerRefSeqNumber = 0;
31
+ const dirtyContainerEvent = "dirty";
32
+ const savedContainerEvent = "saved";
33
+ const packageNotFactoryError = "Code package does not implement IRuntimeFactory";
34
+ const hasBlobsSummaryTree = ".hasAttachmentBlobs";
35
+ /**
36
+ * Waits until container connects to delta storage and gets up-to-date.
37
+ *
38
+ * Useful when resolving URIs and hitting 404, due to container being loaded from (stale) snapshot and not being
39
+ * up to date. Host may chose to wait in such case and retry resolving URI.
40
+ *
41
+ * Warning: Will wait infinitely for connection to establish if there is no connection.
42
+ * May result in deadlock if Container.disconnect() is called and never followed by a call to Container.connect().
43
+ *
44
+ * @returns `true`: container is up to date, it processed all the ops that were know at the time of first connection.
45
+ *
46
+ * `false`: storage does not provide indication of how far the client is. Container processed all the ops known to it,
47
+ * but it maybe still behind.
48
+ *
49
+ * @throws an error beginning with `"Container closed"` if the container is closed before it catches up.
50
+ * @alpha
51
+ */
52
+ async function waitContainerToCatchUp(container) {
53
+ // Make sure we stop waiting if container is closed.
54
+ if (container.closed) {
55
+ throw new telemetry_utils_1.UsageError("waitContainerToCatchUp: Container closed");
56
+ }
57
+ return new Promise((resolve, reject) => {
58
+ const deltaManager = container.deltaManager;
59
+ const closedCallback = (err) => {
60
+ container.off("closed", closedCallback);
61
+ const baseMessage = "Container closed while waiting to catch up";
62
+ reject(err !== undefined
63
+ ? (0, telemetry_utils_1.wrapError)(err, (innerMessage) => new telemetry_utils_1.GenericError(`${baseMessage}: ${innerMessage}`))
64
+ : new telemetry_utils_1.GenericError(baseMessage));
65
+ };
66
+ container.on("closed", closedCallback);
67
+ // Depending on config, transition to "connected" state may include the guarantee
68
+ // that all known ops have been processed. If so, we may introduce additional wait here.
69
+ // Waiting for "connected" state in either case gets us at least to our own Join op
70
+ // which is a reasonable approximation of "caught up"
71
+ const waitForOps = () => {
72
+ (0, core_utils_1.assert)(container.connectionState === connectionState_1.ConnectionState.CatchingUp ||
73
+ container.connectionState === connectionState_1.ConnectionState.Connected, 0x0cd /* "Container disconnected while waiting for ops!" */);
74
+ const hasCheckpointSequenceNumber = deltaManager.hasCheckpointSequenceNumber;
75
+ const connectionOpSeqNumber = deltaManager.lastKnownSeqNumber;
76
+ (0, core_utils_1.assert)(deltaManager.lastSequenceNumber <= connectionOpSeqNumber, 0x266 /* "lastKnownSeqNumber should never be below last processed sequence number" */);
77
+ if (deltaManager.lastSequenceNumber === connectionOpSeqNumber) {
78
+ container.off("closed", closedCallback);
79
+ resolve(hasCheckpointSequenceNumber);
80
+ return;
81
+ }
82
+ const callbackOps = (message) => {
83
+ if (connectionOpSeqNumber <= message.sequenceNumber) {
84
+ container.off("closed", closedCallback);
85
+ resolve(hasCheckpointSequenceNumber);
86
+ deltaManager.off("op", callbackOps);
87
+ }
88
+ };
89
+ deltaManager.on("op", callbackOps);
90
+ };
91
+ // We can leverage DeltaManager's "connect" event here and test for ConnectionState.Disconnected
92
+ // But that works only if service provides us checkPointSequenceNumber
93
+ // Our internal testing is based on R11S that does not, but almost all tests connect as "write" and
94
+ // use this function to catch up, so leveraging our own join op as a fence/barrier
95
+ if (container.connectionState === connectionState_1.ConnectionState.Connected) {
96
+ waitForOps();
97
+ return;
98
+ }
99
+ const callback = () => {
100
+ container.off(telemetry_utils_1.connectedEventName, callback);
101
+ waitForOps();
102
+ };
103
+ container.on(telemetry_utils_1.connectedEventName, callback);
104
+ if (container.connectionState === connectionState_1.ConnectionState.Disconnected) {
105
+ container.connect();
106
+ }
107
+ });
108
+ }
109
+ exports.waitContainerToCatchUp = waitContainerToCatchUp;
110
+ const getCodeProposal =
111
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
112
+ (quorum) => quorum.get("code") ?? quorum.get("code2");
113
+ /**
114
+ * Helper function to report to telemetry cases where operation takes longer than expected (200ms)
115
+ * @param logger - logger to use
116
+ * @param eventName - event name
117
+ * @param action - functor to call and measure
118
+ */
119
+ async function ReportIfTooLong(logger, eventName, action) {
120
+ const event = telemetry_utils_1.PerformanceEvent.start(logger, { eventName });
121
+ const props = await action();
122
+ if (event.duration > 200) {
123
+ event.end(props);
124
+ }
125
+ }
126
+ exports.ReportIfTooLong = ReportIfTooLong;
127
+ const summarizerClientType = "summarizer";
128
+ class Container extends telemetry_utils_1.EventEmitterWithErrorHandling {
129
+ /**
130
+ * Load an existing container.
131
+ * @internal
132
+ */
133
+ static async load(loadProps, createProps) {
134
+ const { version, pendingLocalState, loadMode, resolvedUrl, loadToSequenceNumber } = loadProps;
135
+ const container = new Container(createProps, loadProps);
136
+ const disableRecordHeapSize = container.mc.config.getBoolean("Fluid.Loader.DisableRecordHeapSize");
137
+ return telemetry_utils_1.PerformanceEvent.timedExecAsync(container.mc.logger, { eventName: "Load" }, async (event) => new Promise((resolve, reject) => {
138
+ const defaultMode = { opsBeforeReturn: "cached" };
139
+ // if we have pendingLocalState, anything we cached is not useful and we shouldn't wait for connection
140
+ // to return container, so ignore this value and use undefined for opsBeforeReturn
141
+ const mode = pendingLocalState
142
+ ? { ...(loadMode ?? defaultMode), opsBeforeReturn: undefined }
143
+ : loadMode ?? defaultMode;
144
+ const onClosed = (err) => {
145
+ // pre-0.58 error message: containerClosedWithoutErrorDuringLoad
146
+ reject(err ?? new telemetry_utils_1.GenericError("Container closed without error during load"));
147
+ };
148
+ container.on("closed", onClosed);
149
+ container
150
+ .load(version, mode, resolvedUrl, pendingLocalState, loadToSequenceNumber)
151
+ .finally(() => {
152
+ container.removeListener("closed", onClosed);
153
+ })
154
+ .then((props) => {
155
+ event.end({ ...props, ...loadMode });
156
+ resolve(container);
157
+ }, (error) => {
158
+ const err = (0, telemetry_utils_1.normalizeError)(error);
159
+ // Depending where error happens, we can be attempting to connect to web socket
160
+ // and continuously retrying (consider offline mode)
161
+ // Host has no container to close, so it's prudent to do it here
162
+ // Note: We could only dispose the container instead of just close but that would
163
+ // the telemetry where users sometimes search for ContainerClose event to look
164
+ // for load failures. So not removing this at this time.
165
+ container.close(err);
166
+ container.dispose(err);
167
+ onClosed(err);
168
+ });
169
+ }), { start: true, end: true, cancel: "generic" }, disableRecordHeapSize !== true /* recordHeapSize */);
170
+ }
171
+ /**
172
+ * Create a new container in a detached state.
173
+ */
174
+ static async createDetached(createProps, codeDetails) {
175
+ const container = new Container(createProps);
176
+ return telemetry_utils_1.PerformanceEvent.timedExecAsync(container.mc.logger, { eventName: "CreateDetached" }, async (_event) => {
177
+ await container.createDetached(codeDetails);
178
+ return container;
179
+ }, { start: true, end: true, cancel: "generic" });
180
+ }
181
+ /**
182
+ * Create a new container in a detached state that is initialized with a
183
+ * snapshot from a previous detached container.
184
+ */
185
+ static async rehydrateDetachedFromSnapshot(createProps, snapshot) {
186
+ const container = new Container(createProps);
187
+ return telemetry_utils_1.PerformanceEvent.timedExecAsync(container.mc.logger, { eventName: "RehydrateDetachedFromSnapshot" }, async (_event) => {
188
+ const deserializedSummary = JSON.parse(snapshot);
189
+ if (!(0, driver_utils_1.isCombinedAppAndProtocolSummary)(deserializedSummary, hasBlobsSummaryTree)) {
190
+ throw new telemetry_utils_1.UsageError("Cannot rehydrate detached container. Incorrect format");
191
+ }
192
+ await container.rehydrateDetachedFromSnapshot(deserializedSummary);
193
+ return container;
194
+ }, { start: true, end: true, cancel: "generic" });
195
+ }
196
+ setLoaded() {
197
+ // It's conceivable the container could be closed when this is called
198
+ // Only transition states if currently loading
199
+ if (this._lifecycleState === "loading") {
200
+ // Propagate current connection state through the system.
201
+ this.propagateConnectionState(true /* initial transition */);
202
+ this._lifecycleState = "loaded";
203
+ }
204
+ }
205
+ get closed() {
206
+ return (this._lifecycleState === "closing" || this._lifecycleState === "closed" || this.disposed);
207
+ }
208
+ get disposed() {
209
+ return this._lifecycleState === "disposing" || this._lifecycleState === "disposed";
210
+ }
211
+ get runtime() {
212
+ if (this._runtime === undefined) {
213
+ throw new Error("Attempted to access runtime before it was defined");
214
+ }
215
+ return this._runtime;
216
+ }
217
+ get protocolHandler() {
218
+ if (this._protocolHandler === undefined) {
219
+ throw new Error("Attempted to access protocolHandler before it was defined");
220
+ }
221
+ return this._protocolHandler;
222
+ }
223
+ get connectionMode() {
224
+ return this._deltaManager.connectionManager.connectionMode;
225
+ }
226
+ get resolvedUrl() {
227
+ /**
228
+ * All attached containers will have a document service,
229
+ * this is required, as attached containers are attached to
230
+ * a service. Detached containers will neither have a document
231
+ * service or a resolved url as they only exist locally.
232
+ * in order to create a document service a resolved url must
233
+ * first be obtained, this is how the container is identified.
234
+ * Because of this, the document service's resolved url
235
+ * is always the same as the containers, as we had to
236
+ * obtain the resolved url, and then create the service from it.
237
+ */
238
+ return this.service?.resolvedUrl;
239
+ }
240
+ get readOnlyInfo() {
241
+ return this._deltaManager.readOnlyInfo;
242
+ }
243
+ /**
244
+ * Sends signal to runtime (and data stores) to be read-only.
245
+ * Hosts may have read only views, indicating to data stores that no edits are allowed.
246
+ * This is independent from this._readonlyPermissions (permissions) and this.connectionMode
247
+ * (server can return "write" mode even when asked for "read")
248
+ * Leveraging same "readonly" event as runtime & data stores should behave the same in such case
249
+ * as in read-only permissions.
250
+ * But this.active can be used by some DDSes to figure out if ops can be sent
251
+ * (for example, read-only view still participates in code proposals / upgrades decisions)
252
+ *
253
+ * Forcing Readonly does not prevent DDS from generating ops. It is up to user code to honour
254
+ * the readonly flag. If ops are generated, they will accumulate locally and not be sent. If
255
+ * there are pending in the outbound queue, it will stop sending until force readonly is
256
+ * cleared.
257
+ *
258
+ * @param readonly - set or clear force readonly.
259
+ */
260
+ forceReadonly(readonly) {
261
+ this._deltaManager.connectionManager.forceReadonly(readonly);
262
+ }
263
+ get deltaManager() {
264
+ return this._deltaManager;
265
+ }
266
+ get connectionState() {
267
+ return this.connectionStateHandler.connectionState;
268
+ }
269
+ get connected() {
270
+ return this.connectionStateHandler.connectionState === connectionState_1.ConnectionState.Connected;
271
+ }
272
+ /**
273
+ * The server provided id of the client.
274
+ * Set once this.connected is true, otherwise undefined
275
+ */
276
+ get clientId() {
277
+ return this._clientId;
278
+ }
279
+ get offlineLoadEnabled() {
280
+ const enabled = this.mc.config.getBoolean("Fluid.Container.enableOfflineLoad") ??
281
+ this.options?.enableOfflineLoad === true;
282
+ // summarizer will not have any pending state we want to save
283
+ return enabled && this.deltaManager.clientDetails.capabilities.interactive;
284
+ }
285
+ /**
286
+ * Get the code details that are currently specified for the container.
287
+ * @returns The current code details if any are specified, undefined if none are specified.
288
+ */
289
+ getSpecifiedCodeDetails() {
290
+ return this.getCodeDetailsFromQuorum();
291
+ }
292
+ /**
293
+ * Get the code details that were used to load the container.
294
+ * @returns The code details that were used to load the container if it is loaded, undefined if it is not yet
295
+ * loaded.
296
+ */
297
+ getLoadedCodeDetails() {
298
+ return this._loadedCodeDetails;
299
+ }
300
+ /**
301
+ * Retrieves the audience associated with the document
302
+ */
303
+ get audience() {
304
+ return this.protocolHandler.audience;
305
+ }
306
+ /**
307
+ * Returns true if container is dirty.
308
+ * Which means data loss if container is closed at that same moment
309
+ * Most likely that happens when there is no network connection to Relay Service
310
+ */
311
+ get isDirty() {
312
+ return this._dirtyContainer;
313
+ }
314
+ /**
315
+ * {@inheritDoc @fluidframework/container-definitions#IContainer.entryPoint}
316
+ */
317
+ async getEntryPoint() {
318
+ if (this._disposed) {
319
+ throw new telemetry_utils_1.UsageError("The context is already disposed");
320
+ }
321
+ if (this._runtime !== undefined) {
322
+ return this._runtime.getEntryPoint?.();
323
+ }
324
+ return new Promise((resolve, reject) => {
325
+ const runtimeInstantiatedHandler = () => {
326
+ (0, core_utils_1.assert)(this._runtime !== undefined, 0x5a3 /* runtimeInstantiated fired but runtime is still undefined */);
327
+ resolve(this._runtime.getEntryPoint?.());
328
+ this._lifecycleEvents.off("disposed", disposedHandler);
329
+ };
330
+ const disposedHandler = () => {
331
+ reject(new Error("ContainerContext was disposed"));
332
+ this._lifecycleEvents.off("runtimeInstantiated", runtimeInstantiatedHandler);
333
+ };
334
+ this._lifecycleEvents.once("runtimeInstantiated", runtimeInstantiatedHandler);
335
+ this._lifecycleEvents.once("disposed", disposedHandler);
336
+ });
337
+ }
338
+ /**
339
+ * @internal
340
+ */
341
+ constructor(createProps, loadProps) {
342
+ super((name, error) => {
343
+ this.mc.logger.sendErrorEvent({
344
+ eventName: "ContainerEventHandlerException",
345
+ name: typeof name === "string" ? name : undefined,
346
+ }, error);
347
+ });
348
+ /**
349
+ * Lifecycle state of the container, used mainly to prevent re-entrancy and telemetry
350
+ *
351
+ * States are allowed to progress to further states:
352
+ * "loading" - "loaded" - "closing" - "disposing" - "closed" - "disposed"
353
+ *
354
+ * For example, moving from "closed" to "disposing" is not allowed since it is an earlier state.
355
+ *
356
+ * loading: Container has been created, but is not yet in normal/loaded state
357
+ * loaded: Container is in normal/loaded state
358
+ * closing: Container has started closing process (for re-entrancy prevention)
359
+ * disposing: Container has started disposing process (for re-entrancy prevention)
360
+ * closed: Container has closed
361
+ * disposed: Container has been disposed
362
+ */
363
+ this._lifecycleState = "loading";
364
+ this._attachState = container_definitions_1.AttachState.Detached;
365
+ /** During initialization we pause the inbound queues. We track this state to ensure we only call resume once */
366
+ this.inboundQueuePausedFromInit = true;
367
+ this.firstConnection = true;
368
+ this.connectionTransitionTimes = [];
369
+ this.attachStarted = false;
370
+ this._dirtyContainer = false;
371
+ this.savedOps = [];
372
+ this.clientsWhoShouldHaveLeft = new Set();
373
+ this.setAutoReconnectTime = client_utils_1.performance.now();
374
+ this._lifecycleEvents = new client_utils_1.TypedEventEmitter();
375
+ this._disposed = false;
376
+ this.getAbsoluteUrl = async (relativeUrl) => {
377
+ if (this.resolvedUrl === undefined) {
378
+ return undefined;
379
+ }
380
+ return this.urlResolver.getAbsoluteUrl(this.resolvedUrl, relativeUrl, (0, contracts_1.getPackageName)(this._loadedCodeDetails));
381
+ };
382
+ this.updateDirtyContainerState = (dirty) => {
383
+ if (this._dirtyContainer === dirty) {
384
+ return;
385
+ }
386
+ this._dirtyContainer = dirty;
387
+ this.emit(dirty ? dirtyContainerEvent : savedContainerEvent);
388
+ };
389
+ const { canReconnect, clientDetailsOverride, urlResolver, documentServiceFactory, codeLoader, options, scope, subLogger, detachedBlobStorage, protocolHandlerBuilder, } = createProps;
390
+ this.connectionTransitionTimes[connectionState_1.ConnectionState.Disconnected] = client_utils_1.performance.now();
391
+ const pendingLocalState = loadProps?.pendingLocalState;
392
+ this._clientId = pendingLocalState?.clientId;
393
+ this._canReconnect = canReconnect ?? true;
394
+ this.clientDetailsOverride = clientDetailsOverride;
395
+ this.urlResolver = urlResolver;
396
+ this.serviceFactory = documentServiceFactory;
397
+ this.codeLoader = codeLoader;
398
+ // Warning: this is only a shallow clone. Mutation of any individual loader option will mutate it for
399
+ // all clients that were loaded from the same loader (including summarizer clients).
400
+ // Tracking alternative ways to handle this in AB#4129.
401
+ this.options = { ...options };
402
+ this.scope = scope;
403
+ this.detachedBlobStorage = detachedBlobStorage;
404
+ this.protocolHandlerBuilder =
405
+ protocolHandlerBuilder ??
406
+ ((attributes, quorumSnapshot, sendProposal) => new protocol_1.ProtocolHandler(attributes, quorumSnapshot, sendProposal, new audience_1.Audience(), (clientId) => this.clientsWhoShouldHaveLeft.has(clientId)));
407
+ // Note that we capture the createProps here so we can replicate the creation call when we want to clone.
408
+ this.clone = async (_loadProps, createParamOverrides) => {
409
+ return Container.load(_loadProps, {
410
+ ...createProps,
411
+ ...createParamOverrides,
412
+ });
413
+ };
414
+ this._containerId = (0, uuid_1.v4)();
415
+ this.client = Container.setupClient(this._containerId, this.options, this.clientDetailsOverride);
416
+ // Create logger for data stores to use
417
+ const type = this.client.details.type;
418
+ const interactive = this.client.details.capabilities.interactive;
419
+ const clientType = `${interactive ? "interactive" : "noninteractive"}${type !== undefined && type !== "" ? `/${type}` : ""}`;
420
+ // Need to use the property getter for docId because for detached flow we don't have the docId initially.
421
+ // We assign the id later so property getter is used.
422
+ this.subLogger = (0, telemetry_utils_1.createChildLogger)({
423
+ logger: subLogger,
424
+ properties: {
425
+ all: {
426
+ clientType,
427
+ containerId: this._containerId,
428
+ docId: () => this.resolvedUrl?.id,
429
+ containerAttachState: () => this._attachState,
430
+ containerLifecycleState: () => this._lifecycleState,
431
+ containerConnectionState: () => connectionState_1.ConnectionState[this.connectionState],
432
+ serializedContainer: pendingLocalState !== undefined,
433
+ },
434
+ // we need to be judicious with our logging here to avoid generating too much data
435
+ // all data logged here should be broadly applicable, and not specific to a
436
+ // specific error or class of errors
437
+ error: {
438
+ // load information to associate errors with the specific load point
439
+ dmInitialSeqNumber: () => this._deltaManager?.initialSequenceNumber,
440
+ dmLastProcessedSeqNumber: () => this._deltaManager?.lastSequenceNumber,
441
+ dmLastKnownSeqNumber: () => this._deltaManager?.lastKnownSeqNumber,
442
+ containerLoadedFromVersionId: () => this._loadedFromVersion?.id,
443
+ containerLoadedFromVersionDate: () => this._loadedFromVersion?.date,
444
+ // message information to associate errors with the specific execution state
445
+ // dmLastMsqSeqNumber: if present, same as dmLastProcessedSeqNumber
446
+ dmLastMsqSeqNumber: () => this.deltaManager?.lastMessage?.sequenceNumber,
447
+ dmLastMsqSeqTimestamp: () => this.deltaManager?.lastMessage?.timestamp,
448
+ dmLastMsqSeqClientId: () => this.deltaManager?.lastMessage?.clientId === null
449
+ ? "null"
450
+ : this.deltaManager?.lastMessage?.clientId,
451
+ dmLastMsgClientSeq: () => this.deltaManager?.lastMessage?.clientSequenceNumber,
452
+ connectionStateDuration: () => client_utils_1.performance.now() - this.connectionTransitionTimes[this.connectionState],
453
+ },
454
+ },
455
+ });
456
+ // Prefix all events in this file with container-loader
457
+ this.mc = (0, telemetry_utils_1.createChildMonitoringContext)({ logger: this.subLogger, namespace: "Container" });
458
+ this._deltaManager = this.createDeltaManager();
459
+ this.connectionStateHandler = (0, connectionStateHandler_1.createConnectionStateHandler)({
460
+ logger: this.mc.logger,
461
+ connectionStateChanged: (value, oldState, reason) => {
462
+ if (value === connectionState_1.ConnectionState.Connected) {
463
+ this._clientId = this.connectionStateHandler.pendingClientId;
464
+ }
465
+ this.logConnectionStateChangeTelemetry(value, oldState, reason);
466
+ if (this._lifecycleState === "loaded") {
467
+ this.propagateConnectionState(false /* initial transition */, value === connectionState_1.ConnectionState.Disconnected
468
+ ? reason
469
+ : undefined /* disconnectedReason */);
470
+ }
471
+ },
472
+ shouldClientJoinWrite: () => this._deltaManager.connectionManager.shouldJoinWrite(),
473
+ maxClientLeaveWaitTime: options.maxClientLeaveWaitTime,
474
+ logConnectionIssue: (eventName, category, details) => {
475
+ const mode = this.connectionMode;
476
+ // We get here when socket does not receive any ops on "write" connection, including
477
+ // its own join op.
478
+ // Report issues only if we already loaded container - op processing is paused while container is loading,
479
+ // so we always time-out processing of join op in cases where fetching snapshot takes a minute.
480
+ // It's not a problem with op processing itself - such issues should be tracked as part of boot perf monitoring instead.
481
+ this._deltaManager.logConnectionIssue({
482
+ eventName,
483
+ mode,
484
+ category: this._lifecycleState === "loading" ? "generic" : category,
485
+ duration: client_utils_1.performance.now() -
486
+ this.connectionTransitionTimes[connectionState_1.ConnectionState.CatchingUp],
487
+ ...(details === undefined ? {} : { details: JSON.stringify(details) }),
488
+ });
489
+ // If this is "write" connection, it took too long to receive join op. But in most cases that's due
490
+ // to very slow op fetches and we will eventually get there.
491
+ // For "read" connections, we get here due to self join signal not arriving on time. We will need to
492
+ // better understand when and why it may happen.
493
+ // For now, attempt to recover by reconnecting. In future, maybe we can query relay service for
494
+ // current state of audience.
495
+ // Other possible recovery path - move to connected state (i.e. ConnectionStateHandler.joinOpTimer
496
+ // to call this.applyForConnectedState("addMemberEvent") for "read" connections)
497
+ if (mode === "read") {
498
+ const reason = { text: "NoJoinSignal" };
499
+ this.disconnectInternal(reason);
500
+ this.connectInternal({ reason, fetchOpsFromStorage: false });
501
+ }
502
+ },
503
+ clientShouldHaveLeft: (clientId) => {
504
+ this.clientsWhoShouldHaveLeft.add(clientId);
505
+ },
506
+ }, this.deltaManager, pendingLocalState?.clientId);
507
+ this.on(savedContainerEvent, () => {
508
+ this.connectionStateHandler.containerSaved();
509
+ });
510
+ // We expose our storage publicly, so it's possible others may call uploadSummaryWithContext() with a
511
+ // non-combined summary tree (in particular, ContainerRuntime.submitSummary). We'll intercept those calls
512
+ // using this callback and fix them up.
513
+ const addProtocolSummaryIfMissing = (summaryTree) => (0, driver_utils_1.isCombinedAppAndProtocolSummary)(summaryTree) === true
514
+ ? summaryTree
515
+ : (0, utils_1.combineAppAndProtocolSummary)(summaryTree, this.captureProtocolSummary());
516
+ // Whether the combined summary tree has been forced on by either the loader option or the monitoring context.
517
+ // Even if not forced on via this flag, combined summaries may still be enabled by service policy.
518
+ const forceEnableSummarizeProtocolTree = this.mc.config.getBoolean("Fluid.Container.summarizeProtocolTree2") ??
519
+ options.summarizeProtocolTree;
520
+ this.storageAdapter = new containerStorageAdapter_1.ContainerStorageAdapter(detachedBlobStorage, this.mc.logger, pendingLocalState?.snapshotBlobs, addProtocolSummaryIfMissing, forceEnableSummarizeProtocolTree);
521
+ const isDomAvailable = typeof document === "object" &&
522
+ document !== null &&
523
+ typeof document.addEventListener === "function" &&
524
+ document.addEventListener !== null;
525
+ // keep track of last time page was visible for telemetry (on interactive clients only)
526
+ if (isDomAvailable && interactive) {
527
+ this.lastVisible = document.hidden ? client_utils_1.performance.now() : undefined;
528
+ this.visibilityEventHandler = () => {
529
+ if (document.hidden) {
530
+ this.lastVisible = client_utils_1.performance.now();
531
+ }
532
+ else {
533
+ // settimeout so this will hopefully fire after disconnect event if being hidden caused it
534
+ setTimeout(() => {
535
+ this.lastVisible = undefined;
536
+ }, 0);
537
+ }
538
+ };
539
+ document.addEventListener("visibilitychange", this.visibilityEventHandler);
540
+ }
541
+ }
542
+ /**
543
+ * Retrieves the quorum associated with the document
544
+ */
545
+ getQuorum() {
546
+ return this.protocolHandler.quorum;
547
+ }
548
+ dispose(error) {
549
+ this._deltaManager.dispose(error);
550
+ this.verifyClosed();
551
+ }
552
+ close(error) {
553
+ // 1. Ensure that close sequence is exactly the same no matter if it's initiated by host or by DeltaManager
554
+ // 2. We need to ensure that we deliver disconnect event to runtime properly. See connectionStateChanged
555
+ // handler. We only deliver events if container fully loaded. Transitioning from "loading" ->
556
+ // "closing" will lose that info (can also solve by tracking extra state).
557
+ this._deltaManager.close(error);
558
+ this.verifyClosed();
559
+ }
560
+ verifyClosed() {
561
+ (0, core_utils_1.assert)(this.connectionState === connectionState_1.ConnectionState.Disconnected, 0x0cf /* "disconnect event was not raised!" */);
562
+ (0, core_utils_1.assert)(this._lifecycleState === "closed" || this._lifecycleState === "disposed", 0x314 /* Container properly closed */);
563
+ }
564
+ closeCore(error) {
565
+ (0, core_utils_1.assert)(!this.closed, 0x315 /* re-entrancy */);
566
+ try {
567
+ // Ensure that we raise all key events even if one of these throws
568
+ try {
569
+ // Raise event first, to ensure we capture _lifecycleState before transition.
570
+ // This gives us a chance to know what errors happened on open vs. on fully loaded container.
571
+ // Log generic events instead of error events if container is in loading state, as most errors are not really FF errors
572
+ // which can pollute telemetry for real bugs
573
+ this.mc.logger.sendTelemetryEvent({
574
+ eventName: "ContainerClose",
575
+ category: this._lifecycleState !== "loading" && error !== undefined
576
+ ? "error"
577
+ : "generic",
578
+ }, error);
579
+ this._lifecycleState = "closing";
580
+ this._protocolHandler?.close();
581
+ this.connectionStateHandler.dispose();
582
+ }
583
+ catch (exception) {
584
+ this.mc.logger.sendErrorEvent({ eventName: "ContainerCloseException" }, exception);
585
+ }
586
+ this.emit("closed", error);
587
+ if (this.visibilityEventHandler !== undefined) {
588
+ document.removeEventListener("visibilitychange", this.visibilityEventHandler);
589
+ }
590
+ }
591
+ finally {
592
+ this._lifecycleState = "closed";
593
+ // There is no user for summarizer, so we need to ensure dispose is called
594
+ if (this.client.details.type === summarizerClientType) {
595
+ this.dispose(error);
596
+ }
597
+ }
598
+ }
599
+ disposeCore(error) {
600
+ (0, core_utils_1.assert)(!this._disposed, 0x54c /* Container already disposed */);
601
+ this._disposed = true;
602
+ try {
603
+ // Ensure that we raise all key events even if one of these throws
604
+ try {
605
+ // Raise event first, to ensure we capture _lifecycleState before transition.
606
+ // This gives us a chance to know what errors happened on open vs. on fully loaded container.
607
+ this.mc.logger.sendTelemetryEvent({
608
+ eventName: "ContainerDispose",
609
+ // Only log error if container isn't closed
610
+ category: !this.closed && error !== undefined ? "error" : "generic",
611
+ }, error);
612
+ // ! Progressing from "closed" to "disposing" is not allowed
613
+ if (this._lifecycleState !== "closed") {
614
+ this._lifecycleState = "disposing";
615
+ }
616
+ this._protocolHandler?.close();
617
+ this.connectionStateHandler.dispose();
618
+ const maybeError = error !== undefined ? new Error(error.message) : undefined;
619
+ this._runtime?.dispose(maybeError);
620
+ this.storageAdapter.dispose();
621
+ // Notify storage about critical errors. They may be due to disconnect between client & server knowledge
622
+ // about file, like file being overwritten in storage, but client having stale local cache.
623
+ // Driver need to ensure all caches are cleared on critical errors
624
+ this.service?.dispose(error);
625
+ }
626
+ catch (exception) {
627
+ this.mc.logger.sendErrorEvent({ eventName: "ContainerDisposeException" }, exception);
628
+ }
629
+ this.emit("disposed", error);
630
+ this.removeAllListeners();
631
+ if (this.visibilityEventHandler !== undefined) {
632
+ document.removeEventListener("visibilitychange", this.visibilityEventHandler);
633
+ }
634
+ }
635
+ finally {
636
+ this._lifecycleState = "disposed";
637
+ this._lifecycleEvents.emit("disposed");
638
+ }
639
+ }
640
+ async closeAndGetPendingLocalState(stopBlobAttachingSignal) {
641
+ // runtime matches pending ops to successful ones by clientId and client seq num, so we need to close the
642
+ // container at the same time we get pending state, otherwise this container could reconnect and resubmit with
643
+ // a new clientId and a future container using stale pending state without the new clientId would resubmit them
644
+ const pendingState = await this.getPendingLocalStateCore({
645
+ notifyImminentClosure: true,
646
+ stopBlobAttachingSignal,
647
+ });
648
+ this.close();
649
+ return pendingState;
650
+ }
651
+ async getPendingLocalState() {
652
+ return this.getPendingLocalStateCore({ notifyImminentClosure: false });
653
+ }
654
+ async getPendingLocalStateCore(props) {
655
+ return telemetry_utils_1.PerformanceEvent.timedExecAsync(this.mc.logger, {
656
+ eventName: "getPendingLocalState",
657
+ notifyImminentClosure: props.notifyImminentClosure,
658
+ savedOpsSize: this.savedOps.length,
659
+ clientId: this.clientId,
660
+ }, async () => {
661
+ if (!this.offlineLoadEnabled) {
662
+ throw new telemetry_utils_1.UsageError("Can't get pending local state unless offline load is enabled");
663
+ }
664
+ if (this.closed || this._disposed) {
665
+ throw new telemetry_utils_1.UsageError("Pending state cannot be retried if the container is closed or disposed");
666
+ }
667
+ (0, core_utils_1.assert)(this.attachState === container_definitions_1.AttachState.Attached, 0x0d1 /* "Container should be attached before close" */);
668
+ (0, core_utils_1.assert)(this.resolvedUrl !== undefined && this.resolvedUrl.type === "fluid", 0x0d2 /* "resolved url should be valid Fluid url" */);
669
+ (0, core_utils_1.assert)(!!this.baseSnapshot, 0x5d4 /* no base snapshot */);
670
+ (0, core_utils_1.assert)(!!this.baseSnapshotBlobs, 0x5d5 /* no snapshot blobs */);
671
+ const pendingRuntimeState = await this.runtime.getPendingLocalState(props);
672
+ const pendingState = {
673
+ pendingRuntimeState,
674
+ baseSnapshot: this.baseSnapshot,
675
+ snapshotBlobs: this.baseSnapshotBlobs,
676
+ savedOps: this.savedOps,
677
+ url: this.resolvedUrl.url,
678
+ // no need to save this if there is no pending runtime state
679
+ clientId: pendingRuntimeState !== undefined ? this.clientId : undefined,
680
+ };
681
+ return JSON.stringify(pendingState);
682
+ });
683
+ }
684
+ get attachState() {
685
+ return this._attachState;
686
+ }
687
+ serialize() {
688
+ (0, core_utils_1.assert)(this.attachState === container_definitions_1.AttachState.Detached, 0x0d3 /* "Should only be called in detached container" */);
689
+ const appSummary = this.runtime.createSummary();
690
+ const protocolSummary = this.captureProtocolSummary();
691
+ const combinedSummary = (0, utils_1.combineAppAndProtocolSummary)(appSummary, protocolSummary);
692
+ if (this.detachedBlobStorage && this.detachedBlobStorage.size > 0) {
693
+ combinedSummary.tree[hasBlobsSummaryTree] = {
694
+ type: protocol_definitions_1.SummaryType.Blob,
695
+ content: "true",
696
+ };
697
+ }
698
+ return JSON.stringify(combinedSummary);
699
+ }
700
+ async attach(request, attachProps) {
701
+ await telemetry_utils_1.PerformanceEvent.timedExecAsync(this.mc.logger, { eventName: "Attach" }, async () => {
702
+ if (this._lifecycleState !== "loaded") {
703
+ // pre-0.58 error message: containerNotValidForAttach
704
+ throw new telemetry_utils_1.UsageError(`The Container is not in a valid state for attach [${this._lifecycleState}]`);
705
+ }
706
+ // If container is already attached or attach is in progress, throw an error.
707
+ (0, core_utils_1.assert)(this._attachState === container_definitions_1.AttachState.Detached && !this.attachStarted, 0x205 /* "attach() called more than once" */);
708
+ this.attachStarted = true;
709
+ // If attachment blobs were uploaded in detached state we will go through a different attach flow
710
+ const hasAttachmentBlobs = this.detachedBlobStorage !== undefined && this.detachedBlobStorage.size > 0;
711
+ try {
712
+ (0, core_utils_1.assert)(this.deltaManager.inbound.length === 0, 0x0d6 /* "Inbound queue should be empty when attaching" */);
713
+ let summary;
714
+ if (!hasAttachmentBlobs) {
715
+ // Get the document state post attach - possibly can just call attach but we need to change the
716
+ // semantics around what the attach means as far as async code goes.
717
+ const appSummary = this.runtime.createSummary();
718
+ const protocolSummary = this.captureProtocolSummary();
719
+ summary = (0, utils_1.combineAppAndProtocolSummary)(appSummary, protocolSummary);
720
+ // Set the state as attaching as we are starting the process of attaching container.
721
+ // This should be fired after taking the summary because it is the place where we are
722
+ // starting to attach the container to storage.
723
+ // Also, this should only be fired in detached container.
724
+ this._attachState = container_definitions_1.AttachState.Attaching;
725
+ this.runtime.setAttachState(container_definitions_1.AttachState.Attaching);
726
+ this.emit("attaching");
727
+ if (this.offlineLoadEnabled) {
728
+ const snapshot = (0, utils_1.getSnapshotTreeFromSerializedContainer)(summary);
729
+ this.baseSnapshot = snapshot;
730
+ this.baseSnapshotBlobs =
731
+ (0, containerStorageAdapter_1.getBlobContentsFromTreeWithBlobContents)(snapshot);
732
+ }
733
+ }
734
+ // Actually go and create the resolved document
735
+ if (this.service === undefined) {
736
+ const createNewResolvedUrl = await this.urlResolver.resolve(request);
737
+ (0, core_utils_1.assert)(this.client.details.type !== summarizerClientType &&
738
+ createNewResolvedUrl !== undefined, 0x2c4 /* "client should not be summarizer before container is created" */);
739
+ this.service = await (0, driver_utils_1.runWithRetry)(async () => this.serviceFactory.createContainer(summary, createNewResolvedUrl, this.subLogger, false), "containerAttach", this.mc.logger, {
740
+ cancel: this._deltaManager.closeAbortController.signal,
741
+ });
742
+ }
743
+ this.storageAdapter.connectToService(this.service);
744
+ if (hasAttachmentBlobs) {
745
+ // upload blobs to storage
746
+ (0, core_utils_1.assert)(!!this.detachedBlobStorage, 0x24e /* "assertion for type narrowing" */);
747
+ // build a table mapping IDs assigned locally to IDs assigned by storage and pass it to runtime to
748
+ // support blob handles that only know about the local IDs
749
+ const redirectTable = new Map();
750
+ // if new blobs are added while uploading, upload them too
751
+ while (redirectTable.size < this.detachedBlobStorage.size) {
752
+ const newIds = this.detachedBlobStorage
753
+ .getBlobIds()
754
+ .filter((id) => !redirectTable.has(id));
755
+ for (const id of newIds) {
756
+ const blob = await this.detachedBlobStorage.readBlob(id);
757
+ const response = await this.storageAdapter.createBlob(blob);
758
+ redirectTable.set(id, response.id);
759
+ }
760
+ }
761
+ // take summary and upload
762
+ const appSummary = this.runtime.createSummary(redirectTable);
763
+ const protocolSummary = this.captureProtocolSummary();
764
+ summary = (0, utils_1.combineAppAndProtocolSummary)(appSummary, protocolSummary);
765
+ this._attachState = container_definitions_1.AttachState.Attaching;
766
+ this.runtime.setAttachState(container_definitions_1.AttachState.Attaching);
767
+ this.emit("attaching");
768
+ if (this.offlineLoadEnabled) {
769
+ const snapshot = (0, utils_1.getSnapshotTreeFromSerializedContainer)(summary);
770
+ this.baseSnapshot = snapshot;
771
+ this.baseSnapshotBlobs =
772
+ (0, containerStorageAdapter_1.getBlobContentsFromTreeWithBlobContents)(snapshot);
773
+ }
774
+ await this.storageAdapter.uploadSummaryWithContext(summary, {
775
+ referenceSequenceNumber: 0,
776
+ ackHandle: undefined,
777
+ proposalHandle: undefined,
778
+ });
779
+ }
780
+ this._attachState = container_definitions_1.AttachState.Attached;
781
+ this.runtime.setAttachState(container_definitions_1.AttachState.Attached);
782
+ this.emit("attached");
783
+ if (!this.closed) {
784
+ this.handleDeltaConnectionArg({
785
+ fetchOpsFromStorage: false,
786
+ reason: { text: "createDetached" },
787
+ }, attachProps?.deltaConnection);
788
+ }
789
+ }
790
+ catch (error) {
791
+ // add resolved URL on error object so that host has the ability to find this document and delete it
792
+ const newError = (0, telemetry_utils_1.normalizeError)(error);
793
+ newError.addTelemetryProperties({ resolvedUrl: this.resolvedUrl?.url });
794
+ this.close(newError);
795
+ throw newError;
796
+ }
797
+ }, { start: true, end: true, cancel: "generic" });
798
+ }
799
+ setAutoReconnectInternal(mode, reason) {
800
+ const currentMode = this._deltaManager.connectionManager.reconnectMode;
801
+ if (currentMode === mode) {
802
+ return;
803
+ }
804
+ const now = client_utils_1.performance.now();
805
+ const duration = now - this.setAutoReconnectTime;
806
+ this.setAutoReconnectTime = now;
807
+ this.mc.logger.sendTelemetryEvent({
808
+ eventName: mode === contracts_1.ReconnectMode.Enabled ? "AutoReconnectEnabled" : "AutoReconnectDisabled",
809
+ connectionMode: this.connectionMode,
810
+ connectionState: connectionState_1.ConnectionState[this.connectionState],
811
+ duration,
812
+ });
813
+ this._deltaManager.connectionManager.setAutoReconnect(mode, reason);
814
+ }
815
+ connect() {
816
+ if (this.closed) {
817
+ throw new telemetry_utils_1.UsageError(`The Container is closed and cannot be connected`);
818
+ }
819
+ else if (this._attachState !== container_definitions_1.AttachState.Attached) {
820
+ throw new telemetry_utils_1.UsageError(`The Container is not attached and cannot be connected`);
821
+ }
822
+ else if (!this.connected) {
823
+ // Note: no need to fetch ops as we do it preemptively as part of DeltaManager.attachOpHandler().
824
+ // If there is gap, we will learn about it once connected, but the gap should be small (if any),
825
+ // assuming that connect() is called quickly after initial container boot.
826
+ this.connectInternal({
827
+ reason: { text: "DocumentConnect" },
828
+ fetchOpsFromStorage: false,
829
+ });
830
+ }
831
+ }
832
+ connectInternal(args) {
833
+ (0, core_utils_1.assert)(!this.closed, 0x2c5 /* "Attempting to connect() a closed Container" */);
834
+ (0, core_utils_1.assert)(this._attachState === container_definitions_1.AttachState.Attached, 0x2c6 /* "Attempting to connect() a container that is not attached" */);
835
+ // Resume processing ops and connect to delta stream
836
+ this.resumeInternal(args);
837
+ // Set Auto Reconnect Mode
838
+ const mode = contracts_1.ReconnectMode.Enabled;
839
+ this.setAutoReconnectInternal(mode, args.reason);
840
+ }
841
+ disconnect() {
842
+ if (this.closed) {
843
+ throw new telemetry_utils_1.UsageError(`The Container is closed and cannot be disconnected`);
844
+ }
845
+ else {
846
+ this.disconnectInternal({ text: "DocumentDisconnect" });
847
+ }
848
+ }
849
+ disconnectInternal(reason) {
850
+ (0, core_utils_1.assert)(!this.closed, 0x2c7 /* "Attempting to disconnect() a closed Container" */);
851
+ // Set Auto Reconnect Mode
852
+ const mode = contracts_1.ReconnectMode.Disabled;
853
+ this.setAutoReconnectInternal(mode, reason);
854
+ }
855
+ resumeInternal(args) {
856
+ (0, core_utils_1.assert)(!this.closed, 0x0d9 /* "Attempting to connect() a closed DeltaManager" */);
857
+ // Resume processing ops
858
+ if (this.inboundQueuePausedFromInit) {
859
+ this.inboundQueuePausedFromInit = false;
860
+ this._deltaManager.inbound.resume();
861
+ this._deltaManager.inboundSignal.resume();
862
+ }
863
+ // Ensure connection to web socket
864
+ this.connectToDeltaStream(args);
865
+ }
866
+ async proposeCodeDetails(codeDetails) {
867
+ if (!(0, container_definitions_1.isFluidCodeDetails)(codeDetails)) {
868
+ throw new Error("Provided codeDetails are not IFluidCodeDetails");
869
+ }
870
+ if (this.codeLoader.IFluidCodeDetailsComparer) {
871
+ const comparison = await this.codeLoader.IFluidCodeDetailsComparer.compare(codeDetails, this.getCodeDetailsFromQuorum());
872
+ if (comparison !== undefined && comparison <= 0) {
873
+ throw new Error("Proposed code details should be greater than the current");
874
+ }
875
+ }
876
+ return this.protocolHandler.quorum
877
+ .propose("code", codeDetails)
878
+ .then(() => true)
879
+ .catch(() => false);
880
+ }
881
+ async processCodeProposal() {
882
+ const codeDetails = this.getCodeDetailsFromQuorum();
883
+ await Promise.all([
884
+ this.deltaManager.inbound.pause(),
885
+ this.deltaManager.inboundSignal.pause(),
886
+ ]);
887
+ if ((await this.satisfies(codeDetails)) === true) {
888
+ this.deltaManager.inbound.resume();
889
+ this.deltaManager.inboundSignal.resume();
890
+ return;
891
+ }
892
+ // pre-0.58 error message: existingContextDoesNotSatisfyIncomingProposal
893
+ const error = new telemetry_utils_1.GenericError("Existing context does not satisfy incoming proposal");
894
+ this.close(error);
895
+ }
896
+ /**
897
+ * Determines if the currently loaded module satisfies the incoming constraint code details
898
+ */
899
+ async satisfies(constraintCodeDetails) {
900
+ // If we have no module, it can't satisfy anything.
901
+ if (this._loadedModule === undefined) {
902
+ return false;
903
+ }
904
+ const comparers = [];
905
+ const maybeCompareCodeLoader = this.codeLoader;
906
+ if (maybeCompareCodeLoader.IFluidCodeDetailsComparer !== undefined) {
907
+ comparers.push(maybeCompareCodeLoader.IFluidCodeDetailsComparer);
908
+ }
909
+ const maybeCompareExport = this._loadedModule?.module.fluidExport;
910
+ if (maybeCompareExport?.IFluidCodeDetailsComparer !== undefined) {
911
+ comparers.push(maybeCompareExport.IFluidCodeDetailsComparer);
912
+ }
913
+ // If there are no comparers, then it's impossible to know if the currently loaded package satisfies
914
+ // the incoming constraint, so we return false. Assuming it does not satisfy is safer, to force a reload
915
+ // rather than potentially running with incompatible code.
916
+ if (comparers.length === 0) {
917
+ return false;
918
+ }
919
+ for (const comparer of comparers) {
920
+ const satisfies = await comparer.satisfies(this._loadedModule?.details, constraintCodeDetails);
921
+ if (satisfies === false) {
922
+ return false;
923
+ }
924
+ }
925
+ return true;
926
+ }
927
+ async getVersion(version) {
928
+ const versions = await this.storageAdapter.getVersions(version, 1);
929
+ return versions[0];
930
+ }
931
+ connectToDeltaStream(args) {
932
+ // All agents need "write" access, including summarizer.
933
+ if (!this._canReconnect || !this.client.details.capabilities.interactive) {
934
+ args.mode = "write";
935
+ }
936
+ this._deltaManager.connect(args);
937
+ }
938
+ /**
939
+ * Load container.
940
+ *
941
+ * @param specifiedVersion - Version SHA to load snapshot. If not specified, will fetch the latest snapshot.
942
+ */
943
+ async load(specifiedVersion, loadMode, resolvedUrl, pendingLocalState, loadToSequenceNumber) {
944
+ const timings = { phase1: client_utils_1.performance.now() };
945
+ this.service = await this.serviceFactory.createDocumentService(resolvedUrl, this.subLogger, this.client.details.type === summarizerClientType);
946
+ // Except in cases where it has stashed ops or requested by feature gate, the container will connect in "read" mode
947
+ const mode = this.mc.config.getBoolean("Fluid.Container.ForceWriteConnection") === true ||
948
+ (pendingLocalState?.savedOps.length ?? 0) > 0
949
+ ? "write"
950
+ : "read";
951
+ const connectionArgs = {
952
+ reason: { text: "DocumentOpen" },
953
+ mode,
954
+ fetchOpsFromStorage: false,
955
+ };
956
+ // Start websocket connection as soon as possible. Note that there is no op handler attached yet, but the
957
+ // DeltaManager is resilient to this and will wait to start processing ops until after it is attached.
958
+ if (loadMode.deltaConnection === undefined && !pendingLocalState) {
959
+ this.connectToDeltaStream(connectionArgs);
960
+ }
961
+ this.storageAdapter.connectToService(this.service);
962
+ this._attachState = container_definitions_1.AttachState.Attached;
963
+ timings.phase2 = client_utils_1.performance.now();
964
+ // Fetch specified snapshot.
965
+ const { snapshot, versionId } = pendingLocalState === undefined
966
+ ? await this.fetchSnapshotTree(specifiedVersion)
967
+ : { snapshot: pendingLocalState.baseSnapshot, versionId: undefined };
968
+ if (pendingLocalState) {
969
+ this.baseSnapshot = pendingLocalState.baseSnapshot;
970
+ this.baseSnapshotBlobs = pendingLocalState.snapshotBlobs;
971
+ }
972
+ else {
973
+ (0, core_utils_1.assert)(snapshot !== undefined, 0x237 /* "Snapshot should exist" */);
974
+ if (this.offlineLoadEnabled) {
975
+ this.baseSnapshot = snapshot;
976
+ // Save contents of snapshot now, otherwise closeAndGetPendingLocalState() must be async
977
+ this.baseSnapshotBlobs = await (0, containerStorageAdapter_1.getBlobContentsFromTree)(snapshot, this.storageAdapter);
978
+ }
979
+ }
980
+ const attributes = await this.getDocumentAttributes(this.storageAdapter, snapshot);
981
+ // If we saved ops, we will replay them and don't need DeltaManager to fetch them
982
+ const sequenceNumber = pendingLocalState?.savedOps[pendingLocalState.savedOps.length - 1]?.sequenceNumber;
983
+ const dmAttributes = sequenceNumber !== undefined ? { ...attributes, sequenceNumber } : attributes;
984
+ let opsBeforeReturnP;
985
+ if (loadMode.pauseAfterLoad === true) {
986
+ // If we are trying to pause at a specific sequence number, ensure the latest snapshot is not newer than the desired sequence number.
987
+ if (loadMode.opsBeforeReturn === "sequenceNumber") {
988
+ (0, core_utils_1.assert)(loadToSequenceNumber !== undefined, 0x727 /* sequenceNumber should be defined */);
989
+ // Note: It is possible that we think the latest snapshot is newer than the specified sequence number
990
+ // due to saved ops that may be replayed after the snapshot.
991
+ // https://dev.azure.com/fluidframework/internal/_workitems/edit/5055
992
+ if (dmAttributes.sequenceNumber > loadToSequenceNumber) {
993
+ throw new Error("Cannot satisfy request to pause the container at the specified sequence number. Most recent snapshot is newer than the specified sequence number.");
994
+ }
995
+ }
996
+ // Force readonly mode - this will ensure we don't receive an error for the lack of join op
997
+ this.forceReadonly(true);
998
+ // We need to setup a listener to stop op processing once we reach the desired sequence number (if specified).
999
+ const opHandler = () => {
1000
+ if (loadToSequenceNumber === undefined) {
1001
+ // If there is no specified sequence number, pause after the inbound queue is empty.
1002
+ if (this.deltaManager.inbound.length !== 0) {
1003
+ return;
1004
+ }
1005
+ }
1006
+ else {
1007
+ // If there is a specified sequence number, keep processing until we reach it.
1008
+ if (this.deltaManager.lastSequenceNumber < loadToSequenceNumber) {
1009
+ return;
1010
+ }
1011
+ }
1012
+ // Pause op processing once we have processed the desired number of ops.
1013
+ void this.deltaManager.inbound.pause();
1014
+ void this.deltaManager.outbound.pause();
1015
+ this.off("op", opHandler);
1016
+ };
1017
+ if ((loadToSequenceNumber === undefined && this.deltaManager.inbound.length === 0) ||
1018
+ this.deltaManager.lastSequenceNumber === loadToSequenceNumber) {
1019
+ // If we have already reached the desired sequence number, call opHandler() to pause immediately.
1020
+ opHandler();
1021
+ }
1022
+ else {
1023
+ // If we have not yet reached the desired sequence number, setup a listener to pause once we reach it.
1024
+ this.on("op", opHandler);
1025
+ }
1026
+ }
1027
+ // Attach op handlers to finish initialization and be able to start processing ops
1028
+ // Kick off any ops fetching if required.
1029
+ switch (loadMode.opsBeforeReturn) {
1030
+ case undefined:
1031
+ // Start prefetch, but not set opsBeforeReturnP - boot is not blocked by it!
1032
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
1033
+ this.attachDeltaManagerOpHandler(dmAttributes, loadMode.deltaConnection !== "none" ? "all" : "none");
1034
+ break;
1035
+ case "sequenceNumber":
1036
+ case "cached":
1037
+ case "all":
1038
+ opsBeforeReturnP = this.attachDeltaManagerOpHandler(dmAttributes, loadMode.opsBeforeReturn);
1039
+ break;
1040
+ default:
1041
+ (0, core_utils_1.unreachableCase)(loadMode.opsBeforeReturn);
1042
+ }
1043
+ // ...load in the existing quorum
1044
+ // Initialize the protocol handler
1045
+ await this.initializeProtocolStateFromSnapshot(attributes, this.storageAdapter, snapshot);
1046
+ timings.phase3 = client_utils_1.performance.now();
1047
+ const codeDetails = this.getCodeDetailsFromQuorum();
1048
+ await this.instantiateRuntime(codeDetails, snapshot,
1049
+ // give runtime a dummy value so it knows we're loading from a stash blob
1050
+ pendingLocalState ? pendingLocalState?.pendingRuntimeState ?? {} : undefined);
1051
+ // replay saved ops
1052
+ if (pendingLocalState) {
1053
+ for (const message of pendingLocalState.savedOps) {
1054
+ this.processRemoteMessage({
1055
+ ...message,
1056
+ metadata: { ...message.metadata, savedOp: true },
1057
+ });
1058
+ // allow runtime to apply stashed ops at this op's sequence number
1059
+ await this.runtime.notifyOpReplay?.(message);
1060
+ }
1061
+ pendingLocalState.savedOps = [];
1062
+ }
1063
+ // We might have hit some failure that did not manifest itself in exception in this flow,
1064
+ // do not start op processing in such case - static version of Container.load() will handle it correctly.
1065
+ if (!this.closed) {
1066
+ if (opsBeforeReturnP !== undefined) {
1067
+ this._deltaManager.inbound.resume();
1068
+ await telemetry_utils_1.PerformanceEvent.timedExecAsync(this.mc.logger, { eventName: "WaitOps" }, async () => opsBeforeReturnP);
1069
+ await telemetry_utils_1.PerformanceEvent.timedExecAsync(this.mc.logger, { eventName: "WaitOpProcessing" }, async () => this._deltaManager.inbound.waitTillProcessingDone());
1070
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
1071
+ this._deltaManager.inbound.pause();
1072
+ }
1073
+ this.handleDeltaConnectionArg(connectionArgs, loadMode.deltaConnection, pendingLocalState !== undefined);
1074
+ }
1075
+ // If we have not yet reached `loadToSequenceNumber`, we will wait for ops to arrive until we reach it
1076
+ if (loadToSequenceNumber !== undefined &&
1077
+ this.deltaManager.lastSequenceNumber < loadToSequenceNumber) {
1078
+ await new Promise((resolve, reject) => {
1079
+ const opHandler = (message) => {
1080
+ if (message.sequenceNumber >= loadToSequenceNumber) {
1081
+ resolve();
1082
+ this.off("op", opHandler);
1083
+ }
1084
+ };
1085
+ this.on("op", opHandler);
1086
+ });
1087
+ }
1088
+ // Safety net: static version of Container.load() should have learned about it through "closed" handler.
1089
+ // But if that did not happen for some reason, fail load for sure.
1090
+ // Otherwise we can get into situations where container is closed and does not try to connect to ordering
1091
+ // service, but caller does not know that (callers do expect container to be not closed on successful path
1092
+ // and listen only on "closed" event)
1093
+ if (this.closed) {
1094
+ throw new Error("Container was closed while load()");
1095
+ }
1096
+ // Internal context is fully loaded at this point
1097
+ this.setLoaded();
1098
+ timings.end = client_utils_1.performance.now();
1099
+ this.subLogger.sendTelemetryEvent({
1100
+ eventName: "LoadStagesTimings",
1101
+ details: JSON.stringify(timings),
1102
+ }, undefined, core_interfaces_1.LogLevel.verbose);
1103
+ return {
1104
+ sequenceNumber: attributes.sequenceNumber,
1105
+ version: versionId,
1106
+ dmLastProcessedSeqNumber: this._deltaManager.lastSequenceNumber,
1107
+ dmLastKnownSeqNumber: this._deltaManager.lastKnownSeqNumber,
1108
+ };
1109
+ }
1110
+ async createDetached(codeDetails) {
1111
+ const attributes = {
1112
+ sequenceNumber: detachedContainerRefSeqNumber,
1113
+ minimumSequenceNumber: 0,
1114
+ };
1115
+ await this.attachDeltaManagerOpHandler(attributes);
1116
+ // Need to just seed the source data in the code quorum. Quorum itself is empty
1117
+ const qValues = (0, quorum_1.initQuorumValuesFromCodeDetails)(codeDetails);
1118
+ this.initializeProtocolState(attributes, {
1119
+ members: [],
1120
+ proposals: [],
1121
+ values: qValues,
1122
+ });
1123
+ await this.instantiateRuntime(codeDetails, undefined);
1124
+ this.setLoaded();
1125
+ }
1126
+ async rehydrateDetachedFromSnapshot(detachedContainerSnapshot) {
1127
+ if (detachedContainerSnapshot.tree[hasBlobsSummaryTree] !== undefined) {
1128
+ (0, core_utils_1.assert)(!!this.detachedBlobStorage && this.detachedBlobStorage.size > 0, 0x250 /* "serialized container with attachment blobs must be rehydrated with detached blob storage" */);
1129
+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
1130
+ delete detachedContainerSnapshot.tree[hasBlobsSummaryTree];
1131
+ }
1132
+ const snapshotTree = (0, utils_1.getSnapshotTreeFromSerializedContainer)(detachedContainerSnapshot);
1133
+ this.storageAdapter.loadSnapshotForRehydratingContainer(snapshotTree);
1134
+ const attributes = await this.getDocumentAttributes(this.storageAdapter, snapshotTree);
1135
+ await this.attachDeltaManagerOpHandler(attributes);
1136
+ // Initialize the protocol handler
1137
+ const baseTree = (0, utils_1.getProtocolSnapshotTree)(snapshotTree);
1138
+ const qValues = await (0, driver_utils_1.readAndParse)(this.storageAdapter, baseTree.blobs.quorumValues);
1139
+ this.initializeProtocolState(attributes, {
1140
+ members: [],
1141
+ proposals: [],
1142
+ values: qValues,
1143
+ });
1144
+ const codeDetails = this.getCodeDetailsFromQuorum();
1145
+ await this.instantiateRuntime(codeDetails, snapshotTree);
1146
+ this.setLoaded();
1147
+ }
1148
+ async getDocumentAttributes(storage, tree) {
1149
+ if (tree === undefined) {
1150
+ return {
1151
+ minimumSequenceNumber: 0,
1152
+ sequenceNumber: 0,
1153
+ };
1154
+ }
1155
+ // Backward compatibility: old docs would have ".attributes" instead of "attributes"
1156
+ const attributesHash = ".protocol" in tree.trees
1157
+ ? tree.trees[".protocol"].blobs.attributes
1158
+ : tree.blobs[".attributes"];
1159
+ const attributes = await (0, driver_utils_1.readAndParse)(storage, attributesHash);
1160
+ return attributes;
1161
+ }
1162
+ async initializeProtocolStateFromSnapshot(attributes, storage, snapshot) {
1163
+ const quorumSnapshot = {
1164
+ members: [],
1165
+ proposals: [],
1166
+ values: [],
1167
+ };
1168
+ if (snapshot !== undefined) {
1169
+ const baseTree = (0, utils_1.getProtocolSnapshotTree)(snapshot);
1170
+ [quorumSnapshot.members, quorumSnapshot.proposals, quorumSnapshot.values] =
1171
+ await Promise.all([
1172
+ (0, driver_utils_1.readAndParse)(storage, baseTree.blobs.quorumMembers),
1173
+ (0, driver_utils_1.readAndParse)(storage, baseTree.blobs.quorumProposals),
1174
+ (0, driver_utils_1.readAndParse)(storage, baseTree.blobs.quorumValues),
1175
+ ]);
1176
+ }
1177
+ this.initializeProtocolState(attributes, quorumSnapshot);
1178
+ }
1179
+ initializeProtocolState(attributes, quorumSnapshot) {
1180
+ const protocol = this.protocolHandlerBuilder(attributes, quorumSnapshot, (key, value) => this.submitMessage(protocol_definitions_1.MessageType.Propose, JSON.stringify({ key, value })));
1181
+ const protocolLogger = (0, telemetry_utils_1.createChildLogger)({
1182
+ logger: this.subLogger,
1183
+ namespace: "ProtocolHandler",
1184
+ });
1185
+ protocol.quorum.on("error", (error) => {
1186
+ protocolLogger.sendErrorEvent(error);
1187
+ });
1188
+ // Track membership changes and update connection state accordingly
1189
+ this.connectionStateHandler.initProtocol(protocol);
1190
+ protocol.quorum.on("addProposal", (proposal) => {
1191
+ if (proposal.key === "code" || proposal.key === "code2") {
1192
+ this.emit("codeDetailsProposed", proposal.value, proposal);
1193
+ }
1194
+ });
1195
+ protocol.quorum.on("approveProposal", (sequenceNumber, key, value) => {
1196
+ if (key === "code" || key === "code2") {
1197
+ if (!(0, container_definitions_1.isFluidCodeDetails)(value)) {
1198
+ this.mc.logger.sendErrorEvent({
1199
+ eventName: "CodeProposalNotIFluidCodeDetails",
1200
+ });
1201
+ }
1202
+ this.processCodeProposal().catch((error) => {
1203
+ const normalizedError = (0, telemetry_utils_1.normalizeError)(error);
1204
+ this.close(normalizedError);
1205
+ throw error;
1206
+ });
1207
+ }
1208
+ });
1209
+ // we need to make sure this member get set in a synchronous context,
1210
+ // or other things can happen after the object that will be set is created, but not yet set
1211
+ // this was breaking this._initialClients handling
1212
+ //
1213
+ this._protocolHandler = protocol;
1214
+ }
1215
+ captureProtocolSummary() {
1216
+ const quorumSnapshot = this.protocolHandler.snapshot();
1217
+ const summary = {
1218
+ tree: {
1219
+ attributes: {
1220
+ content: JSON.stringify(this.protocolHandler.attributes),
1221
+ type: protocol_definitions_1.SummaryType.Blob,
1222
+ },
1223
+ quorumMembers: {
1224
+ content: JSON.stringify(quorumSnapshot.members),
1225
+ type: protocol_definitions_1.SummaryType.Blob,
1226
+ },
1227
+ quorumProposals: {
1228
+ content: JSON.stringify(quorumSnapshot.proposals),
1229
+ type: protocol_definitions_1.SummaryType.Blob,
1230
+ },
1231
+ quorumValues: {
1232
+ content: JSON.stringify(quorumSnapshot.values),
1233
+ type: protocol_definitions_1.SummaryType.Blob,
1234
+ },
1235
+ },
1236
+ type: protocol_definitions_1.SummaryType.Tree,
1237
+ };
1238
+ return summary;
1239
+ }
1240
+ getCodeDetailsFromQuorum() {
1241
+ const quorum = this.protocolHandler.quorum;
1242
+ const pkg = getCodeProposal(quorum);
1243
+ return pkg;
1244
+ }
1245
+ static setupClient(containerId, options, clientDetailsOverride) {
1246
+ const loaderOptionsClient = structuredClone(options?.client);
1247
+ const client = loaderOptionsClient !== undefined
1248
+ ? loaderOptionsClient
1249
+ : {
1250
+ details: {
1251
+ capabilities: { interactive: true },
1252
+ },
1253
+ mode: "read",
1254
+ permission: [],
1255
+ scopes: [],
1256
+ user: { id: "" },
1257
+ };
1258
+ if (clientDetailsOverride !== undefined) {
1259
+ client.details = {
1260
+ ...client.details,
1261
+ ...clientDetailsOverride,
1262
+ capabilities: {
1263
+ ...client.details.capabilities,
1264
+ ...clientDetailsOverride?.capabilities,
1265
+ },
1266
+ };
1267
+ }
1268
+ client.details.environment = [
1269
+ client.details.environment,
1270
+ ` loaderVersion:${packageVersion_1.pkgVersion}`,
1271
+ ` containerId:${containerId}`,
1272
+ ].join(";");
1273
+ return client;
1274
+ }
1275
+ /**
1276
+ * Returns true if connection is active, i.e. it's "write" connection and
1277
+ * container runtime was notified about this connection (i.e. we are up-to-date and could send ops).
1278
+ * This happens after client received its own joinOp and thus is in the quorum.
1279
+ * If it's not true, runtime is not in position to send ops.
1280
+ */
1281
+ activeConnection() {
1282
+ return (this.connectionState === connectionState_1.ConnectionState.Connected && this.connectionMode === "write");
1283
+ }
1284
+ createDeltaManager() {
1285
+ const serviceProvider = () => this.service;
1286
+ const deltaManager = new deltaManager_1.DeltaManager(serviceProvider, (0, telemetry_utils_1.createChildLogger)({ logger: this.subLogger, namespace: "DeltaManager" }), () => this.activeConnection(), (props) => new connectionManager_1.ConnectionManager(serviceProvider, () => this.isDirty, this.client, this._canReconnect, (0, telemetry_utils_1.createChildLogger)({ logger: this.subLogger, namespace: "ConnectionManager" }), props));
1287
+ // Disable inbound queues as Container is not ready to accept any ops until we are fully loaded!
1288
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
1289
+ deltaManager.inbound.pause();
1290
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
1291
+ deltaManager.inboundSignal.pause();
1292
+ deltaManager.on("connect", (details, _opsBehind) => {
1293
+ (0, core_utils_1.assert)(this.connectionMode === details.mode, 0x4b7 /* mismatch */);
1294
+ this.connectionStateHandler.receivedConnectEvent(details);
1295
+ });
1296
+ deltaManager.on("establishingConnection", (reason) => {
1297
+ this.connectionStateHandler.establishingConnection(reason);
1298
+ });
1299
+ deltaManager.on("cancelEstablishingConnection", (reason) => {
1300
+ this.connectionStateHandler.cancelEstablishingConnection(reason);
1301
+ });
1302
+ deltaManager.on("disconnect", (reason) => {
1303
+ this.noopHeuristic?.notifyDisconnect();
1304
+ if (!this.closed) {
1305
+ this.connectionStateHandler.receivedDisconnectEvent(reason);
1306
+ }
1307
+ });
1308
+ deltaManager.on("throttled", (warning) => {
1309
+ const warn = warning;
1310
+ // Some "warning" events come from outside the container and are logged
1311
+ // elsewhere (e.g. summarizing container). We shouldn't log these here.
1312
+ if (warn.logged !== true) {
1313
+ this.mc.logger.sendTelemetryEvent({ eventName: "ContainerWarning" }, warn);
1314
+ }
1315
+ this.emit("warning", warn);
1316
+ });
1317
+ deltaManager.on("readonly", (readonly) => {
1318
+ this.setContextConnectedState(this.connectionState === connectionState_1.ConnectionState.Connected, readonly);
1319
+ this.emit("readonly", readonly);
1320
+ });
1321
+ deltaManager.on("closed", (error) => {
1322
+ this.closeCore(error);
1323
+ });
1324
+ deltaManager.on("disposed", (error) => {
1325
+ this.disposeCore(error);
1326
+ });
1327
+ return deltaManager;
1328
+ }
1329
+ async attachDeltaManagerOpHandler(attributes, prefetchType) {
1330
+ return this._deltaManager.attachOpHandler(attributes.minimumSequenceNumber, attributes.sequenceNumber, {
1331
+ process: (message) => this.processRemoteMessage(message),
1332
+ processSignal: (message) => {
1333
+ this.processSignal(message);
1334
+ },
1335
+ }, prefetchType);
1336
+ }
1337
+ logConnectionStateChangeTelemetry(value, oldState, reason) {
1338
+ // Log actual event
1339
+ const time = client_utils_1.performance.now();
1340
+ this.connectionTransitionTimes[value] = time;
1341
+ const duration = time - this.connectionTransitionTimes[oldState];
1342
+ let durationFromDisconnected;
1343
+ let connectionInitiationReason;
1344
+ let autoReconnect;
1345
+ let checkpointSequenceNumber;
1346
+ let opsBehind;
1347
+ if (value === connectionState_1.ConnectionState.Disconnected) {
1348
+ autoReconnect = this._deltaManager.connectionManager.reconnectMode;
1349
+ }
1350
+ else {
1351
+ if (value === connectionState_1.ConnectionState.Connected) {
1352
+ durationFromDisconnected =
1353
+ time - this.connectionTransitionTimes[connectionState_1.ConnectionState.Disconnected];
1354
+ durationFromDisconnected = (0, telemetry_utils_1.formatTick)(durationFromDisconnected);
1355
+ }
1356
+ else if (value === connectionState_1.ConnectionState.CatchingUp) {
1357
+ // This info is of most interesting while Catching Up.
1358
+ checkpointSequenceNumber = this.deltaManager.lastKnownSeqNumber;
1359
+ // Need to check that we have already loaded and fetched the snapshot.
1360
+ if (this.deltaManager.hasCheckpointSequenceNumber &&
1361
+ this._lifecycleState === "loaded") {
1362
+ opsBehind = checkpointSequenceNumber - this.deltaManager.lastSequenceNumber;
1363
+ }
1364
+ }
1365
+ connectionInitiationReason = this.firstConnection ? "InitialConnect" : "AutoReconnect";
1366
+ }
1367
+ this.mc.logger.sendPerformanceEvent({
1368
+ eventName: `ConnectionStateChange_${connectionState_1.ConnectionState[value]}`,
1369
+ from: connectionState_1.ConnectionState[oldState],
1370
+ duration,
1371
+ durationFromDisconnected,
1372
+ reason: reason?.text,
1373
+ connectionInitiationReason,
1374
+ pendingClientId: this.connectionStateHandler.pendingClientId,
1375
+ clientId: this.clientId,
1376
+ autoReconnect,
1377
+ opsBehind,
1378
+ online: driver_utils_1.OnlineStatus[(0, driver_utils_1.isOnline)()],
1379
+ lastVisible: this.lastVisible !== undefined
1380
+ ? client_utils_1.performance.now() - this.lastVisible
1381
+ : undefined,
1382
+ checkpointSequenceNumber,
1383
+ quorumSize: this._protocolHandler?.quorum.getMembers().size,
1384
+ isDirty: this.isDirty,
1385
+ ...this._deltaManager.connectionProps,
1386
+ }, reason?.error);
1387
+ if (value === connectionState_1.ConnectionState.Connected) {
1388
+ this.firstConnection = false;
1389
+ }
1390
+ }
1391
+ propagateConnectionState(initialTransition, disconnectedReason) {
1392
+ // When container loaded, we want to propagate initial connection state.
1393
+ // After that, we communicate only transitions to Connected & Disconnected states, skipping all other states.
1394
+ // This can be changed in the future, for example we likely should add "CatchingUp" event on Container.
1395
+ if (!initialTransition &&
1396
+ this.connectionState !== connectionState_1.ConnectionState.Connected &&
1397
+ this.connectionState !== connectionState_1.ConnectionState.Disconnected) {
1398
+ return;
1399
+ }
1400
+ const state = this.connectionState === connectionState_1.ConnectionState.Connected;
1401
+ // Both protocol and context should not be undefined if we got so far.
1402
+ this.setContextConnectedState(state, this.readOnlyInfo.readonly ?? false);
1403
+ this.protocolHandler.setConnectionState(state, this.clientId);
1404
+ (0, telemetry_utils_1.raiseConnectedEvent)(this.mc.logger, this, state, this.clientId, disconnectedReason?.text);
1405
+ }
1406
+ // back-compat: ADO #1385: Remove in the future, summary op should come through submitSummaryMessage()
1407
+ submitContainerMessage(type, contents, batch, metadata) {
1408
+ switch (type) {
1409
+ case protocol_definitions_1.MessageType.Operation:
1410
+ return this.submitMessage(type, JSON.stringify(contents), batch, metadata);
1411
+ case protocol_definitions_1.MessageType.Summarize:
1412
+ return this.submitSummaryMessage(contents);
1413
+ default: {
1414
+ const newError = new telemetry_utils_1.GenericError("invalidContainerSubmitOpType", undefined /* error */, { messageType: type });
1415
+ this.close(newError);
1416
+ return -1;
1417
+ }
1418
+ }
1419
+ }
1420
+ /** @returns clientSequenceNumber of last message in a batch */
1421
+ submitBatch(batch, referenceSequenceNumber) {
1422
+ let clientSequenceNumber = -1;
1423
+ for (const message of batch) {
1424
+ clientSequenceNumber = this.submitMessage(protocol_definitions_1.MessageType.Operation, message.contents, true, // batch
1425
+ message.metadata, message.compression, referenceSequenceNumber);
1426
+ }
1427
+ this._deltaManager.flush();
1428
+ return clientSequenceNumber;
1429
+ }
1430
+ submitSummaryMessage(summary, referenceSequenceNumber) {
1431
+ // github #6451: this is only needed for staging so the server
1432
+ // know when the protocol tree is included
1433
+ // this can be removed once all clients send
1434
+ // protocol tree by default
1435
+ if (summary.details === undefined) {
1436
+ summary.details = {};
1437
+ }
1438
+ summary.details.includesProtocolTree = this.storageAdapter.summarizeProtocolTree;
1439
+ return this.submitMessage(protocol_definitions_1.MessageType.Summarize, JSON.stringify(summary), false /* batch */, undefined /* metadata */, undefined /* compression */, referenceSequenceNumber);
1440
+ }
1441
+ submitMessage(type, contents, batch, metadata, compression, referenceSequenceNumber) {
1442
+ if (this.connectionState !== connectionState_1.ConnectionState.Connected) {
1443
+ this.mc.logger.sendErrorEvent({ eventName: "SubmitMessageWithNoConnection", type });
1444
+ return -1;
1445
+ }
1446
+ this.noopHeuristic?.notifyMessageSent();
1447
+ return this._deltaManager.submit(type, contents, batch, metadata, compression, referenceSequenceNumber);
1448
+ }
1449
+ processRemoteMessage(message) {
1450
+ if (this.offlineLoadEnabled) {
1451
+ this.savedOps.push(message);
1452
+ }
1453
+ const local = this.clientId === message.clientId;
1454
+ // Allow the protocol handler to process the message
1455
+ const result = this.protocolHandler.processMessage(message, local);
1456
+ // Forward messages to the loaded runtime for processing
1457
+ this.runtime.process(message, local);
1458
+ // Inactive (not in quorum or not writers) clients don't take part in the minimum sequence number calculation.
1459
+ if (this.activeConnection()) {
1460
+ if (this.noopHeuristic === undefined) {
1461
+ const serviceConfiguration = this.deltaManager.serviceConfiguration;
1462
+ // Note that config from first connection will be used for this container's lifetime.
1463
+ // That means that if relay service changes settings, such changes will impact only newly booted
1464
+ // clients.
1465
+ // All existing will continue to use settings they got earlier.
1466
+ (0, core_utils_1.assert)(serviceConfiguration !== undefined, 0x2e4 /* "there should be service config for active connection" */);
1467
+ this.noopHeuristic = new noopHeuristic_1.NoopHeuristic(serviceConfiguration.noopTimeFrequency, serviceConfiguration.noopCountFrequency);
1468
+ this.noopHeuristic.on("wantsNoop", () => {
1469
+ // On disconnect we notify the heuristic which should prevent it from wanting a noop.
1470
+ // Hitting this assert would imply we lost activeConnection between notifying the heuristic of a processed message and
1471
+ // running the microtask that the heuristic queued in response.
1472
+ (0, core_utils_1.assert)(this.activeConnection(), 0x241 /* "Trying to send noop without active connection" */);
1473
+ this.submitMessage(protocol_definitions_1.MessageType.NoOp);
1474
+ });
1475
+ }
1476
+ this.noopHeuristic.notifyMessageProcessed(message);
1477
+ // The contract with the protocolHandler is that returning "immediateNoOp" is equivalent to "please immediately accept the proposal I just processed".
1478
+ if (result.immediateNoOp === true) {
1479
+ // ADO:1385: Remove cast and use MessageType once definition changes propagate
1480
+ this.submitMessage(driver_utils_1.MessageType2.Accept);
1481
+ }
1482
+ }
1483
+ this.emit("op", message);
1484
+ }
1485
+ submitSignal(content, targetClientId) {
1486
+ this._deltaManager.submitSignal(JSON.stringify(content), targetClientId);
1487
+ }
1488
+ processSignal(message) {
1489
+ // No clientId indicates a system signal message.
1490
+ if ((0, protocol_1.protocolHandlerShouldProcessSignal)(message)) {
1491
+ this.protocolHandler.processSignal(message);
1492
+ }
1493
+ else {
1494
+ const local = this.clientId === message.clientId;
1495
+ this.runtime.processSignal(message, local);
1496
+ }
1497
+ }
1498
+ /**
1499
+ * Get the most recent snapshot, or a specific version.
1500
+ * @param specifiedVersion - The specific version of the snapshot to retrieve
1501
+ * @returns The snapshot requested, or the latest snapshot if no version was specified, plus version ID
1502
+ */
1503
+ async fetchSnapshotTree(specifiedVersion) {
1504
+ const version = await this.getVersion(specifiedVersion ?? null);
1505
+ if (version === undefined && specifiedVersion !== undefined) {
1506
+ // We should have a defined version to load from if specified version requested
1507
+ this.mc.logger.sendErrorEvent({
1508
+ eventName: "NoVersionFoundWhenSpecified",
1509
+ id: specifiedVersion,
1510
+ });
1511
+ }
1512
+ this._loadedFromVersion = version;
1513
+ const snapshot = (await this.storageAdapter.getSnapshotTree(version)) ?? undefined;
1514
+ if (snapshot === undefined && version !== undefined) {
1515
+ this.mc.logger.sendErrorEvent({ eventName: "getSnapshotTreeFailed", id: version.id });
1516
+ }
1517
+ return { snapshot, versionId: version?.id };
1518
+ }
1519
+ async instantiateRuntime(codeDetails, snapshot, pendingLocalState) {
1520
+ (0, core_utils_1.assert)(this._runtime?.disposed !== false, 0x0dd /* "Existing runtime not disposed" */);
1521
+ // The relative loader will proxy requests to '/' to the loader itself assuming no non-cache flags
1522
+ // are set. Global requests will still go directly to the loader
1523
+ const maybeLoader = this.scope;
1524
+ const loader = new loader_1.RelativeLoader(this, maybeLoader.ILoader);
1525
+ const loadCodeResult = await telemetry_utils_1.PerformanceEvent.timedExecAsync(this.subLogger, { eventName: "CodeLoad" }, async () => this.codeLoader.load(codeDetails));
1526
+ this._loadedModule = {
1527
+ module: loadCodeResult.module,
1528
+ // An older interface ICodeLoader could return an IFluidModule which didn't have details.
1529
+ // If we're using one of those older ICodeLoaders, then we fix up the module with the specified details here.
1530
+ // TODO: Determine if this is still a realistic scenario or if this fixup could be removed.
1531
+ details: loadCodeResult.details ?? codeDetails,
1532
+ };
1533
+ const fluidExport = this._loadedModule.module.fluidExport;
1534
+ const runtimeFactory = fluidExport?.IRuntimeFactory;
1535
+ if (runtimeFactory === undefined) {
1536
+ throw new Error(packageNotFactoryError);
1537
+ }
1538
+ const getSpecifiedCodeDetails = () => (this.protocolHandler.quorum.get("code") ??
1539
+ this.protocolHandler.quorum.get("code2"));
1540
+ const existing = snapshot !== undefined;
1541
+ const context = new containerContext_1.ContainerContext(this.options, this.scope, snapshot, this._loadedFromVersion, this._deltaManager, this.storageAdapter, this.protocolHandler.quorum, this.protocolHandler.audience, loader, (type, contents, batch, metadata) => this.submitContainerMessage(type, contents, batch, metadata), (summaryOp, referenceSequenceNumber) => this.submitSummaryMessage(summaryOp, referenceSequenceNumber), (batch, referenceSequenceNumber) => this.submitBatch(batch, referenceSequenceNumber), (content, targetClientId) => this.submitSignal(content, targetClientId), (error) => this.dispose(error), (error) => this.close(error), this.updateDirtyContainerState, this.getAbsoluteUrl, () => this.resolvedUrl?.id, () => this.clientId, () => this.attachState, () => this.connected, getSpecifiedCodeDetails, this._deltaManager.clientDetails, existing, this.subLogger, pendingLocalState);
1542
+ this._runtime = await telemetry_utils_1.PerformanceEvent.timedExecAsync(this.subLogger, { eventName: "InstantiateRuntime" }, async () => runtimeFactory.instantiateRuntime(context, existing));
1543
+ this._lifecycleEvents.emit("runtimeInstantiated");
1544
+ this._loadedCodeDetails = codeDetails;
1545
+ }
1546
+ /**
1547
+ * Set the connected state of the ContainerContext
1548
+ * This controls the "connected" state of the ContainerRuntime as well
1549
+ * @param state - Is the container currently connected?
1550
+ * @param readonly - Is the container in readonly mode?
1551
+ */
1552
+ setContextConnectedState(state, readonly) {
1553
+ if (this._runtime?.disposed === false) {
1554
+ /**
1555
+ * We want to lie to the ContainerRuntime when we are in readonly mode to prevent issues with pending
1556
+ * ops getting through to the DeltaManager.
1557
+ * The ContainerRuntime's "connected" state simply means it is ok to send ops
1558
+ * See https://dev.azure.com/fluidframework/internal/_workitems/edit/1246
1559
+ */
1560
+ this.runtime.setConnectionState(state && !readonly, this.clientId);
1561
+ }
1562
+ }
1563
+ handleDeltaConnectionArg(connectionArgs, deltaConnectionArg, canConnect = true) {
1564
+ switch (deltaConnectionArg) {
1565
+ case undefined:
1566
+ if (canConnect) {
1567
+ // connect to delta stream now since we did not before
1568
+ this.connectToDeltaStream(connectionArgs);
1569
+ }
1570
+ // intentional fallthrough
1571
+ case "delayed":
1572
+ (0, core_utils_1.assert)(this.inboundQueuePausedFromInit, 0x346 /* inboundQueuePausedFromInit should be true */);
1573
+ this.inboundQueuePausedFromInit = false;
1574
+ this._deltaManager.inbound.resume();
1575
+ this._deltaManager.inboundSignal.resume();
1576
+ break;
1577
+ case "none":
1578
+ break;
1579
+ default:
1580
+ (0, core_utils_1.unreachableCase)(deltaConnectionArg);
1581
+ }
1582
+ }
1583
+ }
1584
+ exports.Container = Container;
1585
+ //# sourceMappingURL=container.cjs.map