@fluidframework/container-runtime 2.0.0-dev.2.3.0.115467 → 2.0.0-dev.3.1.0.125672

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 (340) hide show
  1. package/.eslintrc.js +21 -10
  2. package/.mocharc.js +2 -2
  3. package/api-extractor.json +2 -2
  4. package/dist/batchTracker.d.ts +1 -2
  5. package/dist/batchTracker.d.ts.map +1 -1
  6. package/dist/batchTracker.js +2 -1
  7. package/dist/batchTracker.js.map +1 -1
  8. package/dist/blobManager.d.ts +53 -34
  9. package/dist/blobManager.d.ts.map +1 -1
  10. package/dist/blobManager.js +236 -124
  11. package/dist/blobManager.js.map +1 -1
  12. package/dist/connectionTelemetry.d.ts.map +1 -1
  13. package/dist/connectionTelemetry.js +11 -9
  14. package/dist/connectionTelemetry.js.map +1 -1
  15. package/dist/containerHandleContext.d.ts.map +1 -1
  16. package/dist/containerHandleContext.js +3 -1
  17. package/dist/containerHandleContext.js.map +1 -1
  18. package/dist/containerRuntime.d.ts +95 -46
  19. package/dist/containerRuntime.d.ts.map +1 -1
  20. package/dist/containerRuntime.js +288 -135
  21. package/dist/containerRuntime.js.map +1 -1
  22. package/dist/dataStore.d.ts.map +1 -1
  23. package/dist/dataStore.js +11 -9
  24. package/dist/dataStore.js.map +1 -1
  25. package/dist/dataStoreContext.d.ts +2 -1
  26. package/dist/dataStoreContext.d.ts.map +1 -1
  27. package/dist/dataStoreContext.js +38 -21
  28. package/dist/dataStoreContext.js.map +1 -1
  29. package/dist/dataStoreContexts.d.ts.map +1 -1
  30. package/dist/dataStoreContexts.js +7 -3
  31. package/dist/dataStoreContexts.js.map +1 -1
  32. package/dist/dataStoreRegistry.d.ts.map +1 -1
  33. package/dist/dataStoreRegistry.js +3 -1
  34. package/dist/dataStoreRegistry.js.map +1 -1
  35. package/dist/dataStores.d.ts +12 -9
  36. package/dist/dataStores.d.ts.map +1 -1
  37. package/dist/dataStores.js +68 -46
  38. package/dist/dataStores.js.map +1 -1
  39. package/dist/deltaScheduler.d.ts.map +1 -1
  40. package/dist/deltaScheduler.js +8 -3
  41. package/dist/deltaScheduler.js.map +1 -1
  42. package/dist/garbageCollection.d.ts +50 -26
  43. package/dist/garbageCollection.d.ts.map +1 -1
  44. package/dist/garbageCollection.js +348 -196
  45. package/dist/garbageCollection.js.map +1 -1
  46. package/dist/garbageCollectionConstants.d.ts +7 -3
  47. package/dist/garbageCollectionConstants.d.ts.map +1 -1
  48. package/dist/garbageCollectionConstants.js +10 -8
  49. package/dist/garbageCollectionConstants.js.map +1 -1
  50. package/dist/garbageCollectionHelpers.d.ts +15 -0
  51. package/dist/garbageCollectionHelpers.d.ts.map +1 -0
  52. package/dist/garbageCollectionHelpers.js +27 -0
  53. package/dist/garbageCollectionHelpers.js.map +1 -0
  54. package/dist/gcSweepReadyUsageDetection.d.ts +5 -5
  55. package/dist/gcSweepReadyUsageDetection.d.ts.map +1 -1
  56. package/dist/gcSweepReadyUsageDetection.js +14 -10
  57. package/dist/gcSweepReadyUsageDetection.js.map +1 -1
  58. package/dist/index.d.ts +3 -4
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js +3 -5
  61. package/dist/index.js.map +1 -1
  62. package/dist/opLifecycle/batchManager.d.ts +13 -1
  63. package/dist/opLifecycle/batchManager.d.ts.map +1 -1
  64. package/dist/opLifecycle/batchManager.js +48 -7
  65. package/dist/opLifecycle/batchManager.js.map +1 -1
  66. package/dist/opLifecycle/definitions.d.ts +25 -1
  67. package/dist/opLifecycle/definitions.d.ts.map +1 -1
  68. package/dist/opLifecycle/definitions.js.map +1 -1
  69. package/dist/opLifecycle/index.d.ts +2 -2
  70. package/dist/opLifecycle/index.d.ts.map +1 -1
  71. package/dist/opLifecycle/index.js +2 -1
  72. package/dist/opLifecycle/index.js.map +1 -1
  73. package/dist/opLifecycle/opCompressor.d.ts +1 -1
  74. package/dist/opLifecycle/opCompressor.d.ts.map +1 -1
  75. package/dist/opLifecycle/opCompressor.js +24 -10
  76. package/dist/opLifecycle/opCompressor.js.map +1 -1
  77. package/dist/opLifecycle/opDecompressor.d.ts +2 -1
  78. package/dist/opLifecycle/opDecompressor.d.ts.map +1 -1
  79. package/dist/opLifecycle/opDecompressor.js +33 -17
  80. package/dist/opLifecycle/opDecompressor.js.map +1 -1
  81. package/dist/opLifecycle/opSplitter.d.ts +34 -2
  82. package/dist/opLifecycle/opSplitter.d.ts.map +1 -1
  83. package/dist/opLifecycle/opSplitter.js +117 -5
  84. package/dist/opLifecycle/opSplitter.js.map +1 -1
  85. package/dist/opLifecycle/outbox.d.ts +5 -0
  86. package/dist/opLifecycle/outbox.d.ts.map +1 -1
  87. package/dist/opLifecycle/outbox.js +38 -27
  88. package/dist/opLifecycle/outbox.js.map +1 -1
  89. package/dist/opLifecycle/remoteMessageProcessor.d.ts.map +1 -1
  90. package/dist/opLifecycle/remoteMessageProcessor.js +17 -2
  91. package/dist/opLifecycle/remoteMessageProcessor.js.map +1 -1
  92. package/dist/opProperties.d.ts.map +1 -1
  93. package/dist/opProperties.js +1 -3
  94. package/dist/opProperties.js.map +1 -1
  95. package/dist/orderedClientElection.d.ts.map +1 -1
  96. package/dist/orderedClientElection.js +10 -4
  97. package/dist/orderedClientElection.js.map +1 -1
  98. package/dist/packageVersion.d.ts +1 -1
  99. package/dist/packageVersion.js +1 -1
  100. package/dist/packageVersion.js.map +1 -1
  101. package/dist/pendingStateManager.d.ts +4 -13
  102. package/dist/pendingStateManager.d.ts.map +1 -1
  103. package/dist/pendingStateManager.js +134 -161
  104. package/dist/pendingStateManager.js.map +1 -1
  105. package/dist/runWhileConnectedCoordinator.d.ts.map +1 -1
  106. package/dist/runWhileConnectedCoordinator.js.map +1 -1
  107. package/dist/runningSummarizer.d.ts.map +1 -1
  108. package/dist/runningSummarizer.js +34 -22
  109. package/dist/runningSummarizer.js.map +1 -1
  110. package/dist/scheduleManager.d.ts +0 -1
  111. package/dist/scheduleManager.d.ts.map +1 -1
  112. package/dist/scheduleManager.js +11 -21
  113. package/dist/scheduleManager.js.map +1 -1
  114. package/dist/serializedSnapshotStorage.d.ts.map +1 -1
  115. package/dist/serializedSnapshotStorage.js +3 -1
  116. package/dist/serializedSnapshotStorage.js.map +1 -1
  117. package/dist/summarizer.d.ts +2 -3
  118. package/dist/summarizer.d.ts.map +1 -1
  119. package/dist/summarizer.js +39 -18
  120. package/dist/summarizer.js.map +1 -1
  121. package/dist/summarizerClientElection.d.ts +1 -2
  122. package/dist/summarizerClientElection.d.ts.map +1 -1
  123. package/dist/summarizerClientElection.js +3 -30
  124. package/dist/summarizerClientElection.js.map +1 -1
  125. package/dist/summarizerHandle.d.ts.map +1 -1
  126. package/dist/summarizerHandle.js.map +1 -1
  127. package/dist/summarizerHeuristics.d.ts.map +1 -1
  128. package/dist/summarizerHeuristics.js +6 -9
  129. package/dist/summarizerHeuristics.js.map +1 -1
  130. package/dist/summarizerTypes.d.ts +22 -25
  131. package/dist/summarizerTypes.d.ts.map +1 -1
  132. package/dist/summarizerTypes.js.map +1 -1
  133. package/dist/summaryCollection.d.ts.map +1 -1
  134. package/dist/summaryCollection.js +18 -8
  135. package/dist/summaryCollection.js.map +1 -1
  136. package/dist/summaryFormat.d.ts.map +1 -1
  137. package/dist/summaryFormat.js +18 -11
  138. package/dist/summaryFormat.js.map +1 -1
  139. package/dist/summaryGenerator.d.ts.map +1 -1
  140. package/dist/summaryGenerator.js +32 -14
  141. package/dist/summaryGenerator.js.map +1 -1
  142. package/dist/summaryManager.d.ts.map +1 -1
  143. package/dist/summaryManager.js +21 -9
  144. package/dist/summaryManager.js.map +1 -1
  145. package/dist/throttler.d.ts +2 -2
  146. package/dist/throttler.d.ts.map +1 -1
  147. package/dist/throttler.js +4 -4
  148. package/dist/throttler.js.map +1 -1
  149. package/garbageCollection.md +15 -2
  150. package/lib/batchTracker.d.ts +1 -2
  151. package/lib/batchTracker.d.ts.map +1 -1
  152. package/lib/batchTracker.js +2 -1
  153. package/lib/batchTracker.js.map +1 -1
  154. package/lib/blobManager.d.ts +53 -34
  155. package/lib/blobManager.d.ts.map +1 -1
  156. package/lib/blobManager.js +239 -127
  157. package/lib/blobManager.js.map +1 -1
  158. package/lib/connectionTelemetry.d.ts.map +1 -1
  159. package/lib/connectionTelemetry.js +11 -9
  160. package/lib/connectionTelemetry.js.map +1 -1
  161. package/lib/containerHandleContext.d.ts.map +1 -1
  162. package/lib/containerHandleContext.js +3 -1
  163. package/lib/containerHandleContext.js.map +1 -1
  164. package/lib/containerRuntime.d.ts +95 -46
  165. package/lib/containerRuntime.d.ts.map +1 -1
  166. package/lib/containerRuntime.js +291 -138
  167. package/lib/containerRuntime.js.map +1 -1
  168. package/lib/dataStore.d.ts.map +1 -1
  169. package/lib/dataStore.js +11 -9
  170. package/lib/dataStore.js.map +1 -1
  171. package/lib/dataStoreContext.d.ts +2 -1
  172. package/lib/dataStoreContext.d.ts.map +1 -1
  173. package/lib/dataStoreContext.js +40 -23
  174. package/lib/dataStoreContext.js.map +1 -1
  175. package/lib/dataStoreContexts.d.ts.map +1 -1
  176. package/lib/dataStoreContexts.js +7 -3
  177. package/lib/dataStoreContexts.js.map +1 -1
  178. package/lib/dataStoreRegistry.d.ts.map +1 -1
  179. package/lib/dataStoreRegistry.js +3 -1
  180. package/lib/dataStoreRegistry.js.map +1 -1
  181. package/lib/dataStores.d.ts +12 -9
  182. package/lib/dataStores.d.ts.map +1 -1
  183. package/lib/dataStores.js +74 -52
  184. package/lib/dataStores.js.map +1 -1
  185. package/lib/deltaScheduler.d.ts.map +1 -1
  186. package/lib/deltaScheduler.js +9 -4
  187. package/lib/deltaScheduler.js.map +1 -1
  188. package/lib/garbageCollection.d.ts +50 -26
  189. package/lib/garbageCollection.d.ts.map +1 -1
  190. package/lib/garbageCollection.js +347 -195
  191. package/lib/garbageCollection.js.map +1 -1
  192. package/lib/garbageCollectionConstants.d.ts +7 -3
  193. package/lib/garbageCollectionConstants.d.ts.map +1 -1
  194. package/lib/garbageCollectionConstants.js +9 -7
  195. package/lib/garbageCollectionConstants.js.map +1 -1
  196. package/lib/garbageCollectionHelpers.d.ts +15 -0
  197. package/lib/garbageCollectionHelpers.d.ts.map +1 -0
  198. package/lib/garbageCollectionHelpers.js +23 -0
  199. package/lib/garbageCollectionHelpers.js.map +1 -0
  200. package/lib/gcSweepReadyUsageDetection.d.ts +5 -5
  201. package/lib/gcSweepReadyUsageDetection.d.ts.map +1 -1
  202. package/lib/gcSweepReadyUsageDetection.js +14 -10
  203. package/lib/gcSweepReadyUsageDetection.js.map +1 -1
  204. package/lib/index.d.ts +3 -4
  205. package/lib/index.d.ts.map +1 -1
  206. package/lib/index.js +2 -3
  207. package/lib/index.js.map +1 -1
  208. package/lib/opLifecycle/batchManager.d.ts +13 -1
  209. package/lib/opLifecycle/batchManager.d.ts.map +1 -1
  210. package/lib/opLifecycle/batchManager.js +48 -7
  211. package/lib/opLifecycle/batchManager.js.map +1 -1
  212. package/lib/opLifecycle/definitions.d.ts +25 -1
  213. package/lib/opLifecycle/definitions.d.ts.map +1 -1
  214. package/lib/opLifecycle/definitions.js.map +1 -1
  215. package/lib/opLifecycle/index.d.ts +2 -2
  216. package/lib/opLifecycle/index.d.ts.map +1 -1
  217. package/lib/opLifecycle/index.js +1 -1
  218. package/lib/opLifecycle/index.js.map +1 -1
  219. package/lib/opLifecycle/opCompressor.d.ts +1 -1
  220. package/lib/opLifecycle/opCompressor.d.ts.map +1 -1
  221. package/lib/opLifecycle/opCompressor.js +24 -10
  222. package/lib/opLifecycle/opCompressor.js.map +1 -1
  223. package/lib/opLifecycle/opDecompressor.d.ts +2 -1
  224. package/lib/opLifecycle/opDecompressor.d.ts.map +1 -1
  225. package/lib/opLifecycle/opDecompressor.js +33 -17
  226. package/lib/opLifecycle/opDecompressor.js.map +1 -1
  227. package/lib/opLifecycle/opSplitter.d.ts +34 -2
  228. package/lib/opLifecycle/opSplitter.d.ts.map +1 -1
  229. package/lib/opLifecycle/opSplitter.js +116 -5
  230. package/lib/opLifecycle/opSplitter.js.map +1 -1
  231. package/lib/opLifecycle/outbox.d.ts +5 -0
  232. package/lib/opLifecycle/outbox.d.ts.map +1 -1
  233. package/lib/opLifecycle/outbox.js +38 -27
  234. package/lib/opLifecycle/outbox.js.map +1 -1
  235. package/lib/opLifecycle/remoteMessageProcessor.d.ts.map +1 -1
  236. package/lib/opLifecycle/remoteMessageProcessor.js +17 -2
  237. package/lib/opLifecycle/remoteMessageProcessor.js.map +1 -1
  238. package/lib/opProperties.d.ts.map +1 -1
  239. package/lib/opProperties.js +1 -3
  240. package/lib/opProperties.js.map +1 -1
  241. package/lib/orderedClientElection.d.ts.map +1 -1
  242. package/lib/orderedClientElection.js +10 -4
  243. package/lib/orderedClientElection.js.map +1 -1
  244. package/lib/packageVersion.d.ts +1 -1
  245. package/lib/packageVersion.js +1 -1
  246. package/lib/packageVersion.js.map +1 -1
  247. package/lib/pendingStateManager.d.ts +4 -13
  248. package/lib/pendingStateManager.d.ts.map +1 -1
  249. package/lib/pendingStateManager.js +134 -161
  250. package/lib/pendingStateManager.js.map +1 -1
  251. package/lib/runWhileConnectedCoordinator.d.ts.map +1 -1
  252. package/lib/runWhileConnectedCoordinator.js.map +1 -1
  253. package/lib/runningSummarizer.d.ts.map +1 -1
  254. package/lib/runningSummarizer.js +35 -23
  255. package/lib/runningSummarizer.js.map +1 -1
  256. package/lib/scheduleManager.d.ts +0 -1
  257. package/lib/scheduleManager.d.ts.map +1 -1
  258. package/lib/scheduleManager.js +11 -21
  259. package/lib/scheduleManager.js.map +1 -1
  260. package/lib/serializedSnapshotStorage.d.ts.map +1 -1
  261. package/lib/serializedSnapshotStorage.js +3 -1
  262. package/lib/serializedSnapshotStorage.js.map +1 -1
  263. package/lib/summarizer.d.ts +2 -3
  264. package/lib/summarizer.d.ts.map +1 -1
  265. package/lib/summarizer.js +39 -18
  266. package/lib/summarizer.js.map +1 -1
  267. package/lib/summarizerClientElection.d.ts +1 -2
  268. package/lib/summarizerClientElection.d.ts.map +1 -1
  269. package/lib/summarizerClientElection.js +3 -30
  270. package/lib/summarizerClientElection.js.map +1 -1
  271. package/lib/summarizerHandle.d.ts.map +1 -1
  272. package/lib/summarizerHandle.js.map +1 -1
  273. package/lib/summarizerHeuristics.d.ts.map +1 -1
  274. package/lib/summarizerHeuristics.js +6 -9
  275. package/lib/summarizerHeuristics.js.map +1 -1
  276. package/lib/summarizerTypes.d.ts +22 -25
  277. package/lib/summarizerTypes.d.ts.map +1 -1
  278. package/lib/summarizerTypes.js.map +1 -1
  279. package/lib/summaryCollection.d.ts.map +1 -1
  280. package/lib/summaryCollection.js +18 -8
  281. package/lib/summaryCollection.js.map +1 -1
  282. package/lib/summaryFormat.d.ts.map +1 -1
  283. package/lib/summaryFormat.js +20 -13
  284. package/lib/summaryFormat.js.map +1 -1
  285. package/lib/summaryGenerator.d.ts.map +1 -1
  286. package/lib/summaryGenerator.js +32 -14
  287. package/lib/summaryGenerator.js.map +1 -1
  288. package/lib/summaryManager.d.ts.map +1 -1
  289. package/lib/summaryManager.js +21 -9
  290. package/lib/summaryManager.js.map +1 -1
  291. package/lib/throttler.d.ts +2 -2
  292. package/lib/throttler.d.ts.map +1 -1
  293. package/lib/throttler.js +4 -4
  294. package/lib/throttler.js.map +1 -1
  295. package/package.json +27 -24
  296. package/prettier.config.cjs +1 -1
  297. package/src/batchTracker.ts +55 -50
  298. package/src/blobManager.ts +799 -593
  299. package/src/connectionTelemetry.ts +280 -249
  300. package/src/containerHandleContext.ts +27 -29
  301. package/src/containerRuntime.ts +3123 -2793
  302. package/src/dataStore.ts +172 -159
  303. package/src/dataStoreContext.ts +1048 -991
  304. package/src/dataStoreContexts.ts +178 -161
  305. package/src/dataStoreRegistry.ts +25 -20
  306. package/src/dataStores.ts +784 -711
  307. package/src/deltaScheduler.ts +158 -150
  308. package/src/garbageCollection.ts +1795 -1546
  309. package/src/garbageCollectionConstants.ts +10 -7
  310. package/src/garbageCollectionHelpers.ts +37 -0
  311. package/src/gcSweepReadyUsageDetection.ts +89 -83
  312. package/src/index.ts +67 -69
  313. package/src/opLifecycle/batchManager.ts +148 -86
  314. package/src/opLifecycle/definitions.ts +45 -19
  315. package/src/opLifecycle/index.ts +6 -5
  316. package/src/opLifecycle/opCompressor.ts +57 -39
  317. package/src/opLifecycle/opDecompressor.ts +104 -64
  318. package/src/opLifecycle/opSplitter.ts +226 -66
  319. package/src/opLifecycle/outbox.ts +206 -182
  320. package/src/opLifecycle/remoteMessageProcessor.ts +63 -47
  321. package/src/opProperties.ts +11 -9
  322. package/src/orderedClientElection.ts +489 -457
  323. package/src/packageVersion.ts +1 -1
  324. package/src/pendingStateManager.ts +379 -381
  325. package/src/runWhileConnectedCoordinator.ts +78 -71
  326. package/src/runningSummarizer.ts +619 -582
  327. package/src/scheduleManager.ts +299 -280
  328. package/src/serializedSnapshotStorage.ts +116 -111
  329. package/src/summarizer.ts +417 -381
  330. package/src/summarizerClientElection.ts +107 -129
  331. package/src/summarizerHandle.ts +11 -9
  332. package/src/summarizerHeuristics.ts +183 -186
  333. package/src/summarizerTypes.ts +344 -333
  334. package/src/summaryCollection.ts +378 -349
  335. package/src/summaryFormat.ts +146 -127
  336. package/src/summaryGenerator.ts +464 -406
  337. package/src/summaryManager.ts +377 -348
  338. package/src/throttler.ts +131 -122
  339. package/tsconfig.esnext.json +6 -6
  340. package/tsconfig.json +9 -13
package/src/dataStores.ts CHANGED
@@ -4,59 +4,78 @@
4
4
  */
5
5
 
6
6
  import { ITelemetryBaseLogger, IDisposable } from "@fluidframework/common-definitions";
7
- import { DataCorruptionError, extractSafePropertiesFromMessage } from "@fluidframework/container-utils";
7
+ import {
8
+ DataCorruptionError,
9
+ extractSafePropertiesFromMessage,
10
+ } from "@fluidframework/container-utils";
8
11
  import { IFluidHandle } from "@fluidframework/core-interfaces";
9
12
  import { FluidObjectHandle } from "@fluidframework/datastore";
13
+ import { ISequencedDocumentMessage, ISnapshotTree } from "@fluidframework/protocol-definitions";
10
14
  import {
11
- ISequencedDocumentMessage,
12
- ISnapshotTree,
13
- } from "@fluidframework/protocol-definitions";
14
- import {
15
- AliasResult,
16
- channelsTreeName,
17
- CreateChildSummarizerNodeFn,
18
- CreateChildSummarizerNodeParam,
19
- CreateSummarizerNodeSource,
20
- IAttachMessage,
21
- IEnvelope,
22
- IFluidDataStoreContextDetached,
23
- IGarbageCollectionData,
24
- IGarbageCollectionDetailsBase,
25
- IInboundSignalMessage,
26
- InboundAttachMessage,
27
- ISummarizeResult,
28
- ISummaryTreeWithStats,
29
- ITelemetryContext,
15
+ AliasResult,
16
+ channelsTreeName,
17
+ CreateChildSummarizerNodeFn,
18
+ CreateChildSummarizerNodeParam,
19
+ CreateSummarizerNodeSource,
20
+ IAttachMessage,
21
+ IEnvelope,
22
+ IFluidDataStoreContextDetached,
23
+ IGarbageCollectionData,
24
+ IGarbageCollectionDetailsBase,
25
+ IInboundSignalMessage,
26
+ InboundAttachMessage,
27
+ ISummarizeResult,
28
+ ISummaryTreeWithStats,
29
+ ITelemetryContext,
30
30
  } from "@fluidframework/runtime-definitions";
31
31
  import {
32
- convertSnapshotTreeToSummaryTree,
33
- convertToSummaryTree,
34
- create404Response,
35
- createResponseError,
36
- responseToException,
37
- packagePathToTelemetryProperty,
38
- SummaryTreeBuilder,
32
+ convertSnapshotTreeToSummaryTree,
33
+ convertToSummaryTree,
34
+ create404Response,
35
+ createResponseError,
36
+ responseToException,
37
+ SummaryTreeBuilder,
39
38
  } from "@fluidframework/runtime-utils";
40
- import { ChildLogger, loggerToMonitoringContext, LoggingError, MonitoringContext, TelemetryDataTag } from "@fluidframework/telemetry-utils";
39
+ import {
40
+ ChildLogger,
41
+ loggerToMonitoringContext,
42
+ LoggingError,
43
+ MonitoringContext,
44
+ TelemetryDataTag,
45
+ } from "@fluidframework/telemetry-utils";
41
46
  import { AttachState } from "@fluidframework/container-definitions";
42
47
  import { BlobCacheStorageService, buildSnapshotTree } from "@fluidframework/driver-utils";
43
48
  import { assert, Lazy, LazyPromise } from "@fluidframework/common-utils";
44
49
  import { v4 as uuid } from "uuid";
45
- import { GCDataBuilder, unpackChildNodesUsedRoutes } from "@fluidframework/garbage-collector";
50
+ import {
51
+ GCDataBuilder,
52
+ unpackChildNodesGCDetails,
53
+ unpackChildNodesUsedRoutes,
54
+ } from "@fluidframework/garbage-collector";
46
55
  import { DataStoreContexts } from "./dataStoreContexts";
47
- import { ContainerRuntime } from "./containerRuntime";
48
56
  import {
49
- FluidDataStoreContext,
50
- RemoteFluidDataStoreContext,
51
- LocalFluidDataStoreContext,
52
- createAttributesBlob,
53
- LocalDetachedFluidDataStoreContext,
57
+ ContainerRuntime,
58
+ defaultRuntimeHeaderData,
59
+ RuntimeHeaderData,
60
+ TombstoneResponseHeaderKey,
61
+ } from "./containerRuntime";
62
+ import {
63
+ FluidDataStoreContext,
64
+ RemoteFluidDataStoreContext,
65
+ LocalFluidDataStoreContext,
66
+ createAttributesBlob,
67
+ LocalDetachedFluidDataStoreContext,
54
68
  } from "./dataStoreContext";
55
- import { IContainerRuntimeMetadata, nonDataStorePaths, rootHasIsolatedChannels } from "./summaryFormat";
69
+ import {
70
+ IContainerRuntimeMetadata,
71
+ nonDataStorePaths,
72
+ rootHasIsolatedChannels,
73
+ } from "./summaryFormat";
56
74
  import { IDataStoreAliasMessage, isDataStoreAliasMessage } from "./dataStore";
57
75
  import { GCNodeType } from "./garbageCollection";
58
- import { throwOnTombstoneUsageKey } from "./garbageCollectionConstants";
76
+ import { throwOnTombstoneLoadKey } from "./garbageCollectionConstants";
59
77
  import { summarizerClientType } from "./summarizerClientElection";
78
+ import { sendGCUnexpectedUsageEvent } from "./garbageCollectionHelpers";
60
79
 
61
80
  type PendingAliasResolve = (success: boolean) => void;
62
81
 
@@ -65,682 +84,736 @@ type PendingAliasResolve = (success: boolean) => void;
65
84
  * but eventually could be hosted on any channel once we formalize the channel api boundary.
66
85
  */
67
86
  export class DataStores implements IDisposable {
68
- // Stores tracked by the Domain
69
- private readonly pendingAttach = new Map<string, IAttachMessage>();
70
- // 0.24 back-compat attachingBeforeSummary
71
- public readonly attachOpFiredForDataStore = new Set<string>();
72
-
73
- private readonly mc: MonitoringContext;
74
-
75
- private readonly disposeOnce = new Lazy<void>(() => this.contexts.dispose());
76
-
77
- public readonly containerLoadStats: {
78
- // number of dataStores during loadContainer
79
- readonly containerLoadDataStoreCount: number;
80
- // number of unreferenced dataStores during loadContainer
81
- readonly referencedDataStoreCount: number;
82
- };
83
-
84
- // Stores the ids of new data stores between two GC runs. This is used to notify the garbage collector of new
85
- // root data stores that are added.
86
- private dataStoresSinceLastGC: string[] = [];
87
- /** If true, throw an error when a tombstone data store is retrieved. */
88
- private readonly throwOnTombstoneUsage: boolean;
89
- // The handle to the container runtime. This is used mainly for GC purposes to represent outbound reference from
90
- // the container runtime to other nodes.
91
- private readonly containerRuntimeHandle: IFluidHandle;
92
- private readonly pendingAliasMap: Map<string, Promise<AliasResult>> = new Map<string, Promise<AliasResult>>();
93
-
94
- constructor(
95
- private readonly baseSnapshot: ISnapshotTree | undefined,
96
- private readonly runtime: ContainerRuntime,
97
- private readonly submitAttachFn: (attachContent: any) => void,
98
- private readonly getCreateChildSummarizerNodeFn:
99
- (id: string, createParam: CreateChildSummarizerNodeParam) => CreateChildSummarizerNodeFn,
100
- private readonly deleteChildSummarizerNodeFn: (id: string) => void,
101
- baseLogger: ITelemetryBaseLogger,
102
- getBaseGCDetails: () => Promise<Map<string, IGarbageCollectionDetailsBase>>,
103
- private readonly gcNodeUpdated: (
104
- nodePath: string, timestampMs: number, packagePath?: readonly string[]) => void,
105
- private readonly aliasMap: Map<string, string>,
106
- private readonly contexts: DataStoreContexts = new DataStoreContexts(baseLogger),
107
- ) {
108
- this.mc = loggerToMonitoringContext(ChildLogger.create(baseLogger));
109
- this.containerRuntimeHandle = new FluidObjectHandle(this.runtime, "/", this.runtime.IFluidHandleContext);
110
-
111
- const baseGCDetailsP = new LazyPromise(async () => {
112
- return getBaseGCDetails();
113
- });
114
- // Returns the base GC details for the data store with the given id.
115
- const dataStoreBaseGCDetails = async (dataStoreId: string) => {
116
- const baseGCDetails = await baseGCDetailsP;
117
- return baseGCDetails.get(dataStoreId);
118
- };
119
- // Tombstone should only throw when the feature flag is enabled and the client isn't a summarizer
120
- this.throwOnTombstoneUsage =
121
- this.mc.config.getBoolean(throwOnTombstoneUsageKey) === true &&
122
- this.runtime.clientDetails.type !== summarizerClientType;
123
-
124
- // Extract stores stored inside the snapshot
125
- const fluidDataStores = new Map<string, ISnapshotTree>();
126
- if (baseSnapshot) {
127
- for (const [key, value] of Object.entries(baseSnapshot.trees)) {
128
- fluidDataStores.set(key, value);
129
- }
130
- }
131
-
132
- let unreferencedDataStoreCount = 0;
133
- // Create a context for each of them
134
- for (const [key, value] of fluidDataStores) {
135
- let dataStoreContext: FluidDataStoreContext;
136
-
137
- // counting number of unreferenced data stores
138
- if (value.unreferenced) {
139
- unreferencedDataStoreCount++;
140
- }
141
- // If we have a detached container, then create local data store contexts.
142
- if (this.runtime.attachState !== AttachState.Detached) {
143
- dataStoreContext = new RemoteFluidDataStoreContext({
144
- id: key,
145
- snapshotTree: value,
146
- getBaseGCDetails: async () => dataStoreBaseGCDetails(key),
147
- runtime: this.runtime,
148
- storage: this.runtime.storage,
149
- scope: this.runtime.scope,
150
- createSummarizerNodeFn: this.getCreateChildSummarizerNodeFn(
151
- key,
152
- { type: CreateSummarizerNodeSource.FromSummary },
153
- ),
154
- });
155
- } else {
156
- if (typeof value !== "object") {
157
- throw new LoggingError("Snapshot should be there to load from!!");
158
- }
159
- const snapshotTree = value;
160
- dataStoreContext = new LocalFluidDataStoreContext({
161
- id: key,
162
- pkg: undefined,
163
- runtime: this.runtime,
164
- storage: this.runtime.storage,
165
- scope: this.runtime.scope,
166
- createSummarizerNodeFn: this.getCreateChildSummarizerNodeFn(
167
- key,
168
- { type: CreateSummarizerNodeSource.FromSummary },
169
- ),
170
- makeLocallyVisibleFn: () => this.makeDataStoreLocallyVisible(key),
171
- snapshotTree,
172
- isRootDataStore: undefined,
173
- });
174
- }
175
- this.contexts.addBoundOrRemoted(dataStoreContext);
176
- }
177
- this.containerLoadStats = {
178
- containerLoadDataStoreCount: fluidDataStores.size,
179
- referencedDataStoreCount: fluidDataStores.size - unreferencedDataStoreCount,
180
- };
181
- }
182
-
183
- public get aliases(): ReadonlyMap<string, string> {
184
- return this.aliasMap;
185
- }
186
-
187
- public get pendingAliases(): Map<string, Promise<AliasResult>> {
188
- return this.pendingAliasMap;
189
- }
190
-
191
- public async waitIfPendingAlias(maybeAlias: string): Promise<AliasResult> {
192
- const pendingAliasPromise = this.pendingAliases.get(maybeAlias);
193
- return pendingAliasPromise === undefined ? "Success" : pendingAliasPromise;
194
- }
195
-
196
- public processAttachMessage(message: ISequencedDocumentMessage, local: boolean) {
197
- const attachMessage = message.contents as InboundAttachMessage;
198
-
199
- this.dataStoresSinceLastGC.push(attachMessage.id);
200
-
201
- // The local object has already been attached
202
- if (local) {
203
- assert(this.pendingAttach.has(attachMessage.id),
204
- 0x15e /* "Local object does not have matching attach message id" */);
205
- this.contexts.get(attachMessage.id)?.emit("attached");
206
- this.pendingAttach.delete(attachMessage.id);
207
- return;
208
- }
209
-
210
- // If a non-local operation then go and create the object, otherwise mark it as officially attached.
211
- if (this.alreadyProcessed(attachMessage.id)) {
212
- // TODO: dataStoreId may require a different tag from PackageData #7488
213
- const error = new DataCorruptionError(
214
- // pre-0.58 error message: duplicateDataStoreCreatedWithExistingId
215
- "Duplicate DataStore created with existing id",
216
- {
217
- ...extractSafePropertiesFromMessage(message),
218
- dataStoreId: {
219
- value: attachMessage.id,
220
- tag: TelemetryDataTag.CodeArtifact,
221
- },
222
- },
223
- );
224
- throw error;
225
- }
226
-
227
- const flatBlobs = new Map<string, ArrayBufferLike>();
228
- let snapshotTree: ISnapshotTree | undefined;
229
- if (attachMessage.snapshot) {
230
- snapshotTree = buildSnapshotTree(attachMessage.snapshot.entries, flatBlobs);
231
- }
232
-
233
- // Include the type of attach message which is the pkg of the store to be
234
- // used by RemoteFluidDataStoreContext in case it is not in the snapshot.
235
- const pkg = [attachMessage.type];
236
- const remoteFluidDataStoreContext = new RemoteFluidDataStoreContext({
237
- id: attachMessage.id,
238
- snapshotTree,
239
- // New data stores begin with empty GC details since GC hasn't run on them yet.
240
- getBaseGCDetails: async () => { return {}; },
241
- runtime: this.runtime,
242
- storage: new BlobCacheStorageService(this.runtime.storage, flatBlobs),
243
- scope: this.runtime.scope,
244
- createSummarizerNodeFn: this.getCreateChildSummarizerNodeFn(
245
- attachMessage.id,
246
- {
247
- type: CreateSummarizerNodeSource.FromAttach,
248
- sequenceNumber: message.sequenceNumber,
249
- snapshot: attachMessage.snapshot ?? {
250
- entries: [createAttributesBlob(
251
- pkg,
252
- true /* isRootDataStore */,
253
- )],
254
- },
255
- },
256
- ),
257
- pkg,
258
- });
259
-
260
- this.contexts.addBoundOrRemoted(remoteFluidDataStoreContext);
261
- }
262
-
263
- public processAliasMessage(
264
- message: ISequencedDocumentMessage,
265
- localOpMetadata: unknown,
266
- local: boolean,
267
- ): void {
268
- const aliasMessage = message.contents as IDataStoreAliasMessage;
269
- if (!isDataStoreAliasMessage(aliasMessage)) {
270
- throw new DataCorruptionError(
271
- "malformedDataStoreAliasMessage",
272
- {
273
- ...extractSafePropertiesFromMessage(message),
274
- },
275
- );
276
- }
277
-
278
- const resolve = localOpMetadata as PendingAliasResolve;
279
- const aliasResult = this.processAliasMessageCore(aliasMessage);
280
- if (local) {
281
- resolve(aliasResult);
282
- }
283
- }
284
-
285
- public processAliasMessageCore(aliasMessage: IDataStoreAliasMessage): boolean {
286
- if (this.alreadyProcessed(aliasMessage.alias)) {
287
- return false;
288
- }
289
-
290
- const context = this.contexts.get(aliasMessage.internalId);
291
- if (context === undefined) {
292
- this.mc.logger.sendErrorEvent({
293
- eventName: "AliasFluidDataStoreNotFound",
294
- fluidDataStoreId: aliasMessage.internalId,
295
- });
296
- return false;
297
- }
298
-
299
- const handle = new FluidObjectHandle(
300
- context,
301
- aliasMessage.internalId,
302
- this.runtime.IFluidHandleContext,
303
- );
304
- this.runtime.addedGCOutboundReference(this.containerRuntimeHandle, handle);
305
-
306
- this.aliasMap.set(aliasMessage.alias, context.id);
307
- context.setInMemoryRoot();
308
- return true;
309
- }
310
-
311
- private alreadyProcessed(id: string): boolean {
312
- return this.aliasMap.get(id) !== undefined || this.contexts.get(id) !== undefined;
313
- }
314
-
315
- /**
316
- * Make the data stores locally visible in the container graph by moving the data store context from unbound to
317
- * bound list. This data store can now be reached from the root.
318
- * @param id - The id of the data store context to make visible.
319
- */
320
- private makeDataStoreLocallyVisible(id: string): void {
321
- const localContext = this.contexts.getUnbound(id);
322
- assert(!!localContext, 0x15f /* "Could not find unbound context to bind" */);
323
-
324
- /**
325
- * If the container is not detached, it is globally visible to all clients. This data store should also be
326
- * globally visible. Move it to attaching state and send an "attach" op for it.
327
- * If the container is detached, this data store will be part of the summary that makes the container attached.
328
- */
329
- if (this.runtime.attachState !== AttachState.Detached) {
330
- localContext.emit("attaching");
331
- const message = localContext.generateAttachMessage();
332
-
333
- this.pendingAttach.set(id, message);
334
- this.submitAttachFn(message);
335
- this.attachOpFiredForDataStore.add(id);
336
- }
337
-
338
- this.contexts.bind(id);
339
- }
340
-
341
- public createDetachedDataStoreCore(
342
- pkg: Readonly<string[]>,
343
- isRoot: boolean,
344
- id = uuid()): IFluidDataStoreContextDetached {
345
- assert(!id.includes("/"), 0x30c /* Id cannot contain slashes */);
346
-
347
- const context = new LocalDetachedFluidDataStoreContext({
348
- id,
349
- pkg,
350
- runtime: this.runtime,
351
- storage: this.runtime.storage,
352
- scope: this.runtime.scope,
353
- createSummarizerNodeFn: this.getCreateChildSummarizerNodeFn(
354
- id,
355
- { type: CreateSummarizerNodeSource.Local },
356
- ),
357
- makeLocallyVisibleFn: () => this.makeDataStoreLocallyVisible(id),
358
- snapshotTree: undefined,
359
- isRootDataStore: isRoot,
360
- });
361
- this.contexts.addUnbound(context);
362
- return context;
363
- }
364
-
365
- public _createFluidDataStoreContext(pkg: string[], id: string, props?: any) {
366
- assert(!id.includes("/"), 0x30d /* Id cannot contain slashes */);
367
- const context = new LocalFluidDataStoreContext({
368
- id,
369
- pkg,
370
- runtime: this.runtime,
371
- storage: this.runtime.storage,
372
- scope: this.runtime.scope,
373
- createSummarizerNodeFn: this.getCreateChildSummarizerNodeFn(
374
- id,
375
- { type: CreateSummarizerNodeSource.Local },
376
- ),
377
- makeLocallyVisibleFn: () => this.makeDataStoreLocallyVisible(id),
378
- snapshotTree: undefined,
379
- isRootDataStore: false,
380
- createProps: props,
381
- });
382
- this.contexts.addUnbound(context);
383
- return context;
384
- }
385
-
386
- public get disposed() { return this.disposeOnce.evaluated; }
387
- public readonly dispose = () => this.disposeOnce.value;
388
-
389
- public resubmitDataStoreOp(content: any, localOpMetadata: unknown) {
390
- const envelope = content as IEnvelope;
391
- const context = this.contexts.get(envelope.address);
392
- assert(!!context, 0x160 /* "There should be a store context for the op" */);
393
- context.reSubmit(envelope.contents, localOpMetadata);
394
- }
395
-
396
- public rollbackDataStoreOp(content: any, localOpMetadata: unknown) {
397
- const envelope = content as IEnvelope;
398
- const context = this.contexts.get(envelope.address);
399
- assert(!!context, 0x2e8 /* "There should be a store context for the op" */);
400
- context.rollback(envelope.contents, localOpMetadata);
401
- }
402
-
403
- public async applyStashedOp(content: any): Promise<unknown> {
404
- const envelope = content as IEnvelope;
405
- const context = this.contexts.get(envelope.address);
406
- assert(!!context, 0x161 /* "There should be a store context for the op" */);
407
- return context.applyStashedOp(envelope.contents);
408
- }
409
-
410
- public async applyStashedAttachOp(message: IAttachMessage) {
411
- this.pendingAttach.set(message.id, message);
412
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
413
- this.processAttachMessage({ contents: message } as ISequencedDocumentMessage, false);
414
- }
415
-
416
- public processFluidDataStoreOp(message: ISequencedDocumentMessage, local: boolean, localMessageMetadata: unknown) {
417
- const envelope = message.contents as IEnvelope;
418
- const transformed = { ...message, contents: envelope.contents };
419
- const context = this.contexts.get(envelope.address);
420
- assert(!!context, 0x162 /* "There should be a store context for the op" */);
421
- context.process(transformed, local, localMessageMetadata);
422
-
423
- // Notify that a GC node for the data store changed. This is used to detect if a deleted data store is
424
- // being used.
425
- this.gcNodeUpdated(
426
- `/${envelope.address}`,
427
- message.timestamp,
428
- context.isLoaded ? context.packagePath : undefined,
429
- );
430
- }
431
-
432
- public async getDataStore(id: string, wait: boolean, viaHandle: boolean): Promise<FluidDataStoreContext> {
433
- const context = await this.contexts.getBoundOrRemoted(id, wait);
434
- const request = { url: id };
435
- if (context === undefined) {
436
- // The requested data store does not exits. Throw a 404 response exception.
437
- throw responseToException(create404Response(request), request);
438
- }
439
-
440
- if (context.tombstoned) {
441
- // The requested data store is removed by gc. Create a 404 gc response exception.
442
- const error = responseToException(createResponseError(404, "Datastore removed by gc", request), request);
443
- // Note: if a user writes a request to look like it's viaHandle, we will also send this telemetry event
444
- this.mc.logger.sendErrorEvent({
445
- eventName: "GC_Tombstone_DataStore_Requested",
446
- url: request.url,
447
- pkg: packagePathToTelemetryProperty(context.isLoaded ? context.packagePath : undefined),
448
- viaHandle,
449
- }, error);
450
- // Always log an error when tombstoned data store is used. However, throw an error only if
451
- // throwOnTombstoneUsage is set.
452
- if (this.throwOnTombstoneUsage) {
453
- throw error;
454
- }
455
- }
456
-
457
- return context;
458
- }
459
-
460
- public processSignal(address: string, message: IInboundSignalMessage, local: boolean) {
461
- const context = this.contexts.get(address);
462
- if (!context) {
463
- // Attach message may not have been processed yet
464
- assert(!local, 0x163 /* "Missing datastore for local signal" */);
465
- this.mc.logger.sendTelemetryEvent({
466
- eventName: "SignalFluidDataStoreNotFound",
467
- fluidDataStoreId: {
468
- value: address,
469
- tag: TelemetryDataTag.CodeArtifact,
470
- },
471
- });
472
- return;
473
- }
474
-
475
- context.processSignal(message, local);
476
- }
477
-
478
- public setConnectionState(connected: boolean, clientId?: string) {
479
- for (const [fluidDataStore, context] of this.contexts) {
480
- try {
481
- context.setConnectionState(connected, clientId);
482
- } catch (error) {
483
- this.mc.logger.sendErrorEvent({
484
- eventName: "SetConnectionStateError",
485
- clientId,
486
- fluidDataStore,
487
- }, error);
488
- }
489
- }
490
- }
491
-
492
- public setAttachState(attachState: AttachState.Attaching | AttachState.Attached): void {
493
- const eventName = attachState === AttachState.Attaching ? "attaching" : "attached";
494
- for (const [, context] of this.contexts) {
495
- // Fire only for bounded stores.
496
- if (!this.contexts.isNotBound(context.id)) {
497
- context.emit(eventName);
498
- }
499
- }
500
- }
501
-
502
- public get size(): number {
503
- return this.contexts.size;
504
- }
505
-
506
- public async summarize(
507
- fullTree: boolean,
508
- trackState: boolean,
509
- telemetryContext?: ITelemetryContext,
510
- ): Promise<ISummaryTreeWithStats> {
511
- const summaryBuilder = new SummaryTreeBuilder();
512
-
513
- // Iterate over each store and ask it to snapshot
514
- await Promise.all(Array.from(this.contexts)
515
- .filter(([_, context]) => {
516
- // Summarizer works only with clients with no local changes!
517
- assert(context.attachState !== AttachState.Attaching,
518
- 0x165 /* "Summarizer cannot work if client has local changes" */);
519
- return context.attachState === AttachState.Attached;
520
- }).map(async ([contextId, context]) => {
521
- const contextSummary = await context.summarize(fullTree, trackState, telemetryContext);
522
- summaryBuilder.addWithStats(contextId, contextSummary);
523
- }));
524
-
525
- return summaryBuilder.getSummaryTree();
526
- }
527
-
528
- public createSummary(telemetryContext?: ITelemetryContext): ISummaryTreeWithStats {
529
- const builder = new SummaryTreeBuilder();
530
- // Attaching graph of some stores can cause other stores to get bound too.
531
- // So keep taking summary until no new stores get bound.
532
- let notBoundContextsLength: number;
533
- do {
534
- const builderTree = builder.summary.tree;
535
- notBoundContextsLength = this.contexts.notBoundLength();
536
- // Iterate over each data store and ask it to snapshot
537
- Array.from(this.contexts)
538
- .filter(([key, _]) =>
539
- // Take summary of bounded data stores only, make sure we haven't summarized them already
540
- // and no attach op has been fired for that data store because for loader versions <= 0.24
541
- // we set attach state as "attaching" before taking createNew summary.
542
- !(this.contexts.isNotBound(key)
543
- || builderTree[key]
544
- || this.attachOpFiredForDataStore.has(key)),
545
- )
546
- .map(([key, value]) => {
547
- let dataStoreSummary: ISummarizeResult;
548
- if (value.isLoaded) {
549
- const snapshot = value.generateAttachMessage().snapshot;
550
- dataStoreSummary = convertToSummaryTree(snapshot, true);
551
- } else {
552
- // If this data store is not yet loaded, then there should be no changes in the snapshot from
553
- // which it was created as it is detached container. So just use the previous snapshot.
554
- assert(!!this.baseSnapshot,
555
- 0x166 /* "BaseSnapshot should be there as detached container loaded from snapshot" */);
556
- dataStoreSummary = convertSnapshotTreeToSummaryTree(this.baseSnapshot.trees[key]);
557
- }
558
- builder.addWithStats(key, dataStoreSummary);
559
- });
560
- } while (notBoundContextsLength !== this.contexts.notBoundLength());
561
-
562
- return builder.getSummaryTree();
563
- }
564
-
565
- /**
566
- * Before GC runs, called by the garbage collector to update any pending GC state.
567
- * The garbage collector needs to know all outbound references that are added. Since root data stores are not
568
- * explicitly marked as referenced, notify GC of new root data stores that were added since the last GC run.
569
- */
570
- public async updateStateBeforeGC(): Promise<void> {
571
- for (const id of this.dataStoresSinceLastGC) {
572
- const context = this.contexts.get(id);
573
- assert(context !== undefined, 0x2b6 /* Missing data store context */);
574
- if (await context.isRoot()) {
575
- // A root data store is basically a reference from the container runtime to the data store.
576
- const handle = new FluidObjectHandle(context, id, this.runtime.IFluidHandleContext);
577
- this.runtime.addedGCOutboundReference(this.containerRuntimeHandle, handle);
578
- }
579
- }
580
- this.dataStoresSinceLastGC = [];
581
- }
582
-
583
- /**
584
- * Generates data used for garbage collection. It does the following:
585
- *
586
- * 1. Calls into each child data store context to get its GC data.
587
- *
588
- * 2. Prefixes the child context's id to the GC nodes in the child's GC data. This makes sure that the node can be
589
- * identified as belonging to the child.
590
- *
591
- * 3. Adds a GC node for this channel to the nodes received from the children. All these nodes together represent
592
- * the GC data of this channel.
593
- *
594
- * @param fullGC - true to bypass optimizations and force full generation of GC data.
595
- */
596
- public async getGCData(fullGC: boolean = false): Promise<IGarbageCollectionData> {
597
- const builder = new GCDataBuilder();
598
- // Iterate over each store and get their GC data.
599
- await Promise.all(Array.from(this.contexts)
600
- .filter(([_, context]) => {
601
- // Get GC data only for attached contexts. Detached contexts are not connected in the GC reference
602
- // graph so any references they might have won't be connected as well.
603
- return context.attachState === AttachState.Attached;
604
- }).map(async ([contextId, context]) => {
605
- const contextGCData = await context.getGCData(fullGC);
606
- // Prefix the child's id to the ids of its GC nodes so they can be identified as belonging to the child.
607
- // This also gradually builds the id of each node to be a path from the root.
608
- builder.prefixAndAddNodes(contextId, contextGCData.gcNodes);
609
- }));
610
-
611
- // Get the outbound routes and add a GC node for this channel.
612
- builder.addNode("/", await this.getOutboundRoutes());
613
- return builder.getGCData();
614
- }
615
-
616
- /**
617
- * After GC has run, called to notify this Container's data stores of routes that are used in it.
618
- * @param usedRoutes - The routes that are used in all data stores in this Container.
619
- */
620
- public updateUsedRoutes(usedRoutes: string[]) {
621
- // Get a map of data store ids to routes used in it.
622
- const usedDataStoreRoutes = unpackChildNodesUsedRoutes(usedRoutes);
623
-
624
- // Verify that the used routes are correct.
625
- for (const [id] of usedDataStoreRoutes) {
626
- assert(this.contexts.has(id), 0x167 /* "Used route does not belong to any known data store" */);
627
-
628
- // Revive datastores regardless of whether or not tombstone the tombstone flag is flipped
629
- const dataStore = this.contexts.get(id);
630
- assert(dataStore !== undefined, 0x46e /* No data store retrieved with specified id */);
631
- dataStore.setTombstone(false /* tombstone */);
632
- }
633
-
634
- // Update the used routes in each data store. Used routes is empty for unused data stores.
635
- for (const [contextId, context] of this.contexts) {
636
- context.updateUsedRoutes(usedDataStoreRoutes.get(contextId) ?? []);
637
- }
638
- }
639
-
640
- /**
641
- * This is called to update objects whose routes are unused. The unused objects are either deleted or marked as
642
- * tombstones.
643
- * @param unusedRoutes - The routes that are unused in all data stores in this Container.
644
- * @param tombstone - if true, the objects corresponding to unused routes are marked tombstones. Otherwise, they
645
- * are deleted.
646
- */
647
- public updateUnusedRoutes(unusedRoutes: string[], tombstone: boolean) {
648
- for (const route of unusedRoutes) {
649
- const pathParts = route.split("/");
650
- // Delete data store only if its route (/datastoreId) is in unusedRoutes. We don't want to delete a data
651
- // store based on its DDS being unused.
652
- if (pathParts.length > 2) {
653
- continue;
654
- }
655
- const dataStoreId = pathParts[1];
656
- assert(this.contexts.has(dataStoreId), 0x2d7 /* No data store with specified id */);
657
-
658
- /**
659
- * When running GC in tombstone mode, datastore contexts are tombstoned. Tombstoned datastore contexts
660
- * enable testing scenarios with accessing deleted content without actually deleting content from
661
- * summaries.
662
- */
663
- if (tombstone) {
664
- const dataStore = this.contexts.get(dataStoreId);
665
- assert(dataStore !== undefined, 0x442 /* No data store retrieved with specified id */);
666
- dataStore.setTombstone(true /* tombstone */);
667
- continue;
668
- }
669
-
670
- // Delete the contexts of unused data stores.
671
- this.contexts.delete(dataStoreId);
672
- // Delete the summarizer node of the unused data stores.
673
- this.deleteChildSummarizerNodeFn(dataStoreId);
674
- }
675
- }
676
-
677
- /**
678
- * Returns the outbound routes of this channel. Only root data stores are considered referenced and their paths are
679
- * part of outbound routes.
680
- */
681
- private async getOutboundRoutes(): Promise<string[]> {
682
- const outboundRoutes: string[] = [];
683
- for (const [contextId, context] of this.contexts) {
684
- const isRootDataStore = await context.isRoot();
685
- if (isRootDataStore) {
686
- outboundRoutes.push(`/${contextId}`);
687
- }
688
- }
689
- return outboundRoutes;
690
- }
691
-
692
- /**
693
- * Called by GC to retrieve the package path of a data store node with the given path.
694
- */
695
- public async getDataStorePackagePath(nodePath: string): Promise<readonly string[] | undefined> {
696
- // If the node belongs to a data store, return its package path. For DDSes, we return the package path of the
697
- // data store that contains it.
698
- const context = this.contexts.get(nodePath.split("/")[1]);
699
- return (await context?.getInitialSnapshotDetails())?.pkg;
700
- }
701
-
702
- /**
703
- * Called by GC to determine if a node is for a data store or for an object within a data store (for e.g. DDS).
704
- * @returns the GC node type if the node belongs to a data store or object within data store, undefined otherwise.
705
- */
706
- public getGCNodeType(nodePath: string): GCNodeType | undefined {
707
- const pathParts = nodePath.split("/");
708
- if (!this.contexts.has(pathParts[1])) {
709
- return undefined;
710
- }
711
-
712
- // Data stores paths are of the format "/dataStoreId".
713
- // Sub data store paths are of the format "/dataStoreId/subPath/...".
714
- if (pathParts.length === 2) {
715
- return GCNodeType.DataStore;
716
- }
717
- return GCNodeType.SubDataStore;
718
- }
87
+ // Stores tracked by the Domain
88
+ private readonly pendingAttach = new Map<string, IAttachMessage>();
89
+ // 0.24 back-compat attachingBeforeSummary
90
+ public readonly attachOpFiredForDataStore = new Set<string>();
91
+
92
+ private readonly mc: MonitoringContext;
93
+
94
+ private readonly disposeOnce = new Lazy<void>(() => this.contexts.dispose());
95
+
96
+ public readonly containerLoadStats: {
97
+ // number of dataStores during loadContainer
98
+ readonly containerLoadDataStoreCount: number;
99
+ // number of unreferenced dataStores during loadContainer
100
+ readonly referencedDataStoreCount: number;
101
+ };
102
+
103
+ // Stores the ids of new data stores between two GC runs. This is used to notify the garbage collector of new
104
+ // root data stores that are added.
105
+ private dataStoresSinceLastGC: string[] = [];
106
+ /** If true, throw an error when a tombstone data store is retrieved. */
107
+ private readonly throwOnTombstoneLoad: boolean;
108
+ // The handle to the container runtime. This is used mainly for GC purposes to represent outbound reference from
109
+ // the container runtime to other nodes.
110
+ private readonly containerRuntimeHandle: IFluidHandle;
111
+ private readonly pendingAliasMap: Map<string, Promise<AliasResult>> = new Map<
112
+ string,
113
+ Promise<AliasResult>
114
+ >();
115
+
116
+ constructor(
117
+ private readonly baseSnapshot: ISnapshotTree | undefined,
118
+ private readonly runtime: ContainerRuntime,
119
+ private readonly submitAttachFn: (attachContent: any) => void,
120
+ private readonly getCreateChildSummarizerNodeFn: (
121
+ id: string,
122
+ createParam: CreateChildSummarizerNodeParam,
123
+ ) => CreateChildSummarizerNodeFn,
124
+ private readonly deleteChildSummarizerNodeFn: (id: string) => void,
125
+ baseLogger: ITelemetryBaseLogger,
126
+ getBaseGCDetails: () => Promise<IGarbageCollectionDetailsBase>,
127
+ private readonly gcNodeUpdated: (
128
+ nodePath: string,
129
+ timestampMs: number,
130
+ packagePath?: readonly string[],
131
+ ) => void,
132
+ private readonly aliasMap: Map<string, string>,
133
+ private readonly contexts: DataStoreContexts = new DataStoreContexts(baseLogger),
134
+ ) {
135
+ this.mc = loggerToMonitoringContext(ChildLogger.create(baseLogger));
136
+ this.containerRuntimeHandle = new FluidObjectHandle(
137
+ this.runtime,
138
+ "/",
139
+ this.runtime.IFluidHandleContext,
140
+ );
141
+
142
+ const baseGCDetailsP = new LazyPromise(async () => {
143
+ const baseGCDetails = await getBaseGCDetails();
144
+ return unpackChildNodesGCDetails(baseGCDetails);
145
+ });
146
+ // Returns the base GC details for the data store with the given id.
147
+ const dataStoreBaseGCDetails = async (dataStoreId: string) => {
148
+ const baseGCDetails = await baseGCDetailsP;
149
+ return baseGCDetails.get(dataStoreId);
150
+ };
151
+ // Tombstone should only throw when the feature flag is enabled and the client isn't a summarizer
152
+ this.throwOnTombstoneLoad =
153
+ this.mc.config.getBoolean(throwOnTombstoneLoadKey) === true &&
154
+ this.runtime.clientDetails.type !== summarizerClientType;
155
+
156
+ // Extract stores stored inside the snapshot
157
+ const fluidDataStores = new Map<string, ISnapshotTree>();
158
+ if (baseSnapshot) {
159
+ for (const [key, value] of Object.entries(baseSnapshot.trees)) {
160
+ fluidDataStores.set(key, value);
161
+ }
162
+ }
163
+
164
+ let unreferencedDataStoreCount = 0;
165
+ // Create a context for each of them
166
+ for (const [key, value] of fluidDataStores) {
167
+ let dataStoreContext: FluidDataStoreContext;
168
+
169
+ // counting number of unreferenced data stores
170
+ if (value.unreferenced) {
171
+ unreferencedDataStoreCount++;
172
+ }
173
+ // If we have a detached container, then create local data store contexts.
174
+ if (this.runtime.attachState !== AttachState.Detached) {
175
+ dataStoreContext = new RemoteFluidDataStoreContext({
176
+ id: key,
177
+ snapshotTree: value,
178
+ getBaseGCDetails: async () => dataStoreBaseGCDetails(key),
179
+ runtime: this.runtime,
180
+ storage: this.runtime.storage,
181
+ scope: this.runtime.scope,
182
+ createSummarizerNodeFn: this.getCreateChildSummarizerNodeFn(key, {
183
+ type: CreateSummarizerNodeSource.FromSummary,
184
+ }),
185
+ });
186
+ } else {
187
+ if (typeof value !== "object") {
188
+ throw new LoggingError("Snapshot should be there to load from!!");
189
+ }
190
+ const snapshotTree = value;
191
+ dataStoreContext = new LocalFluidDataStoreContext({
192
+ id: key,
193
+ pkg: undefined,
194
+ runtime: this.runtime,
195
+ storage: this.runtime.storage,
196
+ scope: this.runtime.scope,
197
+ createSummarizerNodeFn: this.getCreateChildSummarizerNodeFn(key, {
198
+ type: CreateSummarizerNodeSource.FromSummary,
199
+ }),
200
+ makeLocallyVisibleFn: () => this.makeDataStoreLocallyVisible(key),
201
+ snapshotTree,
202
+ isRootDataStore: undefined,
203
+ });
204
+ }
205
+ this.contexts.addBoundOrRemoted(dataStoreContext);
206
+ }
207
+ this.containerLoadStats = {
208
+ containerLoadDataStoreCount: fluidDataStores.size,
209
+ referencedDataStoreCount: fluidDataStores.size - unreferencedDataStoreCount,
210
+ };
211
+ }
212
+
213
+ public get aliases(): ReadonlyMap<string, string> {
214
+ return this.aliasMap;
215
+ }
216
+
217
+ public get pendingAliases(): Map<string, Promise<AliasResult>> {
218
+ return this.pendingAliasMap;
219
+ }
220
+
221
+ public async waitIfPendingAlias(maybeAlias: string): Promise<AliasResult> {
222
+ const pendingAliasPromise = this.pendingAliases.get(maybeAlias);
223
+ return pendingAliasPromise === undefined ? "Success" : pendingAliasPromise;
224
+ }
225
+
226
+ public processAttachMessage(message: ISequencedDocumentMessage, local: boolean) {
227
+ const attachMessage = message.contents as InboundAttachMessage;
228
+
229
+ this.dataStoresSinceLastGC.push(attachMessage.id);
230
+
231
+ // The local object has already been attached
232
+ if (local) {
233
+ assert(
234
+ this.pendingAttach.has(attachMessage.id),
235
+ 0x15e /* "Local object does not have matching attach message id" */,
236
+ );
237
+ this.contexts.get(attachMessage.id)?.emit("attached");
238
+ this.pendingAttach.delete(attachMessage.id);
239
+ return;
240
+ }
241
+
242
+ // If a non-local operation then go and create the object, otherwise mark it as officially attached.
243
+ if (this.alreadyProcessed(attachMessage.id)) {
244
+ // TODO: dataStoreId may require a different tag from PackageData #7488
245
+ const error = new DataCorruptionError(
246
+ // pre-0.58 error message: duplicateDataStoreCreatedWithExistingId
247
+ "Duplicate DataStore created with existing id",
248
+ {
249
+ ...extractSafePropertiesFromMessage(message),
250
+ dataStoreId: {
251
+ value: attachMessage.id,
252
+ tag: TelemetryDataTag.CodeArtifact,
253
+ },
254
+ },
255
+ );
256
+ throw error;
257
+ }
258
+
259
+ const flatBlobs = new Map<string, ArrayBufferLike>();
260
+ let snapshotTree: ISnapshotTree | undefined;
261
+ if (attachMessage.snapshot) {
262
+ snapshotTree = buildSnapshotTree(attachMessage.snapshot.entries, flatBlobs);
263
+ }
264
+
265
+ // Include the type of attach message which is the pkg of the store to be
266
+ // used by RemoteFluidDataStoreContext in case it is not in the snapshot.
267
+ const pkg = [attachMessage.type];
268
+ const remoteFluidDataStoreContext = new RemoteFluidDataStoreContext({
269
+ id: attachMessage.id,
270
+ snapshotTree,
271
+ // New data stores begin with empty GC details since GC hasn't run on them yet.
272
+ getBaseGCDetails: async () => {
273
+ return {};
274
+ },
275
+ runtime: this.runtime,
276
+ storage: new BlobCacheStorageService(this.runtime.storage, flatBlobs),
277
+ scope: this.runtime.scope,
278
+ createSummarizerNodeFn: this.getCreateChildSummarizerNodeFn(attachMessage.id, {
279
+ type: CreateSummarizerNodeSource.FromAttach,
280
+ sequenceNumber: message.sequenceNumber,
281
+ snapshot: attachMessage.snapshot ?? {
282
+ entries: [createAttributesBlob(pkg, true /* isRootDataStore */)],
283
+ },
284
+ }),
285
+ pkg,
286
+ });
287
+
288
+ this.contexts.addBoundOrRemoted(remoteFluidDataStoreContext);
289
+ }
290
+
291
+ public processAliasMessage(
292
+ message: ISequencedDocumentMessage,
293
+ localOpMetadata: unknown,
294
+ local: boolean,
295
+ ): void {
296
+ const aliasMessage = message.contents as IDataStoreAliasMessage;
297
+ if (!isDataStoreAliasMessage(aliasMessage)) {
298
+ throw new DataCorruptionError("malformedDataStoreAliasMessage", {
299
+ ...extractSafePropertiesFromMessage(message),
300
+ });
301
+ }
302
+
303
+ const resolve = localOpMetadata as PendingAliasResolve;
304
+ const aliasResult = this.processAliasMessageCore(aliasMessage);
305
+ if (local) {
306
+ resolve(aliasResult);
307
+ }
308
+ }
309
+
310
+ public processAliasMessageCore(aliasMessage: IDataStoreAliasMessage): boolean {
311
+ if (this.alreadyProcessed(aliasMessage.alias)) {
312
+ return false;
313
+ }
314
+
315
+ const context = this.contexts.get(aliasMessage.internalId);
316
+ if (context === undefined) {
317
+ this.mc.logger.sendErrorEvent({
318
+ eventName: "AliasFluidDataStoreNotFound",
319
+ fluidDataStoreId: aliasMessage.internalId,
320
+ });
321
+ return false;
322
+ }
323
+
324
+ const handle = new FluidObjectHandle(
325
+ context,
326
+ aliasMessage.internalId,
327
+ this.runtime.IFluidHandleContext,
328
+ );
329
+ this.runtime.addedGCOutboundReference(this.containerRuntimeHandle, handle);
330
+
331
+ this.aliasMap.set(aliasMessage.alias, context.id);
332
+ context.setInMemoryRoot();
333
+ return true;
334
+ }
335
+
336
+ private alreadyProcessed(id: string): boolean {
337
+ return this.aliasMap.get(id) !== undefined || this.contexts.get(id) !== undefined;
338
+ }
339
+
340
+ /**
341
+ * Make the data stores locally visible in the container graph by moving the data store context from unbound to
342
+ * bound list. This data store can now be reached from the root.
343
+ * @param id - The id of the data store context to make visible.
344
+ */
345
+ private makeDataStoreLocallyVisible(id: string): void {
346
+ const localContext = this.contexts.getUnbound(id);
347
+ assert(!!localContext, 0x15f /* "Could not find unbound context to bind" */);
348
+
349
+ /**
350
+ * If the container is not detached, it is globally visible to all clients. This data store should also be
351
+ * globally visible. Move it to attaching state and send an "attach" op for it.
352
+ * If the container is detached, this data store will be part of the summary that makes the container attached.
353
+ */
354
+ if (this.runtime.attachState !== AttachState.Detached) {
355
+ localContext.emit("attaching");
356
+ const message = localContext.generateAttachMessage();
357
+
358
+ this.pendingAttach.set(id, message);
359
+ this.submitAttachFn(message);
360
+ this.attachOpFiredForDataStore.add(id);
361
+ }
362
+
363
+ this.contexts.bind(id);
364
+ }
365
+
366
+ public createDetachedDataStoreCore(
367
+ pkg: Readonly<string[]>,
368
+ isRoot: boolean,
369
+ id = uuid(),
370
+ ): IFluidDataStoreContextDetached {
371
+ assert(!id.includes("/"), 0x30c /* Id cannot contain slashes */);
372
+
373
+ const context = new LocalDetachedFluidDataStoreContext({
374
+ id,
375
+ pkg,
376
+ runtime: this.runtime,
377
+ storage: this.runtime.storage,
378
+ scope: this.runtime.scope,
379
+ createSummarizerNodeFn: this.getCreateChildSummarizerNodeFn(id, {
380
+ type: CreateSummarizerNodeSource.Local,
381
+ }),
382
+ makeLocallyVisibleFn: () => this.makeDataStoreLocallyVisible(id),
383
+ snapshotTree: undefined,
384
+ isRootDataStore: isRoot,
385
+ });
386
+ this.contexts.addUnbound(context);
387
+ return context;
388
+ }
389
+
390
+ public _createFluidDataStoreContext(pkg: string[], id: string, props?: any) {
391
+ assert(!id.includes("/"), 0x30d /* Id cannot contain slashes */);
392
+ const context = new LocalFluidDataStoreContext({
393
+ id,
394
+ pkg,
395
+ runtime: this.runtime,
396
+ storage: this.runtime.storage,
397
+ scope: this.runtime.scope,
398
+ createSummarizerNodeFn: this.getCreateChildSummarizerNodeFn(id, {
399
+ type: CreateSummarizerNodeSource.Local,
400
+ }),
401
+ makeLocallyVisibleFn: () => this.makeDataStoreLocallyVisible(id),
402
+ snapshotTree: undefined,
403
+ isRootDataStore: false,
404
+ createProps: props,
405
+ });
406
+ this.contexts.addUnbound(context);
407
+ return context;
408
+ }
409
+
410
+ public get disposed() {
411
+ return this.disposeOnce.evaluated;
412
+ }
413
+ public readonly dispose = () => this.disposeOnce.value;
414
+
415
+ public resubmitDataStoreOp(content: any, localOpMetadata: unknown) {
416
+ const envelope = content as IEnvelope;
417
+ const context = this.contexts.get(envelope.address);
418
+ assert(!!context, 0x160 /* "There should be a store context for the op" */);
419
+ context.reSubmit(envelope.contents, localOpMetadata);
420
+ }
421
+
422
+ public rollbackDataStoreOp(content: any, localOpMetadata: unknown) {
423
+ const envelope = content as IEnvelope;
424
+ const context = this.contexts.get(envelope.address);
425
+ assert(!!context, 0x2e8 /* "There should be a store context for the op" */);
426
+ context.rollback(envelope.contents, localOpMetadata);
427
+ }
428
+
429
+ public async applyStashedOp(content: any): Promise<unknown> {
430
+ const envelope = content as IEnvelope;
431
+ const context = this.contexts.get(envelope.address);
432
+ assert(!!context, 0x161 /* "There should be a store context for the op" */);
433
+ return context.applyStashedOp(envelope.contents);
434
+ }
435
+
436
+ public async applyStashedAttachOp(message: IAttachMessage) {
437
+ this.pendingAttach.set(message.id, message);
438
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
439
+ this.processAttachMessage({ contents: message } as ISequencedDocumentMessage, false);
440
+ }
441
+
442
+ public processFluidDataStoreOp(
443
+ message: ISequencedDocumentMessage,
444
+ local: boolean,
445
+ localMessageMetadata: unknown,
446
+ ) {
447
+ const envelope = message.contents as IEnvelope;
448
+ const transformed = { ...message, contents: envelope.contents };
449
+ const context = this.contexts.get(envelope.address);
450
+ assert(!!context, 0x162 /* "There should be a store context for the op" */);
451
+ context.process(transformed, local, localMessageMetadata);
452
+
453
+ // Notify that a GC node for the data store changed. This is used to detect if a deleted data store is
454
+ // being used.
455
+ this.gcNodeUpdated(
456
+ `/${envelope.address}`,
457
+ message.timestamp,
458
+ context.isLoaded ? context.packagePath : undefined,
459
+ );
460
+ }
461
+
462
+ public async getDataStore(
463
+ id: string,
464
+ requestHeaderData: RuntimeHeaderData,
465
+ ): Promise<FluidDataStoreContext> {
466
+ const headerData = { ...defaultRuntimeHeaderData, ...requestHeaderData };
467
+
468
+ const context = await this.contexts.getBoundOrRemoted(id, headerData.wait);
469
+ const request = { url: id };
470
+ if (context === undefined) {
471
+ // The requested data store does not exits. Throw a 404 response exception.
472
+ throw responseToException(create404Response(request), request);
473
+ }
474
+
475
+ if (context.tombstoned) {
476
+ const shouldFail = this.throwOnTombstoneLoad && !headerData.allowTombstone;
477
+
478
+ // The requested data store is removed by gc. Create a 404 gc response exception.
479
+ const error = responseToException(
480
+ createResponseError(404, "DataStore was deleted", request, {
481
+ [TombstoneResponseHeaderKey]: true,
482
+ }),
483
+ request,
484
+ );
485
+ sendGCUnexpectedUsageEvent(
486
+ this.mc,
487
+ {
488
+ eventName: "GC_Tombstone_DataStore_Requested",
489
+ category: shouldFail ? "error" : "generic",
490
+ isSummarizerClient: this.runtime.clientDetails.type === summarizerClientType,
491
+ headers: JSON.stringify(requestHeaderData),
492
+ },
493
+ context.isLoaded ? context.packagePath : undefined,
494
+ error,
495
+ );
496
+
497
+ if (shouldFail) {
498
+ throw error;
499
+ }
500
+ }
501
+
502
+ return context;
503
+ }
504
+
505
+ public processSignal(address: string, message: IInboundSignalMessage, local: boolean) {
506
+ const context = this.contexts.get(address);
507
+ if (!context) {
508
+ // Attach message may not have been processed yet
509
+ assert(!local, 0x163 /* "Missing datastore for local signal" */);
510
+ this.mc.logger.sendTelemetryEvent({
511
+ eventName: "SignalFluidDataStoreNotFound",
512
+ fluidDataStoreId: {
513
+ value: address,
514
+ tag: TelemetryDataTag.CodeArtifact,
515
+ },
516
+ });
517
+ return;
518
+ }
519
+
520
+ context.processSignal(message, local);
521
+ }
522
+
523
+ public setConnectionState(connected: boolean, clientId?: string) {
524
+ for (const [fluidDataStore, context] of this.contexts) {
525
+ try {
526
+ context.setConnectionState(connected, clientId);
527
+ } catch (error) {
528
+ this.mc.logger.sendErrorEvent(
529
+ {
530
+ eventName: "SetConnectionStateError",
531
+ clientId,
532
+ fluidDataStore,
533
+ },
534
+ error,
535
+ );
536
+ }
537
+ }
538
+ }
539
+
540
+ public setAttachState(attachState: AttachState.Attaching | AttachState.Attached): void {
541
+ const eventName = attachState === AttachState.Attaching ? "attaching" : "attached";
542
+ for (const [, context] of this.contexts) {
543
+ // Fire only for bounded stores.
544
+ if (!this.contexts.isNotBound(context.id)) {
545
+ context.emit(eventName);
546
+ }
547
+ }
548
+ }
549
+
550
+ public get size(): number {
551
+ return this.contexts.size;
552
+ }
553
+
554
+ public async summarize(
555
+ fullTree: boolean,
556
+ trackState: boolean,
557
+ telemetryContext?: ITelemetryContext,
558
+ ): Promise<ISummaryTreeWithStats> {
559
+ const summaryBuilder = new SummaryTreeBuilder();
560
+
561
+ // Iterate over each store and ask it to snapshot
562
+ await Promise.all(
563
+ Array.from(this.contexts)
564
+ .filter(([_, context]) => {
565
+ // Summarizer works only with clients with no local changes!
566
+ assert(
567
+ context.attachState !== AttachState.Attaching,
568
+ 0x165 /* "Summarizer cannot work if client has local changes" */,
569
+ );
570
+ return context.attachState === AttachState.Attached;
571
+ })
572
+ .map(async ([contextId, context]) => {
573
+ const contextSummary = await context.summarize(
574
+ fullTree,
575
+ trackState,
576
+ telemetryContext,
577
+ );
578
+ summaryBuilder.addWithStats(contextId, contextSummary);
579
+ }),
580
+ );
581
+
582
+ return summaryBuilder.getSummaryTree();
583
+ }
584
+
585
+ public createSummary(telemetryContext?: ITelemetryContext): ISummaryTreeWithStats {
586
+ const builder = new SummaryTreeBuilder();
587
+ // Attaching graph of some stores can cause other stores to get bound too.
588
+ // So keep taking summary until no new stores get bound.
589
+ let notBoundContextsLength: number;
590
+ do {
591
+ const builderTree = builder.summary.tree;
592
+ notBoundContextsLength = this.contexts.notBoundLength();
593
+ // Iterate over each data store and ask it to snapshot
594
+ Array.from(this.contexts)
595
+ .filter(
596
+ ([key, _]) =>
597
+ // Take summary of bounded data stores only, make sure we haven't summarized them already
598
+ // and no attach op has been fired for that data store because for loader versions <= 0.24
599
+ // we set attach state as "attaching" before taking createNew summary.
600
+ !(
601
+ this.contexts.isNotBound(key) ||
602
+ builderTree[key] ||
603
+ this.attachOpFiredForDataStore.has(key)
604
+ ),
605
+ )
606
+ .map(([key, value]) => {
607
+ let dataStoreSummary: ISummarizeResult;
608
+ if (value.isLoaded) {
609
+ const snapshot = value.generateAttachMessage().snapshot;
610
+ dataStoreSummary = convertToSummaryTree(snapshot, true);
611
+ } else {
612
+ // If this data store is not yet loaded, then there should be no changes in the snapshot from
613
+ // which it was created as it is detached container. So just use the previous snapshot.
614
+ assert(
615
+ !!this.baseSnapshot,
616
+ 0x166 /* "BaseSnapshot should be there as detached container loaded from snapshot" */,
617
+ );
618
+ dataStoreSummary = convertSnapshotTreeToSummaryTree(
619
+ this.baseSnapshot.trees[key],
620
+ );
621
+ }
622
+ builder.addWithStats(key, dataStoreSummary);
623
+ });
624
+ } while (notBoundContextsLength !== this.contexts.notBoundLength());
625
+
626
+ return builder.getSummaryTree();
627
+ }
628
+
629
+ /**
630
+ * Before GC runs, called by the garbage collector to update any pending GC state.
631
+ * The garbage collector needs to know all outbound references that are added. Since root data stores are not
632
+ * explicitly marked as referenced, notify GC of new root data stores that were added since the last GC run.
633
+ */
634
+ public async updateStateBeforeGC(): Promise<void> {
635
+ for (const id of this.dataStoresSinceLastGC) {
636
+ const context = this.contexts.get(id);
637
+ assert(context !== undefined, 0x2b6 /* Missing data store context */);
638
+ if (await context.isRoot()) {
639
+ // A root data store is basically a reference from the container runtime to the data store.
640
+ const handle = new FluidObjectHandle(context, id, this.runtime.IFluidHandleContext);
641
+ this.runtime.addedGCOutboundReference(this.containerRuntimeHandle, handle);
642
+ }
643
+ }
644
+ this.dataStoresSinceLastGC = [];
645
+ }
646
+
647
+ /**
648
+ * Generates data used for garbage collection. It does the following:
649
+ *
650
+ * 1. Calls into each child data store context to get its GC data.
651
+ *
652
+ * 2. Prefixes the child context's id to the GC nodes in the child's GC data. This makes sure that the node can be
653
+ * identified as belonging to the child.
654
+ *
655
+ * 3. Adds a GC node for this channel to the nodes received from the children. All these nodes together represent
656
+ * the GC data of this channel.
657
+ *
658
+ * @param fullGC - true to bypass optimizations and force full generation of GC data.
659
+ */
660
+ public async getGCData(fullGC: boolean = false): Promise<IGarbageCollectionData> {
661
+ const builder = new GCDataBuilder();
662
+ // Iterate over each store and get their GC data.
663
+ await Promise.all(
664
+ Array.from(this.contexts)
665
+ .filter(([_, context]) => {
666
+ // Get GC data only for attached contexts. Detached contexts are not connected in the GC reference
667
+ // graph so any references they might have won't be connected as well.
668
+ return context.attachState === AttachState.Attached;
669
+ })
670
+ .map(async ([contextId, context]) => {
671
+ const contextGCData = await context.getGCData(fullGC);
672
+ // Prefix the child's id to the ids of its GC nodes so they can be identified as belonging to the child.
673
+ // This also gradually builds the id of each node to be a path from the root.
674
+ builder.prefixAndAddNodes(contextId, contextGCData.gcNodes);
675
+ }),
676
+ );
677
+
678
+ // Get the outbound routes and add a GC node for this channel.
679
+ builder.addNode("/", await this.getOutboundRoutes());
680
+ return builder.getGCData();
681
+ }
682
+
683
+ /**
684
+ * After GC has run, called to notify this Container's data stores of routes that are used in it.
685
+ * @param usedRoutes - The routes that are used in all data stores in this Container.
686
+ */
687
+ public updateUsedRoutes(usedRoutes: string[]) {
688
+ // Get a map of data store ids to routes used in it.
689
+ const usedDataStoreRoutes = unpackChildNodesUsedRoutes(usedRoutes);
690
+
691
+ // Verify that the used routes are correct.
692
+ for (const [id] of usedDataStoreRoutes) {
693
+ assert(
694
+ this.contexts.has(id),
695
+ 0x167 /* "Used route does not belong to any known data store" */,
696
+ );
697
+ }
698
+
699
+ // Update the used routes in each data store. Used routes is empty for unused data stores.
700
+ for (const [contextId, context] of this.contexts) {
701
+ context.updateUsedRoutes(usedDataStoreRoutes.get(contextId) ?? []);
702
+ }
703
+ }
704
+
705
+ /**
706
+ * This is called to update objects whose routes are unused. The unused objects are deleted.
707
+ * @param unusedRoutes - The routes that are unused in all data stores in this Container.
708
+ */
709
+ public updateUnusedRoutes(unusedRoutes: string[]) {
710
+ for (const route of unusedRoutes) {
711
+ const pathParts = route.split("/");
712
+ // Delete data store only if its route (/datastoreId) is in unusedRoutes. We don't want to delete a data
713
+ // store based on its DDS being unused.
714
+ if (pathParts.length > 2) {
715
+ continue;
716
+ }
717
+ const dataStoreId = pathParts[1];
718
+ assert(this.contexts.has(dataStoreId), 0x2d7 /* No data store with specified id */);
719
+ // Delete the contexts of unused data stores.
720
+ this.contexts.delete(dataStoreId);
721
+ // Delete the summarizer node of the unused data stores.
722
+ this.deleteChildSummarizerNodeFn(dataStoreId);
723
+ }
724
+ }
725
+
726
+ /**
727
+ * This is called to update objects whose routes are tombstones. Tombstoned datastore contexts enable testing
728
+ * scenarios with accessing deleted content without actually deleting content from summaries.
729
+ * @param tombstonedRoutes - The routes that are tombstones in all data stores in this Container.
730
+ */
731
+ public updateTombstonedRoutes(tombstonedRoutes: string[]) {
732
+ const tombstonedDataStoresSet: Set<string> = new Set();
733
+ for (const route of tombstonedRoutes) {
734
+ const pathParts = route.split("/");
735
+ // Tombstone data store only if its route (/datastoreId) is directly in tombstoneRoutes.
736
+ if (pathParts.length > 2) {
737
+ continue;
738
+ }
739
+ const dataStoreId = pathParts[1];
740
+ assert(this.contexts.has(dataStoreId), 0x510 /* No data store with specified id */);
741
+ tombstonedDataStoresSet.add(dataStoreId);
742
+ }
743
+
744
+ // Update the used routes in each data store. Used routes is empty for unused data stores.
745
+ for (const [contextId, context] of this.contexts) {
746
+ context.setTombstone(tombstonedDataStoresSet.has(contextId));
747
+ }
748
+ }
749
+
750
+ /**
751
+ * Returns the outbound routes of this channel. Only root data stores are considered referenced and their paths are
752
+ * part of outbound routes.
753
+ */
754
+ private async getOutboundRoutes(): Promise<string[]> {
755
+ const outboundRoutes: string[] = [];
756
+ for (const [contextId, context] of this.contexts) {
757
+ const isRootDataStore = await context.isRoot();
758
+ if (isRootDataStore) {
759
+ outboundRoutes.push(`/${contextId}`);
760
+ }
761
+ }
762
+ return outboundRoutes;
763
+ }
764
+
765
+ /**
766
+ * Called by GC to retrieve the package path of a data store node with the given path.
767
+ */
768
+ public async getDataStorePackagePath(nodePath: string): Promise<readonly string[] | undefined> {
769
+ // If the node belongs to a data store, return its package path. For DDSes, we return the package path of the
770
+ // data store that contains it.
771
+ const context = this.contexts.get(nodePath.split("/")[1]);
772
+ return (await context?.getInitialSnapshotDetails())?.pkg;
773
+ }
774
+
775
+ /**
776
+ * Called by GC to determine if a node is for a data store or for an object within a data store (for e.g. DDS).
777
+ * @returns the GC node type if the node belongs to a data store or object within data store, undefined otherwise.
778
+ */
779
+ public getGCNodeType(nodePath: string): GCNodeType | undefined {
780
+ const pathParts = nodePath.split("/");
781
+ if (!this.contexts.has(pathParts[1])) {
782
+ return undefined;
783
+ }
784
+
785
+ // Data stores paths are of the format "/dataStoreId".
786
+ // Sub data store paths are of the format "/dataStoreId/subPath/...".
787
+ if (pathParts.length === 2) {
788
+ return GCNodeType.DataStore;
789
+ }
790
+ return GCNodeType.SubDataStore;
791
+ }
719
792
  }
720
793
 
721
794
  export function getSummaryForDatastores(
722
- snapshot: ISnapshotTree | undefined,
723
- metadata?: IContainerRuntimeMetadata,
795
+ snapshot: ISnapshotTree | undefined,
796
+ metadata?: IContainerRuntimeMetadata,
724
797
  ): ISnapshotTree | undefined {
725
- if (!snapshot) {
726
- return undefined;
727
- }
728
-
729
- if (rootHasIsolatedChannels(metadata)) {
730
- const datastoresSnapshot = snapshot.trees[channelsTreeName];
731
- assert(!!datastoresSnapshot, 0x168 /* Expected tree in snapshot not found */);
732
- return datastoresSnapshot;
733
- } else {
734
- // back-compat: strip out all non-datastore paths before giving to DataStores object.
735
- const datastoresTrees: ISnapshotTree["trees"] = {};
736
- for (const [key, value] of Object.entries(snapshot.trees)) {
737
- if (!nonDataStorePaths.includes(key)) {
738
- datastoresTrees[key] = value;
739
- }
740
- }
741
- return {
742
- ...snapshot,
743
- trees: datastoresTrees,
744
- };
745
- }
798
+ if (!snapshot) {
799
+ return undefined;
800
+ }
801
+
802
+ if (rootHasIsolatedChannels(metadata)) {
803
+ const datastoresSnapshot = snapshot.trees[channelsTreeName];
804
+ assert(!!datastoresSnapshot, 0x168 /* Expected tree in snapshot not found */);
805
+ return datastoresSnapshot;
806
+ } else {
807
+ // back-compat: strip out all non-datastore paths before giving to DataStores object.
808
+ const datastoresTrees: ISnapshotTree["trees"] = {};
809
+ for (const [key, value] of Object.entries(snapshot.trees)) {
810
+ if (!nonDataStorePaths.includes(key)) {
811
+ datastoresTrees[key] = value;
812
+ }
813
+ }
814
+ return {
815
+ ...snapshot,
816
+ trees: datastoresTrees,
817
+ };
818
+ }
746
819
  }