@fluidframework/container-runtime 2.0.0-internal.3.0.0 → 2.0.0-internal.3.1.0

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