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