@fluidframework/container-runtime 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 (705) hide show
  1. package/.eslintrc.js +19 -29
  2. package/.mocharc.js +12 -0
  3. package/CHANGELOG.md +427 -0
  4. package/README.md +69 -0
  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-runtime.api.md +863 -0
  9. package/dist/{batchTracker.js → batchTracker.cjs} +9 -8
  10. package/dist/batchTracker.cjs.map +1 -0
  11. package/dist/batchTracker.d.ts +6 -5
  12. package/dist/batchTracker.d.ts.map +1 -1
  13. package/dist/blobManager.cjs +709 -0
  14. package/dist/blobManager.cjs.map +1 -0
  15. package/dist/blobManager.d.ts +140 -39
  16. package/dist/blobManager.d.ts.map +1 -1
  17. package/dist/connectionTelemetry.cjs +230 -0
  18. package/dist/connectionTelemetry.cjs.map +1 -0
  19. package/dist/connectionTelemetry.d.ts +2 -2
  20. package/dist/connectionTelemetry.d.ts.map +1 -1
  21. package/dist/container-runtime-alpha.d.ts +1690 -0
  22. package/dist/container-runtime-beta.d.ts +250 -0
  23. package/dist/container-runtime-public.d.ts +250 -0
  24. package/dist/container-runtime-untrimmed.d.ts +1805 -0
  25. package/dist/{containerHandleContext.js → containerHandleContext.cjs} +4 -2
  26. package/dist/containerHandleContext.cjs.map +1 -0
  27. package/dist/containerHandleContext.d.ts.map +1 -1
  28. package/dist/containerRuntime.cjs +2535 -0
  29. package/dist/containerRuntime.cjs.map +1 -0
  30. package/dist/containerRuntime.d.ts +458 -256
  31. package/dist/containerRuntime.d.ts.map +1 -1
  32. package/dist/{dataStore.js → dataStore.cjs} +54 -45
  33. package/dist/dataStore.cjs.map +1 -0
  34. package/dist/dataStore.d.ts +2 -2
  35. package/dist/dataStore.d.ts.map +1 -1
  36. package/dist/{dataStoreContext.js → dataStoreContext.cjs} +343 -247
  37. package/dist/dataStoreContext.cjs.map +1 -0
  38. package/dist/dataStoreContext.d.ts +73 -41
  39. package/dist/dataStoreContext.d.ts.map +1 -1
  40. package/dist/{dataStoreContexts.js → dataStoreContexts.cjs} +19 -15
  41. package/dist/dataStoreContexts.cjs.map +1 -0
  42. package/dist/dataStoreContexts.d.ts +1 -1
  43. package/dist/dataStoreContexts.d.ts.map +1 -1
  44. package/dist/{dataStoreRegistry.js → dataStoreRegistry.cjs} +9 -4
  45. package/dist/dataStoreRegistry.cjs.map +1 -0
  46. package/dist/dataStoreRegistry.d.ts +3 -0
  47. package/dist/dataStoreRegistry.d.ts.map +1 -1
  48. package/dist/{dataStores.js → dataStores.cjs} +276 -124
  49. package/dist/dataStores.cjs.map +1 -0
  50. package/dist/dataStores.d.ts +56 -23
  51. package/dist/dataStores.d.ts.map +1 -1
  52. package/dist/deltaManagerProxyBase.cjs +77 -0
  53. package/dist/deltaManagerProxyBase.cjs.map +1 -0
  54. package/dist/deltaManagerProxyBase.d.ts +35 -0
  55. package/dist/deltaManagerProxyBase.d.ts.map +1 -0
  56. package/dist/deltaManagerSummarizerProxy.cjs +42 -0
  57. package/dist/deltaManagerSummarizerProxy.cjs.map +1 -0
  58. package/dist/deltaManagerSummarizerProxy.d.ts +19 -0
  59. package/dist/deltaManagerSummarizerProxy.d.ts.map +1 -0
  60. package/dist/{deltaScheduler.js → deltaScheduler.cjs} +25 -18
  61. package/dist/deltaScheduler.cjs.map +1 -0
  62. package/dist/deltaScheduler.d.ts +8 -6
  63. package/dist/deltaScheduler.d.ts.map +1 -1
  64. package/dist/error.cjs +21 -0
  65. package/dist/error.cjs.map +1 -0
  66. package/dist/error.d.ts +14 -0
  67. package/dist/error.d.ts.map +1 -0
  68. package/dist/gc/garbageCollection.cjs +865 -0
  69. package/dist/gc/garbageCollection.cjs.map +1 -0
  70. package/dist/gc/garbageCollection.d.ts +224 -0
  71. package/dist/gc/garbageCollection.d.ts.map +1 -0
  72. package/dist/gc/gcConfigs.cjs +160 -0
  73. package/dist/gc/gcConfigs.cjs.map +1 -0
  74. package/dist/gc/gcConfigs.d.ts +23 -0
  75. package/dist/gc/gcConfigs.d.ts.map +1 -0
  76. package/dist/gc/gcDefinitions.cjs +96 -0
  77. package/dist/gc/gcDefinitions.cjs.map +1 -0
  78. package/dist/gc/gcDefinitions.d.ts +458 -0
  79. package/dist/gc/gcDefinitions.d.ts.map +1 -0
  80. package/dist/gc/gcHelpers.cjs +235 -0
  81. package/dist/gc/gcHelpers.cjs.map +1 -0
  82. package/dist/gc/gcHelpers.d.ts +71 -0
  83. package/dist/gc/gcHelpers.d.ts.map +1 -0
  84. package/dist/gc/gcReferenceGraphAlgorithm.cjs +49 -0
  85. package/dist/gc/gcReferenceGraphAlgorithm.cjs.map +1 -0
  86. package/dist/gc/gcReferenceGraphAlgorithm.d.ts +16 -0
  87. package/dist/gc/gcReferenceGraphAlgorithm.d.ts.map +1 -0
  88. package/dist/{summarizerTypes.js → gc/gcSummaryDefinitions.cjs} +1 -6
  89. package/dist/gc/gcSummaryDefinitions.cjs.map +1 -0
  90. package/dist/gc/gcSummaryDefinitions.d.ts +52 -0
  91. package/dist/gc/gcSummaryDefinitions.d.ts.map +1 -0
  92. package/dist/gc/gcSummaryStateTracker.cjs +213 -0
  93. package/dist/gc/gcSummaryStateTracker.cjs.map +1 -0
  94. package/dist/gc/gcSummaryStateTracker.d.ts +94 -0
  95. package/dist/gc/gcSummaryStateTracker.d.ts.map +1 -0
  96. package/dist/gc/gcTelemetry.cjs +307 -0
  97. package/dist/gc/gcTelemetry.cjs.map +1 -0
  98. package/dist/gc/gcTelemetry.d.ts +99 -0
  99. package/dist/gc/gcTelemetry.d.ts.map +1 -0
  100. package/dist/gc/gcUnreferencedStateTracker.cjs +118 -0
  101. package/dist/gc/gcUnreferencedStateTracker.cjs.map +1 -0
  102. package/dist/gc/gcUnreferencedStateTracker.d.ts +40 -0
  103. package/dist/gc/gcUnreferencedStateTracker.d.ts.map +1 -0
  104. package/dist/gc/index.cjs +44 -0
  105. package/dist/gc/index.cjs.map +1 -0
  106. package/dist/gc/index.d.ts +13 -0
  107. package/dist/gc/index.d.ts.map +1 -0
  108. package/dist/index.cjs +47 -0
  109. package/dist/index.cjs.map +1 -0
  110. package/dist/index.d.ts +19 -8
  111. package/dist/index.d.ts.map +1 -1
  112. package/dist/messageTypes.cjs +37 -0
  113. package/dist/messageTypes.cjs.map +1 -0
  114. package/dist/messageTypes.d.ts +142 -0
  115. package/dist/messageTypes.d.ts.map +1 -0
  116. package/dist/metadata.cjs +7 -0
  117. package/dist/metadata.cjs.map +1 -0
  118. package/dist/metadata.d.ts +24 -0
  119. package/dist/metadata.d.ts.map +1 -0
  120. package/dist/opLifecycle/batchManager.cjs +139 -0
  121. package/dist/opLifecycle/batchManager.cjs.map +1 -0
  122. package/dist/opLifecycle/batchManager.d.ts +48 -0
  123. package/dist/opLifecycle/batchManager.d.ts.map +1 -0
  124. package/dist/opLifecycle/definitions.cjs +7 -0
  125. package/dist/opLifecycle/definitions.cjs.map +1 -0
  126. package/dist/opLifecycle/definitions.d.ts +83 -0
  127. package/dist/opLifecycle/definitions.d.ts.map +1 -0
  128. package/dist/opLifecycle/index.cjs +26 -0
  129. package/dist/opLifecycle/index.cjs.map +1 -0
  130. package/dist/opLifecycle/index.d.ts +13 -0
  131. package/dist/opLifecycle/index.d.ts.map +1 -0
  132. package/dist/opLifecycle/opCompressor.cjs +84 -0
  133. package/dist/opLifecycle/opCompressor.cjs.map +1 -0
  134. package/dist/opLifecycle/opCompressor.d.ts +18 -0
  135. package/dist/opLifecycle/opCompressor.d.ts.map +1 -0
  136. package/dist/opLifecycle/opDecompressor.cjs +132 -0
  137. package/dist/opLifecycle/opDecompressor.cjs.map +1 -0
  138. package/dist/opLifecycle/opDecompressor.d.ts +25 -0
  139. package/dist/opLifecycle/opDecompressor.d.ts.map +1 -0
  140. package/dist/opLifecycle/opGroupingManager.cjs +95 -0
  141. package/dist/opLifecycle/opGroupingManager.cjs.map +1 -0
  142. package/dist/opLifecycle/opGroupingManager.d.ts +22 -0
  143. package/dist/opLifecycle/opGroupingManager.d.ts.map +1 -0
  144. package/dist/opLifecycle/opSplitter.cjs +202 -0
  145. package/dist/opLifecycle/opSplitter.cjs.map +1 -0
  146. package/dist/opLifecycle/opSplitter.d.ts +61 -0
  147. package/dist/opLifecycle/opSplitter.d.ts.map +1 -0
  148. package/dist/opLifecycle/outbox.cjs +326 -0
  149. package/dist/opLifecycle/outbox.cjs.map +1 -0
  150. package/dist/opLifecycle/outbox.d.ts +104 -0
  151. package/dist/opLifecycle/outbox.d.ts.map +1 -0
  152. package/dist/opLifecycle/remoteMessageProcessor.cjs +136 -0
  153. package/dist/opLifecycle/remoteMessageProcessor.cjs.map +1 -0
  154. package/dist/opLifecycle/remoteMessageProcessor.d.ts +47 -0
  155. package/dist/opLifecycle/remoteMessageProcessor.d.ts.map +1 -0
  156. package/dist/opProperties.cjs +17 -0
  157. package/dist/opProperties.cjs.map +1 -0
  158. package/dist/opProperties.d.ts +7 -0
  159. package/dist/opProperties.d.ts.map +1 -0
  160. package/dist/{packageVersion.js → packageVersion.cjs} +2 -2
  161. package/dist/packageVersion.cjs.map +1 -0
  162. package/dist/packageVersion.d.ts +1 -1
  163. package/dist/packageVersion.d.ts.map +1 -1
  164. package/dist/pendingStateManager.cjs +282 -0
  165. package/dist/pendingStateManager.cjs.map +1 -0
  166. package/dist/pendingStateManager.d.ts +32 -69
  167. package/dist/pendingStateManager.d.ts.map +1 -1
  168. package/dist/scheduleManager.cjs +258 -0
  169. package/dist/scheduleManager.cjs.map +1 -0
  170. package/dist/scheduleManager.d.ts +31 -0
  171. package/dist/scheduleManager.d.ts.map +1 -0
  172. package/dist/storageServiceWithAttachBlobs.cjs +32 -0
  173. package/dist/storageServiceWithAttachBlobs.cjs.map +1 -0
  174. package/dist/storageServiceWithAttachBlobs.d.ts +17 -0
  175. package/dist/storageServiceWithAttachBlobs.d.ts.map +1 -0
  176. package/dist/summary/index.cjs +51 -0
  177. package/dist/summary/index.cjs.map +1 -0
  178. package/dist/summary/index.d.ts +17 -0
  179. package/dist/summary/index.d.ts.map +1 -0
  180. package/dist/{orderedClientElection.js → summary/orderedClientElection.cjs} +100 -84
  181. package/dist/summary/orderedClientElection.cjs.map +1 -0
  182. package/{lib → dist/summary}/orderedClientElection.d.ts +41 -18
  183. package/dist/summary/orderedClientElection.d.ts.map +1 -0
  184. package/dist/{runWhileConnectedCoordinator.js → summary/runWhileConnectedCoordinator.cjs} +12 -10
  185. package/dist/summary/runWhileConnectedCoordinator.cjs.map +1 -0
  186. package/{lib → dist/summary}/runWhileConnectedCoordinator.d.ts +8 -2
  187. package/dist/summary/runWhileConnectedCoordinator.d.ts.map +1 -0
  188. package/dist/summary/runningSummarizer.cjs +679 -0
  189. package/dist/summary/runningSummarizer.cjs.map +1 -0
  190. package/dist/summary/runningSummarizer.d.ts +128 -0
  191. package/dist/summary/runningSummarizer.d.ts.map +1 -0
  192. package/dist/summary/summarizer.cjs +263 -0
  193. package/dist/summary/summarizer.cjs.map +1 -0
  194. package/dist/{summarizer.d.ts → summary/summarizer.d.ts} +18 -33
  195. package/dist/summary/summarizer.d.ts.map +1 -0
  196. package/dist/{summarizerClientElection.js → summary/summarizerClientElection.cjs} +15 -46
  197. package/dist/summary/summarizerClientElection.cjs.map +1 -0
  198. package/{lib → dist/summary}/summarizerClientElection.d.ts +4 -4
  199. package/dist/summary/summarizerClientElection.d.ts.map +1 -0
  200. package/dist/summary/summarizerHeuristics.cjs +156 -0
  201. package/dist/summary/summarizerHeuristics.cjs.map +1 -0
  202. package/{lib → dist/summary}/summarizerHeuristics.d.ts +28 -6
  203. package/dist/summary/summarizerHeuristics.d.ts.map +1 -0
  204. package/dist/summary/summarizerNode/index.cjs +12 -0
  205. package/dist/summary/summarizerNode/index.cjs.map +1 -0
  206. package/dist/summary/summarizerNode/index.d.ts +8 -0
  207. package/dist/summary/summarizerNode/index.d.ts.map +1 -0
  208. package/dist/summary/summarizerNode/summarizerNode.cjs +526 -0
  209. package/dist/summary/summarizerNode/summarizerNode.cjs.map +1 -0
  210. package/dist/summary/summarizerNode/summarizerNode.d.ts +167 -0
  211. package/dist/summary/summarizerNode/summarizerNode.d.ts.map +1 -0
  212. package/dist/summary/summarizerNode/summarizerNodeUtils.cjs +130 -0
  213. package/dist/summary/summarizerNode/summarizerNodeUtils.cjs.map +1 -0
  214. package/dist/summary/summarizerNode/summarizerNodeUtils.d.ts +121 -0
  215. package/dist/summary/summarizerNode/summarizerNodeUtils.d.ts.map +1 -0
  216. package/dist/summary/summarizerNode/summarizerNodeWithGc.cjs +375 -0
  217. package/dist/summary/summarizerNode/summarizerNodeWithGc.cjs.map +1 -0
  218. package/dist/summary/summarizerNode/summarizerNodeWithGc.d.ts +153 -0
  219. package/dist/summary/summarizerNode/summarizerNodeWithGc.d.ts.map +1 -0
  220. package/dist/summary/summarizerTypes.cjs +7 -0
  221. package/dist/summary/summarizerTypes.cjs.map +1 -0
  222. package/{lib → dist/summary}/summarizerTypes.d.ts +233 -83
  223. package/dist/summary/summarizerTypes.d.ts.map +1 -0
  224. package/dist/{summaryCollection.js → summary/summaryCollection.cjs} +80 -49
  225. package/dist/summary/summaryCollection.cjs.map +1 -0
  226. package/dist/{summaryCollection.d.ts → summary/summaryCollection.d.ts} +23 -5
  227. package/dist/summary/summaryCollection.d.ts.map +1 -0
  228. package/dist/{summaryFormat.js → summary/summaryFormat.cjs} +29 -26
  229. package/dist/summary/summaryFormat.cjs.map +1 -0
  230. package/{lib → dist/summary}/summaryFormat.d.ts +25 -30
  231. package/dist/summary/summaryFormat.d.ts.map +1 -0
  232. package/dist/{summaryGenerator.js → summary/summaryGenerator.cjs} +162 -74
  233. package/dist/summary/summaryGenerator.cjs.map +1 -0
  234. package/dist/{summaryGenerator.d.ts → summary/summaryGenerator.d.ts} +53 -11
  235. package/dist/summary/summaryGenerator.d.ts.map +1 -0
  236. package/dist/{summaryManager.js → summary/summaryManager.cjs} +98 -55
  237. package/dist/summary/summaryManager.cjs.map +1 -0
  238. package/{lib → dist/summary}/summaryManager.d.ts +13 -11
  239. package/dist/summary/summaryManager.d.ts.map +1 -0
  240. package/dist/{throttler.js → throttler.cjs} +21 -21
  241. package/dist/throttler.cjs.map +1 -0
  242. package/dist/throttler.d.ts +2 -2
  243. package/dist/throttler.d.ts.map +1 -1
  244. package/dist/tsdoc-metadata.json +11 -0
  245. package/lib/{batchTracker.d.ts → batchTracker.d.mts} +7 -6
  246. package/lib/batchTracker.d.mts.map +1 -0
  247. package/lib/{batchTracker.js → batchTracker.mjs} +9 -8
  248. package/lib/batchTracker.mjs.map +1 -0
  249. package/lib/blobManager.d.mts +196 -0
  250. package/lib/blobManager.d.mts.map +1 -0
  251. package/lib/blobManager.mjs +704 -0
  252. package/lib/blobManager.mjs.map +1 -0
  253. package/lib/{connectionTelemetry.d.ts → connectionTelemetry.d.mts} +3 -3
  254. package/lib/connectionTelemetry.d.mts.map +1 -0
  255. package/lib/connectionTelemetry.mjs +226 -0
  256. package/lib/connectionTelemetry.mjs.map +1 -0
  257. package/lib/container-runtime-alpha.d.mts +1690 -0
  258. package/lib/container-runtime-beta.d.mts +250 -0
  259. package/lib/container-runtime-public.d.mts +250 -0
  260. package/lib/container-runtime-untrimmed.d.mts +1805 -0
  261. package/lib/{containerHandleContext.d.ts → containerHandleContext.d.mts} +2 -2
  262. package/lib/containerHandleContext.d.mts.map +1 -0
  263. package/lib/{containerHandleContext.js → containerHandleContext.mjs} +4 -2
  264. package/lib/containerHandleContext.mjs.map +1 -0
  265. package/lib/containerRuntime.d.mts +813 -0
  266. package/lib/containerRuntime.d.mts.map +1 -0
  267. package/lib/containerRuntime.mjs +2530 -0
  268. package/lib/containerRuntime.mjs.map +1 -0
  269. package/lib/{dataStore.d.ts → dataStore.d.mts} +5 -5
  270. package/lib/dataStore.d.mts.map +1 -0
  271. package/lib/{dataStore.js → dataStore.mjs} +52 -43
  272. package/lib/dataStore.mjs.map +1 -0
  273. package/lib/{dataStoreContext.d.ts → dataStoreContext.d.mts} +75 -43
  274. package/lib/dataStoreContext.d.mts.map +1 -0
  275. package/lib/{dataStoreContext.js → dataStoreContext.mjs} +309 -213
  276. package/lib/dataStoreContext.mjs.map +1 -0
  277. package/lib/{dataStoreContexts.d.ts → dataStoreContexts.d.mts} +3 -3
  278. package/lib/dataStoreContexts.d.mts.map +1 -0
  279. package/lib/{dataStoreContexts.js → dataStoreContexts.mjs} +12 -8
  280. package/lib/dataStoreContexts.mjs.map +1 -0
  281. package/lib/{dataStoreRegistry.d.ts → dataStoreRegistry.d.mts} +4 -1
  282. package/lib/dataStoreRegistry.d.mts.map +1 -0
  283. package/lib/{dataStoreRegistry.js → dataStoreRegistry.mjs} +7 -6
  284. package/lib/dataStoreRegistry.mjs.map +1 -0
  285. package/lib/{dataStores.d.ts → dataStores.d.mts} +60 -27
  286. package/lib/dataStores.d.mts.map +1 -0
  287. package/lib/{dataStores.js → dataStores.mjs} +257 -105
  288. package/lib/dataStores.mjs.map +1 -0
  289. package/lib/deltaManagerProxyBase.d.mts +35 -0
  290. package/lib/deltaManagerProxyBase.d.mts.map +1 -0
  291. package/lib/deltaManagerProxyBase.mjs +73 -0
  292. package/lib/deltaManagerProxyBase.mjs.map +1 -0
  293. package/lib/deltaManagerSummarizerProxy.d.mts +19 -0
  294. package/lib/deltaManagerSummarizerProxy.d.mts.map +1 -0
  295. package/lib/deltaManagerSummarizerProxy.mjs +38 -0
  296. package/lib/deltaManagerSummarizerProxy.mjs.map +1 -0
  297. package/lib/{deltaScheduler.d.ts → deltaScheduler.d.mts} +9 -7
  298. package/lib/deltaScheduler.d.mts.map +1 -0
  299. package/lib/{deltaScheduler.js → deltaScheduler.mjs} +22 -15
  300. package/lib/deltaScheduler.mjs.map +1 -0
  301. package/lib/error.d.mts +14 -0
  302. package/lib/error.d.mts.map +1 -0
  303. package/lib/error.mjs +17 -0
  304. package/lib/error.mjs.map +1 -0
  305. package/lib/gc/garbageCollection.d.mts +224 -0
  306. package/lib/gc/garbageCollection.d.mts.map +1 -0
  307. package/lib/gc/garbageCollection.mjs +861 -0
  308. package/lib/gc/garbageCollection.mjs.map +1 -0
  309. package/lib/gc/gcConfigs.d.mts +23 -0
  310. package/lib/gc/gcConfigs.d.mts.map +1 -0
  311. package/lib/gc/gcConfigs.mjs +156 -0
  312. package/lib/gc/gcConfigs.mjs.map +1 -0
  313. package/lib/gc/gcDefinitions.d.mts +458 -0
  314. package/lib/gc/gcDefinitions.d.mts.map +1 -0
  315. package/lib/gc/gcDefinitions.mjs +93 -0
  316. package/lib/gc/gcDefinitions.mjs.map +1 -0
  317. package/lib/gc/gcHelpers.d.mts +71 -0
  318. package/lib/gc/gcHelpers.d.mts.map +1 -0
  319. package/lib/gc/gcHelpers.mjs +222 -0
  320. package/lib/gc/gcHelpers.mjs.map +1 -0
  321. package/lib/gc/gcReferenceGraphAlgorithm.d.mts +16 -0
  322. package/lib/gc/gcReferenceGraphAlgorithm.d.mts.map +1 -0
  323. package/lib/gc/gcReferenceGraphAlgorithm.mjs +45 -0
  324. package/lib/gc/gcReferenceGraphAlgorithm.mjs.map +1 -0
  325. package/lib/gc/gcSummaryDefinitions.d.mts +52 -0
  326. package/lib/gc/gcSummaryDefinitions.d.mts.map +1 -0
  327. package/lib/gc/gcSummaryDefinitions.mjs +6 -0
  328. package/lib/gc/gcSummaryDefinitions.mjs.map +1 -0
  329. package/lib/gc/gcSummaryStateTracker.d.mts +94 -0
  330. package/lib/gc/gcSummaryStateTracker.d.mts.map +1 -0
  331. package/lib/gc/gcSummaryStateTracker.mjs +209 -0
  332. package/lib/gc/gcSummaryStateTracker.mjs.map +1 -0
  333. package/lib/gc/gcTelemetry.d.mts +99 -0
  334. package/lib/gc/gcTelemetry.d.mts.map +1 -0
  335. package/lib/gc/gcTelemetry.mjs +302 -0
  336. package/lib/gc/gcTelemetry.mjs.map +1 -0
  337. package/lib/gc/gcUnreferencedStateTracker.d.mts +40 -0
  338. package/lib/gc/gcUnreferencedStateTracker.d.mts.map +1 -0
  339. package/lib/gc/gcUnreferencedStateTracker.mjs +114 -0
  340. package/lib/gc/gcUnreferencedStateTracker.mjs.map +1 -0
  341. package/lib/gc/index.d.mts +13 -0
  342. package/lib/gc/index.d.mts.map +1 -0
  343. package/lib/gc/index.mjs +12 -0
  344. package/lib/gc/index.mjs.map +1 -0
  345. package/lib/index.d.mts +25 -0
  346. package/lib/index.d.mts.map +1 -0
  347. package/lib/index.mjs +24 -0
  348. package/lib/index.mjs.map +1 -0
  349. package/lib/messageTypes.d.mts +142 -0
  350. package/lib/messageTypes.d.mts.map +1 -0
  351. package/lib/messageTypes.mjs +34 -0
  352. package/lib/messageTypes.mjs.map +1 -0
  353. package/lib/metadata.d.mts +24 -0
  354. package/lib/metadata.d.mts.map +1 -0
  355. package/lib/metadata.mjs +6 -0
  356. package/lib/metadata.mjs.map +1 -0
  357. package/lib/opLifecycle/batchManager.d.mts +48 -0
  358. package/lib/opLifecycle/batchManager.d.mts.map +1 -0
  359. package/lib/opLifecycle/batchManager.mjs +133 -0
  360. package/lib/opLifecycle/batchManager.mjs.map +1 -0
  361. package/lib/opLifecycle/definitions.d.mts +83 -0
  362. package/lib/opLifecycle/definitions.d.mts.map +1 -0
  363. package/lib/opLifecycle/definitions.mjs +6 -0
  364. package/lib/opLifecycle/definitions.mjs.map +1 -0
  365. package/lib/opLifecycle/index.d.mts +13 -0
  366. package/lib/opLifecycle/index.d.mts.map +1 -0
  367. package/lib/opLifecycle/index.mjs +12 -0
  368. package/lib/opLifecycle/index.mjs.map +1 -0
  369. package/lib/opLifecycle/opCompressor.d.mts +18 -0
  370. package/lib/opLifecycle/opCompressor.d.mts.map +1 -0
  371. package/lib/opLifecycle/opCompressor.mjs +80 -0
  372. package/lib/opLifecycle/opCompressor.mjs.map +1 -0
  373. package/lib/opLifecycle/opDecompressor.d.mts +25 -0
  374. package/lib/opLifecycle/opDecompressor.d.mts.map +1 -0
  375. package/lib/opLifecycle/opDecompressor.mjs +128 -0
  376. package/lib/opLifecycle/opDecompressor.mjs.map +1 -0
  377. package/lib/opLifecycle/opGroupingManager.d.mts +22 -0
  378. package/lib/opLifecycle/opGroupingManager.d.mts.map +1 -0
  379. package/lib/opLifecycle/opGroupingManager.mjs +91 -0
  380. package/lib/opLifecycle/opGroupingManager.mjs.map +1 -0
  381. package/lib/opLifecycle/opSplitter.d.mts +61 -0
  382. package/lib/opLifecycle/opSplitter.d.mts.map +1 -0
  383. package/lib/opLifecycle/opSplitter.mjs +197 -0
  384. package/lib/opLifecycle/opSplitter.mjs.map +1 -0
  385. package/lib/opLifecycle/outbox.d.mts +104 -0
  386. package/lib/opLifecycle/outbox.d.mts.map +1 -0
  387. package/lib/opLifecycle/outbox.mjs +321 -0
  388. package/lib/opLifecycle/outbox.mjs.map +1 -0
  389. package/lib/opLifecycle/remoteMessageProcessor.d.mts +47 -0
  390. package/lib/opLifecycle/remoteMessageProcessor.d.mts.map +1 -0
  391. package/lib/opLifecycle/remoteMessageProcessor.mjs +131 -0
  392. package/lib/opLifecycle/remoteMessageProcessor.mjs.map +1 -0
  393. package/lib/opProperties.d.mts +7 -0
  394. package/lib/opProperties.d.mts.map +1 -0
  395. package/lib/opProperties.mjs +13 -0
  396. package/lib/opProperties.mjs.map +1 -0
  397. package/lib/{packageVersion.d.ts → packageVersion.d.mts} +2 -2
  398. package/lib/packageVersion.d.mts.map +1 -0
  399. package/lib/{packageVersion.js → packageVersion.mjs} +2 -2
  400. package/lib/packageVersion.mjs.map +1 -0
  401. package/lib/{pendingStateManager.d.ts → pendingStateManager.d.mts} +33 -70
  402. package/lib/pendingStateManager.d.mts.map +1 -0
  403. package/lib/pendingStateManager.mjs +275 -0
  404. package/lib/pendingStateManager.mjs.map +1 -0
  405. package/lib/scheduleManager.d.mts +27 -0
  406. package/lib/scheduleManager.d.mts.map +1 -0
  407. package/lib/scheduleManager.mjs +254 -0
  408. package/lib/scheduleManager.mjs.map +1 -0
  409. package/lib/storageServiceWithAttachBlobs.d.mts +17 -0
  410. package/lib/storageServiceWithAttachBlobs.d.mts.map +1 -0
  411. package/lib/storageServiceWithAttachBlobs.mjs +28 -0
  412. package/lib/storageServiceWithAttachBlobs.mjs.map +1 -0
  413. package/lib/summary/index.d.mts +17 -0
  414. package/lib/summary/index.d.mts.map +1 -0
  415. package/lib/summary/index.mjs +16 -0
  416. package/lib/summary/index.mjs.map +1 -0
  417. package/{dist/orderedClientElection.d.ts → lib/summary/orderedClientElection.d.mts} +42 -23
  418. package/lib/summary/orderedClientElection.d.mts.map +1 -0
  419. package/lib/{orderedClientElection.js → summary/orderedClientElection.mjs} +95 -79
  420. package/lib/summary/orderedClientElection.mjs.map +1 -0
  421. package/{dist/runWhileConnectedCoordinator.d.ts → lib/summary/runWhileConnectedCoordinator.d.mts} +10 -4
  422. package/lib/summary/runWhileConnectedCoordinator.d.mts.map +1 -0
  423. package/lib/{runWhileConnectedCoordinator.js → summary/runWhileConnectedCoordinator.mjs} +12 -10
  424. package/lib/summary/runWhileConnectedCoordinator.mjs.map +1 -0
  425. package/lib/summary/runningSummarizer.d.mts +128 -0
  426. package/lib/summary/runningSummarizer.d.mts.map +1 -0
  427. package/lib/summary/runningSummarizer.mjs +675 -0
  428. package/lib/summary/runningSummarizer.mjs.map +1 -0
  429. package/lib/{summarizer.d.ts → summary/summarizer.d.mts} +21 -36
  430. package/lib/summary/summarizer.d.mts.map +1 -0
  431. package/lib/summary/summarizer.mjs +257 -0
  432. package/lib/summary/summarizer.mjs.map +1 -0
  433. package/{dist/summarizerClientElection.d.ts → lib/summary/summarizerClientElection.d.mts} +7 -7
  434. package/lib/summary/summarizerClientElection.d.mts.map +1 -0
  435. package/lib/{summarizerClientElection.js → summary/summarizerClientElection.mjs} +14 -45
  436. package/lib/summary/summarizerClientElection.mjs.map +1 -0
  437. package/{dist/summarizerHeuristics.d.ts → lib/summary/summarizerHeuristics.d.mts} +30 -8
  438. package/lib/summary/summarizerHeuristics.d.mts.map +1 -0
  439. package/lib/summary/summarizerHeuristics.mjs +151 -0
  440. package/lib/summary/summarizerHeuristics.mjs.map +1 -0
  441. package/lib/summary/summarizerNode/index.d.mts +8 -0
  442. package/lib/summary/summarizerNode/index.d.mts.map +1 -0
  443. package/lib/summary/summarizerNode/index.mjs +7 -0
  444. package/lib/summary/summarizerNode/index.mjs.map +1 -0
  445. package/lib/summary/summarizerNode/summarizerNode.d.mts +167 -0
  446. package/lib/summary/summarizerNode/summarizerNode.d.mts.map +1 -0
  447. package/lib/summary/summarizerNode/summarizerNode.mjs +521 -0
  448. package/lib/summary/summarizerNode/summarizerNode.mjs.map +1 -0
  449. package/lib/summary/summarizerNode/summarizerNodeUtils.d.mts +121 -0
  450. package/lib/summary/summarizerNode/summarizerNodeUtils.d.mts.map +1 -0
  451. package/lib/summary/summarizerNode/summarizerNodeUtils.mjs +123 -0
  452. package/lib/summary/summarizerNode/summarizerNodeUtils.mjs.map +1 -0
  453. package/lib/summary/summarizerNode/summarizerNodeWithGc.d.mts +153 -0
  454. package/lib/summary/summarizerNode/summarizerNodeWithGc.d.mts.map +1 -0
  455. package/lib/summary/summarizerNode/summarizerNodeWithGc.mjs +370 -0
  456. package/lib/summary/summarizerNode/summarizerNodeWithGc.mjs.map +1 -0
  457. package/{dist/summarizerTypes.d.ts → lib/summary/summarizerTypes.d.mts} +235 -85
  458. package/lib/summary/summarizerTypes.d.mts.map +1 -0
  459. package/lib/summary/summarizerTypes.mjs +6 -0
  460. package/lib/summary/summarizerTypes.mjs.map +1 -0
  461. package/lib/{summaryCollection.d.ts → summary/summaryCollection.d.mts} +24 -6
  462. package/lib/summary/summaryCollection.d.mts.map +1 -0
  463. package/lib/{summaryCollection.js → summary/summaryCollection.mjs} +76 -45
  464. package/lib/summary/summaryCollection.mjs.map +1 -0
  465. package/{dist/summaryFormat.d.ts → lib/summary/summaryFormat.d.mts} +26 -31
  466. package/lib/summary/summaryFormat.d.mts.map +1 -0
  467. package/lib/{summaryFormat.js → summary/summaryFormat.mjs} +30 -26
  468. package/lib/summary/summaryFormat.mjs.map +1 -0
  469. package/lib/summary/summaryGenerator.d.mts +127 -0
  470. package/lib/summary/summaryGenerator.d.mts.map +1 -0
  471. package/lib/{summaryGenerator.js → summary/summaryGenerator.mjs} +153 -67
  472. package/lib/summary/summaryGenerator.mjs.map +1 -0
  473. package/{dist/summaryManager.d.ts → lib/summary/summaryManager.d.mts} +16 -14
  474. package/lib/summary/summaryManager.d.mts.map +1 -0
  475. package/lib/{summaryManager.js → summary/summaryManager.mjs} +94 -51
  476. package/lib/summary/summaryManager.mjs.map +1 -0
  477. package/lib/{throttler.d.ts → throttler.d.mts} +3 -3
  478. package/lib/throttler.d.mts.map +1 -0
  479. package/lib/{throttler.js → throttler.mjs} +21 -21
  480. package/lib/throttler.mjs.map +1 -0
  481. package/package.json +199 -71
  482. package/prettier.config.cjs +8 -0
  483. package/src/batchTracker.ts +59 -54
  484. package/src/blobManager.ts +942 -294
  485. package/src/connectionTelemetry.ts +342 -252
  486. package/src/containerHandleContext.ts +27 -29
  487. package/src/containerRuntime.ts +3883 -3143
  488. package/src/dataStore.ts +170 -140
  489. package/src/dataStoreContext.ts +1166 -986
  490. package/src/dataStoreContexts.ts +176 -163
  491. package/src/dataStoreRegistry.ts +29 -21
  492. package/src/dataStores.ts +924 -678
  493. package/src/deltaManagerProxyBase.ts +111 -0
  494. package/src/deltaManagerSummarizerProxy.ts +49 -0
  495. package/src/deltaScheduler.ts +161 -156
  496. package/src/error.ts +21 -0
  497. package/src/gc/garbageCollection.md +106 -0
  498. package/src/gc/garbageCollection.ts +1157 -0
  499. package/src/gc/gcConfigs.ts +224 -0
  500. package/src/gc/gcDefinitions.ts +524 -0
  501. package/src/gc/gcHelpers.ts +284 -0
  502. package/src/gc/gcReferenceGraphAlgorithm.ts +52 -0
  503. package/src/gc/gcSummaryDefinitions.ts +54 -0
  504. package/src/gc/gcSummaryStateTracker.ts +299 -0
  505. package/src/gc/gcTelemetry.ts +433 -0
  506. package/src/gc/gcUnreferencedStateTracker.ts +153 -0
  507. package/src/gc/index.ts +60 -0
  508. package/src/index.ts +101 -74
  509. package/src/messageTypes.ts +238 -0
  510. package/src/metadata.ts +26 -0
  511. package/src/opLifecycle/README.md +321 -0
  512. package/src/opLifecycle/batchManager.ts +179 -0
  513. package/src/opLifecycle/definitions.ts +89 -0
  514. package/src/opLifecycle/index.ts +19 -0
  515. package/src/opLifecycle/opCompressor.ts +99 -0
  516. package/src/opLifecycle/opDecompressor.ts +190 -0
  517. package/src/opLifecycle/opGroupingManager.ts +133 -0
  518. package/src/opLifecycle/opSplitter.ts +279 -0
  519. package/src/opLifecycle/outbox.ts +474 -0
  520. package/src/opLifecycle/remoteMessageProcessor.ts +175 -0
  521. package/src/opProperties.ts +21 -0
  522. package/src/packageVersion.ts +1 -1
  523. package/src/pendingStateManager.ts +396 -465
  524. package/src/scheduleManager.ts +358 -0
  525. package/src/storageServiceWithAttachBlobs.ts +38 -0
  526. package/src/summary/index.ts +109 -0
  527. package/src/summary/orderedClientElection.ts +571 -0
  528. package/src/summary/runWhileConnectedCoordinator.ts +117 -0
  529. package/src/summary/runningSummarizer.ts +920 -0
  530. package/src/summary/summarizer.ts +352 -0
  531. package/src/summary/summarizerClientElection.ts +140 -0
  532. package/src/summary/summarizerHeuristics.ts +227 -0
  533. package/src/summary/summarizerNode/index.ts +12 -0
  534. package/src/summary/summarizerNode/summarizerNode.ts +725 -0
  535. package/src/summary/summarizerNode/summarizerNodeUtils.ts +206 -0
  536. package/src/summary/summarizerNode/summarizerNodeWithGc.ts +571 -0
  537. package/src/summary/summarizerTypes.ts +631 -0
  538. package/src/summary/summaryCollection.ts +474 -0
  539. package/src/summary/summaryFormat.ts +249 -0
  540. package/src/summary/summaryGenerator.ts +539 -0
  541. package/src/summary/summaryManager.ts +452 -0
  542. package/src/throttler.ts +131 -122
  543. package/tsc-multi.test.json +4 -0
  544. package/tsconfig.json +11 -13
  545. package/dist/batchTracker.js.map +0 -1
  546. package/dist/blobManager.js +0 -249
  547. package/dist/blobManager.js.map +0 -1
  548. package/dist/connectionTelemetry.js +0 -178
  549. package/dist/connectionTelemetry.js.map +0 -1
  550. package/dist/containerHandleContext.js.map +0 -1
  551. package/dist/containerRuntime.js +0 -2174
  552. package/dist/containerRuntime.js.map +0 -1
  553. package/dist/dataStore.js.map +0 -1
  554. package/dist/dataStoreContext.js.map +0 -1
  555. package/dist/dataStoreContexts.js.map +0 -1
  556. package/dist/dataStoreRegistry.js.map +0 -1
  557. package/dist/dataStores.js.map +0 -1
  558. package/dist/deltaScheduler.js.map +0 -1
  559. package/dist/garbageCollection.d.ts +0 -319
  560. package/dist/garbageCollection.d.ts.map +0 -1
  561. package/dist/garbageCollection.js +0 -993
  562. package/dist/garbageCollection.js.map +0 -1
  563. package/dist/index.js +0 -33
  564. package/dist/index.js.map +0 -1
  565. package/dist/opTelemetry.d.ts +0 -22
  566. package/dist/opTelemetry.d.ts.map +0 -1
  567. package/dist/opTelemetry.js +0 -60
  568. package/dist/opTelemetry.js.map +0 -1
  569. package/dist/orderedClientElection.d.ts.map +0 -1
  570. package/dist/orderedClientElection.js.map +0 -1
  571. package/dist/packageVersion.js.map +0 -1
  572. package/dist/pendingStateManager.js +0 -346
  573. package/dist/pendingStateManager.js.map +0 -1
  574. package/dist/runWhileConnectedCoordinator.d.ts.map +0 -1
  575. package/dist/runWhileConnectedCoordinator.js.map +0 -1
  576. package/dist/runningSummarizer.d.ts +0 -93
  577. package/dist/runningSummarizer.d.ts.map +0 -1
  578. package/dist/runningSummarizer.js +0 -384
  579. package/dist/runningSummarizer.js.map +0 -1
  580. package/dist/serializedSnapshotStorage.d.ts +0 -58
  581. package/dist/serializedSnapshotStorage.d.ts.map +0 -1
  582. package/dist/serializedSnapshotStorage.js +0 -108
  583. package/dist/serializedSnapshotStorage.js.map +0 -1
  584. package/dist/summarizer.d.ts.map +0 -1
  585. package/dist/summarizer.js +0 -348
  586. package/dist/summarizer.js.map +0 -1
  587. package/dist/summarizerClientElection.d.ts.map +0 -1
  588. package/dist/summarizerClientElection.js.map +0 -1
  589. package/dist/summarizerHandle.d.ts +0 -12
  590. package/dist/summarizerHandle.d.ts.map +0 -1
  591. package/dist/summarizerHandle.js +0 -22
  592. package/dist/summarizerHandle.js.map +0 -1
  593. package/dist/summarizerHeuristics.d.ts.map +0 -1
  594. package/dist/summarizerHeuristics.js +0 -84
  595. package/dist/summarizerHeuristics.js.map +0 -1
  596. package/dist/summarizerTypes.d.ts.map +0 -1
  597. package/dist/summarizerTypes.js.map +0 -1
  598. package/dist/summaryCollection.d.ts.map +0 -1
  599. package/dist/summaryCollection.js.map +0 -1
  600. package/dist/summaryFormat.d.ts.map +0 -1
  601. package/dist/summaryFormat.js.map +0 -1
  602. package/dist/summaryGenerator.d.ts.map +0 -1
  603. package/dist/summaryGenerator.js.map +0 -1
  604. package/dist/summaryManager.d.ts.map +0 -1
  605. package/dist/summaryManager.js.map +0 -1
  606. package/dist/throttler.js.map +0 -1
  607. package/garbageCollection.md +0 -41
  608. package/lib/batchTracker.d.ts.map +0 -1
  609. package/lib/batchTracker.js.map +0 -1
  610. package/lib/blobManager.d.ts +0 -95
  611. package/lib/blobManager.d.ts.map +0 -1
  612. package/lib/blobManager.js +0 -244
  613. package/lib/blobManager.js.map +0 -1
  614. package/lib/connectionTelemetry.d.ts.map +0 -1
  615. package/lib/connectionTelemetry.js +0 -174
  616. package/lib/connectionTelemetry.js.map +0 -1
  617. package/lib/containerHandleContext.d.ts.map +0 -1
  618. package/lib/containerHandleContext.js.map +0 -1
  619. package/lib/containerRuntime.d.ts +0 -615
  620. package/lib/containerRuntime.d.ts.map +0 -1
  621. package/lib/containerRuntime.js +0 -2166
  622. package/lib/containerRuntime.js.map +0 -1
  623. package/lib/dataStore.d.ts.map +0 -1
  624. package/lib/dataStore.js.map +0 -1
  625. package/lib/dataStoreContext.d.ts.map +0 -1
  626. package/lib/dataStoreContext.js.map +0 -1
  627. package/lib/dataStoreContexts.d.ts.map +0 -1
  628. package/lib/dataStoreContexts.js.map +0 -1
  629. package/lib/dataStoreRegistry.d.ts.map +0 -1
  630. package/lib/dataStoreRegistry.js.map +0 -1
  631. package/lib/dataStores.d.ts.map +0 -1
  632. package/lib/dataStores.js.map +0 -1
  633. package/lib/deltaScheduler.d.ts.map +0 -1
  634. package/lib/deltaScheduler.js.map +0 -1
  635. package/lib/garbageCollection.d.ts +0 -319
  636. package/lib/garbageCollection.d.ts.map +0 -1
  637. package/lib/garbageCollection.js +0 -989
  638. package/lib/garbageCollection.js.map +0 -1
  639. package/lib/index.d.ts +0 -14
  640. package/lib/index.d.ts.map +0 -1
  641. package/lib/index.js +0 -13
  642. package/lib/index.js.map +0 -1
  643. package/lib/opTelemetry.d.ts +0 -22
  644. package/lib/opTelemetry.d.ts.map +0 -1
  645. package/lib/opTelemetry.js +0 -56
  646. package/lib/opTelemetry.js.map +0 -1
  647. package/lib/orderedClientElection.d.ts.map +0 -1
  648. package/lib/orderedClientElection.js.map +0 -1
  649. package/lib/packageVersion.d.ts.map +0 -1
  650. package/lib/packageVersion.js.map +0 -1
  651. package/lib/pendingStateManager.d.ts.map +0 -1
  652. package/lib/pendingStateManager.js +0 -339
  653. package/lib/pendingStateManager.js.map +0 -1
  654. package/lib/runWhileConnectedCoordinator.d.ts.map +0 -1
  655. package/lib/runWhileConnectedCoordinator.js.map +0 -1
  656. package/lib/runningSummarizer.d.ts +0 -93
  657. package/lib/runningSummarizer.d.ts.map +0 -1
  658. package/lib/runningSummarizer.js +0 -380
  659. package/lib/runningSummarizer.js.map +0 -1
  660. package/lib/serializedSnapshotStorage.d.ts +0 -58
  661. package/lib/serializedSnapshotStorage.d.ts.map +0 -1
  662. package/lib/serializedSnapshotStorage.js +0 -104
  663. package/lib/serializedSnapshotStorage.js.map +0 -1
  664. package/lib/summarizer.d.ts.map +0 -1
  665. package/lib/summarizer.js +0 -342
  666. package/lib/summarizer.js.map +0 -1
  667. package/lib/summarizerClientElection.d.ts.map +0 -1
  668. package/lib/summarizerClientElection.js.map +0 -1
  669. package/lib/summarizerHandle.d.ts +0 -12
  670. package/lib/summarizerHandle.d.ts.map +0 -1
  671. package/lib/summarizerHandle.js +0 -18
  672. package/lib/summarizerHandle.js.map +0 -1
  673. package/lib/summarizerHeuristics.d.ts.map +0 -1
  674. package/lib/summarizerHeuristics.js +0 -79
  675. package/lib/summarizerHeuristics.js.map +0 -1
  676. package/lib/summarizerTypes.d.ts.map +0 -1
  677. package/lib/summarizerTypes.js +0 -9
  678. package/lib/summarizerTypes.js.map +0 -1
  679. package/lib/summaryCollection.d.ts.map +0 -1
  680. package/lib/summaryCollection.js.map +0 -1
  681. package/lib/summaryFormat.d.ts.map +0 -1
  682. package/lib/summaryFormat.js.map +0 -1
  683. package/lib/summaryGenerator.d.ts +0 -85
  684. package/lib/summaryGenerator.d.ts.map +0 -1
  685. package/lib/summaryGenerator.js.map +0 -1
  686. package/lib/summaryManager.d.ts.map +0 -1
  687. package/lib/summaryManager.js.map +0 -1
  688. package/lib/throttler.d.ts.map +0 -1
  689. package/lib/throttler.js.map +0 -1
  690. package/src/garbageCollection.ts +0 -1434
  691. package/src/opTelemetry.ts +0 -71
  692. package/src/orderedClientElection.ts +0 -511
  693. package/src/runWhileConnectedCoordinator.ts +0 -106
  694. package/src/runningSummarizer.ts +0 -550
  695. package/src/serializedSnapshotStorage.ts +0 -146
  696. package/src/summarizer.ts +0 -438
  697. package/src/summarizerClientElection.ts +0 -161
  698. package/src/summarizerHandle.ts +0 -21
  699. package/src/summarizerHeuristics.ts +0 -108
  700. package/src/summarizerTypes.ts +0 -462
  701. package/src/summaryCollection.ts +0 -406
  702. package/src/summaryFormat.ts +0 -239
  703. package/src/summaryGenerator.ts +0 -427
  704. package/src/summaryManager.ts +0 -368
  705. package/tsconfig.esnext.json +0 -7
@@ -0,0 +1,2530 @@
1
+ import { AttachState, LoaderHeader, } from "@fluidframework/container-definitions";
2
+ import { assert, delay, LazyPromise } from "@fluidframework/core-utils";
3
+ import { Trace, TypedEventEmitter } from "@fluid-internal/client-utils";
4
+ import { createChildLogger, createChildMonitoringContext, DataCorruptionError, DataProcessingError, GenericError, raiseConnectedEvent, PerformanceEvent,
5
+ // eslint-disable-next-line import/no-deprecated
6
+ TaggedLoggerAdapter, wrapError, UsageError, LoggingError, } from "@fluidframework/telemetry-utils";
7
+ import { DriverHeader, FetchSource, } from "@fluidframework/driver-definitions";
8
+ import { readAndParse } from "@fluidframework/driver-utils";
9
+ import { MessageType, SummaryType, } from "@fluidframework/protocol-definitions";
10
+ import { FlushMode, FlushModeExperimental, gcTreeKey, channelsTreeName, } from "@fluidframework/runtime-definitions";
11
+ import { addBlobToSummary, addSummarizeResultToSummary, addTreeToSummary, RequestParser, create404Response, exceptionToResponse, GCDataBuilder, seqFromTree, calculateStats, TelemetryContext, responseToException, } from "@fluidframework/runtime-utils";
12
+ import { v4 as uuid } from "uuid";
13
+ import { ContainerFluidHandleContext } from "./containerHandleContext.mjs";
14
+ import { FluidDataStoreRegistry } from "./dataStoreRegistry.mjs";
15
+ import { ReportOpPerfTelemetry } from "./connectionTelemetry.mjs";
16
+ import { PendingStateManager, } from "./pendingStateManager.mjs";
17
+ import { pkgVersion } from "./packageVersion.mjs";
18
+ import { BlobManager } from "./blobManager.mjs";
19
+ import { DataStores, getSummaryForDatastores } from "./dataStores.mjs";
20
+ import { aliasBlobName, blobsTreeName, chunksBlobName, createRootSummarizerNodeWithGC, electedSummarizerBlobName, extractSummaryMetadataMessage, idCompressorBlobName, metadataBlobName, Summarizer, SummaryManager, wrapSummaryInChannelsTree, SummaryCollection, OrderedClientCollection, OrderedClientElection, SummarizerClientElection, summarizerClientType, RunWhileConnectedCoordinator, RetriableSummaryError, } from "./summary/index.mjs";
21
+ import { formExponentialFn, Throttler } from "./throttler.mjs";
22
+ import { GarbageCollector, GCNodeType, gcGenerationOptionName, trimLeadingAndTrailingSlashes, } from "./gc/index.mjs";
23
+ import { channelToDataStore, isDataStoreAliasMessage } from "./dataStore.mjs";
24
+ import { BindBatchTracker } from "./batchTracker.mjs";
25
+ import { ScheduleManager } from "./scheduleManager.mjs";
26
+ import { OpCompressor, OpDecompressor, Outbox, OpSplitter, RemoteMessageProcessor, OpGroupingManager, getLongStack, } from "./opLifecycle/index.mjs";
27
+ import { DeltaManagerSummarizerProxy } from "./deltaManagerSummarizerProxy.mjs";
28
+ import { ContainerMessageType, } from "./messageTypes.mjs";
29
+ /**
30
+ * Utility to implement compat behaviors given an unknown message type
31
+ * The parameters are typed to support compile-time enforcement of handling all known types/behaviors
32
+ *
33
+ * @param _unknownContainerRuntimeMessageType - Typed as something unexpected, to ensure all known types have been
34
+ * handled before calling this function (e.g. in a switch statement).
35
+ * @param compatBehavior - Typed redundantly with CompatModeBehavior to ensure handling is added when updating that type
36
+ */
37
+ function compatBehaviorAllowsMessageType(_unknownContainerRuntimeMessageType, compatBehavior) {
38
+ // undefined defaults to same behavior as "FailToProcess"
39
+ return compatBehavior === "Ignore";
40
+ }
41
+ /**
42
+ * @alpha
43
+ */
44
+ export const DefaultSummaryConfiguration = {
45
+ state: "enabled",
46
+ minIdleTime: 0,
47
+ maxIdleTime: 30 * 1000,
48
+ maxTime: 60 * 1000,
49
+ maxOps: 100,
50
+ minOpsForLastSummaryAttempt: 10,
51
+ maxAckWaitTime: 3 * 60 * 1000,
52
+ maxOpsSinceLastSummary: 7000,
53
+ initialSummarizerDelayMs: 5 * 1000,
54
+ nonRuntimeOpWeight: 0.1,
55
+ runtimeOpWeight: 1.0,
56
+ nonRuntimeHeuristicThreshold: 20,
57
+ };
58
+ /**
59
+ * Accepted header keys for requests coming to the runtime.
60
+ * @internal
61
+ */
62
+ export var RuntimeHeaders;
63
+ (function (RuntimeHeaders) {
64
+ /** True to wait for a data store to be created and loaded before returning it. */
65
+ RuntimeHeaders["wait"] = "wait";
66
+ /** True if the request is coming from an IFluidHandle. */
67
+ RuntimeHeaders["viaHandle"] = "viaHandle";
68
+ })(RuntimeHeaders || (RuntimeHeaders = {}));
69
+ /** True if a tombstoned object should be returned without erroring
70
+ * @alpha
71
+ */
72
+ export const AllowTombstoneRequestHeaderKey = "allowTombstone"; // Belongs in the enum above, but avoiding the breaking change
73
+ /**
74
+ * [IRRELEVANT IF throwOnInactiveLoad OPTION NOT SET] True if an inactive object should be returned without erroring
75
+ * @internal
76
+ */
77
+ export const AllowInactiveRequestHeaderKey = "allowInactive"; // Belongs in the enum above, but avoiding the breaking change
78
+ /**
79
+ * Tombstone error responses will have this header set to true
80
+ * @alpha
81
+ */
82
+ export const TombstoneResponseHeaderKey = "isTombstoned";
83
+ /**
84
+ * Inactive error responses will have this header set to true
85
+ * @alpha
86
+ */
87
+ export const InactiveResponseHeaderKey = "isInactive";
88
+ /** Default values for Runtime Headers */
89
+ export const defaultRuntimeHeaderData = {
90
+ wait: true,
91
+ viaHandle: false,
92
+ allowTombstone: false,
93
+ allowInactive: false,
94
+ };
95
+ /**
96
+ * Available compression algorithms for op compression.
97
+ * @alpha
98
+ */
99
+ export var CompressionAlgorithms;
100
+ (function (CompressionAlgorithms) {
101
+ CompressionAlgorithms["lz4"] = "lz4";
102
+ })(CompressionAlgorithms || (CompressionAlgorithms = {}));
103
+ const maxConsecutiveReconnectsKey = "Fluid.ContainerRuntime.MaxConsecutiveReconnects";
104
+ const defaultFlushMode = FlushMode.TurnBased;
105
+ // The actual limit is 1Mb (socket.io and Kafka limits)
106
+ // We can't estimate it fully, as we
107
+ // - do not know what properties relay service will add
108
+ // - we do not stringify final op, thus we do not know how much escaping will be added.
109
+ const defaultMaxBatchSizeInBytes = 700 * 1024;
110
+ const defaultCompressionConfig = {
111
+ // Batches with content size exceeding this value will be compressed
112
+ minimumBatchSizeInBytes: 614400,
113
+ compressionAlgorithm: CompressionAlgorithms.lz4,
114
+ };
115
+ const defaultChunkSizeInBytes = 204800;
116
+ /** The default time to wait for pending ops to be processed during summarization */
117
+ export const defaultPendingOpsWaitTimeoutMs = 1000;
118
+ /** The default time to delay a summarization retry attempt when there are pending ops */
119
+ export const defaultPendingOpsRetryDelayMs = 1000;
120
+ /**
121
+ * Instead of refreshing from latest because we do not have 100% confidence in the state
122
+ * of the current system, we should close the summarizer and let it recover.
123
+ * This delay's goal is to prevent tight restart loops
124
+ */
125
+ const defaultCloseSummarizerDelayMs = 5000; // 5 seconds
126
+ /**
127
+ * @deprecated use ContainerRuntimeMessageType instead
128
+ * @internal
129
+ */
130
+ export var RuntimeMessage;
131
+ (function (RuntimeMessage) {
132
+ RuntimeMessage["FluidDataStoreOp"] = "component";
133
+ RuntimeMessage["Attach"] = "attach";
134
+ RuntimeMessage["ChunkedOp"] = "chunkedOp";
135
+ RuntimeMessage["BlobAttach"] = "blobAttach";
136
+ RuntimeMessage["Rejoin"] = "rejoin";
137
+ RuntimeMessage["Alias"] = "alias";
138
+ RuntimeMessage["Operation"] = "op";
139
+ })(RuntimeMessage || (RuntimeMessage = {}));
140
+ /**
141
+ * @deprecated please use version in driver-utils
142
+ * @internal
143
+ */
144
+ export function isRuntimeMessage(message) {
145
+ return Object.values(RuntimeMessage).includes(message.type);
146
+ }
147
+ /**
148
+ * Legacy ID for the built-in AgentScheduler. To minimize disruption while removing it, retaining this as a
149
+ * special-case for document dirty state. Ultimately we should have no special-cases from the
150
+ * ContainerRuntime's perspective.
151
+ * @internal
152
+ */
153
+ export const agentSchedulerId = "_scheduler";
154
+ // safely check navigator and get the hardware spec value
155
+ export function getDeviceSpec() {
156
+ try {
157
+ if (typeof navigator === "object" && navigator !== null) {
158
+ return {
159
+ deviceMemory: navigator.deviceMemory,
160
+ hardwareConcurrency: navigator.hardwareConcurrency,
161
+ };
162
+ }
163
+ }
164
+ catch { }
165
+ return {};
166
+ }
167
+ /**
168
+ * Older loader doesn't have a submitBatchFn member, this is the older way of submitting a batch.
169
+ * Rather than exposing the submitFn (now deprecated) and IDeltaManager (dangerous to hand out) to the Outbox,
170
+ * we can provide a partially-applied function to keep those items private to the ContainerRuntime.
171
+ */
172
+ export const makeLegacySendBatchFn = (submitFn, deltaManager) => (batch) => {
173
+ for (const message of batch.content) {
174
+ submitFn(MessageType.Operation,
175
+ // For back-compat (submitFn only works on deserialized content)
176
+ message.contents === undefined ? undefined : JSON.parse(message.contents), true, // batch
177
+ message.metadata);
178
+ }
179
+ deltaManager.flush();
180
+ };
181
+ const summarizerRequestUrl = "_summarizer";
182
+ /**
183
+ * Create and retrieve the summmarizer
184
+ */
185
+ async function createSummarizer(loader, url) {
186
+ const request = {
187
+ headers: {
188
+ [LoaderHeader.cache]: false,
189
+ [LoaderHeader.clientDetails]: {
190
+ capabilities: { interactive: false },
191
+ type: summarizerClientType,
192
+ },
193
+ [DriverHeader.summarizingClient]: true,
194
+ [LoaderHeader.reconnect]: false,
195
+ },
196
+ url,
197
+ };
198
+ const resolvedContainer = await loader.resolve(request);
199
+ let fluidObject;
200
+ // Older containers may not have the "getEntryPoint" API
201
+ // ! This check will need to stay until LTS of loader moves past 2.0.0-internal.7.0.0
202
+ if (resolvedContainer.getEntryPoint !== undefined) {
203
+ fluidObject = await resolvedContainer.getEntryPoint();
204
+ }
205
+ else {
206
+ const response = await resolvedContainer.request({
207
+ url: `/${summarizerRequestUrl}`,
208
+ });
209
+ if (response.status !== 200 || response.mimeType !== "fluid/object") {
210
+ throw responseToException(response, request);
211
+ }
212
+ fluidObject = response.value;
213
+ }
214
+ if (fluidObject?.ISummarizer === undefined) {
215
+ throw new UsageError("Fluid object does not implement ISummarizer");
216
+ }
217
+ return fluidObject.ISummarizer;
218
+ }
219
+ /**
220
+ * Represents the runtime of the container. Contains helper functions/state of the container.
221
+ * It will define the store level mappings.
222
+ * @alpha
223
+ */
224
+ export class ContainerRuntime extends TypedEventEmitter {
225
+ /**
226
+ * Load the stores from a snapshot and returns the runtime.
227
+ * @param params - An object housing the runtime properties:
228
+ * - context - Context of the container.
229
+ * - registryEntries - Mapping from data store types to their corresponding factories.
230
+ * - existing - Pass 'true' if loading from an existing snapshot.
231
+ * - requestHandler - (optional) Request handler for the request() method of the container runtime.
232
+ * Only relevant for back-compat while we remove the request() method and move fully to entryPoint as the main pattern.
233
+ * - runtimeOptions - Additional options to be passed to the runtime
234
+ * - containerScope - runtime services provided with context
235
+ * - containerRuntimeCtor - Constructor to use to create the ContainerRuntime instance.
236
+ * This allows mixin classes to leverage this method to define their own async initializer.
237
+ * - provideEntryPoint - Promise that resolves to an object which will act as entryPoint for the Container.
238
+ * This object should provide all the functionality that the Container is expected to provide to the loader layer.
239
+ */
240
+ static async loadRuntime(params) {
241
+ const { context, registryEntries, existing, requestHandler, provideEntryPoint, runtimeOptions = {}, containerScope = {}, containerRuntimeCtor = ContainerRuntime, } = params;
242
+ // If taggedLogger exists, use it. Otherwise, wrap the vanilla logger:
243
+ // back-compat: Remove the TaggedLoggerAdapter fallback once all the host are using loader > 0.45
244
+ const backCompatContext = context;
245
+ const passLogger = backCompatContext.taggedLogger ??
246
+ // eslint-disable-next-line import/no-deprecated
247
+ new TaggedLoggerAdapter(backCompatContext.logger);
248
+ const logger = createChildLogger({
249
+ logger: passLogger,
250
+ properties: {
251
+ all: {
252
+ runtimeVersion: pkgVersion,
253
+ },
254
+ },
255
+ });
256
+ const { summaryOptions = {}, gcOptions = {}, loadSequenceNumberVerification = "close", flushMode = defaultFlushMode, compressionOptions = defaultCompressionConfig, maxBatchSizeInBytes = defaultMaxBatchSizeInBytes, enableRuntimeIdCompressor = false, chunkSizeInBytes = defaultChunkSizeInBytes, enableOpReentryCheck = false, enableGroupedBatching = false, } = runtimeOptions;
257
+ const registry = new FluidDataStoreRegistry(registryEntries);
258
+ const tryFetchBlob = async (blobName) => {
259
+ const blobId = context.baseSnapshot?.blobs[blobName];
260
+ if (context.baseSnapshot && blobId) {
261
+ // IContainerContext storage api return type still has undefined in 0.39 package version.
262
+ // So once we release 0.40 container-defn package we can remove this check.
263
+ assert(context.storage !== undefined, 0x1f5 /* "Attached state should have storage" */);
264
+ return readAndParse(context.storage, blobId);
265
+ }
266
+ };
267
+ const [chunks, metadata, electedSummarizerData, aliases, serializedIdCompressor] = await Promise.all([
268
+ tryFetchBlob(chunksBlobName),
269
+ tryFetchBlob(metadataBlobName),
270
+ tryFetchBlob(electedSummarizerBlobName),
271
+ tryFetchBlob(aliasBlobName),
272
+ tryFetchBlob(idCompressorBlobName),
273
+ ]);
274
+ // read snapshot blobs needed for BlobManager to load
275
+ const blobManagerSnapshot = await BlobManager.load(context.baseSnapshot?.trees[blobsTreeName], async (id) => {
276
+ // IContainerContext storage api return type still has undefined in 0.39 package version.
277
+ // So once we release 0.40 container-defn package we can remove this check.
278
+ assert(context.storage !== undefined, 0x256 /* "storage undefined in attached container" */);
279
+ return readAndParse(context.storage, id);
280
+ });
281
+ // Verify summary runtime sequence number matches protocol sequence number.
282
+ const runtimeSequenceNumber = metadata?.message?.sequenceNumber;
283
+ // When we load with pending state, we reuse an old snapshot so we don't expect these numbers to match
284
+ if (!context.pendingLocalState && runtimeSequenceNumber !== undefined) {
285
+ const protocolSequenceNumber = context.deltaManager.initialSequenceNumber;
286
+ // Unless bypass is explicitly set, then take action when sequence numbers mismatch.
287
+ if (loadSequenceNumberVerification !== "bypass" &&
288
+ runtimeSequenceNumber !== protocolSequenceNumber) {
289
+ // "Load from summary, runtime metadata sequenceNumber !== initialSequenceNumber"
290
+ const error = new DataCorruptionError(
291
+ // pre-0.58 error message: SummaryMetadataMismatch
292
+ "Summary metadata mismatch", { runtimeVersion: pkgVersion, runtimeSequenceNumber, protocolSequenceNumber });
293
+ if (loadSequenceNumberVerification === "log") {
294
+ logger.sendErrorEvent({ eventName: "SequenceNumberMismatch" }, error);
295
+ }
296
+ else {
297
+ context.closeFn(error);
298
+ }
299
+ }
300
+ }
301
+ const idCompressorEnabled = metadata?.idCompressorEnabled ?? runtimeOptions.enableRuntimeIdCompressor ?? false;
302
+ let idCompressor;
303
+ if (idCompressorEnabled) {
304
+ const { createIdCompressor, deserializeIdCompressor, createSessionId } = await import("@fluidframework/id-compressor");
305
+ const pendingLocalState = context.pendingLocalState;
306
+ if (pendingLocalState?.pendingIdCompressorState !== undefined) {
307
+ idCompressor = deserializeIdCompressor(pendingLocalState.pendingIdCompressorState);
308
+ }
309
+ else if (serializedIdCompressor !== undefined) {
310
+ idCompressor = deserializeIdCompressor(serializedIdCompressor, createSessionId());
311
+ }
312
+ else {
313
+ idCompressor = createIdCompressor(logger);
314
+ }
315
+ }
316
+ const runtime = new containerRuntimeCtor(context, registry, metadata, electedSummarizerData, chunks ?? [], aliases ?? [], {
317
+ summaryOptions,
318
+ gcOptions,
319
+ loadSequenceNumberVerification,
320
+ flushMode,
321
+ compressionOptions,
322
+ maxBatchSizeInBytes,
323
+ chunkSizeInBytes,
324
+ enableRuntimeIdCompressor,
325
+ enableOpReentryCheck,
326
+ enableGroupedBatching,
327
+ }, containerScope, logger, existing, blobManagerSnapshot, context.storage, idCompressor, provideEntryPoint, requestHandler, undefined);
328
+ // Apply stashed ops with a reference sequence number equal to the sequence number of the snapshot,
329
+ // or zero. This must be done before Container replays saved ops.
330
+ await runtime.pendingStateManager.applyStashedOpsAt(runtimeSequenceNumber ?? 0);
331
+ // Initialize the base state of the runtime before it's returned.
332
+ await runtime.initializeBaseState();
333
+ return runtime;
334
+ }
335
+ get clientId() {
336
+ return this._getClientId();
337
+ }
338
+ get storage() {
339
+ return this._storage;
340
+ }
341
+ get flushMode() {
342
+ return this._flushMode;
343
+ }
344
+ get scope() {
345
+ return this.containerScope;
346
+ }
347
+ get IFluidDataStoreRegistry() {
348
+ return this.registry;
349
+ }
350
+ get attachState() {
351
+ return this._getAttachState();
352
+ }
353
+ get IFluidHandleContext() {
354
+ return this.handleContext;
355
+ }
356
+ /**
357
+ * Invokes the given callback and expects that no ops are submitted
358
+ * until execution finishes. If an op is submitted, an error will be raised.
359
+ *
360
+ * Can be disabled by feature gate `Fluid.ContainerRuntime.DisableOpReentryCheck`
361
+ *
362
+ * @param callback - the callback to be invoked
363
+ */
364
+ ensureNoDataModelChanges(callback) {
365
+ this.ensureNoDataModelChangesCalls++;
366
+ try {
367
+ return callback();
368
+ }
369
+ finally {
370
+ this.ensureNoDataModelChangesCalls--;
371
+ }
372
+ }
373
+ get connected() {
374
+ return this._connected;
375
+ }
376
+ /** clientId of parent (non-summarizing) container that owns summarizer container */
377
+ get summarizerClientId() {
378
+ return this.summarizerClientElection?.electedClientId;
379
+ }
380
+ get disposed() {
381
+ return this._disposed;
382
+ }
383
+ get summarizer() {
384
+ assert(this._summarizer !== undefined, 0x257 /* "This is not summarizing container" */);
385
+ return this._summarizer;
386
+ }
387
+ isSummariesDisabled() {
388
+ return this.summaryConfiguration.state === "disabled";
389
+ }
390
+ isHeuristicsDisabled() {
391
+ return this.summaryConfiguration.state === "disableHeuristics";
392
+ }
393
+ getMaxOpsSinceLastSummary() {
394
+ return this.summaryConfiguration.state !== "disabled"
395
+ ? this.summaryConfiguration.maxOpsSinceLastSummary
396
+ : 0;
397
+ }
398
+ getInitialSummarizerDelayMs() {
399
+ // back-compat: initialSummarizerDelayMs was moved from ISummaryRuntimeOptions
400
+ // to ISummaryConfiguration in 0.60.
401
+ if (this.runtimeOptions.summaryOptions.initialSummarizerDelayMs !== undefined) {
402
+ return this.runtimeOptions.summaryOptions.initialSummarizerDelayMs;
403
+ }
404
+ return this.summaryConfiguration.state !== "disabled"
405
+ ? this.summaryConfiguration.initialSummarizerDelayMs
406
+ : 0;
407
+ }
408
+ /** If false, loading or using a Tombstoned object should merely log, not fail */
409
+ get gcTombstoneEnforcementAllowed() {
410
+ return this.garbageCollector.tombstoneEnforcementAllowed;
411
+ }
412
+ /** If true, throw an error when a tombstone data store is used. */
413
+ get gcThrowOnTombstoneUsage() {
414
+ return this.garbageCollector.throwOnTombstoneUsage;
415
+ }
416
+ /***/
417
+ constructor(context, registry, metadata, electedSummarizerData, chunks, dataStoreAliasMap, runtimeOptions, containerScope, logger, existing, blobManagerSnapshot, _storage, idCompressor, provideEntryPoint, requestHandler, summaryConfiguration = {
418
+ // the defaults
419
+ ...DefaultSummaryConfiguration,
420
+ // the runtime configuration overrides
421
+ ...runtimeOptions.summaryOptions?.summaryConfigOverrides,
422
+ }) {
423
+ super();
424
+ this.registry = registry;
425
+ this.runtimeOptions = runtimeOptions;
426
+ this.containerScope = containerScope;
427
+ this.logger = logger;
428
+ this._storage = _storage;
429
+ this.requestHandler = requestHandler;
430
+ this.summaryConfiguration = summaryConfiguration;
431
+ this.imminentClosure = false;
432
+ this.defaultMaxConsecutiveReconnects = 7;
433
+ this._orderSequentiallyCalls = 0;
434
+ this.flushTaskExists = false;
435
+ this.consecutiveReconnects = 0;
436
+ this.ensureNoDataModelChangesCalls = 0;
437
+ /**
438
+ * Tracks the number of detected reentrant ops to report,
439
+ * in order to self-throttle the telemetry events.
440
+ *
441
+ * This should be removed as part of ADO:2322
442
+ */
443
+ this.opReentryCallsToReport = 5;
444
+ this._disposed = false;
445
+ this.emitDirtyDocumentEvent = true;
446
+ this.defaultTelemetrySignalSampleCount = 100;
447
+ this._perfSignalData = {
448
+ signalsLost: 0,
449
+ signalSequenceNumber: 0,
450
+ signalTimestamp: 0,
451
+ trackingSignalSequenceNumber: undefined,
452
+ };
453
+ const { options, clientDetails, connected, baseSnapshot, submitFn, submitBatchFn, submitSummaryFn, submitSignalFn, disposeFn, closeFn, deltaManager, quorum, audience, loader, pendingLocalState, supportedFeatures, } = context;
454
+ this.innerDeltaManager = deltaManager;
455
+ this.deltaManager = new DeltaManagerSummarizerProxy(this.innerDeltaManager);
456
+ // Here we could wrap/intercept on these functions to block/modify outgoing messages if needed.
457
+ // This makes ContainerRuntime the final gatekeeper for outgoing messages.
458
+ this.submitFn = submitFn;
459
+ this.submitBatchFn = submitBatchFn;
460
+ this.submitSummaryFn = submitSummaryFn;
461
+ this.submitSignalFn = submitSignalFn;
462
+ this.options = options;
463
+ this.clientDetails = clientDetails;
464
+ this.isSummarizerClient = this.clientDetails.type === summarizerClientType;
465
+ this.loadedFromVersionId = context.getLoadedFromVersion()?.id;
466
+ this._getClientId = () => context.clientId;
467
+ this._getAttachState = () => context.attachState;
468
+ this.getAbsoluteUrl = async (relativeUrl) => {
469
+ if (context.getAbsoluteUrl === undefined) {
470
+ throw new Error("Driver does not implement getAbsoluteUrl");
471
+ }
472
+ if (this.attachState !== AttachState.Attached) {
473
+ return undefined;
474
+ }
475
+ return context.getAbsoluteUrl(relativeUrl);
476
+ };
477
+ // TODO: Consider that the Container could just listen to these events itself, or even more appropriately maybe the
478
+ // customer should observe dirty state on the runtime (the owner of dirty state) directly, rather than on the IContainer.
479
+ this.on("dirty", () => context.updateDirtyContainerState(true));
480
+ this.on("saved", () => context.updateDirtyContainerState(false));
481
+ // In old loaders without dispose functionality, closeFn is equivalent but will also switch container to readonly mode
482
+ this.disposeFn = disposeFn ?? closeFn;
483
+ // In cases of summarizer, we want to dispose instead since consumer doesn't interact with this container
484
+ this.closeFn = this.isSummarizerClient ? this.disposeFn : closeFn;
485
+ this.mc = createChildMonitoringContext({
486
+ logger: this.logger,
487
+ namespace: "ContainerRuntime",
488
+ });
489
+ let loadSummaryNumber;
490
+ // Get the container creation metadata. For new container, we initialize these. For existing containers,
491
+ // get the values from the metadata blob.
492
+ if (existing) {
493
+ this.createContainerMetadata = {
494
+ createContainerRuntimeVersion: metadata?.createContainerRuntimeVersion,
495
+ createContainerTimestamp: metadata?.createContainerTimestamp,
496
+ };
497
+ // summaryNumber was renamed from summaryCount. For older docs that haven't been opened for a long time,
498
+ // the count is reset to 0.
499
+ loadSummaryNumber = metadata?.summaryNumber ?? 0;
500
+ // Enabling the IdCompressor is a one-way operation and we only want to
501
+ // allow new containers to turn it on
502
+ this.idCompressorEnabled = metadata?.idCompressorEnabled ?? false;
503
+ }
504
+ else {
505
+ this.createContainerMetadata = {
506
+ createContainerRuntimeVersion: pkgVersion,
507
+ createContainerTimestamp: Date.now(),
508
+ };
509
+ loadSummaryNumber = 0;
510
+ this.idCompressorEnabled =
511
+ this.mc.config.getBoolean("Fluid.ContainerRuntime.IdCompressorEnabled") ??
512
+ idCompressor !== undefined;
513
+ }
514
+ this.nextSummaryNumber = loadSummaryNumber + 1;
515
+ this.messageAtLastSummary = metadata?.message;
516
+ // Note that we only need to pull the *initial* connected state from the context.
517
+ // Later updates come through calls to setConnectionState.
518
+ this._connected = connected;
519
+ this.mc.logger.sendTelemetryEvent({
520
+ eventName: "GCFeatureMatrix",
521
+ metadataValue: JSON.stringify(metadata?.gcFeatureMatrix),
522
+ inputs: JSON.stringify({
523
+ gcOptions_gcGeneration: this.runtimeOptions.gcOptions[gcGenerationOptionName],
524
+ }),
525
+ });
526
+ this.telemetryDocumentId = metadata?.telemetryDocumentId ?? uuid();
527
+ this.disableAttachReorder = this.mc.config.getBoolean("Fluid.ContainerRuntime.disableAttachOpReorder");
528
+ const disableChunking = this.mc.config.getBoolean("Fluid.ContainerRuntime.CompressionChunkingDisabled");
529
+ const opGroupingManager = new OpGroupingManager({
530
+ groupedBatchingEnabled: this.groupedBatchingEnabled,
531
+ opCountThreshold: this.mc.config.getNumber("Fluid.ContainerRuntime.GroupedBatchingOpCount") ?? 2,
532
+ reentrantBatchGroupingEnabled: this.mc.config.getBoolean("Fluid.ContainerRuntime.GroupedBatchingReentrancy") ??
533
+ true,
534
+ }, this.mc.logger);
535
+ const opSplitter = new OpSplitter(chunks, this.submitBatchFn, disableChunking === true ? Number.POSITIVE_INFINITY : runtimeOptions.chunkSizeInBytes, runtimeOptions.maxBatchSizeInBytes, this.mc.logger);
536
+ this.remoteMessageProcessor = new RemoteMessageProcessor(opSplitter, new OpDecompressor(this.mc.logger), opGroupingManager);
537
+ this.handleContext = new ContainerFluidHandleContext("", this);
538
+ if (this.summaryConfiguration.state === "enabled") {
539
+ this.validateSummaryHeuristicConfiguration(this.summaryConfiguration);
540
+ }
541
+ const disableOpReentryCheck = this.mc.config.getBoolean("Fluid.ContainerRuntime.DisableOpReentryCheck");
542
+ this.enableOpReentryCheck =
543
+ runtimeOptions.enableOpReentryCheck === true &&
544
+ // Allow for a break-glass config to override the options
545
+ disableOpReentryCheck !== true;
546
+ this.summariesDisabled = this.isSummariesDisabled();
547
+ this.heuristicsDisabled = this.isHeuristicsDisabled();
548
+ this.maxOpsSinceLastSummary = this.getMaxOpsSinceLastSummary();
549
+ this.initialSummarizerDelayMs = this.getInitialSummarizerDelayMs();
550
+ if (this.idCompressorEnabled) {
551
+ this.idCompressor = idCompressor;
552
+ }
553
+ this.maxConsecutiveReconnects =
554
+ this.mc.config.getNumber(maxConsecutiveReconnectsKey) ??
555
+ this.defaultMaxConsecutiveReconnects;
556
+ if (runtimeOptions.flushMode === FlushModeExperimental.Async &&
557
+ supportedFeatures?.get("referenceSequenceNumbers") !== true) {
558
+ // The loader does not support reference sequence numbers, falling back on FlushMode.TurnBased
559
+ this.mc.logger.sendErrorEvent({ eventName: "FlushModeFallback" });
560
+ this._flushMode = FlushMode.TurnBased;
561
+ }
562
+ else {
563
+ this._flushMode = runtimeOptions.flushMode;
564
+ }
565
+ const pendingRuntimeState = pendingLocalState;
566
+ const maxSnapshotCacheDurationMs = this._storage?.policies?.maximumCacheDurationMs;
567
+ if (maxSnapshotCacheDurationMs !== undefined &&
568
+ maxSnapshotCacheDurationMs > 5 * 24 * 60 * 60 * 1000) {
569
+ // This is a runtime enforcement of what's already explicit in the policy's type itself,
570
+ // which dictates the value is either undefined or exactly 5 days in ms.
571
+ // As long as the actual value is less than 5 days, the assumptions GC makes here are valid.
572
+ throw new UsageError("Driver's maximumCacheDurationMs policy cannot exceed 5 days");
573
+ }
574
+ this.garbageCollector = GarbageCollector.create({
575
+ runtime: this,
576
+ gcOptions: this.runtimeOptions.gcOptions,
577
+ baseSnapshot,
578
+ baseLogger: this.mc.logger,
579
+ existing,
580
+ metadata,
581
+ createContainerMetadata: this.createContainerMetadata,
582
+ isSummarizerClient: this.isSummarizerClient,
583
+ getNodePackagePath: async (nodePath) => this.getGCNodePackagePath(nodePath),
584
+ getLastSummaryTimestampMs: () => this.messageAtLastSummary?.timestamp,
585
+ readAndParseBlob: async (id) => readAndParse(this.storage, id),
586
+ submitMessage: (message) => this.submit(message),
587
+ });
588
+ const loadedFromSequenceNumber = this.deltaManager.initialSequenceNumber;
589
+ this.summarizerNode = createRootSummarizerNodeWithGC(createChildLogger({ logger: this.logger, namespace: "SummarizerNode" }),
590
+ // Summarize function to call when summarize is called. Summarizer node always tracks summary state.
591
+ async (fullTree, trackState, telemetryContext) => this.summarizeInternal(fullTree, trackState, telemetryContext),
592
+ // Latest change sequence number, no changes since summary applied yet
593
+ loadedFromSequenceNumber,
594
+ // Summary reference sequence number, undefined if no summary yet
595
+ baseSnapshot !== undefined ? loadedFromSequenceNumber : undefined, {
596
+ // Must set to false to prevent sending summary handle which would be pointing to
597
+ // a summary with an older protocol state.
598
+ canReuseHandle: false,
599
+ // Must set to true to throw on any data stores failure that was too severe to be handled.
600
+ // We also are not decoding the base summaries at the root.
601
+ throwOnFailure: true,
602
+ // If GC should not run, let the summarizer node know so that it does not track GC state.
603
+ gcDisabled: !this.garbageCollector.shouldRunGC,
604
+ },
605
+ // Function to get GC data if needed. This will always be called by the root summarizer node to get GC data.
606
+ async (fullGC) => this.getGCDataInternal(fullGC),
607
+ // Function to get the GC details from the base snapshot we loaded from.
608
+ async () => this.garbageCollector.getBaseGCDetails());
609
+ if (baseSnapshot) {
610
+ this.summarizerNode.updateBaseSummaryState(baseSnapshot);
611
+ }
612
+ this.dataStores = new DataStores(getSummaryForDatastores(baseSnapshot, metadata), this, (attachMsg) => this.submit({ type: ContainerMessageType.Attach, contents: attachMsg }), (id, createParam) => (summarizeInternal, getGCDataFn) => this.summarizerNode.createChild(summarizeInternal, id, createParam, undefined, getGCDataFn), (id) => this.summarizerNode.deleteChild(id), this.mc.logger, (path, timestampMs, packagePath) => this.garbageCollector.nodeUpdated(path, "Changed", timestampMs, packagePath), (path) => this.garbageCollector.isNodeDeleted(path), new Map(dataStoreAliasMap));
613
+ this.blobManager = new BlobManager(this.handleContext, blobManagerSnapshot, () => this.storage, (localId, blobId) => {
614
+ if (!this.disposed) {
615
+ this.submit({ type: ContainerMessageType.BlobAttach, contents: undefined }, undefined, {
616
+ localId,
617
+ blobId,
618
+ });
619
+ }
620
+ }, (blobPath) => this.garbageCollector.nodeUpdated(blobPath, "Loaded"), (blobPath) => this.garbageCollector.isNodeDeleted(blobPath), this, pendingRuntimeState?.pendingAttachmentBlobs, (error) => this.closeFn(error));
621
+ this.scheduleManager = new ScheduleManager(this.innerDeltaManager, this, () => this.clientId, createChildLogger({ logger: this.logger, namespace: "ScheduleManager" }));
622
+ this.pendingStateManager = new PendingStateManager({
623
+ applyStashedOp: this.applyStashedOp.bind(this),
624
+ clientId: () => this.clientId,
625
+ close: this.closeFn,
626
+ connected: () => this.connected,
627
+ reSubmit: this.reSubmit.bind(this),
628
+ reSubmitBatch: this.reSubmitBatch.bind(this),
629
+ isActiveConnection: () => this.innerDeltaManager.active,
630
+ }, pendingRuntimeState?.pending, this.logger);
631
+ const disableCompression = this.mc.config.getBoolean("Fluid.ContainerRuntime.CompressionDisabled");
632
+ const compressionOptions = disableCompression === true
633
+ ? {
634
+ minimumBatchSizeInBytes: Number.POSITIVE_INFINITY,
635
+ compressionAlgorithm: CompressionAlgorithms.lz4,
636
+ }
637
+ : runtimeOptions.compressionOptions;
638
+ const disablePartialFlush = this.mc.config.getBoolean("Fluid.ContainerRuntime.DisablePartialFlush");
639
+ const legacySendBatchFn = makeLegacySendBatchFn(this.submitFn, this.innerDeltaManager);
640
+ this.outbox = new Outbox({
641
+ shouldSend: () => this.canSendOps(),
642
+ pendingStateManager: this.pendingStateManager,
643
+ submitBatchFn: this.submitBatchFn,
644
+ legacySendBatchFn,
645
+ compressor: new OpCompressor(this.mc.logger),
646
+ splitter: opSplitter,
647
+ config: {
648
+ compressionOptions,
649
+ maxBatchSizeInBytes: runtimeOptions.maxBatchSizeInBytes,
650
+ disablePartialFlush: disablePartialFlush === true,
651
+ },
652
+ logger: this.mc.logger,
653
+ groupingManager: opGroupingManager,
654
+ getCurrentSequenceNumbers: () => ({
655
+ referenceSequenceNumber: this.deltaManager.lastSequenceNumber,
656
+ clientSequenceNumber: this._processedClientSequenceNumber,
657
+ }),
658
+ reSubmit: this.reSubmit.bind(this),
659
+ opReentrancy: () => this.ensureNoDataModelChangesCalls > 0,
660
+ closeContainer: this.closeFn,
661
+ });
662
+ this._quorum = quorum;
663
+ this._quorum.on("removeMember", (clientId) => {
664
+ this.remoteMessageProcessor.clearPartialMessagesFor(clientId);
665
+ });
666
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
667
+ this._audience = audience;
668
+ const closeSummarizerDelayOverride = this.mc.config.getNumber("Fluid.ContainerRuntime.Test.CloseSummarizerDelayOverrideMs");
669
+ this.closeSummarizerDelayMs = closeSummarizerDelayOverride ?? defaultCloseSummarizerDelayMs;
670
+ this.validateSummaryBeforeUpload =
671
+ this.mc.config.getBoolean("Fluid.Summarizer.ValidateSummaryBeforeUpload") ?? false;
672
+ this.summaryCollection = new SummaryCollection(this.deltaManager, this.logger);
673
+ this.dirtyContainer =
674
+ this.attachState !== AttachState.Attached || this.hasPendingMessages();
675
+ context.updateDirtyContainerState(this.dirtyContainer);
676
+ if (this.summariesDisabled) {
677
+ this.mc.logger.sendTelemetryEvent({ eventName: "SummariesDisabled" });
678
+ }
679
+ else {
680
+ const orderedClientLogger = createChildLogger({
681
+ logger: this.logger,
682
+ namespace: "OrderedClientElection",
683
+ });
684
+ const orderedClientCollection = new OrderedClientCollection(orderedClientLogger, this.innerDeltaManager, this._quorum);
685
+ const orderedClientElectionForSummarizer = new OrderedClientElection(orderedClientLogger, orderedClientCollection, electedSummarizerData ?? this.innerDeltaManager.lastSequenceNumber, SummarizerClientElection.isClientEligible);
686
+ this.summarizerClientElection = new SummarizerClientElection(orderedClientLogger, this.summaryCollection, orderedClientElectionForSummarizer, this.maxOpsSinceLastSummary);
687
+ if (this.isSummarizerClient) {
688
+ this._summarizer = new Summarizer(this /* ISummarizerRuntime */, () => this.summaryConfiguration, this /* ISummarizerInternalsProvider */, this.handleContext, this.summaryCollection, async (runtime) => RunWhileConnectedCoordinator.create(runtime,
689
+ // Summarization runs in summarizer client and needs access to the real (non-proxy) active
690
+ // information. The proxy delta manager would always return false for summarizer client.
691
+ () => this.innerDeltaManager.active));
692
+ }
693
+ else if (SummarizerClientElection.clientDetailsPermitElection(this.clientDetails)) {
694
+ // Only create a SummaryManager and SummarizerClientElection
695
+ // if summaries are enabled and we are not the summarizer client.
696
+ const defaultAction = () => {
697
+ if (this.summaryCollection.opsSinceLastAck > this.maxOpsSinceLastSummary) {
698
+ this.mc.logger.sendTelemetryEvent({ eventName: "SummaryStatus:Behind" });
699
+ // unregister default to no log on every op after falling behind
700
+ // and register summary ack handler to re-register this handler
701
+ // after successful summary
702
+ this.summaryCollection.once(MessageType.SummaryAck, () => {
703
+ this.mc.logger.sendTelemetryEvent({
704
+ eventName: "SummaryStatus:CaughtUp",
705
+ });
706
+ // we've caught up, so re-register the default action to monitor for
707
+ // falling behind, and unregister ourself
708
+ this.summaryCollection.on("default", defaultAction);
709
+ });
710
+ this.summaryCollection.off("default", defaultAction);
711
+ }
712
+ };
713
+ this.summaryCollection.on("default", defaultAction);
714
+ // Create the SummaryManager and mark the initial state
715
+ this.summaryManager = new SummaryManager(this.summarizerClientElection, this, // IConnectedState
716
+ this.summaryCollection, this.logger, this.formCreateSummarizerFn(loader), new Throttler(60 * 1000, // 60 sec delay window
717
+ 30 * 1000, // 30 sec max delay
718
+ // throttling function increases exponentially (0ms, 40ms, 80ms, 160ms, etc)
719
+ formExponentialFn({ coefficient: 20, initialDelay: 0 })), {
720
+ initialDelayMs: this.initialSummarizerDelayMs,
721
+ }, this.heuristicsDisabled);
722
+ this.summaryManager.on("summarize", (eventProps) => {
723
+ this.emit("summarize", eventProps);
724
+ });
725
+ this.summaryManager.start();
726
+ }
727
+ }
728
+ // logging hardware telemetry
729
+ logger.sendTelemetryEvent({
730
+ eventName: "DeviceSpec",
731
+ ...getDeviceSpec(),
732
+ });
733
+ this.mc.logger.sendTelemetryEvent({
734
+ eventName: "ContainerLoadStats",
735
+ ...this.createContainerMetadata,
736
+ ...this.dataStores.containerLoadStats,
737
+ summaryNumber: loadSummaryNumber,
738
+ summaryFormatVersion: metadata?.summaryFormatVersion,
739
+ disableIsolatedChannels: metadata?.disableIsolatedChannels,
740
+ gcVersion: metadata?.gcFeature,
741
+ options: JSON.stringify(runtimeOptions),
742
+ featureGates: JSON.stringify({
743
+ disableCompression,
744
+ disableOpReentryCheck,
745
+ disableChunking,
746
+ disableAttachReorder: this.disableAttachReorder,
747
+ disablePartialFlush,
748
+ idCompressorEnabled: this.idCompressorEnabled,
749
+ closeSummarizerDelayOverride,
750
+ }),
751
+ telemetryDocumentId: this.telemetryDocumentId,
752
+ groupedBatchingEnabled: this.groupedBatchingEnabled,
753
+ });
754
+ ReportOpPerfTelemetry(this.clientId, this.deltaManager, this.logger);
755
+ BindBatchTracker(this, this.logger);
756
+ this.entryPoint = new LazyPromise(async () => {
757
+ if (this.isSummarizerClient) {
758
+ assert(this._summarizer !== undefined, 0x5bf /* Summarizer object is undefined in a summarizer client */);
759
+ return this._summarizer;
760
+ }
761
+ return provideEntryPoint(this);
762
+ });
763
+ }
764
+ /**
765
+ * Initializes the state from the base snapshot this container runtime loaded from.
766
+ */
767
+ async initializeBaseState() {
768
+ await this.garbageCollector.initializeBaseState();
769
+ }
770
+ dispose(error) {
771
+ if (this._disposed) {
772
+ return;
773
+ }
774
+ this._disposed = true;
775
+ this.mc.logger.sendTelemetryEvent({
776
+ eventName: "ContainerRuntimeDisposed",
777
+ isDirty: this.isDirty,
778
+ lastSequenceNumber: this.deltaManager.lastSequenceNumber,
779
+ attachState: this.attachState,
780
+ }, error);
781
+ if (this.summaryManager !== undefined) {
782
+ this.summaryManager.dispose();
783
+ }
784
+ this.garbageCollector.dispose();
785
+ this._summarizer?.dispose();
786
+ this.dataStores.dispose();
787
+ this.pendingStateManager.dispose();
788
+ this.emit("dispose");
789
+ this.removeAllListeners();
790
+ }
791
+ /**
792
+ * Notifies this object about the request made to the container.
793
+ * @param request - Request made to the handler.
794
+ * @deprecated Will be removed in future major release. This method needs to stay private until LTS version of Loader moves to "2.0.0-internal.7.0.0".
795
+ */
796
+ // @ts-expect-error expected to be used by LTS Loaders and Containers
797
+ async request(request) {
798
+ try {
799
+ const parser = RequestParser.create(request);
800
+ const id = parser.pathParts[0];
801
+ if (id === summarizerRequestUrl && parser.pathParts.length === 1) {
802
+ if (this._summarizer !== undefined) {
803
+ return {
804
+ status: 200,
805
+ mimeType: "fluid/object",
806
+ value: this.summarizer,
807
+ };
808
+ }
809
+ return create404Response(request);
810
+ }
811
+ if (this.requestHandler !== undefined) {
812
+ // eslint-disable-next-line @typescript-eslint/return-await -- Adding an await here causes test failures
813
+ return this.requestHandler(parser, this);
814
+ }
815
+ return create404Response(request);
816
+ }
817
+ catch (error) {
818
+ return exceptionToResponse(error);
819
+ }
820
+ }
821
+ /**
822
+ * Resolves URI representing handle
823
+ * @param request - Request made to the handler.
824
+ */
825
+ async resolveHandle(request) {
826
+ try {
827
+ const requestParser = RequestParser.create(request);
828
+ const id = requestParser.pathParts[0];
829
+ if (id === "_channels") {
830
+ // eslint-disable-next-line @typescript-eslint/return-await -- Adding an await here causes test failures
831
+ return this.resolveHandle(requestParser.createSubRequest(1));
832
+ }
833
+ if (id === BlobManager.basePath && requestParser.isLeaf(2)) {
834
+ const blob = await this.blobManager.getBlob(requestParser.pathParts[1]);
835
+ return blob
836
+ ? {
837
+ status: 200,
838
+ mimeType: "fluid/object",
839
+ value: blob,
840
+ }
841
+ : create404Response(request);
842
+ }
843
+ else if (requestParser.pathParts.length > 0) {
844
+ // Differentiate between requesting the dataStore directly, or one of its children
845
+ const requestForChild = !requestParser.isLeaf(1);
846
+ const dataStore = await this.getDataStoreFromRequest(id, request, requestForChild);
847
+ const subRequest = requestParser.createSubRequest(1);
848
+ // We always expect createSubRequest to include a leading slash, but asserting here to protect against
849
+ // unintentionally modifying the url if that changes.
850
+ assert(subRequest.url.startsWith("/"), 0x126 /* "Expected createSubRequest url to include a leading slash" */);
851
+ // eslint-disable-next-line @typescript-eslint/return-await -- Adding an await here causes test failures
852
+ return dataStore.request(subRequest);
853
+ }
854
+ return create404Response(request);
855
+ }
856
+ catch (error) {
857
+ return exceptionToResponse(error);
858
+ }
859
+ }
860
+ /**
861
+ * {@inheritDoc @fluidframework/container-definitions#IRuntime.getEntryPoint}
862
+ */
863
+ async getEntryPoint() {
864
+ return this.entryPoint;
865
+ }
866
+ internalId(maybeAlias) {
867
+ return this.dataStores.aliases.get(maybeAlias) ?? maybeAlias;
868
+ }
869
+ async getDataStoreFromRequest(id, request, requestForChild) {
870
+ const headerData = {};
871
+ if (typeof request.headers?.[RuntimeHeaders.wait] === "boolean") {
872
+ headerData.wait = request.headers[RuntimeHeaders.wait];
873
+ }
874
+ if (typeof request.headers?.[RuntimeHeaders.viaHandle] === "boolean") {
875
+ headerData.viaHandle = request.headers[RuntimeHeaders.viaHandle];
876
+ }
877
+ if (typeof request.headers?.[AllowTombstoneRequestHeaderKey] === "boolean") {
878
+ headerData.allowTombstone = request.headers[AllowTombstoneRequestHeaderKey];
879
+ }
880
+ if (typeof request.headers?.[AllowInactiveRequestHeaderKey] === "boolean") {
881
+ headerData.allowInactive = request.headers[AllowInactiveRequestHeaderKey];
882
+ }
883
+ // We allow Tombstone requests for sub-DataStore objects
884
+ if (requestForChild) {
885
+ headerData.allowTombstone = true;
886
+ }
887
+ await this.dataStores.waitIfPendingAlias(id);
888
+ const internalId = this.internalId(id);
889
+ const dataStoreContext = await this.dataStores.getDataStore(internalId, headerData);
890
+ // Remove query params, leading and trailing slashes from the url. This is done to make sure the format is
891
+ // the same as GC nodes id.
892
+ const urlWithoutQuery = trimLeadingAndTrailingSlashes(request.url.split("?")[0]);
893
+ // Get the initial snapshot details which contain the data store package path.
894
+ const details = await dataStoreContext.getInitialSnapshotDetails();
895
+ // Note that this will throw if the data store is inactive or tombstoned and throwing on incorrect usage
896
+ // is configured.
897
+ this.garbageCollector.nodeUpdated(`/${urlWithoutQuery}`, "Loaded", undefined /* timestampMs */, details.pkg, request, headerData);
898
+ return dataStoreContext.realize();
899
+ }
900
+ /** Adds the container's metadata to the given summary tree. */
901
+ addMetadataToSummary(summaryTree) {
902
+ const metadata = {
903
+ ...this.createContainerMetadata,
904
+ // Increment the summary number for the next summary that will be generated.
905
+ summaryNumber: this.nextSummaryNumber++,
906
+ summaryFormatVersion: 1,
907
+ ...this.garbageCollector.getMetadata(),
908
+ // The last message processed at the time of summary. If there are no new messages, use the message from the
909
+ // last summary.
910
+ message: extractSummaryMetadataMessage(this.deltaManager.lastMessage) ??
911
+ this.messageAtLastSummary,
912
+ telemetryDocumentId: this.telemetryDocumentId,
913
+ idCompressorEnabled: this.idCompressorEnabled ? true : undefined,
914
+ };
915
+ addBlobToSummary(summaryTree, metadataBlobName, JSON.stringify(metadata));
916
+ }
917
+ addContainerStateToSummary(summaryTree, fullTree, trackState, telemetryContext) {
918
+ this.addMetadataToSummary(summaryTree);
919
+ if (this.idCompressorEnabled) {
920
+ assert(this.idCompressor !== undefined, 0x67a /* IdCompressor should be defined if enabled */);
921
+ const idCompressorState = JSON.stringify(this.idCompressor.serialize(false));
922
+ addBlobToSummary(summaryTree, idCompressorBlobName, idCompressorState);
923
+ }
924
+ if (this.remoteMessageProcessor.partialMessages.size > 0) {
925
+ const content = JSON.stringify([...this.remoteMessageProcessor.partialMessages]);
926
+ addBlobToSummary(summaryTree, chunksBlobName, content);
927
+ }
928
+ const dataStoreAliases = this.dataStores.aliases;
929
+ if (dataStoreAliases.size > 0) {
930
+ addBlobToSummary(summaryTree, aliasBlobName, JSON.stringify([...dataStoreAliases]));
931
+ }
932
+ if (this.summarizerClientElection) {
933
+ const electedSummarizerContent = JSON.stringify(this.summarizerClientElection?.serialize());
934
+ addBlobToSummary(summaryTree, electedSummarizerBlobName, electedSummarizerContent);
935
+ }
936
+ const blobManagerSummary = this.blobManager.summarize();
937
+ // Some storage (like git) doesn't allow empty tree, so we can omit it.
938
+ // and the blob manager can handle the tree not existing when loading
939
+ if (Object.keys(blobManagerSummary.summary.tree).length > 0) {
940
+ addTreeToSummary(summaryTree, blobsTreeName, blobManagerSummary);
941
+ }
942
+ const gcSummary = this.garbageCollector.summarize(fullTree, trackState, telemetryContext);
943
+ if (gcSummary !== undefined) {
944
+ addSummarizeResultToSummary(summaryTree, gcTreeKey, gcSummary);
945
+ }
946
+ }
947
+ // Track how many times the container tries to reconnect with pending messages.
948
+ // This happens when the connection state is changed and we reset the counter
949
+ // when we are able to process a local op or when there are no pending messages.
950
+ // If this counter reaches a max, it's a good indicator that the container
951
+ // is not making progress and it is stuck in a retry loop.
952
+ shouldContinueReconnecting() {
953
+ if (this.maxConsecutiveReconnects <= 0) {
954
+ // Feature disabled, we never stop reconnecting
955
+ return true;
956
+ }
957
+ if (!this.hasPendingMessages()) {
958
+ // If there are no pending messages, we can always reconnect
959
+ this.resetReconnectCount();
960
+ return true;
961
+ }
962
+ if (this.consecutiveReconnects === Math.floor(this.maxConsecutiveReconnects / 2)) {
963
+ // If we're halfway through the max reconnects, send an event in order
964
+ // to better identify false positives, if any. If the rate of this event
965
+ // matches Container Close count below, we can safely cut down
966
+ // maxConsecutiveReconnects to half.
967
+ this.mc.logger.sendTelemetryEvent({
968
+ eventName: "ReconnectsWithNoProgress",
969
+ attempts: this.consecutiveReconnects,
970
+ pendingMessages: this.pendingMessagesCount,
971
+ });
972
+ }
973
+ return this.consecutiveReconnects < this.maxConsecutiveReconnects;
974
+ }
975
+ resetReconnectCount(message) {
976
+ // Chunked ops don't count towards making progress as they are sent
977
+ // in their own batches before the originating batch is sent.
978
+ // Therefore, receiving them while attempting to send the originating batch
979
+ // does not mean that the container is making any progress.
980
+ if (message?.type !== ContainerMessageType.ChunkedOp) {
981
+ this.consecutiveReconnects = 0;
982
+ }
983
+ }
984
+ replayPendingStates() {
985
+ // We need to be able to send ops to replay states
986
+ if (!this.canSendOps()) {
987
+ return;
988
+ }
989
+ // We need to temporary clear the dirty flags and disable
990
+ // dirty state change events to detect whether replaying ops
991
+ // has any effect.
992
+ // Save the old state, reset to false, disable event emit
993
+ const oldState = this.dirtyContainer;
994
+ this.dirtyContainer = false;
995
+ assert(this.emitDirtyDocumentEvent, 0x127 /* "dirty document event not set on replay" */);
996
+ this.emitDirtyDocumentEvent = false;
997
+ let newState;
998
+ try {
999
+ // replay the ops
1000
+ this.pendingStateManager.replayPendingStates();
1001
+ }
1002
+ finally {
1003
+ // Save the new start and restore the old state, re-enable event emit
1004
+ newState = this.dirtyContainer;
1005
+ this.dirtyContainer = oldState;
1006
+ this.emitDirtyDocumentEvent = true;
1007
+ }
1008
+ // Officially transition from the old state to the new state.
1009
+ this.updateDocumentDirtyState(newState);
1010
+ }
1011
+ /**
1012
+ * Parse an op's type and actual content from given serialized content
1013
+ * ! Note: this format needs to be in-line with what is set in the "ContainerRuntime.submit(...)" method
1014
+ */
1015
+ // TODO: markfields: confirm Local- versus Outbound- ContainerRuntimeMessage typing
1016
+ parseLocalOpContent(serializedContents) {
1017
+ assert(serializedContents !== undefined, 0x6d5 /* content must be defined */);
1018
+ const message = JSON.parse(serializedContents);
1019
+ assert(message.type !== undefined, 0x6d6 /* incorrect op content format */);
1020
+ return message;
1021
+ }
1022
+ async applyStashedOp(serializedOpContent) {
1023
+ // Need to parse from string for back-compat
1024
+ const opContents = this.parseLocalOpContent(serializedOpContent);
1025
+ switch (opContents.type) {
1026
+ case ContainerMessageType.FluidDataStoreOp:
1027
+ return this.dataStores.applyStashedOp(opContents.contents);
1028
+ case ContainerMessageType.Attach:
1029
+ return this.dataStores.applyStashedAttachOp(opContents.contents);
1030
+ case ContainerMessageType.IdAllocation:
1031
+ assert(this.idCompressor !== undefined, 0x67b /* IdCompressor should be defined if enabled */);
1032
+ return;
1033
+ case ContainerMessageType.Alias:
1034
+ case ContainerMessageType.BlobAttach:
1035
+ return;
1036
+ case ContainerMessageType.ChunkedOp:
1037
+ throw new Error("chunkedOp not expected here");
1038
+ case ContainerMessageType.Rejoin:
1039
+ throw new Error("rejoin not expected here");
1040
+ case ContainerMessageType.GC:
1041
+ // GC op is only sent in summarizer which should never have stashed ops.
1042
+ throw new LoggingError("GC op not expected to be stashed in summarizer");
1043
+ default: {
1044
+ // This should be extremely rare for stashed ops.
1045
+ // It would require a newer runtime stashing ops and then an older one applying them,
1046
+ // e.g. if an app rolled back its container version
1047
+ const compatBehavior = opContents.compatDetails?.behavior;
1048
+ if (!compatBehaviorAllowsMessageType(opContents.type, compatBehavior)) {
1049
+ const error = DataProcessingError.create("Stashed runtime message of unknown type", "applyStashedOp", undefined /* sequencedMessage */, {
1050
+ messageDetails: JSON.stringify({
1051
+ type: opContents.type,
1052
+ compatBehavior,
1053
+ }),
1054
+ });
1055
+ this.closeFn(error);
1056
+ throw error;
1057
+ }
1058
+ }
1059
+ }
1060
+ }
1061
+ setConnectionState(connected, clientId) {
1062
+ if (connected === false && this.delayConnectClientId !== undefined) {
1063
+ this.delayConnectClientId = undefined;
1064
+ this.mc.logger.sendTelemetryEvent({
1065
+ eventName: "UnsuccessfulConnectedTransition",
1066
+ });
1067
+ // Don't propagate "disconnected" event because we didn't propagate the previous "connected" event
1068
+ return;
1069
+ }
1070
+ // If there are stashed blobs in the pending state, we need to delay
1071
+ // propagation of the "connected" event until we have uploaded them to
1072
+ // ensure we don't submit ops referencing a blob that has not been uploaded
1073
+ const connecting = connected && !this._connected;
1074
+ if (connecting && this.blobManager.hasPendingStashedBlobs()) {
1075
+ assert(!this.delayConnectClientId, 0x791 /* Connect event delay must be canceled before subsequent connect event */);
1076
+ assert(!!clientId, 0x792 /* Must have clientId when connecting */);
1077
+ this.delayConnectClientId = clientId;
1078
+ this.blobManager.processStashedChanges().then(() => {
1079
+ // make sure we didn't reconnect before the promise resolved
1080
+ if (this.delayConnectClientId === clientId && !this.disposed) {
1081
+ this.delayConnectClientId = undefined;
1082
+ this.setConnectionStateCore(connected, clientId);
1083
+ }
1084
+ }, (error) => this.closeFn(error));
1085
+ return;
1086
+ }
1087
+ this.setConnectionStateCore(connected, clientId);
1088
+ }
1089
+ setConnectionStateCore(connected, clientId) {
1090
+ assert(!this.delayConnectClientId, 0x394 /* connect event delay must be cleared before propagating connect event */);
1091
+ this.verifyNotClosed();
1092
+ // There might be no change of state due to Container calling this API after loading runtime.
1093
+ const changeOfState = this._connected !== connected;
1094
+ const reconnection = changeOfState && !connected;
1095
+ // We need to flush the ops currently collected by Outbox to preserve original order.
1096
+ // This flush NEEDS to happen before we set the ContainerRuntime to "connected".
1097
+ // We want these ops to get to the PendingStateManager without sending to service and have them return to the Outbox upon calling "replayPendingStates".
1098
+ if (changeOfState && connected) {
1099
+ this.flush();
1100
+ }
1101
+ this._connected = connected;
1102
+ if (!connected) {
1103
+ this._perfSignalData.signalsLost = 0;
1104
+ this._perfSignalData.signalTimestamp = 0;
1105
+ this._perfSignalData.trackingSignalSequenceNumber = undefined;
1106
+ }
1107
+ else {
1108
+ assert(this.attachState === AttachState.Attached, 0x3cd /* Connection is possible only if container exists in storage */);
1109
+ }
1110
+ // Fail while disconnected
1111
+ if (reconnection) {
1112
+ this.consecutiveReconnects++;
1113
+ if (!this.shouldContinueReconnecting()) {
1114
+ this.closeFn(DataProcessingError.create("Runtime detected too many reconnects with no progress syncing local ops.", "setConnectionState", undefined, {
1115
+ dataLoss: 1,
1116
+ attempts: this.consecutiveReconnects,
1117
+ pendingMessages: this.pendingMessagesCount,
1118
+ }));
1119
+ return;
1120
+ }
1121
+ }
1122
+ if (changeOfState) {
1123
+ this.replayPendingStates();
1124
+ }
1125
+ this.dataStores.setConnectionState(connected, clientId);
1126
+ this.garbageCollector.setConnectionState(connected, clientId);
1127
+ raiseConnectedEvent(this.mc.logger, this, connected, clientId);
1128
+ }
1129
+ async notifyOpReplay(message) {
1130
+ await this.pendingStateManager.applyStashedOpsAt(message.sequenceNumber);
1131
+ }
1132
+ process(messageArg, local) {
1133
+ this.verifyNotClosed();
1134
+ // Whether or not the message appears to be a runtime message from an up-to-date client.
1135
+ // It may be a legacy runtime message (ie already unpacked and ContainerMessageType)
1136
+ // or something different, like a system message.
1137
+ const modernRuntimeMessage = messageArg.type === MessageType.Operation;
1138
+ // Do shallow copy of message, as the processing flow will modify it.
1139
+ // There might be multiple container instances receiving the same message.
1140
+ // We do not need to make a deep copy. Each layer will just replace message.contents itself,
1141
+ // but will not modify the contents object (likely it will replace it on the message).
1142
+ const messageCopy = { ...messageArg };
1143
+ for (const message of this.remoteMessageProcessor.process(messageCopy)) {
1144
+ if (modernRuntimeMessage) {
1145
+ this.processCore({
1146
+ // Cast it since we expect it to be this based on modernRuntimeMessage computation above.
1147
+ // There is nothing really ensuring that anytime original message.type is Operation that
1148
+ // the result messages will be so. In the end modern bool being true only directs to
1149
+ // throw error if ultimately unrecognized without compat details saying otherwise.
1150
+ message: message,
1151
+ local,
1152
+ modernRuntimeMessage,
1153
+ });
1154
+ }
1155
+ else {
1156
+ // Unrecognized message will be ignored.
1157
+ this.processCore({ message, local, modernRuntimeMessage });
1158
+ }
1159
+ }
1160
+ }
1161
+ /**
1162
+ * Direct the message to the correct subsystem for processing, and implement other side effects
1163
+ */
1164
+ processCore(messageWithContext) {
1165
+ const { message, local } = messageWithContext;
1166
+ // Surround the actual processing of the operation with messages to the schedule manager indicating
1167
+ // the beginning and end. This allows it to emit appropriate events and/or pause the processing of new
1168
+ // messages once a batch has been fully processed.
1169
+ this.scheduleManager.beforeOpProcessing(message);
1170
+ this._processedClientSequenceNumber = message.clientSequenceNumber;
1171
+ try {
1172
+ let localOpMetadata;
1173
+ if (local &&
1174
+ messageWithContext.modernRuntimeMessage &&
1175
+ message.type !== ContainerMessageType.ChunkedOp) {
1176
+ localOpMetadata = this.pendingStateManager.processPendingLocalMessage(messageWithContext.message);
1177
+ }
1178
+ // If there are no more pending messages after processing a local message,
1179
+ // the document is no longer dirty.
1180
+ if (!this.hasPendingMessages()) {
1181
+ this.updateDocumentDirtyState(false);
1182
+ }
1183
+ this.validateAndProcessRuntimeMessage(messageWithContext, localOpMetadata);
1184
+ this.emit("op", message, messageWithContext.modernRuntimeMessage);
1185
+ this.scheduleManager.afterOpProcessing(undefined, message);
1186
+ if (local) {
1187
+ // If we have processed a local op, this means that the container is
1188
+ // making progress and we can reset the counter for how many times
1189
+ // we have consecutively replayed the pending states
1190
+ this.resetReconnectCount(message);
1191
+ }
1192
+ }
1193
+ catch (e) {
1194
+ this.scheduleManager.afterOpProcessing(e, message);
1195
+ throw e;
1196
+ }
1197
+ }
1198
+ /**
1199
+ * Assuming the given message is also a TypedContainerRuntimeMessage,
1200
+ * checks its type and dispatches the message to the appropriate handler in the runtime.
1201
+ * Throws a DataProcessingError if the message looks like but doesn't conform to a known TypedContainerRuntimeMessage type.
1202
+ */
1203
+ validateAndProcessRuntimeMessage(messageWithContext, localOpMetadata) {
1204
+ // TODO: destructure message and modernRuntimeMessage once using typescript 5.2.2+
1205
+ const { local } = messageWithContext;
1206
+ switch (messageWithContext.message.type) {
1207
+ case ContainerMessageType.Attach:
1208
+ this.dataStores.processAttachMessage(messageWithContext.message, local);
1209
+ break;
1210
+ case ContainerMessageType.Alias:
1211
+ this.dataStores.processAliasMessage(messageWithContext.message, localOpMetadata, local);
1212
+ break;
1213
+ case ContainerMessageType.FluidDataStoreOp:
1214
+ this.dataStores.processFluidDataStoreOp(messageWithContext.message, local, localOpMetadata);
1215
+ break;
1216
+ case ContainerMessageType.BlobAttach:
1217
+ this.blobManager.processBlobAttachOp(messageWithContext.message, local);
1218
+ break;
1219
+ case ContainerMessageType.IdAllocation:
1220
+ assert(this.idCompressor !== undefined, 0x67c /* IdCompressor should be defined if enabled */);
1221
+ // Don't re-finalize the range if we're processing a "savedOp" in
1222
+ // stashed ops flow. The compressor is stashed with these ops already processed.
1223
+ if (messageWithContext.message.metadata?.savedOp !== true) {
1224
+ this.idCompressor.finalizeCreationRange(messageWithContext.message.contents);
1225
+ }
1226
+ break;
1227
+ case ContainerMessageType.GC:
1228
+ this.garbageCollector.processMessage(messageWithContext.message, local);
1229
+ break;
1230
+ case ContainerMessageType.ChunkedOp:
1231
+ case ContainerMessageType.Rejoin:
1232
+ break;
1233
+ default: {
1234
+ // If we didn't necessarily expect a runtime message type, then no worries - just return
1235
+ // e.g. this case applies to system ops, or legacy ops that would have fallen into the above cases anyway.
1236
+ if (!messageWithContext.modernRuntimeMessage) {
1237
+ return;
1238
+ }
1239
+ const compatBehavior = messageWithContext.message.compatDetails?.behavior;
1240
+ if (!compatBehaviorAllowsMessageType(messageWithContext.message.type, compatBehavior)) {
1241
+ const { message } = messageWithContext;
1242
+ const error = DataProcessingError.create(
1243
+ // Former assert 0x3ce
1244
+ "Runtime message of unknown type", "OpProcessing", message, {
1245
+ local,
1246
+ messageDetails: JSON.stringify({
1247
+ type: message.type,
1248
+ contentType: typeof message.contents,
1249
+ compatBehavior,
1250
+ batch: message.metadata?.batch,
1251
+ compression: message.compression,
1252
+ }),
1253
+ });
1254
+ this.closeFn(error);
1255
+ throw error;
1256
+ }
1257
+ }
1258
+ }
1259
+ }
1260
+ /**
1261
+ * Emits the Signal event and update the perf signal data.
1262
+ * @param clientSignalSequenceNumber - is the client signal sequence number to be uploaded.
1263
+ */
1264
+ sendSignalTelemetryEvent(clientSignalSequenceNumber) {
1265
+ const duration = Date.now() - this._perfSignalData.signalTimestamp;
1266
+ this.mc.logger.sendPerformanceEvent({
1267
+ eventName: "SignalLatency",
1268
+ duration,
1269
+ signalsLost: this._perfSignalData.signalsLost,
1270
+ });
1271
+ this._perfSignalData.signalsLost = 0;
1272
+ this._perfSignalData.signalTimestamp = 0;
1273
+ }
1274
+ processSignal(message, local) {
1275
+ const envelope = message.content;
1276
+ const transformed = {
1277
+ clientId: message.clientId,
1278
+ content: envelope.contents.content,
1279
+ type: envelope.contents.type,
1280
+ };
1281
+ // Only collect signal telemetry for messages sent by the current client.
1282
+ if (message.clientId === this.clientId && this.connected) {
1283
+ // Check to see if the signal was lost.
1284
+ if (this._perfSignalData.trackingSignalSequenceNumber !== undefined &&
1285
+ envelope.clientSignalSequenceNumber >
1286
+ this._perfSignalData.trackingSignalSequenceNumber) {
1287
+ this._perfSignalData.signalsLost++;
1288
+ this._perfSignalData.trackingSignalSequenceNumber = undefined;
1289
+ this.mc.logger.sendErrorEvent({
1290
+ eventName: "SignalLost",
1291
+ type: envelope.contents.type,
1292
+ signalsLost: this._perfSignalData.signalsLost,
1293
+ trackingSequenceNumber: this._perfSignalData.trackingSignalSequenceNumber,
1294
+ clientSignalSequenceNumber: envelope.clientSignalSequenceNumber,
1295
+ });
1296
+ }
1297
+ else if (envelope.clientSignalSequenceNumber ===
1298
+ this._perfSignalData.trackingSignalSequenceNumber) {
1299
+ // only logging for the first connection and the trackingSignalSequenceNUmber.
1300
+ if (this.consecutiveReconnects === 0) {
1301
+ this.sendSignalTelemetryEvent(envelope.clientSignalSequenceNumber);
1302
+ }
1303
+ this._perfSignalData.trackingSignalSequenceNumber = undefined;
1304
+ }
1305
+ }
1306
+ if (envelope.address === undefined) {
1307
+ // No address indicates a container signal message.
1308
+ this.emit("signal", transformed, local);
1309
+ return;
1310
+ }
1311
+ this.dataStores.processSignal(envelope.address, transformed, local);
1312
+ }
1313
+ /**
1314
+ * Flush the pending ops manually.
1315
+ * This method is expected to be called at the end of a batch.
1316
+ */
1317
+ flush() {
1318
+ assert(this._orderSequentiallyCalls === 0, 0x24c /* "Cannot call `flush()` from `orderSequentially`'s callback" */);
1319
+ this.outbox.flush();
1320
+ assert(this.outbox.isEmpty, 0x3cf /* reentrancy */);
1321
+ }
1322
+ orderSequentially(callback) {
1323
+ let checkpoint;
1324
+ let result;
1325
+ if (this.mc.config.getBoolean("Fluid.ContainerRuntime.EnableRollback")) {
1326
+ // Note: we are not touching this.pendingAttachBatch here, for two reasons:
1327
+ // 1. It would not help, as we flush attach ops as they become available.
1328
+ // 2. There is no way to undo process of data store creation.
1329
+ checkpoint = this.outbox.checkpoint().mainBatch;
1330
+ }
1331
+ try {
1332
+ this._orderSequentiallyCalls++;
1333
+ result = callback();
1334
+ }
1335
+ catch (error) {
1336
+ if (checkpoint) {
1337
+ // This will throw and close the container if rollback fails
1338
+ try {
1339
+ checkpoint.rollback((message) => this.rollback(message.contents, message.localOpMetadata));
1340
+ }
1341
+ catch (err) {
1342
+ const error2 = wrapError(err, (message) => {
1343
+ return DataProcessingError.create(`RollbackError: ${message}`, "checkpointRollback", undefined);
1344
+ });
1345
+ this.closeFn(error2);
1346
+ throw error2;
1347
+ }
1348
+ }
1349
+ else {
1350
+ // pre-0.58 error message: orderSequentiallyCallbackException
1351
+ this.closeFn(new GenericError("orderSequentially callback exception", error));
1352
+ }
1353
+ throw error; // throw the original error for the consumer of the runtime
1354
+ }
1355
+ finally {
1356
+ this._orderSequentiallyCalls--;
1357
+ }
1358
+ // We don't flush on TurnBased since we expect all messages in the same JS turn to be part of the same batch
1359
+ if (this.flushMode !== FlushMode.TurnBased && this._orderSequentiallyCalls === 0) {
1360
+ this.flush();
1361
+ }
1362
+ return result;
1363
+ }
1364
+ /**
1365
+ * Returns the aliased data store's entryPoint, given the alias.
1366
+ * @param alias - The alias for the data store.
1367
+ * @returns The data store's entry point ({@link @fluidframework/core-interfaces#IFluidHandle}) if it exists and is aliased.
1368
+ * Returns undefined if no data store has been assigned the given alias.
1369
+ */
1370
+ async getAliasedDataStoreEntryPoint(alias) {
1371
+ await this.dataStores.waitIfPendingAlias(alias);
1372
+ const internalId = this.internalId(alias);
1373
+ const context = await this.dataStores.getDataStoreIfAvailable(internalId, { wait: false });
1374
+ // If the data store is not available or not an alias, return undefined.
1375
+ if (context === undefined || !(await context.isRoot())) {
1376
+ return undefined;
1377
+ }
1378
+ const channel = await context.realize();
1379
+ if (channel.entryPoint === undefined) {
1380
+ throw new UsageError("entryPoint must be defined on data store runtime for using getAliasedDataStoreEntryPoint");
1381
+ }
1382
+ this.garbageCollector.nodeUpdated(`/${internalId}`, "Loaded", undefined /* timestampMs */, context.packagePath);
1383
+ return channel.entryPoint;
1384
+ }
1385
+ createDetachedRootDataStore(pkg, rootDataStoreId) {
1386
+ if (rootDataStoreId.includes("/")) {
1387
+ throw new UsageError(`Id cannot contain slashes: '${rootDataStoreId}'`);
1388
+ }
1389
+ return this.dataStores.createDetachedDataStoreCore(pkg, true, rootDataStoreId);
1390
+ }
1391
+ createDetachedDataStore(pkg) {
1392
+ return this.dataStores.createDetachedDataStoreCore(pkg, false);
1393
+ }
1394
+ async createDataStore(pkg) {
1395
+ const id = uuid();
1396
+ return channelToDataStore(await this.dataStores
1397
+ ._createFluidDataStoreContext(Array.isArray(pkg) ? pkg : [pkg], id)
1398
+ .realize(), id, this, this.dataStores, this.mc.logger);
1399
+ }
1400
+ /**
1401
+ * @deprecated 0.16 Issue #1537, #3631
1402
+ */
1403
+ async _createDataStoreWithProps(pkg, props, id = uuid()) {
1404
+ return channelToDataStore(await this.dataStores
1405
+ ._createFluidDataStoreContext(Array.isArray(pkg) ? pkg : [pkg], id, props)
1406
+ .realize(), id, this, this.dataStores, this.mc.logger);
1407
+ }
1408
+ canSendOps() {
1409
+ // Note that the real (non-proxy) delta manager is needed here to get the readonly info. This is because
1410
+ // container runtime's ability to send ops depend on the actual readonly state of the delta manager.
1411
+ return (this.connected && !this.innerDeltaManager.readOnlyInfo.readonly && !this.imminentClosure);
1412
+ }
1413
+ /**
1414
+ * Are we in the middle of batching ops together?
1415
+ */
1416
+ currentlyBatching() {
1417
+ return this.flushMode !== FlushMode.Immediate || this._orderSequentiallyCalls !== 0;
1418
+ }
1419
+ getQuorum() {
1420
+ return this._quorum;
1421
+ }
1422
+ getAudience() {
1423
+ return this._audience;
1424
+ }
1425
+ /**
1426
+ * Returns true of container is dirty, i.e. there are some pending local changes that
1427
+ * either were not sent out to delta stream or were not yet acknowledged.
1428
+ */
1429
+ get isDirty() {
1430
+ return this.dirtyContainer;
1431
+ }
1432
+ isContainerMessageDirtyable({ type, contents }) {
1433
+ // Certain container runtime messages should not mark the container dirty such as the old built-in
1434
+ // AgentScheduler and Garbage collector messages.
1435
+ switch (type) {
1436
+ case ContainerMessageType.Attach: {
1437
+ const attachMessage = contents;
1438
+ if (attachMessage.id === agentSchedulerId) {
1439
+ return false;
1440
+ }
1441
+ break;
1442
+ }
1443
+ case ContainerMessageType.FluidDataStoreOp: {
1444
+ const envelope = contents;
1445
+ if (envelope.address === agentSchedulerId) {
1446
+ return false;
1447
+ }
1448
+ break;
1449
+ }
1450
+ case ContainerMessageType.GC: {
1451
+ return false;
1452
+ }
1453
+ default:
1454
+ break;
1455
+ }
1456
+ return true;
1457
+ }
1458
+ createNewSignalEnvelope(address, type, content) {
1459
+ const newSequenceNumber = ++this._perfSignalData.signalSequenceNumber;
1460
+ const newEnvelope = {
1461
+ address,
1462
+ clientSignalSequenceNumber: newSequenceNumber,
1463
+ contents: { type, content },
1464
+ };
1465
+ // We should not track any signals in case we already have a tracking number.
1466
+ if (newSequenceNumber % this.defaultTelemetrySignalSampleCount === 1 &&
1467
+ this._perfSignalData.trackingSignalSequenceNumber === undefined) {
1468
+ this._perfSignalData.signalTimestamp = Date.now();
1469
+ this._perfSignalData.trackingSignalSequenceNumber = newSequenceNumber;
1470
+ }
1471
+ return newEnvelope;
1472
+ }
1473
+ /**
1474
+ * Submits the signal to be sent to other clients.
1475
+ * @param type - Type of the signal.
1476
+ * @param content - Content of the signal.
1477
+ * @param targetClientId - When specified, the signal is only sent to the provided client id.
1478
+ */
1479
+ submitSignal(type, content, targetClientId) {
1480
+ this.verifyNotClosed();
1481
+ const envelope = this.createNewSignalEnvelope(undefined /* address */, type, content);
1482
+ return this.submitSignalFn(envelope, targetClientId);
1483
+ }
1484
+ /**
1485
+ * Submits the signal to be sent to other clients.
1486
+ * @param type - Type of the signal.
1487
+ * @param content - Content of the signal.
1488
+ * @param targetClientId - When specified, the signal is only sent to the provided client id.
1489
+ */
1490
+ submitDataStoreSignal(address, type, content, targetClientId) {
1491
+ const envelope = this.createNewSignalEnvelope(address, type, content);
1492
+ return this.submitSignalFn(envelope, targetClientId);
1493
+ }
1494
+ setAttachState(attachState) {
1495
+ if (attachState === AttachState.Attaching) {
1496
+ assert(this.attachState === AttachState.Attaching, 0x12d /* "Container Context should already be in attaching state" */);
1497
+ }
1498
+ else {
1499
+ assert(this.attachState === AttachState.Attached, 0x12e /* "Container Context should already be in attached state" */);
1500
+ this.emit("attached");
1501
+ }
1502
+ if (attachState === AttachState.Attached && !this.hasPendingMessages()) {
1503
+ this.updateDocumentDirtyState(false);
1504
+ }
1505
+ this.dataStores.setAttachState(attachState);
1506
+ }
1507
+ /**
1508
+ * Create a summary. Used when attaching or serializing a detached container.
1509
+ *
1510
+ * @param blobRedirectTable - A table passed during the attach process. While detached, blob upload is supported
1511
+ * using IDs generated locally. After attach, these IDs cannot be used, so this table maps the old local IDs to the
1512
+ * new storage IDs so requests can be redirected.
1513
+ * @param telemetryContext - summary data passed through the layers for telemetry purposes
1514
+ */
1515
+ createSummary(blobRedirectTable, telemetryContext) {
1516
+ if (blobRedirectTable) {
1517
+ this.blobManager.setRedirectTable(blobRedirectTable);
1518
+ }
1519
+ const summarizeResult = this.dataStores.createSummary(telemetryContext);
1520
+ // Wrap data store summaries in .channels subtree.
1521
+ wrapSummaryInChannelsTree(summarizeResult);
1522
+ this.addContainerStateToSummary(summarizeResult, true /* fullTree */, false /* trackState */, telemetryContext);
1523
+ return summarizeResult.summary;
1524
+ }
1525
+ async summarizeInternal(fullTree, trackState, telemetryContext) {
1526
+ const summarizeResult = await this.dataStores.summarize(fullTree, trackState, telemetryContext);
1527
+ // Wrap data store summaries in .channels subtree.
1528
+ wrapSummaryInChannelsTree(summarizeResult);
1529
+ const pathPartsForChildren = [channelsTreeName];
1530
+ this.addContainerStateToSummary(summarizeResult, fullTree, trackState, telemetryContext);
1531
+ return {
1532
+ ...summarizeResult,
1533
+ id: "",
1534
+ pathPartsForChildren,
1535
+ };
1536
+ }
1537
+ /**
1538
+ * Returns a summary of the runtime at the current sequence number.
1539
+ */
1540
+ async summarize(options) {
1541
+ this.verifyNotClosed();
1542
+ const { fullTree = false, trackState = true, summaryLogger = this.mc.logger, runGC = this.garbageCollector.shouldRunGC, runSweep, fullGC, } = options;
1543
+ const telemetryContext = new TelemetryContext();
1544
+ // Add the options that are used to generate this summary to the telemetry context.
1545
+ telemetryContext.setMultiple("fluid_Summarize", "Options", {
1546
+ fullTree,
1547
+ trackState,
1548
+ runGC,
1549
+ fullGC,
1550
+ runSweep,
1551
+ });
1552
+ try {
1553
+ if (runGC) {
1554
+ await this.collectGarbage({ logger: summaryLogger, runSweep, fullGC }, telemetryContext);
1555
+ }
1556
+ const { stats, summary } = await this.summarizerNode.summarize(fullTree, trackState, telemetryContext);
1557
+ assert(summary.type === SummaryType.Tree, 0x12f /* "Container Runtime's summarize should always return a tree" */);
1558
+ return { stats, summary };
1559
+ }
1560
+ finally {
1561
+ this.mc.logger.sendTelemetryEvent({
1562
+ eventName: "SummarizeTelemetry",
1563
+ details: telemetryContext.serialize(),
1564
+ });
1565
+ }
1566
+ }
1567
+ /**
1568
+ * Before GC runs, called by the garbage collector to update any pending GC state. This is mainly used to notify
1569
+ * the garbage collector of references detected since the last GC run. Most references are notified immediately
1570
+ * but there can be some for which async operation is required (such as detecting new root data stores).
1571
+ * @see IGarbageCollectionRuntime.updateStateBeforeGC
1572
+ */
1573
+ async updateStateBeforeGC() {
1574
+ return this.dataStores.updateStateBeforeGC();
1575
+ }
1576
+ async getGCDataInternal(fullGC) {
1577
+ return this.dataStores.getGCData(fullGC);
1578
+ }
1579
+ /**
1580
+ * Generates and returns the GC data for this container.
1581
+ * @param fullGC - true to bypass optimizations and force full generation of GC data.
1582
+ * @see IGarbageCollectionRuntime.getGCData
1583
+ */
1584
+ async getGCData(fullGC) {
1585
+ const builder = new GCDataBuilder();
1586
+ const dsGCData = await this.summarizerNode.getGCData(fullGC);
1587
+ builder.addNodes(dsGCData.gcNodes);
1588
+ const blobsGCData = this.blobManager.getGCData(fullGC);
1589
+ builder.addNodes(blobsGCData.gcNodes);
1590
+ return builder.getGCData();
1591
+ }
1592
+ /**
1593
+ * After GC has run, called to notify this container's nodes of routes that are used in it.
1594
+ * @param usedRoutes - The routes that are used in all nodes in this Container.
1595
+ * @see IGarbageCollectionRuntime.updateUsedRoutes
1596
+ */
1597
+ updateUsedRoutes(usedRoutes) {
1598
+ // Update our summarizer node's used routes. Updating used routes in summarizer node before
1599
+ // summarizing is required and asserted by the the summarizer node. We are the root and are
1600
+ // always referenced, so the used routes is only self-route (empty string).
1601
+ this.summarizerNode.updateUsedRoutes([""]);
1602
+ const { dataStoreRoutes } = this.getDataStoreAndBlobManagerRoutes(usedRoutes);
1603
+ this.dataStores.updateUsedRoutes(dataStoreRoutes);
1604
+ }
1605
+ /**
1606
+ * This is called to update objects whose routes are unused.
1607
+ * @param unusedRoutes - Data store and attachment blob routes that are unused in this Container.
1608
+ */
1609
+ updateUnusedRoutes(unusedRoutes) {
1610
+ const { blobManagerRoutes, dataStoreRoutes } = this.getDataStoreAndBlobManagerRoutes(unusedRoutes);
1611
+ this.blobManager.updateUnusedRoutes(blobManagerRoutes);
1612
+ this.dataStores.updateUnusedRoutes(dataStoreRoutes);
1613
+ }
1614
+ /**
1615
+ * @deprecated Replaced by deleteSweepReadyNodes.
1616
+ */
1617
+ deleteUnusedNodes(unusedRoutes) {
1618
+ throw new Error("deleteUnusedRoutes should not be called");
1619
+ }
1620
+ /**
1621
+ * After GC has run and identified nodes that are sweep ready, this is called to delete the sweep ready nodes.
1622
+ * @param sweepReadyRoutes - The routes of nodes that are sweep ready and should be deleted.
1623
+ * @returns The routes of nodes that were deleted.
1624
+ */
1625
+ deleteSweepReadyNodes(sweepReadyRoutes) {
1626
+ const { dataStoreRoutes, blobManagerRoutes } = this.getDataStoreAndBlobManagerRoutes(sweepReadyRoutes);
1627
+ const deletedRoutes = this.dataStores.deleteSweepReadyNodes(dataStoreRoutes);
1628
+ return deletedRoutes.concat(this.blobManager.deleteSweepReadyNodes(blobManagerRoutes));
1629
+ }
1630
+ /**
1631
+ * This is called to update objects that are tombstones.
1632
+ *
1633
+ * A Tombstoned object has been unreferenced long enough that GC knows it won't be referenced again.
1634
+ * Tombstoned objects are eventually deleted by GC.
1635
+ *
1636
+ * @param tombstonedRoutes - Data store and attachment blob routes that are tombstones in this Container.
1637
+ */
1638
+ updateTombstonedRoutes(tombstonedRoutes) {
1639
+ const { blobManagerRoutes, dataStoreRoutes } = this.getDataStoreAndBlobManagerRoutes(tombstonedRoutes);
1640
+ this.blobManager.updateTombstonedRoutes(blobManagerRoutes);
1641
+ this.dataStores.updateTombstonedRoutes(dataStoreRoutes);
1642
+ }
1643
+ /**
1644
+ * Returns a server generated referenced timestamp to be used to track unreferenced nodes by GC.
1645
+ */
1646
+ getCurrentReferenceTimestampMs() {
1647
+ // Use the timestamp of the last message seen by this client as that is server generated. If no messages have
1648
+ // been processed, use the timestamp of the message from the last summary.
1649
+ return this.deltaManager.lastMessage?.timestamp ?? this.messageAtLastSummary?.timestamp;
1650
+ }
1651
+ /**
1652
+ * Returns the type of the GC node. Currently, there are nodes that belong to the root ("/"), data stores or
1653
+ * blob manager.
1654
+ */
1655
+ getNodeType(nodePath) {
1656
+ if (this.isBlobPath(nodePath)) {
1657
+ return GCNodeType.Blob;
1658
+ }
1659
+ return this.dataStores.getGCNodeType(nodePath) ?? GCNodeType.Other;
1660
+ }
1661
+ /**
1662
+ * Called by GC to retrieve the package path of the node with the given path. The node should belong to a
1663
+ * data store or an attachment blob.
1664
+ */
1665
+ async getGCNodePackagePath(nodePath) {
1666
+ switch (this.getNodeType(nodePath)) {
1667
+ case GCNodeType.Blob:
1668
+ return [BlobManager.basePath];
1669
+ case GCNodeType.DataStore:
1670
+ case GCNodeType.SubDataStore:
1671
+ return this.dataStores.getDataStorePackagePath(nodePath);
1672
+ default:
1673
+ assert(false, 0x2de /* "Package path requested for unsupported node type." */);
1674
+ }
1675
+ }
1676
+ /**
1677
+ * Returns whether a given path is for attachment blobs that are in the format - "/BlobManager.basePath/...".
1678
+ */
1679
+ isBlobPath(path) {
1680
+ const pathParts = path.split("/");
1681
+ if (pathParts.length < 2 || pathParts[1] !== BlobManager.basePath) {
1682
+ return false;
1683
+ }
1684
+ return true;
1685
+ }
1686
+ /**
1687
+ * From a given list of routes, separate and return routes that belong to blob manager and data stores.
1688
+ * @param routes - A list of routes that can belong to data stores or blob manager.
1689
+ * @returns Two route lists - One that contains routes for blob manager and another one that contains routes
1690
+ * for data stores.
1691
+ */
1692
+ getDataStoreAndBlobManagerRoutes(routes) {
1693
+ const blobManagerRoutes = [];
1694
+ const dataStoreRoutes = [];
1695
+ for (const route of routes) {
1696
+ if (this.isBlobPath(route)) {
1697
+ blobManagerRoutes.push(route);
1698
+ }
1699
+ else {
1700
+ dataStoreRoutes.push(route);
1701
+ }
1702
+ }
1703
+ return { blobManagerRoutes, dataStoreRoutes };
1704
+ }
1705
+ /**
1706
+ * Runs garbage collection and updates the reference / used state of the nodes in the container.
1707
+ * @returns the statistics of the garbage collection run; undefined if GC did not run.
1708
+ */
1709
+ async collectGarbage(options, telemetryContext) {
1710
+ return this.garbageCollector.collectGarbage(options, telemetryContext);
1711
+ }
1712
+ /**
1713
+ * Called when a new outbound reference is added to another node. This is used by garbage collection to identify
1714
+ * all references added in the system.
1715
+ * @param srcHandle - The handle of the node that added the reference.
1716
+ * @param outboundHandle - The handle of the outbound node that is referenced.
1717
+ */
1718
+ addedGCOutboundReference(srcHandle, outboundHandle) {
1719
+ this.garbageCollector.addedOutboundReference(srcHandle.absolutePath, outboundHandle.absolutePath);
1720
+ }
1721
+ /**
1722
+ * Generates the summary tree, uploads it to storage, and then submits the summarize op.
1723
+ * This is intended to be called by the summarizer, since it is the implementation of
1724
+ * ISummarizerInternalsProvider.submitSummary.
1725
+ * It takes care of state management at the container level, including pausing inbound
1726
+ * op processing, updating SummarizerNode state tracking, and garbage collection.
1727
+ * @param options - options controlling how the summary is generated or submitted
1728
+ */
1729
+ async submitSummary(options) {
1730
+ const { fullTree = false, finalAttempt = false, refreshLatestAck, summaryLogger } = options;
1731
+ // The summary number for this summary. This will be updated during the summary process, so get it now and
1732
+ // use it for all events logged during this summary.
1733
+ const summaryNumber = this.nextSummaryNumber;
1734
+ const summaryNumberLogger = createChildLogger({
1735
+ logger: summaryLogger,
1736
+ properties: {
1737
+ all: { summaryNumber },
1738
+ },
1739
+ });
1740
+ assert(this.outbox.isEmpty, 0x3d1 /* Can't trigger summary in the middle of a batch */);
1741
+ // We close the summarizer and download a new snapshot and reload the container
1742
+ let latestSnapshotVersionId;
1743
+ if (refreshLatestAck === true) {
1744
+ return this.prefetchLatestSummaryThenClose(createChildLogger({
1745
+ logger: summaryNumberLogger,
1746
+ properties: { all: { safeSummary: true } },
1747
+ }));
1748
+ }
1749
+ // If the container is dirty, i.e., there are pending unacked ops, the summary will not be eventual consistent
1750
+ // and it may even be incorrect. So, wait for the container to be saved with a timeout. If the container is not
1751
+ // saved within the timeout, check if it should be failed or can continue.
1752
+ if (this.validateSummaryBeforeUpload && this.isDirty) {
1753
+ const countBefore = this.pendingMessagesCount;
1754
+ // The timeout for waiting for pending ops can be overridden via configurations.
1755
+ const pendingOpsTimeout = this.mc.config.getNumber("Fluid.Summarizer.waitForPendingOpsTimeoutMs") ??
1756
+ defaultPendingOpsWaitTimeoutMs;
1757
+ await new Promise((resolve, reject) => {
1758
+ const timeoutId = setTimeout(() => resolve(), pendingOpsTimeout);
1759
+ this.once("saved", () => {
1760
+ clearTimeout(timeoutId);
1761
+ resolve();
1762
+ });
1763
+ this.once("dispose", () => {
1764
+ clearTimeout(timeoutId);
1765
+ reject(new Error("Runtime is disposed while summarizing"));
1766
+ });
1767
+ });
1768
+ // Log that there are pending ops while summarizing. This will help us gather data on how often this
1769
+ // happens, whether we attempted to wait for these ops to be acked and what was the result.
1770
+ summaryNumberLogger.sendTelemetryEvent({
1771
+ eventName: "PendingOpsWhileSummarizing",
1772
+ saved: !this.isDirty,
1773
+ timeout: pendingOpsTimeout,
1774
+ countBefore,
1775
+ countAfter: this.pendingMessagesCount,
1776
+ });
1777
+ // There could still be pending ops. Check if summary should fail or continue.
1778
+ const pendingMessagesFailResult = await this.shouldFailSummaryOnPendingOps(summaryNumberLogger, this.deltaManager.lastSequenceNumber, this.deltaManager.minimumSequenceNumber, finalAttempt, true /* beforeSummaryGeneration */);
1779
+ if (pendingMessagesFailResult !== undefined) {
1780
+ return pendingMessagesFailResult;
1781
+ }
1782
+ }
1783
+ const shouldPauseInboundSignal = this.mc.config.getBoolean("Fluid.ContainerRuntime.SubmitSummary.disableInboundSignalPause") !== true;
1784
+ let summaryRefSeqNum;
1785
+ try {
1786
+ await this.deltaManager.inbound.pause();
1787
+ if (shouldPauseInboundSignal) {
1788
+ await this.deltaManager.inboundSignal.pause();
1789
+ }
1790
+ summaryRefSeqNum = this.deltaManager.lastSequenceNumber;
1791
+ const minimumSequenceNumber = this.deltaManager.minimumSequenceNumber;
1792
+ const message = `Summary @${summaryRefSeqNum}:${this.deltaManager.minimumSequenceNumber}`;
1793
+ const lastAck = this.summaryCollection.latestAck;
1794
+ this.summarizerNode.startSummary(summaryRefSeqNum, summaryNumberLogger);
1795
+ // Helper function to check whether we should still continue between each async step.
1796
+ const checkContinue = () => {
1797
+ // Do not check for loss of connectivity directly! Instead leave it up to
1798
+ // RunWhileConnectedCoordinator to control policy in a single place.
1799
+ // This will allow easier change of design if we chose to. For example, we may chose to allow
1800
+ // summarizer to reconnect in the future.
1801
+ // Also checking for cancellation is a must as summary process may be abandoned for other reasons,
1802
+ // like loss of connectivity for main (interactive) client.
1803
+ if (options.cancellationToken.cancelled) {
1804
+ return { continue: false, error: "disconnected" };
1805
+ }
1806
+ // That said, we rely on submitSystemMessage() that today only works in connected state.
1807
+ // So if we fail here, it either means that RunWhileConnectedCoordinator does not work correctly,
1808
+ // OR that design changed and we need to remove this check and fix submitSystemMessage.
1809
+ assert(this.connected, 0x258 /* "connected" */);
1810
+ // Ensure that lastSequenceNumber has not changed after pausing.
1811
+ // We need the summary op's reference sequence number to match our summary sequence number,
1812
+ // otherwise we'll get the wrong sequence number stamped on the summary's .protocol attributes.
1813
+ if (this.deltaManager.lastSequenceNumber !== summaryRefSeqNum) {
1814
+ return {
1815
+ continue: false,
1816
+ error: `lastSequenceNumber changed before uploading to storage. ${this.deltaManager.lastSequenceNumber} !== ${summaryRefSeqNum}`,
1817
+ };
1818
+ }
1819
+ assert(summaryRefSeqNum === this.deltaManager.lastMessage?.sequenceNumber, 0x395 /* it's one and the same thing */);
1820
+ if (lastAck !== this.summaryCollection.latestAck) {
1821
+ return {
1822
+ continue: false,
1823
+ error: `Last summary changed while summarizing. ${this.summaryCollection.latestAck} !== ${lastAck}`,
1824
+ };
1825
+ }
1826
+ return { continue: true };
1827
+ };
1828
+ let continueResult = checkContinue();
1829
+ if (!continueResult.continue) {
1830
+ return {
1831
+ stage: "base",
1832
+ referenceSequenceNumber: summaryRefSeqNum,
1833
+ minimumSequenceNumber,
1834
+ error: continueResult.error,
1835
+ };
1836
+ }
1837
+ const trace = Trace.start();
1838
+ let summarizeResult;
1839
+ // If the GC state needs to be reset, we need to force a full tree summary and update the unreferenced
1840
+ // state of all the nodes.
1841
+ const forcedFullTree = this.garbageCollector.summaryStateNeedsReset;
1842
+ try {
1843
+ summarizeResult = await this.summarize({
1844
+ fullTree: fullTree || forcedFullTree,
1845
+ trackState: true,
1846
+ summaryLogger: summaryNumberLogger,
1847
+ runGC: this.garbageCollector.shouldRunGC,
1848
+ });
1849
+ }
1850
+ catch (error) {
1851
+ return {
1852
+ stage: "base",
1853
+ referenceSequenceNumber: summaryRefSeqNum,
1854
+ minimumSequenceNumber,
1855
+ error,
1856
+ };
1857
+ }
1858
+ // If validateSummaryBeforeUpload is true, validate that the summary generated is correct before uploading.
1859
+ if (this.validateSummaryBeforeUpload) {
1860
+ // Validate that the summaries generated by summarize nodes is correct.
1861
+ const validateResult = this.summarizerNode.validateSummary();
1862
+ if (!validateResult.success) {
1863
+ const { success, ...loggingProps } = validateResult;
1864
+ const error = new RetriableSummaryError(validateResult.reason, validateResult.retryAfterSeconds, { ...loggingProps });
1865
+ return {
1866
+ stage: "base",
1867
+ referenceSequenceNumber: summaryRefSeqNum,
1868
+ minimumSequenceNumber,
1869
+ error,
1870
+ };
1871
+ }
1872
+ const pendingMessagesFailResult = await this.shouldFailSummaryOnPendingOps(summaryNumberLogger, summaryRefSeqNum, minimumSequenceNumber, finalAttempt, false /* beforeSummaryGeneration */);
1873
+ if (pendingMessagesFailResult !== undefined) {
1874
+ return pendingMessagesFailResult;
1875
+ }
1876
+ }
1877
+ const { summary: summaryTree, stats: partialStats } = summarizeResult;
1878
+ // Now that we have generated the summary, update the message at last summary to the last message processed.
1879
+ this.messageAtLastSummary = this.deltaManager.lastMessage;
1880
+ // Counting dataStores and handles
1881
+ // Because handles are unchanged dataStores in the current logic,
1882
+ // summarized dataStore count is total dataStore count minus handle count
1883
+ const dataStoreTree = summaryTree.tree[channelsTreeName];
1884
+ assert(dataStoreTree.type === SummaryType.Tree, 0x1fc /* "summary is not a tree" */);
1885
+ const handleCount = Object.values(dataStoreTree.tree).filter((value) => value.type === SummaryType.Handle).length;
1886
+ const gcSummaryTreeStats = summaryTree.tree[gcTreeKey]
1887
+ ? calculateStats(summaryTree.tree[gcTreeKey])
1888
+ : undefined;
1889
+ const summaryStats = {
1890
+ dataStoreCount: this.dataStores.size,
1891
+ summarizedDataStoreCount: this.dataStores.size - handleCount,
1892
+ gcStateUpdatedDataStoreCount: this.garbageCollector.updatedDSCountSinceLastSummary,
1893
+ gcBlobNodeCount: gcSummaryTreeStats?.blobNodeCount,
1894
+ gcTotalBlobsSize: gcSummaryTreeStats?.totalBlobSize,
1895
+ summaryNumber,
1896
+ ...partialStats,
1897
+ };
1898
+ const generateSummaryData = {
1899
+ referenceSequenceNumber: summaryRefSeqNum,
1900
+ minimumSequenceNumber,
1901
+ summaryTree,
1902
+ summaryStats,
1903
+ generateDuration: trace.trace().duration,
1904
+ forcedFullTree,
1905
+ };
1906
+ continueResult = checkContinue();
1907
+ if (!continueResult.continue) {
1908
+ return { stage: "generate", ...generateSummaryData, error: continueResult.error };
1909
+ }
1910
+ // It may happen that the lastAck it not correct due to missing summaryAck in case of single commit
1911
+ // summary. So if the previous summarizer closes just after submitting the summary and before
1912
+ // submitting the summaryOp then we can't rely on summaryAck. So in case we have
1913
+ // latestSnapshotVersionId from storage and it does not match with the lastAck ackHandle, then use
1914
+ // the one fetched from storage as parent as that is the latest.
1915
+ let summaryContext;
1916
+ if (lastAck?.summaryAck.contents.handle !== latestSnapshotVersionId &&
1917
+ latestSnapshotVersionId !== undefined) {
1918
+ summaryContext = {
1919
+ proposalHandle: undefined,
1920
+ ackHandle: latestSnapshotVersionId,
1921
+ referenceSequenceNumber: summaryRefSeqNum,
1922
+ };
1923
+ }
1924
+ else if (lastAck === undefined) {
1925
+ summaryContext = {
1926
+ proposalHandle: undefined,
1927
+ ackHandle: this.loadedFromVersionId,
1928
+ referenceSequenceNumber: summaryRefSeqNum,
1929
+ };
1930
+ }
1931
+ else {
1932
+ summaryContext = {
1933
+ proposalHandle: lastAck.summaryOp.contents.handle,
1934
+ ackHandle: lastAck.summaryAck.contents.handle,
1935
+ referenceSequenceNumber: summaryRefSeqNum,
1936
+ };
1937
+ }
1938
+ let handle;
1939
+ try {
1940
+ handle = await this.storage.uploadSummaryWithContext(summarizeResult.summary, summaryContext);
1941
+ }
1942
+ catch (error) {
1943
+ return { stage: "generate", ...generateSummaryData, error };
1944
+ }
1945
+ const parent = summaryContext.ackHandle;
1946
+ const summaryMessage = {
1947
+ handle,
1948
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1949
+ head: parent,
1950
+ message,
1951
+ parents: parent ? [parent] : [],
1952
+ };
1953
+ const uploadData = {
1954
+ ...generateSummaryData,
1955
+ handle,
1956
+ uploadDuration: trace.trace().duration,
1957
+ };
1958
+ continueResult = checkContinue();
1959
+ if (!continueResult.continue) {
1960
+ return { stage: "upload", ...uploadData, error: continueResult.error };
1961
+ }
1962
+ let clientSequenceNumber;
1963
+ try {
1964
+ clientSequenceNumber = this.submitSummaryMessage(summaryMessage, summaryRefSeqNum);
1965
+ }
1966
+ catch (error) {
1967
+ return { stage: "upload", ...uploadData, error };
1968
+ }
1969
+ const submitData = {
1970
+ stage: "submit",
1971
+ ...uploadData,
1972
+ clientSequenceNumber,
1973
+ submitOpDuration: trace.trace().duration,
1974
+ };
1975
+ try {
1976
+ // If validateSummaryBeforeUpload is false, the summary should be validated in this step.
1977
+ this.summarizerNode.completeSummary(handle, !this.validateSummaryBeforeUpload /* validate */);
1978
+ }
1979
+ catch (error) {
1980
+ return { stage: "upload", ...uploadData, error };
1981
+ }
1982
+ return submitData;
1983
+ }
1984
+ finally {
1985
+ // Cleanup wip summary in case of failure
1986
+ this.summarizerNode.clearSummary();
1987
+ // ! This needs to happen before we resume inbound queues to ensure heuristics are tracked correctly
1988
+ this._summarizer?.recordSummaryAttempt?.(summaryRefSeqNum);
1989
+ // Restart the delta manager
1990
+ this.deltaManager.inbound.resume();
1991
+ if (shouldPauseInboundSignal) {
1992
+ this.deltaManager.inboundSignal.resume();
1993
+ }
1994
+ }
1995
+ }
1996
+ /**
1997
+ * This helper is called during summarization. If the container is dirty, it will return a failed summarize result
1998
+ * (IBaseSummarizeResult) unless this is the final summarize attempt and SkipFailingIncorrectSummary option is set.
1999
+ * @param logger - The logger to be used for sending telemetry.
2000
+ * @param referenceSequenceNumber - The reference sequence number of the summary attempt.
2001
+ * @param minimumSequenceNumber - The minimum sequence number of the summary attempt.
2002
+ * @param finalAttempt - Whether this is the final summary attempt.
2003
+ * @param beforeSummaryGeneration - Whether this is called before summary generation or after.
2004
+ * @returns failed summarize result (IBaseSummarizeResult) if summary should be failed, undefined otherwise.
2005
+ */
2006
+ async shouldFailSummaryOnPendingOps(logger, referenceSequenceNumber, minimumSequenceNumber, finalAttempt, beforeSummaryGeneration) {
2007
+ if (!this.isDirty) {
2008
+ return;
2009
+ }
2010
+ // If "SkipFailingIncorrectSummary" option is true, don't fail the summary in the last attempt.
2011
+ // This is a fallback to make progress in documents where there are consistently pending ops in
2012
+ // the summarizer.
2013
+ if (finalAttempt &&
2014
+ this.mc.config.getBoolean("Fluid.Summarizer.SkipFailingIncorrectSummary")) {
2015
+ const error = DataProcessingError.create("Pending ops during summarization", "submitSummary", undefined, { pendingMessages: this.pendingMessagesCount });
2016
+ logger.sendErrorEvent({
2017
+ eventName: "SkipFailingIncorrectSummary",
2018
+ referenceSequenceNumber,
2019
+ minimumSequenceNumber,
2020
+ beforeGenerate: beforeSummaryGeneration,
2021
+ }, error);
2022
+ }
2023
+ else {
2024
+ // The retry delay when there are pending ops can be overridden via config so that we can adjust it
2025
+ // based on telemetry while we decide on a stable number.
2026
+ const retryDelayMs = this.mc.config.getNumber("Fluid.Summarizer.PendingOpsRetryDelayMs") ??
2027
+ defaultPendingOpsRetryDelayMs;
2028
+ const error = new RetriableSummaryError("PendingOpsWhileSummarizing", retryDelayMs / 1000, {
2029
+ count: this.pendingMessagesCount,
2030
+ beforeGenerate: beforeSummaryGeneration,
2031
+ });
2032
+ return {
2033
+ stage: "base",
2034
+ referenceSequenceNumber,
2035
+ minimumSequenceNumber,
2036
+ error,
2037
+ };
2038
+ }
2039
+ }
2040
+ get pendingMessagesCount() {
2041
+ return this.pendingStateManager.pendingMessagesCount + this.outbox.messageCount;
2042
+ }
2043
+ hasPendingMessages() {
2044
+ return this.pendingMessagesCount !== 0;
2045
+ }
2046
+ updateDocumentDirtyState(dirty) {
2047
+ if (this.attachState !== AttachState.Attached) {
2048
+ assert(dirty, 0x3d2 /* Non-attached container is dirty */);
2049
+ }
2050
+ else {
2051
+ // Other way is not true = see this.isContainerMessageDirtyable()
2052
+ assert(!dirty || this.hasPendingMessages(), 0x3d3 /* if doc is dirty, there has to be pending ops */);
2053
+ }
2054
+ if (this.dirtyContainer === dirty) {
2055
+ return;
2056
+ }
2057
+ this.dirtyContainer = dirty;
2058
+ if (this.emitDirtyDocumentEvent) {
2059
+ this.emit(dirty ? "dirty" : "saved");
2060
+ }
2061
+ }
2062
+ submitDataStoreOp(id, contents, localOpMetadata = undefined) {
2063
+ const envelope = {
2064
+ address: id,
2065
+ contents,
2066
+ };
2067
+ this.submit({ type: ContainerMessageType.FluidDataStoreOp, contents: envelope }, localOpMetadata);
2068
+ }
2069
+ submitDataStoreAliasOp(contents, localOpMetadata) {
2070
+ const aliasMessage = contents;
2071
+ if (!isDataStoreAliasMessage(aliasMessage)) {
2072
+ throw new UsageError("malformedDataStoreAliasMessage");
2073
+ }
2074
+ this.submit({ type: ContainerMessageType.Alias, contents }, localOpMetadata);
2075
+ }
2076
+ async uploadBlob(blob, signal) {
2077
+ this.verifyNotClosed();
2078
+ return this.blobManager.createBlob(blob, signal);
2079
+ }
2080
+ maybeSubmitIdAllocationOp(type) {
2081
+ if (type !== ContainerMessageType.IdAllocation) {
2082
+ let idAllocationBatchMessage;
2083
+ let idRange;
2084
+ if (this.idCompressorEnabled) {
2085
+ assert(this.idCompressor !== undefined, 0x67d /* IdCompressor should be defined if enabled */);
2086
+ idRange = this.idCompressor.takeNextCreationRange();
2087
+ // Don't include the idRange if there weren't any Ids allocated
2088
+ idRange = idRange?.ids !== undefined ? idRange : undefined;
2089
+ }
2090
+ if (idRange !== undefined) {
2091
+ const idAllocationMessage = {
2092
+ type: ContainerMessageType.IdAllocation,
2093
+ contents: idRange,
2094
+ };
2095
+ idAllocationBatchMessage = {
2096
+ contents: JSON.stringify(idAllocationMessage),
2097
+ referenceSequenceNumber: this.deltaManager.lastSequenceNumber,
2098
+ metadata: undefined,
2099
+ localOpMetadata: undefined,
2100
+ type: ContainerMessageType.IdAllocation,
2101
+ };
2102
+ }
2103
+ if (idAllocationBatchMessage !== undefined) {
2104
+ this.outbox.submitIdAllocation(idAllocationBatchMessage);
2105
+ }
2106
+ }
2107
+ }
2108
+ submit(containerRuntimeMessage, localOpMetadata = undefined, metadata = undefined) {
2109
+ this.verifyNotClosed();
2110
+ this.verifyCanSubmitOps();
2111
+ // There should be no ops in detached container state!
2112
+ assert(this.attachState !== AttachState.Detached, 0x132 /* "sending ops in detached container" */);
2113
+ const serializedContent = JSON.stringify(containerRuntimeMessage);
2114
+ // Note that the real (non-proxy) delta manager is used here to get the readonly info. This is because
2115
+ // container runtime's ability to submit ops depend on the actual readonly state of the delta manager.
2116
+ if (this.innerDeltaManager.readOnlyInfo.readonly) {
2117
+ this.mc.logger.sendTelemetryEvent({
2118
+ eventName: "SubmitOpInReadonly",
2119
+ connected: this.connected,
2120
+ });
2121
+ }
2122
+ const type = containerRuntimeMessage.type;
2123
+ const message = {
2124
+ contents: serializedContent,
2125
+ type,
2126
+ metadata,
2127
+ localOpMetadata,
2128
+ referenceSequenceNumber: this.deltaManager.lastSequenceNumber,
2129
+ };
2130
+ try {
2131
+ // Submit an IdAllocation op if any Ids have been generated since
2132
+ // the last op was submitted. Don't submit another if it's an IdAllocation
2133
+ // op as that means we're in resubmission flow and we don't want to send
2134
+ // IdRanges out of order.
2135
+ this.maybeSubmitIdAllocationOp(type);
2136
+ // If this is attach message for new data store, and we are in a batch, send this op out of order
2137
+ // Is it safe:
2138
+ // Yes, this should be safe reordering. Newly created data stores are not visible through API surface.
2139
+ // They become visible only when aliased, or handle to some sub-element of newly created datastore
2140
+ // is stored in some DDS, i.e. only after some other op.
2141
+ // Why:
2142
+ // Attach ops are large, and expensive to process. Plus there are scenarios where a lot of new data
2143
+ // stores are created, causing issues like relay service throttling (too many ops) and catastrophic
2144
+ // failure (batch is too large). Pushing them earlier and outside of main batch should alleviate
2145
+ // these issues.
2146
+ // Cons:
2147
+ // 1. With large batches, relay service may throttle clients. Clients may disconnect while throttled.
2148
+ // This change creates new possibility of a lot of newly created data stores never being referenced
2149
+ // because client died before it had a change to submit the rest of the ops. This will create more
2150
+ // garbage that needs to be collected leveraging GC (Garbage Collection) feature.
2151
+ // 2. Sending ops out of order means they are excluded from rollback functionality. This is not an issue
2152
+ // today as rollback can't undo creation of data store. To some extent not sending them is a bigger
2153
+ // issue than sending.
2154
+ // Please note that this does not change file format, so it can be disabled in the future if this
2155
+ // optimization no longer makes sense (for example, batch compression may make it less appealing).
2156
+ if (this.currentlyBatching() &&
2157
+ type === ContainerMessageType.Attach &&
2158
+ this.disableAttachReorder !== true) {
2159
+ this.outbox.submitAttach(message);
2160
+ }
2161
+ else if (type === ContainerMessageType.BlobAttach) {
2162
+ // BlobAttach ops must have their metadata visible and cannot be grouped (see opGroupingManager.ts)
2163
+ this.outbox.submitBlobAttach(message);
2164
+ }
2165
+ else {
2166
+ this.outbox.submit(message);
2167
+ }
2168
+ if (!this.currentlyBatching()) {
2169
+ this.flush();
2170
+ }
2171
+ else {
2172
+ this.scheduleFlush();
2173
+ }
2174
+ }
2175
+ catch (error) {
2176
+ this.closeFn(error);
2177
+ throw error;
2178
+ }
2179
+ if (this.isContainerMessageDirtyable(containerRuntimeMessage)) {
2180
+ this.updateDocumentDirtyState(true);
2181
+ }
2182
+ }
2183
+ scheduleFlush() {
2184
+ if (this.flushTaskExists) {
2185
+ return;
2186
+ }
2187
+ this.flushTaskExists = true;
2188
+ const flush = () => {
2189
+ this.flushTaskExists = false;
2190
+ try {
2191
+ this.flush();
2192
+ }
2193
+ catch (error) {
2194
+ this.closeFn(error);
2195
+ }
2196
+ };
2197
+ switch (this.flushMode) {
2198
+ case FlushMode.TurnBased:
2199
+ // When in TurnBased flush mode the runtime will buffer operations in the current turn and send them as a single
2200
+ // batch at the end of the turn
2201
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
2202
+ Promise.resolve().then(flush);
2203
+ break;
2204
+ // FlushModeExperimental is experimental and not exposed directly in the runtime APIs
2205
+ case FlushModeExperimental.Async:
2206
+ // When in Async flush mode, the runtime will accumulate all operations across JS turns and send them as a single
2207
+ // batch when all micro-tasks are complete.
2208
+ // Compared to TurnBased, this flush mode will capture more ops into the same batch.
2209
+ setTimeout(flush, 0);
2210
+ break;
2211
+ default:
2212
+ assert(this._orderSequentiallyCalls > 0, 0x587 /* Unreachable unless running under orderSequentially */);
2213
+ break;
2214
+ }
2215
+ }
2216
+ submitSummaryMessage(contents, referenceSequenceNumber) {
2217
+ this.verifyNotClosed();
2218
+ assert(this.connected, 0x133 /* "Container disconnected when trying to submit system message" */);
2219
+ // System message should not be sent in the middle of the batch.
2220
+ assert(this.outbox.isEmpty, 0x3d4 /* System op in the middle of a batch */);
2221
+ // back-compat: ADO #1385: Make this call unconditional in the future
2222
+ return this.submitSummaryFn !== undefined
2223
+ ? this.submitSummaryFn(contents, referenceSequenceNumber)
2224
+ : this.submitFn(MessageType.Summarize, contents, false);
2225
+ }
2226
+ /**
2227
+ * Throw an error if the runtime is closed. Methods that are expected to potentially
2228
+ * be called after dispose due to asynchrony should not call this.
2229
+ */
2230
+ verifyNotClosed() {
2231
+ if (this._disposed) {
2232
+ throw new Error("Runtime is closed");
2233
+ }
2234
+ }
2235
+ verifyCanSubmitOps() {
2236
+ if (this.ensureNoDataModelChangesCalls > 0) {
2237
+ const errorMessage = "Op was submitted from within a `ensureNoDataModelChanges` callback";
2238
+ if (this.opReentryCallsToReport > 0) {
2239
+ this.mc.logger.sendTelemetryEvent({ eventName: "OpReentry" },
2240
+ // We need to capture the call stack in order to inspect the source of this usage pattern
2241
+ getLongStack(() => new UsageError(errorMessage)));
2242
+ this.opReentryCallsToReport--;
2243
+ }
2244
+ // Creating ops while processing ops can lead
2245
+ // to undefined behavior and events observed in the wrong order.
2246
+ // For example, we have two callbacks registered for a DDS, A and B.
2247
+ // Then if on change #1 callback A creates change #2, the invocation flow will be:
2248
+ //
2249
+ // A because of #1
2250
+ // A because of #2
2251
+ // B because of #2
2252
+ // B because of #1
2253
+ //
2254
+ // The runtime must enforce op coherence by not allowing ops to be submitted
2255
+ // while ops are being processed.
2256
+ if (this.enableOpReentryCheck) {
2257
+ throw new UsageError(errorMessage);
2258
+ }
2259
+ }
2260
+ }
2261
+ reSubmitBatch(batch) {
2262
+ this.orderSequentially(() => {
2263
+ for (const message of batch) {
2264
+ this.reSubmit(message);
2265
+ }
2266
+ });
2267
+ this.flush();
2268
+ }
2269
+ reSubmit(message) {
2270
+ // Need to parse from string for back-compat
2271
+ const containerRuntimeMessage = this.parseLocalOpContent(message.content);
2272
+ this.reSubmitCore(containerRuntimeMessage, message.localOpMetadata, message.opMetadata);
2273
+ }
2274
+ /**
2275
+ * Finds the right store and asks it to resubmit the message. This typically happens when we
2276
+ * reconnect and there are pending messages.
2277
+ * ! Note: successfully resubmitting an op that has been successfully sequenced is not possible due to checks in the ConnectionStateHandler (Loader layer)
2278
+ * @param message - The original LocalContainerRuntimeMessage.
2279
+ * @param localOpMetadata - The local metadata associated with the original message.
2280
+ */
2281
+ reSubmitCore(message, localOpMetadata, opMetadata) {
2282
+ switch (message.type) {
2283
+ case ContainerMessageType.FluidDataStoreOp:
2284
+ // For Operations, call resubmitDataStoreOp which will find the right store
2285
+ // and trigger resubmission on it.
2286
+ this.dataStores.resubmitDataStoreOp(message.contents, localOpMetadata);
2287
+ break;
2288
+ case ContainerMessageType.Attach:
2289
+ case ContainerMessageType.Alias:
2290
+ case ContainerMessageType.IdAllocation: {
2291
+ this.submit(message, localOpMetadata);
2292
+ break;
2293
+ }
2294
+ case ContainerMessageType.ChunkedOp:
2295
+ throw new Error(`chunkedOp not expected here`);
2296
+ case ContainerMessageType.BlobAttach:
2297
+ this.blobManager.reSubmit(opMetadata);
2298
+ break;
2299
+ case ContainerMessageType.Rejoin:
2300
+ this.submit(message);
2301
+ break;
2302
+ case ContainerMessageType.GC:
2303
+ // GC op is only sent in summarizer which should never reconnect.
2304
+ throw new LoggingError("GC op not expected to be resubmitted in summarizer");
2305
+ default: {
2306
+ // This case should be very rare - it would imply an op was stashed from a
2307
+ // future version of runtime code and now is being applied on an older version
2308
+ const compatBehavior = message.compatDetails?.behavior;
2309
+ if (compatBehaviorAllowsMessageType(message.type, compatBehavior)) {
2310
+ this.logger.sendTelemetryEvent({
2311
+ eventName: "resubmitUnrecognizedMessageTypeAllowed",
2312
+ messageDetails: { type: message.type, compatBehavior },
2313
+ });
2314
+ }
2315
+ else {
2316
+ const error = DataProcessingError.create("Resubmitting runtime message of unknown type", "reSubmitCore", undefined /* sequencedMessage */, {
2317
+ messageDetails: JSON.stringify({
2318
+ type: message.type,
2319
+ compatBehavior,
2320
+ }),
2321
+ });
2322
+ this.closeFn(error);
2323
+ throw error;
2324
+ }
2325
+ }
2326
+ }
2327
+ }
2328
+ rollback(content, localOpMetadata) {
2329
+ // Need to parse from string for back-compat
2330
+ const { type, contents } = this.parseLocalOpContent(content);
2331
+ switch (type) {
2332
+ case ContainerMessageType.FluidDataStoreOp:
2333
+ // For operations, call rollbackDataStoreOp which will find the right store
2334
+ // and trigger rollback on it.
2335
+ this.dataStores.rollbackDataStoreOp(contents, localOpMetadata);
2336
+ break;
2337
+ default:
2338
+ // Don't check message.compatDetails because this is for rolling back a local op so the type will be known
2339
+ throw new Error(`Can't rollback ${type}`);
2340
+ }
2341
+ }
2342
+ /** Implementation of ISummarizerInternalsProvider.refreshLatestSummaryAck */
2343
+ async refreshLatestSummaryAck(options) {
2344
+ const { proposalHandle, ackHandle, summaryRefSeq, summaryLogger } = options;
2345
+ // proposalHandle is always passed from RunningSummarizer.
2346
+ assert(proposalHandle !== undefined, 0x766 /* proposalHandle should be available */);
2347
+ const readAndParseBlob = async (id) => readAndParse(this.storage, id);
2348
+ const result = await this.summarizerNode.refreshLatestSummary(proposalHandle, summaryRefSeq);
2349
+ /**
2350
+ * When refreshing a summary ack, this check indicates a new ack of a summary that is newer than the
2351
+ * current summary that is tracked, but this summarizer runtime did not produce/track that summary. Thus
2352
+ * it needs to refresh its state. Today refresh is done by fetching the latest snapshot to update the cache
2353
+ * and then close as the current main client is likely to be re-elected as the parent summarizer again.
2354
+ */
2355
+ if (!result.isSummaryTracked && result.isSummaryNewer) {
2356
+ const fetchResult = await this.fetchLatestSnapshotFromStorage(summaryLogger, {
2357
+ eventName: "RefreshLatestSummaryAckFetch",
2358
+ ackHandle,
2359
+ targetSequenceNumber: summaryRefSeq,
2360
+ }, readAndParseBlob);
2361
+ /**
2362
+ * If the fetched snapshot is older than the one for which the ack was received, close the container.
2363
+ * This should never happen because an ack should be sent after the latest summary is updated in the server.
2364
+ * However, there are couple of scenarios where it's possible:
2365
+ * 1. A file was modified externally resulting in modifying the snapshot's sequence number. This can lead to
2366
+ * the document being unusable and we should not proceed.
2367
+ * 2. The server DB failed after the ack was sent which may delete the corresponding snapshot. Ideally, in
2368
+ * such cases, the file will be rolled back along with the ack and we will eventually reach a consistent
2369
+ * state.
2370
+ */
2371
+ if (fetchResult.latestSnapshotRefSeq < summaryRefSeq) {
2372
+ const error = DataProcessingError.create("Fetched snapshot is older than the received ack", "RefreshLatestSummaryAck", undefined /* sequencedMessage */, {
2373
+ ackHandle,
2374
+ summaryRefSeq,
2375
+ fetchedSnapshotRefSeq: fetchResult.latestSnapshotRefSeq,
2376
+ });
2377
+ this.disposeFn(error);
2378
+ throw error;
2379
+ }
2380
+ await this.closeStaleSummarizer("RefreshLatestSummaryAckFetch");
2381
+ return;
2382
+ }
2383
+ // Notify the garbage collector so it can update its latest summary state.
2384
+ await this.garbageCollector.refreshLatestSummary(result);
2385
+ }
2386
+ /**
2387
+ * Fetches the latest snapshot from storage to refresh the cache as a performance optimization and closes the
2388
+ * summarizer to reload from new state.
2389
+ * @param summaryLogger - logger to use when fetching snapshot from storage
2390
+ * @returns a generic summarization error
2391
+ */
2392
+ async prefetchLatestSummaryThenClose(summaryLogger) {
2393
+ const readAndParseBlob = async (id) => readAndParse(this.storage, id);
2394
+ // This is a performance optimization as the same parent is likely to be elected again, and would use its
2395
+ // cache to fetch the snapshot instead of the network.
2396
+ await this.fetchLatestSnapshotFromStorage(summaryLogger, {
2397
+ eventName: "RefreshLatestSummaryFromServerFetch",
2398
+ }, readAndParseBlob);
2399
+ await this.closeStaleSummarizer("RefreshLatestSummaryFromServerFetch");
2400
+ return {
2401
+ stage: "base",
2402
+ error: "summary state stale - Unsupported option 'refreshLatestAck'",
2403
+ referenceSequenceNumber: this.deltaManager.lastSequenceNumber,
2404
+ minimumSequenceNumber: this.deltaManager.minimumSequenceNumber,
2405
+ };
2406
+ }
2407
+ async closeStaleSummarizer(codePath) {
2408
+ // Delay before restarting summarizer to prevent the summarizer from restarting too frequently.
2409
+ await delay(this.closeSummarizerDelayMs);
2410
+ this._summarizer?.stop("latestSummaryStateStale");
2411
+ this.disposeFn();
2412
+ }
2413
+ /**
2414
+ * Downloads the latest snapshot from storage.
2415
+ * By default, it also closes the container after downloading the snapshot. However, this may be
2416
+ * overridden via options.
2417
+ */
2418
+ async fetchLatestSnapshotFromStorage(logger, event, readAndParseBlob) {
2419
+ return PerformanceEvent.timedExecAsync(logger, event, async (perfEvent) => {
2420
+ const stats = {};
2421
+ const trace = Trace.start();
2422
+ const versions = await this.storage.getVersions(null, 1, "prefetchLatestSummaryBeforeClose", FetchSource.noCache);
2423
+ assert(!!versions && !!versions[0], 0x137 /* "Failed to get version from storage" */);
2424
+ stats.getVersionDuration = trace.trace().duration;
2425
+ const maybeSnapshot = await this.storage.getSnapshotTree(versions[0]);
2426
+ assert(!!maybeSnapshot, 0x138 /* "Failed to get snapshot from storage" */);
2427
+ stats.getSnapshotDuration = trace.trace().duration;
2428
+ const latestSnapshotRefSeq = await seqFromTree(maybeSnapshot, readAndParseBlob);
2429
+ stats.snapshotRefSeq = latestSnapshotRefSeq;
2430
+ stats.snapshotVersion = versions[0].id;
2431
+ perfEvent.end(stats);
2432
+ return {
2433
+ snapshotTree: maybeSnapshot,
2434
+ versionId: versions[0].id,
2435
+ latestSnapshotRefSeq,
2436
+ };
2437
+ });
2438
+ }
2439
+ async getPendingLocalState(props) {
2440
+ return PerformanceEvent.timedExecAsync(this.mc.logger, {
2441
+ eventName: "getPendingLocalState",
2442
+ notifyImminentClosure: props?.notifyImminentClosure,
2443
+ }, async (event) => {
2444
+ this.verifyNotClosed();
2445
+ // in case imminentClosure is set to true by future code, we don't
2446
+ // try to change its value
2447
+ if (!this.imminentClosure) {
2448
+ this.imminentClosure = props?.notifyImminentClosure ?? this.imminentClosure;
2449
+ }
2450
+ const stopBlobAttachingSignal = props?.stopBlobAttachingSignal;
2451
+ if (this._orderSequentiallyCalls !== 0) {
2452
+ throw new UsageError("can't get state during orderSequentially");
2453
+ }
2454
+ // Flush pending batch.
2455
+ // getPendingLocalState() is only exposed through Container.closeAndGetPendingLocalState(), so it's safe
2456
+ // to close current batch.
2457
+ this.flush();
2458
+ const pendingAttachmentBlobs = this.imminentClosure
2459
+ ? await this.blobManager.attachAndGetPendingBlobs(stopBlobAttachingSignal)
2460
+ : undefined;
2461
+ const pending = this.pendingStateManager.getLocalState();
2462
+ if (!pendingAttachmentBlobs && !this.hasPendingMessages()) {
2463
+ return; // no pending state to save
2464
+ }
2465
+ const pendingIdCompressorState = this.idCompressor?.serialize(true);
2466
+ const pendingState = {
2467
+ pending,
2468
+ pendingAttachmentBlobs,
2469
+ pendingIdCompressorState,
2470
+ };
2471
+ event.end({
2472
+ attachmentBlobsSize: Object.keys(pendingAttachmentBlobs ?? {}).length,
2473
+ pendingOpsSize: pending?.pendingStates.length,
2474
+ });
2475
+ return pendingState;
2476
+ });
2477
+ }
2478
+ summarizeOnDemand(options) {
2479
+ if (this.isSummarizerClient) {
2480
+ return this.summarizer.summarizeOnDemand(options);
2481
+ }
2482
+ else if (this.summaryManager !== undefined) {
2483
+ return this.summaryManager.summarizeOnDemand(options);
2484
+ }
2485
+ else {
2486
+ // If we're not the summarizer, and we don't have a summaryManager, we expect that
2487
+ // disableSummaries is turned on. We are throwing instead of returning a failure here,
2488
+ // because it is a misuse of the API rather than an expected failure.
2489
+ throw new UsageError(`Can't summarize, disableSummaries: ${this.summariesDisabled}`);
2490
+ }
2491
+ }
2492
+ enqueueSummarize(options) {
2493
+ if (this.isSummarizerClient) {
2494
+ return this.summarizer.enqueueSummarize(options);
2495
+ }
2496
+ else if (this.summaryManager !== undefined) {
2497
+ return this.summaryManager.enqueueSummarize(options);
2498
+ }
2499
+ else {
2500
+ // If we're not the summarizer, and we don't have a summaryManager, we expect that
2501
+ // generateSummaries is turned off. We are throwing instead of returning a failure here,
2502
+ // because it is a misuse of the API rather than an expected failure.
2503
+ throw new UsageError(`Can't summarize, disableSummaries: ${this.summariesDisabled}`);
2504
+ }
2505
+ }
2506
+ /**
2507
+ * Forms a function that will create and retrieve a Summarizer.
2508
+ */
2509
+ formCreateSummarizerFn(loader) {
2510
+ return async () => {
2511
+ return createSummarizer(loader, `/${summarizerRequestUrl}`);
2512
+ };
2513
+ }
2514
+ validateSummaryHeuristicConfiguration(configuration) {
2515
+ // eslint-disable-next-line no-restricted-syntax
2516
+ for (const prop in configuration) {
2517
+ if (typeof configuration[prop] === "number" && configuration[prop] < 0) {
2518
+ throw new UsageError(`Summary heuristic configuration property "${prop}" cannot be less than 0`);
2519
+ }
2520
+ }
2521
+ if (configuration.minIdleTime > configuration.maxIdleTime) {
2522
+ throw new UsageError(`"minIdleTime" [${configuration.minIdleTime}] cannot be greater than "maxIdleTime" [${configuration.maxIdleTime}]`);
2523
+ }
2524
+ }
2525
+ get groupedBatchingEnabled() {
2526
+ const killSwitch = this.mc.config.getBoolean("Fluid.ContainerRuntime.DisableGroupedBatching");
2527
+ return killSwitch !== true && this.runtimeOptions.enableGroupedBatching;
2528
+ }
2529
+ }
2530
+ //# sourceMappingURL=containerRuntime.mjs.map