@fluidframework/container-runtime 2.0.0-internal.3.0.1 → 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
@@ -3,1009 +3,1107 @@
3
3
  * Licensed under the MIT License.
4
4
  */
5
5
 
6
- import { IDisposable, ITelemetryLogger, ITelemetryProperties } from "@fluidframework/common-definitions";
7
6
  import {
8
- FluidObject,
9
- IRequest,
10
- IResponse,
11
- IFluidHandle,
12
- } from "@fluidframework/core-interfaces";
7
+ IDisposable,
8
+ ITelemetryLogger,
9
+ ITelemetryProperties,
10
+ } from "@fluidframework/common-definitions";
11
+ import { FluidObject, IRequest, IResponse, IFluidHandle } from "@fluidframework/core-interfaces";
13
12
  import {
14
- IAudience,
15
- IDeltaManager,
16
- AttachState,
17
- ILoaderOptions,
13
+ IAudience,
14
+ IDeltaManager,
15
+ AttachState,
16
+ ILoaderOptions,
18
17
  } from "@fluidframework/container-definitions";
19
- import {
20
- assert,
21
- Deferred,
22
- LazyPromise,
23
- TypedEventEmitter,
24
- } from "@fluidframework/common-utils";
18
+ import { assert, Deferred, LazyPromise, TypedEventEmitter } from "@fluidframework/common-utils";
25
19
  import { IDocumentStorageService } from "@fluidframework/driver-definitions";
26
20
  import { readAndParse } from "@fluidframework/driver-utils";
27
21
  import { BlobTreeEntry } from "@fluidframework/protocol-base";
28
22
  import {
29
- IClientDetails,
30
- IDocumentMessage,
31
- IQuorumClients,
32
- ISequencedDocumentMessage,
33
- ISnapshotTree,
34
- ITreeEntry,
23
+ IClientDetails,
24
+ IDocumentMessage,
25
+ IQuorumClients,
26
+ ISequencedDocumentMessage,
27
+ ISnapshotTree,
28
+ ITreeEntry,
35
29
  } from "@fluidframework/protocol-definitions";
30
+ import { IContainerRuntime } from "@fluidframework/container-runtime-definitions";
36
31
  import {
37
- IContainerRuntime,
38
- } from "@fluidframework/container-runtime-definitions";
39
- import {
40
- BindState,
41
- channelsTreeName,
42
- CreateChildSummarizerNodeFn,
43
- CreateChildSummarizerNodeParam,
44
- FluidDataStoreRegistryEntry,
45
- IAttachMessage,
46
- IFluidDataStoreChannel,
47
- IFluidDataStoreContext,
48
- IFluidDataStoreContextDetached,
49
- IFluidDataStoreContextEvents,
50
- IFluidDataStoreRegistry,
51
- IGarbageCollectionData,
52
- IGarbageCollectionDetailsBase,
53
- IInboundSignalMessage,
54
- IProvideFluidDataStoreFactory,
55
- ISummarizeInternalResult,
56
- ISummarizeResult,
57
- ISummarizerNodeWithGC,
58
- SummarizeInternalFn,
59
- ITelemetryContext,
32
+ BindState,
33
+ channelsTreeName,
34
+ CreateChildSummarizerNodeFn,
35
+ CreateChildSummarizerNodeParam,
36
+ FluidDataStoreRegistryEntry,
37
+ IAttachMessage,
38
+ IFluidDataStoreChannel,
39
+ IFluidDataStoreContext,
40
+ IFluidDataStoreContextDetached,
41
+ IFluidDataStoreContextEvents,
42
+ IFluidDataStoreRegistry,
43
+ IGarbageCollectionData,
44
+ IGarbageCollectionDetailsBase,
45
+ IInboundSignalMessage,
46
+ IProvideFluidDataStoreFactory,
47
+ ISummarizeInternalResult,
48
+ ISummarizeResult,
49
+ ISummarizerNodeWithGC,
50
+ SummarizeInternalFn,
51
+ ITelemetryContext,
60
52
  } from "@fluidframework/runtime-definitions";
53
+ import { addBlobToSummary, convertSummaryTreeToITree } from "@fluidframework/runtime-utils";
61
54
  import {
62
- addBlobToSummary,
63
- convertSummaryTreeToITree,
64
- } from "@fluidframework/runtime-utils";
65
- import {
66
- ChildLogger,
67
- loggerToMonitoringContext,
68
- LoggingError,
69
- MonitoringContext,
70
- TelemetryDataTag,
71
- ThresholdCounter,
55
+ ChildLogger,
56
+ loggerToMonitoringContext,
57
+ LoggingError,
58
+ MonitoringContext,
59
+ TelemetryDataTag,
60
+ ThresholdCounter,
72
61
  } from "@fluidframework/telemetry-utils";
73
62
  import {
74
- DataCorruptionError,
75
- DataProcessingError,
76
- extractSafePropertiesFromMessage,
63
+ DataCorruptionError,
64
+ DataProcessingError,
65
+ extractSafePropertiesFromMessage,
77
66
  } from "@fluidframework/container-utils";
78
67
 
79
68
  import { ContainerRuntime } from "./containerRuntime";
80
69
  import {
81
- dataStoreAttributesBlobName,
82
- hasIsolatedChannels,
83
- wrapSummaryInChannelsTree,
84
- ReadFluidDataStoreAttributes,
85
- WriteFluidDataStoreAttributes,
86
- getAttributesFormatVersion,
87
- getFluidDataStoreAttributes,
70
+ dataStoreAttributesBlobName,
71
+ hasIsolatedChannels,
72
+ wrapSummaryInChannelsTree,
73
+ ReadFluidDataStoreAttributes,
74
+ WriteFluidDataStoreAttributes,
75
+ getAttributesFormatVersion,
76
+ getFluidDataStoreAttributes,
88
77
  } from "./summaryFormat";
89
78
  import { throwOnTombstoneUsageKey } from "./garbageCollectionConstants";
90
- import { sendGCTombstoneEvent } from "./garbageCollectionTombstoneUtils";
79
+ import { sendGCUnexpectedUsageEvent } from "./garbageCollectionHelpers";
91
80
  import { summarizerClientType } from "./summarizerClientElection";
92
81
 
93
82
  function createAttributes(
94
- pkg: readonly string[],
95
- isRootDataStore: boolean,
83
+ pkg: readonly string[],
84
+ isRootDataStore: boolean,
96
85
  ): WriteFluidDataStoreAttributes {
97
- const stringifiedPkg = JSON.stringify(pkg);
98
- return {
99
- pkg: stringifiedPkg,
100
- summaryFormatVersion: 2,
101
- isRootDataStore,
102
- };
86
+ const stringifiedPkg = JSON.stringify(pkg);
87
+ return {
88
+ pkg: stringifiedPkg,
89
+ summaryFormatVersion: 2,
90
+ isRootDataStore,
91
+ };
103
92
  }
104
- export function createAttributesBlob(
105
- pkg: readonly string[],
106
- isRootDataStore: boolean,
107
- ): ITreeEntry {
108
- const attributes = createAttributes(pkg, isRootDataStore);
109
- return new BlobTreeEntry(dataStoreAttributesBlobName, JSON.stringify(attributes));
93
+ export function createAttributesBlob(pkg: readonly string[], isRootDataStore: boolean): ITreeEntry {
94
+ const attributes = createAttributes(pkg, isRootDataStore);
95
+ return new BlobTreeEntry(dataStoreAttributesBlobName, JSON.stringify(attributes));
110
96
  }
111
97
 
112
98
  interface ISnapshotDetails {
113
- pkg: readonly string[];
114
- isRootDataStore: boolean;
115
- snapshot?: ISnapshotTree;
99
+ pkg: readonly string[];
100
+ isRootDataStore: boolean;
101
+ snapshot?: ISnapshotTree;
116
102
  }
117
103
 
118
104
  interface FluidDataStoreMessage {
119
- content: any;
120
- type: string;
105
+ content: any;
106
+ type: string;
121
107
  }
122
108
 
123
109
  /** Properties necessary for creating a FluidDataStoreContext */
124
110
  export interface IFluidDataStoreContextProps {
125
- readonly id: string;
126
- readonly runtime: ContainerRuntime;
127
- readonly storage: IDocumentStorageService;
128
- readonly scope: FluidObject;
129
- readonly createSummarizerNodeFn: CreateChildSummarizerNodeFn;
130
- readonly pkg?: Readonly<string[]>;
111
+ readonly id: string;
112
+ readonly runtime: ContainerRuntime;
113
+ readonly storage: IDocumentStorageService;
114
+ readonly scope: FluidObject;
115
+ readonly createSummarizerNodeFn: CreateChildSummarizerNodeFn;
116
+ readonly pkg?: Readonly<string[]>;
131
117
  }
132
118
 
133
119
  /** Properties necessary for creating a local FluidDataStoreContext */
134
120
  export interface ILocalFluidDataStoreContextProps extends IFluidDataStoreContextProps {
135
- readonly pkg: Readonly<string[]> | undefined;
136
- readonly snapshotTree: ISnapshotTree | undefined;
137
- readonly isRootDataStore: boolean | undefined;
138
- readonly makeLocallyVisibleFn: () => void;
139
- /**
140
- * @deprecated 0.16 Issue #1635, #3631
141
- */
142
- readonly createProps?: any;
121
+ readonly pkg: Readonly<string[]> | undefined;
122
+ readonly snapshotTree: ISnapshotTree | undefined;
123
+ readonly isRootDataStore: boolean | undefined;
124
+ readonly makeLocallyVisibleFn: () => void;
125
+ /**
126
+ * @deprecated 0.16 Issue #1635, #3631
127
+ */
128
+ readonly createProps?: any;
143
129
  }
144
130
 
145
131
  /** Properties necessary for creating a remote FluidDataStoreContext */
146
132
  export interface IRemoteFluidDataStoreContextProps extends IFluidDataStoreContextProps {
147
- readonly snapshotTree: ISnapshotTree | undefined;
148
- readonly getBaseGCDetails: () => Promise<IGarbageCollectionDetailsBase | undefined>;
133
+ readonly snapshotTree: ISnapshotTree | undefined;
134
+ readonly getBaseGCDetails: () => Promise<IGarbageCollectionDetailsBase | undefined>;
149
135
  }
150
136
 
151
137
  /**
152
138
  * Represents the context for the store. This context is passed to the store runtime.
153
139
  */
154
- export abstract class FluidDataStoreContext extends TypedEventEmitter<IFluidDataStoreContextEvents> implements
155
- IFluidDataStoreContext,
156
- IDisposable {
157
- public get packagePath(): readonly string[] {
158
- assert(this.pkg !== undefined, 0x139 /* "Undefined package path" */);
159
- return this.pkg;
160
- }
161
-
162
- public get options(): ILoaderOptions {
163
- return this._containerRuntime.options;
164
- }
165
-
166
- public get clientId(): string | undefined {
167
- return this._containerRuntime.clientId;
168
- }
169
-
170
- public get clientDetails(): IClientDetails {
171
- return this._containerRuntime.clientDetails;
172
- }
173
-
174
- public get logger(): ITelemetryLogger {
175
- return this._containerRuntime.logger;
176
- }
177
-
178
- public get deltaManager(): IDeltaManager<ISequencedDocumentMessage, IDocumentMessage> {
179
- return this._containerRuntime.deltaManager;
180
- }
181
-
182
- public get connected(): boolean {
183
- return this._containerRuntime.connected;
184
- }
185
-
186
- public get IFluidHandleContext() {
187
- return this._containerRuntime.IFluidHandleContext;
188
- }
189
-
190
- public get containerRuntime(): IContainerRuntime {
191
- return this._containerRuntime;
192
- }
193
-
194
- public ensureNoDataModelChanges<T>(callback: () => T): T {
195
- return this._containerRuntime.ensureNoDataModelChanges(callback);
196
- }
197
-
198
- public get isLoaded(): boolean {
199
- return this.loaded;
200
- }
201
-
202
- public get baseSnapshot(): ISnapshotTree | undefined {
203
- return this._baseSnapshot;
204
- }
205
-
206
- private _disposed = false;
207
- public get disposed() { return this._disposed; }
208
-
209
- /**
210
- * Tombstone is a temporary feature that prevents a data store from sending / receiving ops, signals and from
211
- * loading.
212
- */
213
- private _tombstoned = false;
214
- public get tombstoned() { return this._tombstoned; }
215
- /** If true, throw an error when a tombstone data store is used. */
216
- private readonly throwOnTombstoneUsage: boolean;
217
-
218
- public get attachState(): AttachState {
219
- return this._attachState;
220
- }
221
-
222
- public get IFluidDataStoreRegistry(): IFluidDataStoreRegistry | undefined {
223
- return this.registry;
224
- }
225
-
226
- /**
227
- * A datastore is considered as root if it
228
- * 1. is root in memory - see isInMemoryRoot
229
- * 2. is root as part of the base snapshot that the datastore loaded from
230
- * @returns whether a datastore is root
231
- */
232
- public async isRoot(): Promise<boolean> {
233
- return this.isInMemoryRoot() || (await this.getInitialSnapshotDetails()).isRootDataStore;
234
- }
235
-
236
- /**
237
- * There are 3 states where isInMemoryRoot needs to be true
238
- * 1. when a datastore becomes aliased. This can happen for both remote and local datastores
239
- * 2. when a datastore is created locally as root
240
- * 3. when a datastore is created locally as root and is rehydrated
241
- * @returns whether a datastore is root in memory
242
- */
243
- protected isInMemoryRoot(): boolean {
244
- return this._isInMemoryRoot;
245
- }
246
-
247
- protected registry: IFluidDataStoreRegistry | undefined;
248
-
249
- protected detachedRuntimeCreation = false;
250
- /** @deprecated - To be replaced by calling makeLocallyVisible directly */
251
- public readonly bindToContext: () => void;
252
- protected channel: IFluidDataStoreChannel | undefined;
253
- private loaded = false;
254
- protected pending: ISequencedDocumentMessage[] | undefined = [];
255
- protected channelDeferred: Deferred<IFluidDataStoreChannel> | undefined;
256
- private _baseSnapshot: ISnapshotTree | undefined;
257
- protected _attachState: AttachState;
258
- private _isInMemoryRoot: boolean = false;
259
- protected readonly summarizerNode: ISummarizerNodeWithGC;
260
- private readonly mc: MonitoringContext;
261
- private readonly thresholdOpsCounter: ThresholdCounter;
262
- private static readonly pendingOpsCountThreshold = 1000;
263
-
264
- // The used routes of this node as per the last GC run. This is used to update the used routes of the channel
265
- // if it realizes after GC is run.
266
- private lastUsedRoutes: string[] | undefined;
267
-
268
- public readonly id: string;
269
- private readonly _containerRuntime: ContainerRuntime;
270
- public readonly storage: IDocumentStorageService;
271
- public readonly scope: FluidObject;
272
- protected pkg?: readonly string[];
273
-
274
- constructor(
275
- props: IFluidDataStoreContextProps,
276
- private readonly existing: boolean,
277
- private bindState: BindState, // Used to assert for state tracking purposes
278
- public readonly isLocalDataStore: boolean,
279
- private readonly makeLocallyVisibleFn: () => void,
280
- ) {
281
- super();
282
-
283
- this._containerRuntime = props.runtime;
284
- this.id = props.id;
285
- this.storage = props.storage;
286
- this.scope = props.scope;
287
- this.pkg = props.pkg;
288
-
289
- // URIs use slashes as delimiters. Handles use URIs.
290
- // Thus having slashes in types almost guarantees trouble down the road!
291
- assert(!this.id.includes("/"), 0x13a /* Data store ID contains slash */);
292
-
293
- this._attachState = this.containerRuntime.attachState !== AttachState.Detached && this.existing ?
294
- this.containerRuntime.attachState : AttachState.Detached;
295
-
296
- this.bindToContext = () => {
297
- assert(this.bindState === BindState.NotBound, 0x13b /* "datastore context is already in bound state" */);
298
- this.bindState = BindState.Binding;
299
- assert(this.channel !== undefined, 0x13c /* "undefined channel on datastore context" */);
300
- this.makeLocallyVisible();
301
- this.bindState = BindState.Bound;
302
- };
303
-
304
- const thisSummarizeInternal =
305
- async (fullTree: boolean, trackState: boolean, telemetryContext?: ITelemetryContext) =>
306
- this.summarizeInternal(fullTree, trackState, telemetryContext);
307
-
308
- this.summarizerNode = props.createSummarizerNodeFn(
309
- thisSummarizeInternal,
310
- async (fullGC?: boolean) => this.getGCDataInternal(fullGC),
311
- async () => this.getBaseGCDetails(),
312
- );
313
-
314
- this.mc = loggerToMonitoringContext(ChildLogger.create(this.logger, "FluidDataStoreContext"));
315
- this.thresholdOpsCounter = new ThresholdCounter(FluidDataStoreContext.pendingOpsCountThreshold, this.mc.logger);
316
-
317
- // Tombstone should only throw when the feature flag is enabled and the client isn't a summarizer
318
- this.throwOnTombstoneUsage =
319
- this.mc.config.getBoolean(throwOnTombstoneUsageKey) === true &&
320
- this.clientDetails.type !== summarizerClientType;
321
- }
322
-
323
- public dispose(): void {
324
- if (this._disposed) {
325
- return;
326
- }
327
- this._disposed = true;
328
-
329
- // Dispose any pending runtime after it gets fulfilled
330
- // Errors are logged where this.channelDeferred is consumed/generated (realizeCore(), bindRuntime())
331
- if (this.channelDeferred) {
332
- this.channelDeferred.promise.then((runtime) => {
333
- runtime.dispose();
334
- }).catch((error) => { });
335
- }
336
- }
337
-
338
- public setTombstone(tombstone: boolean) {
339
- if (this.tombstoned === tombstone) {
340
- return;
341
- }
342
-
343
- this._tombstoned = tombstone;
344
- }
345
-
346
- private rejectDeferredRealize(reason: string, packageName?: string): never {
347
- throw new LoggingError(reason, { packageName: { value: packageName, tag: TelemetryDataTag.CodeArtifact } });
348
- }
349
-
350
- public async realize(): Promise<IFluidDataStoreChannel> {
351
- assert(!this.detachedRuntimeCreation, 0x13d /* "Detached runtime creation on realize()" */);
352
- if (!this.channelDeferred) {
353
- this.channelDeferred = new Deferred<IFluidDataStoreChannel>();
354
- this.realizeCore(this.existing).catch((error) => {
355
- const errorWrapped = DataProcessingError.wrapIfUnrecognized(error, "realizeFluidDataStoreContext");
356
- errorWrapped.addTelemetryProperties({
357
- fluidDataStoreId: {
358
- value: this.id,
359
- tag: TelemetryDataTag.CodeArtifact,
360
- },
361
- });
362
- this.channelDeferred?.reject(errorWrapped);
363
- this.logger.sendErrorEvent({ eventName: "RealizeError" }, errorWrapped);
364
- });
365
- }
366
- return this.channelDeferred.promise;
367
- }
368
-
369
- protected async factoryFromPackagePath(packages?: readonly string[]) {
370
- assert(this.pkg === packages, 0x13e /* "Unexpected package path" */);
371
- if (packages === undefined) {
372
- this.rejectDeferredRealize("packages is undefined");
373
- }
374
-
375
- let entry: FluidDataStoreRegistryEntry | undefined;
376
- let registry: IFluidDataStoreRegistry | undefined = this._containerRuntime.IFluidDataStoreRegistry;
377
- let lastPkg: string | undefined;
378
- for (const pkg of packages) {
379
- if (!registry) {
380
- this.rejectDeferredRealize("No registry for package", lastPkg);
381
- }
382
- lastPkg = pkg;
383
- entry = await registry.get(pkg);
384
- if (!entry) {
385
- this.rejectDeferredRealize("Registry does not contain entry for the package", pkg);
386
- }
387
- registry = entry.IFluidDataStoreRegistry;
388
- }
389
- const factory = entry?.IFluidDataStoreFactory;
390
- if (factory === undefined) {
391
- this.rejectDeferredRealize("Can't find factory for package", lastPkg);
392
- }
393
-
394
- return { factory, registry };
395
- }
396
-
397
- private async realizeCore(existing: boolean): Promise<void> {
398
- const details = await this.getInitialSnapshotDetails();
399
- // Base snapshot is the baseline where pending ops are applied to.
400
- // It is important that this be in sync with the pending ops, and also
401
- // that it is set here, before bindRuntime is called.
402
- this._baseSnapshot = details.snapshot;
403
- const packages = details.pkg;
404
-
405
- const { factory, registry } = await this.factoryFromPackagePath(packages);
406
-
407
- assert(this.registry === undefined, 0x13f /* "datastore context registry is already set" */);
408
- this.registry = registry;
409
-
410
- const channel = await factory.instantiateDataStore(this, existing);
411
- assert(channel !== undefined, 0x140 /* "undefined channel on datastore context" */);
412
- this.bindRuntime(channel);
413
- }
414
-
415
- /**
416
- * Notifies this object about changes in the connection state.
417
- * @param value - New connection state.
418
- * @param clientId - ID of the client. Its old ID when in disconnected state and
419
- * its new client ID when we are connecting or connected.
420
- */
421
- public setConnectionState(connected: boolean, clientId?: string) {
422
- // ConnectionState should not fail in tombstone mode as this is internally run
423
- this.verifyNotClosed("setConnectionState", false /* checkTombstone */);
424
-
425
- // Connection events are ignored if the store is not yet loaded
426
- if (!this.loaded) {
427
- return;
428
- }
429
-
430
- assert(this.connected === connected, 0x141 /* "Unexpected connected state" */);
431
-
432
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
433
- this.channel!.setConnectionState(connected, clientId);
434
- }
435
-
436
- public process(messageArg: ISequencedDocumentMessage, local: boolean, localOpMetadata: unknown): void {
437
- this.verifyNotClosed("process", true, extractSafePropertiesFromMessage(messageArg));
438
-
439
- const innerContents = messageArg.contents as FluidDataStoreMessage;
440
- const message = {
441
- ...messageArg,
442
- type: innerContents.type,
443
- contents: innerContents.content,
444
- };
445
-
446
- this.summarizerNode.recordChange(message);
447
-
448
- if (this.loaded) {
449
- return this.channel?.process(message, local, localOpMetadata);
450
- } else {
451
- assert(!local, 0x142 /* "local store channel is not loaded" */);
452
- assert(this.pending !== undefined, 0x23d /* "pending is undefined" */);
453
- this.pending.push(message);
454
- this.thresholdOpsCounter.sendIfMultiple("StorePendingOps", this.pending.length);
455
- }
456
- }
457
-
458
- public processSignal(message: IInboundSignalMessage, local: boolean): void {
459
- this.verifyNotClosed("processSignal");
460
-
461
- // Signals are ignored if the store is not yet loaded
462
- if (!this.loaded) {
463
- return;
464
- }
465
-
466
- this.channel?.processSignal(message, local);
467
- }
468
-
469
- public getQuorum(): IQuorumClients {
470
- return this._containerRuntime.getQuorum();
471
- }
472
-
473
- public getAudience(): IAudience {
474
- return this._containerRuntime.getAudience();
475
- }
476
-
477
- /**
478
- * Returns a summary at the current sequence number.
479
- * @param fullTree - true to bypass optimizations and force a full summary tree
480
- * @param trackState - This tells whether we should track state from this summary.
481
- * @param telemetryContext - summary data passed through the layers for telemetry purposes
482
- */
483
- public async summarize(
484
- fullTree: boolean = false,
485
- trackState: boolean = true,
486
- telemetryContext?: ITelemetryContext,
487
- ): Promise<ISummarizeResult> {
488
- return this.summarizerNode.summarize(fullTree, trackState, telemetryContext);
489
- }
490
-
491
- private async summarizeInternal(
492
- fullTree: boolean,
493
- trackState: boolean,
494
- telemetryContext?: ITelemetryContext,
495
- ): Promise<ISummarizeInternalResult> {
496
- await this.realize();
497
-
498
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
499
- const summarizeResult = await this.channel!.summarize(fullTree, trackState, telemetryContext);
500
-
501
- // Wrap dds summaries in .channels subtree.
502
- wrapSummaryInChannelsTree(summarizeResult);
503
- const pathPartsForChildren = [channelsTreeName];
504
-
505
- // Add data store's attributes to the summary.
506
- const { pkg } = await this.getInitialSnapshotDetails();
507
- const isRoot = await this.isRoot();
508
- const attributes = createAttributes(pkg, isRoot);
509
- addBlobToSummary(summarizeResult, dataStoreAttributesBlobName, JSON.stringify(attributes));
510
-
511
- // If we are not referenced, mark the summary tree as unreferenced. Also, update unreferenced blob
512
- // size in the summary stats with the blobs size of this data store.
513
- if (!this.summarizerNode.isReferenced()) {
514
- summarizeResult.summary.unreferenced = true;
515
- summarizeResult.stats.unreferencedBlobSize = summarizeResult.stats.totalBlobSize;
516
- }
517
-
518
- return {
519
- ...summarizeResult,
520
- id: this.id,
521
- pathPartsForChildren,
522
- };
523
- }
524
-
525
- /**
526
- * Returns the data used for garbage collection. This includes a list of GC nodes that represent this data store
527
- * including any of its child channel contexts. Each node has a set of outbound routes to other GC nodes in the
528
- * document.
529
- * If there is no new data in this data store since the last summary, previous GC data is used.
530
- * If there is new data, the GC data is generated again (by calling getGCDataInternal).
531
- * @param fullGC - true to bypass optimizations and force full generation of GC data.
532
- */
533
- public async getGCData(fullGC: boolean = false): Promise<IGarbageCollectionData> {
534
- return this.summarizerNode.getGCData(fullGC);
535
- }
536
-
537
- /**
538
- * Generates data used for garbage collection. This is called when there is new data since last summary. It
539
- * realizes the data store and calls into each channel context to get its GC data.
540
- * @param fullGC - true to bypass optimizations and force full generation of GC data.
541
- */
542
- private async getGCDataInternal(fullGC: boolean = false): Promise<IGarbageCollectionData> {
543
- await this.realize();
544
- assert(this.channel !== undefined, 0x143 /* "Channel should not be undefined when running GC" */);
545
-
546
- return this.channel.getGCData(fullGC);
547
- }
548
-
549
- /**
550
- * After GC has run, called to notify the data store of routes used in it. These are used for the following:
551
- *
552
- * 1. To identify if this data store is being referenced in the document or not.
553
- *
554
- * 2. To determine if it needs to re-summarize in case used routes changed since last summary.
555
- *
556
- * 3. These are added to the summary generated by the data store.
557
- *
558
- * 4. To notify child contexts of their used routes. This is done immediately if the data store is loaded.
559
- * Else, it is done when realizing the data store.
560
- *
561
- * 5. To update the timestamp when this data store or any children are marked as unreferenced.
562
- *
563
- * @param usedRoutes - The routes that are used in this data store.
564
- */
565
- public updateUsedRoutes(usedRoutes: string[]) {
566
- // Update the used routes in this data store's summarizer node.
567
- this.summarizerNode.updateUsedRoutes(usedRoutes);
568
-
569
- /**
570
- * Store the used routes to update the channel if the data store is not loaded yet. If the used routes changed
571
- * since the previous run, the data store will be loaded during summarize since the used state changed. So, it's
572
- * safe to only store the last used routes.
573
- */
574
- this.lastUsedRoutes = usedRoutes;
575
-
576
- // If we are loaded, call the channel so it can update the used routes of the child contexts.
577
- // If we are not loaded, we will update this when we are realized.
578
- if (this.loaded) {
579
- this.updateChannelUsedRoutes();
580
- }
581
- }
582
-
583
- /**
584
- * Called when a new outbound reference is added to another node. This is used by garbage collection to identify
585
- * all references added in the system.
586
- * @param srcHandle - The handle of the node that added the reference.
587
- * @param outboundHandle - The handle of the outbound node that is referenced.
588
- */
589
- public addedGCOutboundReference(srcHandle: IFluidHandle, outboundHandle: IFluidHandle) {
590
- this._containerRuntime.addedGCOutboundReference(srcHandle, outboundHandle);
591
- }
592
-
593
- /**
594
- * Updates the used routes of the channel and its child contexts. The channel must be loaded before calling this.
595
- * It is called in these two scenarios:
596
- * 1. When the used routes of the data store is updated and the data store is loaded.
597
- * 2. When the data store is realized. This updates the channel's used routes as per last GC run.
598
- */
599
- private updateChannelUsedRoutes() {
600
- assert(this.loaded, 0x144 /* "Channel should be loaded when updating used routes" */);
601
- assert(this.channel !== undefined, 0x145 /* "Channel should be present when data store is loaded" */);
602
-
603
- // If there is no lastUsedRoutes, GC has not run up until this point.
604
- if (this.lastUsedRoutes === undefined) {
605
- return;
606
- }
607
-
608
- // Remove the route to this data store, if it exists.
609
- const usedChannelRoutes = this.lastUsedRoutes.filter(
610
- (id: string) => { return id !== "/" && id !== ""; },
611
- );
612
- this.channel.updateUsedRoutes(usedChannelRoutes);
613
- }
614
-
615
- /**
616
- * @deprecated 0.18.Should call request on the runtime directly
617
- */
618
- public async request(request: IRequest): Promise<IResponse> {
619
- const runtime = await this.realize();
620
- return runtime.request(request);
621
- }
622
-
623
- public submitMessage(type: string, content: any, localOpMetadata: unknown): void {
624
- this.verifyNotClosed("submitMessage");
625
- assert(!!this.channel, 0x146 /* "Channel must exist when submitting message" */);
626
- const fluidDataStoreContent: FluidDataStoreMessage = {
627
- content,
628
- type,
629
- };
630
- this._containerRuntime.submitDataStoreOp(
631
- this.id,
632
- fluidDataStoreContent,
633
- localOpMetadata);
634
- }
635
-
636
- /**
637
- * This is called from a SharedSummaryBlock that does not generate ops but only wants to be part of the summary.
638
- * It indicates that there is data in the object that needs to be summarized.
639
- * We will update the latestSequenceNumber of the summary tracker of this
640
- * store and of the object's channel.
641
- *
642
- * @param address - The address of the channel that is dirty.
643
- *
644
- */
645
- public setChannelDirty(address: string): void {
646
- this.verifyNotClosed("setChannelDirty");
647
-
648
- // Get the latest sequence number.
649
- const latestSequenceNumber = this.deltaManager.lastSequenceNumber;
650
-
651
- this.summarizerNode.invalidate(latestSequenceNumber);
652
-
653
- const channelSummarizerNode = this.summarizerNode.getChild(address);
654
-
655
- if (channelSummarizerNode) {
656
- channelSummarizerNode.invalidate(latestSequenceNumber); // TODO: lazy load problem?
657
- }
658
- }
659
-
660
- public submitSignal(type: string, content: any) {
661
- this.verifyNotClosed("submitSignal");
662
-
663
- assert(!!this.channel, 0x147 /* "Channel must exist on submitting signal" */);
664
- return this._containerRuntime.submitDataStoreSignal(this.id, type, content);
665
- }
666
-
667
- /**
668
- * This is called by the data store channel when it becomes locally visible indicating that it is ready to become
669
- * globally visible now.
670
- */
671
- public makeLocallyVisible() {
672
- assert(this.channel !== undefined, 0x2cf /* "undefined channel on datastore context" */);
673
- this.makeLocallyVisibleFn();
674
- }
675
-
676
- protected bindRuntime(channel: IFluidDataStoreChannel) {
677
- if (this.channel) {
678
- throw new Error("Runtime already bound");
679
- }
680
-
681
- try {
682
- assert(!this.detachedRuntimeCreation, 0x148 /* "Detached runtime creation on runtime bind" */);
683
- assert(this.channelDeferred !== undefined, 0x149 /* "Undefined channel deferral" */);
684
- assert(this.pkg !== undefined, 0x14a /* "Undefined package path" */);
685
-
686
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
687
- const pending = this.pending!;
688
-
689
- // Apply all pending ops
690
- for (const op of pending) {
691
- channel.process(op, false, undefined /* localOpMetadata */);
692
- }
693
-
694
- this.thresholdOpsCounter.send("ProcessPendingOps", pending.length);
695
- this.pending = undefined;
696
-
697
- // And now mark the runtime active
698
- this.loaded = true;
699
- this.channel = channel;
700
-
701
- // Freeze the package path to ensure that someone doesn't modify it when it is
702
- // returned in packagePath().
703
- Object.freeze(this.pkg);
704
-
705
- /**
706
- * Update the used routes of the channel. If GC has run before this data store was realized, we will have
707
- * the used routes saved. So, this will ensure that all the child contexts have up-to-date used routes as
708
- * per the last time GC was run.
709
- * Also, this data store may have been realized during summarize. In that case, the child contexts need to
710
- * have their used routes updated to determine if its needs to summarize again and to add it to the summary.
711
- */
712
- this.updateChannelUsedRoutes();
713
-
714
- // And notify the pending promise it is now available
715
- this.channelDeferred.resolve(this.channel);
716
- } catch (error) {
717
- this.channelDeferred?.reject(error);
718
- this.logger.sendErrorEvent(
719
- {
720
- eventName: "BindRuntimeError", fluidDataStoreId: {
721
- value: this.id,
722
- tag: TelemetryDataTag.CodeArtifact,
723
- },
724
- },
725
- error);
726
- }
727
- }
728
-
729
- public async getAbsoluteUrl(relativeUrl: string): Promise<string | undefined> {
730
- if (this.attachState !== AttachState.Attached) {
731
- return undefined;
732
- }
733
- return this._containerRuntime.getAbsoluteUrl(relativeUrl);
734
- }
735
-
736
- public abstract generateAttachMessage(): IAttachMessage;
737
-
738
- public abstract getInitialSnapshotDetails(): Promise<ISnapshotDetails>;
739
-
740
- /**
741
- * @deprecated Sets the datastore as root, for aliasing purposes: #7948
742
- * This method should not be used outside of the aliasing context.
743
- * It will be removed, as the source of truth for this flag will be the aliasing blob.
744
- */
745
- public setInMemoryRoot(): void {
746
- this._isInMemoryRoot = true;
747
- }
748
-
749
- public abstract getBaseGCDetails(): Promise<IGarbageCollectionDetailsBase>;
750
-
751
- public reSubmit(contents: any, localOpMetadata: unknown) {
752
- assert(!!this.channel, 0x14b /* "Channel must exist when resubmitting ops" */);
753
- const innerContents = contents as FluidDataStoreMessage;
754
- this.channel.reSubmit(innerContents.type, innerContents.content, localOpMetadata);
755
- }
756
-
757
- public rollback(contents: any, localOpMetadata: unknown) {
758
- if (!this.channel) {
759
- throw new Error("Channel must exist when rolling back ops");
760
- }
761
- if (!this.channel.rollback) {
762
- throw new Error("Channel doesn't support rollback");
763
- }
764
- const innerContents = contents as FluidDataStoreMessage;
765
- this.channel.rollback(innerContents.type, innerContents.content, localOpMetadata);
766
- }
767
-
768
- public async applyStashedOp(contents: any): Promise<unknown> {
769
- if (!this.channel) {
770
- await this.realize();
771
- }
772
- assert(!!this.channel, 0x14c /* "Channel must exist when rebasing ops" */);
773
- const innerContents = contents as FluidDataStoreMessage;
774
- return this.channel.applyStashedOp(innerContents.content);
775
- }
776
-
777
- private verifyNotClosed(callSite: string, checkTombstone = true, safeTelemetryProps: ITelemetryProperties = {}) {
778
- if (this._disposed) {
779
- throw new Error(`Context is closed! Call site [${callSite}]`);
780
- }
781
-
782
- if (checkTombstone && this.tombstoned) {
783
- const messageString = `Context is tombstoned! Call site [${callSite}]`;
784
- const error = new DataCorruptionError(messageString, safeTelemetryProps);
785
-
786
- sendGCTombstoneEvent(
787
- this.mc,
788
- {
789
- eventName: "GC_Tombstone_DataStore_Changed",
790
- category: this.throwOnTombstoneUsage ? "error" : "generic",
791
- isSummarizerClient: this.clientDetails.type === summarizerClientType,
792
- callSite,
793
- },
794
- this.pkg,
795
- error,
796
- );
797
- if (this.throwOnTombstoneUsage) {
798
- throw error;
799
- }
800
- }
801
- }
802
-
803
- public getCreateChildSummarizerNodeFn(id: string, createParam: CreateChildSummarizerNodeParam) {
804
- return (
805
- summarizeInternal: SummarizeInternalFn,
806
- getGCDataFn: (fullGC?: boolean) => Promise<IGarbageCollectionData>,
807
- getBaseGCDetailsFn?: () => Promise<IGarbageCollectionDetailsBase>,
808
- ) => this.summarizerNode.createChild(
809
- summarizeInternal,
810
- id,
811
- createParam,
812
- // DDS will not create failure summaries
813
- { throwOnFailure: true },
814
- getGCDataFn,
815
- getBaseGCDetailsFn,
816
- );
817
- }
818
-
819
- public async uploadBlob(blob: ArrayBufferLike): Promise<IFluidHandle<ArrayBufferLike>> {
820
- return this.containerRuntime.uploadBlob(blob);
821
- }
140
+ export abstract class FluidDataStoreContext
141
+ extends TypedEventEmitter<IFluidDataStoreContextEvents>
142
+ implements IFluidDataStoreContext, IDisposable
143
+ {
144
+ public get packagePath(): readonly string[] {
145
+ assert(this.pkg !== undefined, 0x139 /* "Undefined package path" */);
146
+ return this.pkg;
147
+ }
148
+
149
+ public get options(): ILoaderOptions {
150
+ return this._containerRuntime.options;
151
+ }
152
+
153
+ public get clientId(): string | undefined {
154
+ return this._containerRuntime.clientId;
155
+ }
156
+
157
+ public get clientDetails(): IClientDetails {
158
+ return this._containerRuntime.clientDetails;
159
+ }
160
+
161
+ public get logger(): ITelemetryLogger {
162
+ return this._containerRuntime.logger;
163
+ }
164
+
165
+ public get deltaManager(): IDeltaManager<ISequencedDocumentMessage, IDocumentMessage> {
166
+ return this._containerRuntime.deltaManager;
167
+ }
168
+
169
+ public get connected(): boolean {
170
+ return this._containerRuntime.connected;
171
+ }
172
+
173
+ public get IFluidHandleContext() {
174
+ return this._containerRuntime.IFluidHandleContext;
175
+ }
176
+
177
+ public get containerRuntime(): IContainerRuntime {
178
+ return this._containerRuntime;
179
+ }
180
+
181
+ public ensureNoDataModelChanges<T>(callback: () => T): T {
182
+ return this._containerRuntime.ensureNoDataModelChanges(callback);
183
+ }
184
+
185
+ public get isLoaded(): boolean {
186
+ return this.loaded;
187
+ }
188
+
189
+ public get baseSnapshot(): ISnapshotTree | undefined {
190
+ return this._baseSnapshot;
191
+ }
192
+
193
+ private _disposed = false;
194
+ public get disposed() {
195
+ return this._disposed;
196
+ }
197
+
198
+ /**
199
+ * Tombstone is a temporary feature that prevents a data store from sending / receiving ops, signals and from
200
+ * loading.
201
+ */
202
+ private _tombstoned = false;
203
+ public get tombstoned() {
204
+ return this._tombstoned;
205
+ }
206
+ /** If true, throw an error when a tombstone data store is used. */
207
+ private readonly throwOnTombstoneUsage: boolean;
208
+
209
+ /** If true, this means that this data store context and its children have been removed from the runtime */
210
+ private deleted: boolean = false;
211
+
212
+ public get attachState(): AttachState {
213
+ return this._attachState;
214
+ }
215
+
216
+ public get IFluidDataStoreRegistry(): IFluidDataStoreRegistry | undefined {
217
+ return this.registry;
218
+ }
219
+
220
+ /**
221
+ * A datastore is considered as root if it
222
+ * 1. is root in memory - see isInMemoryRoot
223
+ * 2. is root as part of the base snapshot that the datastore loaded from
224
+ * @returns whether a datastore is root
225
+ */
226
+ public async isRoot(): Promise<boolean> {
227
+ return this.isInMemoryRoot() || (await this.getInitialSnapshotDetails()).isRootDataStore;
228
+ }
229
+
230
+ /**
231
+ * There are 3 states where isInMemoryRoot needs to be true
232
+ * 1. when a datastore becomes aliased. This can happen for both remote and local datastores
233
+ * 2. when a datastore is created locally as root
234
+ * 3. when a datastore is created locally as root and is rehydrated
235
+ * @returns whether a datastore is root in memory
236
+ */
237
+ protected isInMemoryRoot(): boolean {
238
+ return this._isInMemoryRoot;
239
+ }
240
+
241
+ protected registry: IFluidDataStoreRegistry | undefined;
242
+
243
+ protected detachedRuntimeCreation = false;
244
+ /** @deprecated - To be replaced by calling makeLocallyVisible directly */
245
+ public readonly bindToContext: () => void;
246
+ protected channel: IFluidDataStoreChannel | undefined;
247
+ private loaded = false;
248
+ protected pending: ISequencedDocumentMessage[] | undefined = [];
249
+ protected channelDeferred: Deferred<IFluidDataStoreChannel> | undefined;
250
+ private _baseSnapshot: ISnapshotTree | undefined;
251
+ protected _attachState: AttachState;
252
+ private _isInMemoryRoot: boolean = false;
253
+ protected readonly summarizerNode: ISummarizerNodeWithGC;
254
+ protected readonly mc: MonitoringContext;
255
+ private readonly thresholdOpsCounter: ThresholdCounter;
256
+ private static readonly pendingOpsCountThreshold = 1000;
257
+
258
+ // The used routes of this node as per the last GC run. This is used to update the used routes of the channel
259
+ // if it realizes after GC is run.
260
+ private lastUsedRoutes: string[] | undefined;
261
+
262
+ public readonly id: string;
263
+ private readonly _containerRuntime: ContainerRuntime;
264
+ public readonly storage: IDocumentStorageService;
265
+ public readonly scope: FluidObject;
266
+ protected pkg?: readonly string[];
267
+
268
+ constructor(
269
+ props: IFluidDataStoreContextProps,
270
+ private readonly existing: boolean,
271
+ private bindState: BindState, // Used to assert for state tracking purposes
272
+ public readonly isLocalDataStore: boolean,
273
+ private readonly makeLocallyVisibleFn: () => void,
274
+ ) {
275
+ super();
276
+
277
+ this._containerRuntime = props.runtime;
278
+ this.id = props.id;
279
+ this.storage = props.storage;
280
+ this.scope = props.scope;
281
+ this.pkg = props.pkg;
282
+
283
+ // URIs use slashes as delimiters. Handles use URIs.
284
+ // Thus having slashes in types almost guarantees trouble down the road!
285
+ assert(!this.id.includes("/"), 0x13a /* Data store ID contains slash */);
286
+
287
+ this._attachState =
288
+ this.containerRuntime.attachState !== AttachState.Detached && this.existing
289
+ ? this.containerRuntime.attachState
290
+ : AttachState.Detached;
291
+
292
+ this.bindToContext = () => {
293
+ assert(
294
+ this.bindState === BindState.NotBound,
295
+ 0x13b /* "datastore context is already in bound state" */,
296
+ );
297
+ this.bindState = BindState.Binding;
298
+ assert(
299
+ this.channel !== undefined,
300
+ 0x13c /* "undefined channel on datastore context" */,
301
+ );
302
+ this.makeLocallyVisible();
303
+ this.bindState = BindState.Bound;
304
+ };
305
+
306
+ const thisSummarizeInternal = async (
307
+ fullTree: boolean,
308
+ trackState: boolean,
309
+ telemetryContext?: ITelemetryContext,
310
+ ) => this.summarizeInternal(fullTree, trackState, telemetryContext);
311
+
312
+ this.summarizerNode = props.createSummarizerNodeFn(
313
+ thisSummarizeInternal,
314
+ async (fullGC?: boolean) => this.getGCDataInternal(fullGC),
315
+ async () => this.getBaseGCDetails(),
316
+ );
317
+
318
+ this.mc = loggerToMonitoringContext(
319
+ ChildLogger.create(this.logger, "FluidDataStoreContext"),
320
+ );
321
+ this.thresholdOpsCounter = new ThresholdCounter(
322
+ FluidDataStoreContext.pendingOpsCountThreshold,
323
+ this.mc.logger,
324
+ );
325
+
326
+ // Tombstone should only throw when the feature flag is enabled and the client isn't a summarizer
327
+ this.throwOnTombstoneUsage =
328
+ this.mc.config.getBoolean(throwOnTombstoneUsageKey) === true &&
329
+ this._containerRuntime.gcTombstoneEnforcementAllowed &&
330
+ this.clientDetails.type !== summarizerClientType;
331
+ }
332
+
333
+ public dispose(): void {
334
+ if (this._disposed) {
335
+ return;
336
+ }
337
+ this._disposed = true;
338
+
339
+ // Dispose any pending runtime after it gets fulfilled
340
+ // Errors are logged where this.channelDeferred is consumed/generated (realizeCore(), bindRuntime())
341
+ if (this.channelDeferred) {
342
+ this.channelDeferred.promise
343
+ .then((runtime) => {
344
+ runtime.dispose();
345
+ })
346
+ .catch((error) => {});
347
+ }
348
+ }
349
+
350
+ /**
351
+ * When delete is called, that means that the data store is permanently removed from the runtime, and will not show up in future summaries
352
+ * This function is called to prevent ops from being generated from this data store once it has been deleted. Furthermore, this data store
353
+ * should not receive any ops/signals.
354
+ */
355
+ public delete() {
356
+ this.deleted = true;
357
+ }
358
+
359
+ public setTombstone(tombstone: boolean) {
360
+ if (this.tombstoned === tombstone) {
361
+ return;
362
+ }
363
+
364
+ this._tombstoned = tombstone;
365
+ }
366
+
367
+ private rejectDeferredRealize(reason: string, packageName?: string): never {
368
+ throw new LoggingError(reason, {
369
+ packageName: { value: packageName, tag: TelemetryDataTag.CodeArtifact },
370
+ });
371
+ }
372
+
373
+ public async realize(): Promise<IFluidDataStoreChannel> {
374
+ assert(!this.detachedRuntimeCreation, 0x13d /* "Detached runtime creation on realize()" */);
375
+ if (!this.channelDeferred) {
376
+ this.channelDeferred = new Deferred<IFluidDataStoreChannel>();
377
+ this.realizeCore(this.existing).catch((error) => {
378
+ const errorWrapped = DataProcessingError.wrapIfUnrecognized(
379
+ error,
380
+ "realizeFluidDataStoreContext",
381
+ );
382
+ errorWrapped.addTelemetryProperties({
383
+ fluidDataStoreId: {
384
+ value: this.id,
385
+ tag: TelemetryDataTag.CodeArtifact,
386
+ },
387
+ });
388
+ this.channelDeferred?.reject(errorWrapped);
389
+ this.logger.sendErrorEvent({ eventName: "RealizeError" }, errorWrapped);
390
+ });
391
+ }
392
+ return this.channelDeferred.promise;
393
+ }
394
+
395
+ protected async factoryFromPackagePath(packages?: readonly string[]) {
396
+ assert(this.pkg === packages, 0x13e /* "Unexpected package path" */);
397
+ if (packages === undefined) {
398
+ this.rejectDeferredRealize("packages is undefined");
399
+ }
400
+
401
+ let entry: FluidDataStoreRegistryEntry | undefined;
402
+ let registry: IFluidDataStoreRegistry | undefined =
403
+ this._containerRuntime.IFluidDataStoreRegistry;
404
+ let lastPkg: string | undefined;
405
+ for (const pkg of packages) {
406
+ if (!registry) {
407
+ this.rejectDeferredRealize("No registry for package", lastPkg);
408
+ }
409
+ lastPkg = pkg;
410
+ entry = await registry.get(pkg);
411
+ if (!entry) {
412
+ this.rejectDeferredRealize("Registry does not contain entry for the package", pkg);
413
+ }
414
+ registry = entry.IFluidDataStoreRegistry;
415
+ }
416
+ const factory = entry?.IFluidDataStoreFactory;
417
+ if (factory === undefined) {
418
+ this.rejectDeferredRealize("Can't find factory for package", lastPkg);
419
+ }
420
+
421
+ return { factory, registry };
422
+ }
423
+
424
+ private async realizeCore(existing: boolean): Promise<void> {
425
+ const details = await this.getInitialSnapshotDetails();
426
+ // Base snapshot is the baseline where pending ops are applied to.
427
+ // It is important that this be in sync with the pending ops, and also
428
+ // that it is set here, before bindRuntime is called.
429
+ this._baseSnapshot = details.snapshot;
430
+ const packages = details.pkg;
431
+
432
+ const { factory, registry } = await this.factoryFromPackagePath(packages);
433
+
434
+ assert(
435
+ this.registry === undefined,
436
+ 0x13f /* "datastore context registry is already set" */,
437
+ );
438
+ this.registry = registry;
439
+
440
+ const channel = await factory.instantiateDataStore(this, existing);
441
+ assert(channel !== undefined, 0x140 /* "undefined channel on datastore context" */);
442
+ this.bindRuntime(channel);
443
+ }
444
+
445
+ /**
446
+ * Notifies this object about changes in the connection state.
447
+ * @param value - New connection state.
448
+ * @param clientId - ID of the client. Its old ID when in disconnected state and
449
+ * its new client ID when we are connecting or connected.
450
+ */
451
+ public setConnectionState(connected: boolean, clientId?: string) {
452
+ // ConnectionState should not fail in tombstone mode as this is internally run
453
+ this.verifyNotClosed("setConnectionState", false /* checkTombstone */);
454
+
455
+ // Connection events are ignored if the store is not yet loaded
456
+ if (!this.loaded) {
457
+ return;
458
+ }
459
+
460
+ assert(this.connected === connected, 0x141 /* "Unexpected connected state" */);
461
+
462
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
463
+ this.channel!.setConnectionState(connected, clientId);
464
+ }
465
+
466
+ public process(
467
+ messageArg: ISequencedDocumentMessage,
468
+ local: boolean,
469
+ localOpMetadata: unknown,
470
+ ): void {
471
+ this.verifyNotClosed("process", true, extractSafePropertiesFromMessage(messageArg));
472
+
473
+ const innerContents = messageArg.contents as FluidDataStoreMessage;
474
+ const message = {
475
+ ...messageArg,
476
+ type: innerContents.type,
477
+ contents: innerContents.content,
478
+ };
479
+
480
+ this.summarizerNode.recordChange(message);
481
+
482
+ if (this.loaded) {
483
+ return this.channel?.process(message, local, localOpMetadata);
484
+ } else {
485
+ assert(!local, 0x142 /* "local store channel is not loaded" */);
486
+ assert(this.pending !== undefined, 0x23d /* "pending is undefined" */);
487
+ this.pending.push(message);
488
+ this.thresholdOpsCounter.sendIfMultiple("StorePendingOps", this.pending.length);
489
+ }
490
+ }
491
+
492
+ public processSignal(message: IInboundSignalMessage, local: boolean): void {
493
+ this.verifyNotClosed("processSignal");
494
+
495
+ // Signals are ignored if the store is not yet loaded
496
+ if (!this.loaded) {
497
+ return;
498
+ }
499
+
500
+ this.channel?.processSignal(message, local);
501
+ }
502
+
503
+ public getQuorum(): IQuorumClients {
504
+ return this._containerRuntime.getQuorum();
505
+ }
506
+
507
+ public getAudience(): IAudience {
508
+ return this._containerRuntime.getAudience();
509
+ }
510
+
511
+ /**
512
+ * Returns a summary at the current sequence number.
513
+ * @param fullTree - true to bypass optimizations and force a full summary tree
514
+ * @param trackState - This tells whether we should track state from this summary.
515
+ * @param telemetryContext - summary data passed through the layers for telemetry purposes
516
+ */
517
+ public async summarize(
518
+ fullTree: boolean = false,
519
+ trackState: boolean = true,
520
+ telemetryContext?: ITelemetryContext,
521
+ ): Promise<ISummarizeResult> {
522
+ return this.summarizerNode.summarize(fullTree, trackState, telemetryContext);
523
+ }
524
+
525
+ private async summarizeInternal(
526
+ fullTree: boolean,
527
+ trackState: boolean,
528
+ telemetryContext?: ITelemetryContext,
529
+ ): Promise<ISummarizeInternalResult> {
530
+ await this.realize();
531
+
532
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
533
+ const summarizeResult = await this.channel!.summarize(
534
+ fullTree,
535
+ trackState,
536
+ telemetryContext,
537
+ );
538
+
539
+ // Wrap dds summaries in .channels subtree.
540
+ wrapSummaryInChannelsTree(summarizeResult);
541
+ const pathPartsForChildren = [channelsTreeName];
542
+
543
+ // Add data store's attributes to the summary.
544
+ const { pkg } = await this.getInitialSnapshotDetails();
545
+ const isRoot = await this.isRoot();
546
+ const attributes = createAttributes(pkg, isRoot);
547
+ addBlobToSummary(summarizeResult, dataStoreAttributesBlobName, JSON.stringify(attributes));
548
+
549
+ // If we are not referenced, mark the summary tree as unreferenced. Also, update unreferenced blob
550
+ // size in the summary stats with the blobs size of this data store.
551
+ if (!this.summarizerNode.isReferenced()) {
552
+ summarizeResult.summary.unreferenced = true;
553
+ summarizeResult.stats.unreferencedBlobSize = summarizeResult.stats.totalBlobSize;
554
+ }
555
+
556
+ return {
557
+ ...summarizeResult,
558
+ id: this.id,
559
+ pathPartsForChildren,
560
+ };
561
+ }
562
+
563
+ /**
564
+ * Returns the data used for garbage collection. This includes a list of GC nodes that represent this data store
565
+ * including any of its child channel contexts. Each node has a set of outbound routes to other GC nodes in the
566
+ * document.
567
+ * If there is no new data in this data store since the last summary, previous GC data is used.
568
+ * If there is new data, the GC data is generated again (by calling getGCDataInternal).
569
+ * @param fullGC - true to bypass optimizations and force full generation of GC data.
570
+ */
571
+ public async getGCData(fullGC: boolean = false): Promise<IGarbageCollectionData> {
572
+ return this.summarizerNode.getGCData(fullGC);
573
+ }
574
+
575
+ /**
576
+ * Generates data used for garbage collection. This is called when there is new data since last summary. It
577
+ * realizes the data store and calls into each channel context to get its GC data.
578
+ * @param fullGC - true to bypass optimizations and force full generation of GC data.
579
+ */
580
+ private async getGCDataInternal(fullGC: boolean = false): Promise<IGarbageCollectionData> {
581
+ await this.realize();
582
+ assert(
583
+ this.channel !== undefined,
584
+ 0x143 /* "Channel should not be undefined when running GC" */,
585
+ );
586
+
587
+ return this.channel.getGCData(fullGC);
588
+ }
589
+
590
+ /**
591
+ * After GC has run, called to notify the data store of routes used in it. These are used for the following:
592
+ *
593
+ * 1. To identify if this data store is being referenced in the document or not.
594
+ *
595
+ * 2. To determine if it needs to re-summarize in case used routes changed since last summary.
596
+ *
597
+ * 3. These are added to the summary generated by the data store.
598
+ *
599
+ * 4. To notify child contexts of their used routes. This is done immediately if the data store is loaded.
600
+ * Else, it is done when realizing the data store.
601
+ *
602
+ * 5. To update the timestamp when this data store or any children are marked as unreferenced.
603
+ *
604
+ * @param usedRoutes - The routes that are used in this data store.
605
+ */
606
+ public updateUsedRoutes(usedRoutes: string[]) {
607
+ // Update the used routes in this data store's summarizer node.
608
+ this.summarizerNode.updateUsedRoutes(usedRoutes);
609
+
610
+ /**
611
+ * Store the used routes to update the channel if the data store is not loaded yet. If the used routes changed
612
+ * since the previous run, the data store will be loaded during summarize since the used state changed. So, it's
613
+ * safe to only store the last used routes.
614
+ */
615
+ this.lastUsedRoutes = usedRoutes;
616
+
617
+ // If we are loaded, call the channel so it can update the used routes of the child contexts.
618
+ // If we are not loaded, we will update this when we are realized.
619
+ if (this.loaded) {
620
+ this.updateChannelUsedRoutes();
621
+ }
622
+ }
623
+
624
+ /**
625
+ * Called when a new outbound reference is added to another node. This is used by garbage collection to identify
626
+ * all references added in the system.
627
+ * @param srcHandle - The handle of the node that added the reference.
628
+ * @param outboundHandle - The handle of the outbound node that is referenced.
629
+ */
630
+ public addedGCOutboundReference(srcHandle: IFluidHandle, outboundHandle: IFluidHandle) {
631
+ this._containerRuntime.addedGCOutboundReference(srcHandle, outboundHandle);
632
+ }
633
+
634
+ /**
635
+ * Updates the used routes of the channel and its child contexts. The channel must be loaded before calling this.
636
+ * It is called in these two scenarios:
637
+ * 1. When the used routes of the data store is updated and the data store is loaded.
638
+ * 2. When the data store is realized. This updates the channel's used routes as per last GC run.
639
+ */
640
+ private updateChannelUsedRoutes() {
641
+ assert(this.loaded, 0x144 /* "Channel should be loaded when updating used routes" */);
642
+ assert(
643
+ this.channel !== undefined,
644
+ 0x145 /* "Channel should be present when data store is loaded" */,
645
+ );
646
+
647
+ // If there is no lastUsedRoutes, GC has not run up until this point.
648
+ if (this.lastUsedRoutes === undefined) {
649
+ return;
650
+ }
651
+
652
+ // Remove the route to this data store, if it exists.
653
+ const usedChannelRoutes = this.lastUsedRoutes.filter((id: string) => {
654
+ return id !== "/" && id !== "";
655
+ });
656
+ this.channel.updateUsedRoutes(usedChannelRoutes);
657
+ }
658
+
659
+ /**
660
+ * @deprecated 0.18.Should call request on the runtime directly
661
+ */
662
+ public async request(request: IRequest): Promise<IResponse> {
663
+ const runtime = await this.realize();
664
+ return runtime.request(request);
665
+ }
666
+
667
+ public submitMessage(type: string, content: any, localOpMetadata: unknown): void {
668
+ this.verifyNotClosed("submitMessage");
669
+ assert(!!this.channel, 0x146 /* "Channel must exist when submitting message" */);
670
+ const fluidDataStoreContent: FluidDataStoreMessage = {
671
+ content,
672
+ type,
673
+ };
674
+ this._containerRuntime.submitDataStoreOp(this.id, fluidDataStoreContent, localOpMetadata);
675
+ }
676
+
677
+ /**
678
+ * This is called from a SharedSummaryBlock that does not generate ops but only wants to be part of the summary.
679
+ * It indicates that there is data in the object that needs to be summarized.
680
+ * We will update the latestSequenceNumber of the summary tracker of this
681
+ * store and of the object's channel.
682
+ *
683
+ * @param address - The address of the channel that is dirty.
684
+ *
685
+ */
686
+ public setChannelDirty(address: string): void {
687
+ this.verifyNotClosed("setChannelDirty");
688
+
689
+ // Get the latest sequence number.
690
+ const latestSequenceNumber = this.deltaManager.lastSequenceNumber;
691
+
692
+ this.summarizerNode.invalidate(latestSequenceNumber);
693
+
694
+ const channelSummarizerNode = this.summarizerNode.getChild(address);
695
+
696
+ if (channelSummarizerNode) {
697
+ channelSummarizerNode.invalidate(latestSequenceNumber); // TODO: lazy load problem?
698
+ }
699
+ }
700
+
701
+ public submitSignal(type: string, content: any) {
702
+ this.verifyNotClosed("submitSignal");
703
+
704
+ assert(!!this.channel, 0x147 /* "Channel must exist on submitting signal" */);
705
+ return this._containerRuntime.submitDataStoreSignal(this.id, type, content);
706
+ }
707
+
708
+ /**
709
+ * This is called by the data store channel when it becomes locally visible indicating that it is ready to become
710
+ * globally visible now.
711
+ */
712
+ public makeLocallyVisible() {
713
+ assert(this.channel !== undefined, 0x2cf /* "undefined channel on datastore context" */);
714
+ this.makeLocallyVisibleFn();
715
+ }
716
+
717
+ protected bindRuntime(channel: IFluidDataStoreChannel) {
718
+ if (this.channel) {
719
+ throw new Error("Runtime already bound");
720
+ }
721
+
722
+ try {
723
+ assert(
724
+ !this.detachedRuntimeCreation,
725
+ 0x148 /* "Detached runtime creation on runtime bind" */,
726
+ );
727
+ assert(this.channelDeferred !== undefined, 0x149 /* "Undefined channel deferral" */);
728
+ assert(this.pkg !== undefined, 0x14a /* "Undefined package path" */);
729
+
730
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
731
+ const pending = this.pending!;
732
+
733
+ // Apply all pending ops
734
+ for (const op of pending) {
735
+ channel.process(op, false, undefined /* localOpMetadata */);
736
+ }
737
+
738
+ this.thresholdOpsCounter.send("ProcessPendingOps", pending.length);
739
+ this.pending = undefined;
740
+
741
+ // And now mark the runtime active
742
+ this.loaded = true;
743
+ this.channel = channel;
744
+
745
+ // Freeze the package path to ensure that someone doesn't modify it when it is
746
+ // returned in packagePath().
747
+ Object.freeze(this.pkg);
748
+
749
+ /**
750
+ * Update the used routes of the channel. If GC has run before this data store was realized, we will have
751
+ * the used routes saved. So, this will ensure that all the child contexts have up-to-date used routes as
752
+ * per the last time GC was run.
753
+ * Also, this data store may have been realized during summarize. In that case, the child contexts need to
754
+ * have their used routes updated to determine if its needs to summarize again and to add it to the summary.
755
+ */
756
+ this.updateChannelUsedRoutes();
757
+
758
+ // And notify the pending promise it is now available
759
+ this.channelDeferred.resolve(this.channel);
760
+ } catch (error) {
761
+ this.channelDeferred?.reject(error);
762
+ this.logger.sendErrorEvent(
763
+ {
764
+ eventName: "BindRuntimeError",
765
+ fluidDataStoreId: {
766
+ value: this.id,
767
+ tag: TelemetryDataTag.CodeArtifact,
768
+ },
769
+ },
770
+ error,
771
+ );
772
+ }
773
+ }
774
+
775
+ public async getAbsoluteUrl(relativeUrl: string): Promise<string | undefined> {
776
+ if (this.attachState !== AttachState.Attached) {
777
+ return undefined;
778
+ }
779
+ return this._containerRuntime.getAbsoluteUrl(relativeUrl);
780
+ }
781
+
782
+ public abstract generateAttachMessage(): IAttachMessage;
783
+
784
+ public abstract getInitialSnapshotDetails(): Promise<ISnapshotDetails>;
785
+
786
+ /**
787
+ * @deprecated Sets the datastore as root, for aliasing purposes: #7948
788
+ * This method should not be used outside of the aliasing context.
789
+ * It will be removed, as the source of truth for this flag will be the aliasing blob.
790
+ */
791
+ public setInMemoryRoot(): void {
792
+ this._isInMemoryRoot = true;
793
+ }
794
+
795
+ public abstract getBaseGCDetails(): Promise<IGarbageCollectionDetailsBase>;
796
+
797
+ public reSubmit(contents: any, localOpMetadata: unknown) {
798
+ assert(!!this.channel, 0x14b /* "Channel must exist when resubmitting ops" */);
799
+ const innerContents = contents as FluidDataStoreMessage;
800
+ this.channel.reSubmit(innerContents.type, innerContents.content, localOpMetadata);
801
+ }
802
+
803
+ public rollback(contents: any, localOpMetadata: unknown) {
804
+ if (!this.channel) {
805
+ throw new Error("Channel must exist when rolling back ops");
806
+ }
807
+ if (!this.channel.rollback) {
808
+ throw new Error("Channel doesn't support rollback");
809
+ }
810
+ const innerContents = contents as FluidDataStoreMessage;
811
+ this.channel.rollback(innerContents.type, innerContents.content, localOpMetadata);
812
+ }
813
+
814
+ public async applyStashedOp(contents: any): Promise<unknown> {
815
+ if (!this.channel) {
816
+ await this.realize();
817
+ }
818
+ assert(!!this.channel, 0x14c /* "Channel must exist when rebasing ops" */);
819
+ const innerContents = contents as FluidDataStoreMessage;
820
+ return this.channel.applyStashedOp(innerContents.content);
821
+ }
822
+
823
+ private verifyNotClosed(
824
+ callSite: string,
825
+ checkTombstone = true,
826
+ safeTelemetryProps: ITelemetryProperties = {},
827
+ ) {
828
+ if (this.deleted) {
829
+ const messageString = `Context is deleted! Call site [${callSite}]`;
830
+ const error = new DataCorruptionError(messageString, safeTelemetryProps);
831
+ this.mc.logger.sendErrorEvent(
832
+ {
833
+ eventName: "GC_Deleted_DataStore_Changed",
834
+ callSite,
835
+ },
836
+ error,
837
+ );
838
+
839
+ throw error;
840
+ }
841
+
842
+ if (this._disposed) {
843
+ throw new Error(`Context is closed! Call site [${callSite}]`);
844
+ }
845
+
846
+ if (checkTombstone && this.tombstoned) {
847
+ const messageString = `Context is tombstoned! Call site [${callSite}]`;
848
+ const error = new DataCorruptionError(messageString, safeTelemetryProps);
849
+
850
+ sendGCUnexpectedUsageEvent(
851
+ this.mc,
852
+ {
853
+ eventName: "GC_Tombstone_DataStore_Changed",
854
+ category: this.throwOnTombstoneUsage ? "error" : "generic",
855
+ gcTombstoneEnforcementAllowed:
856
+ this._containerRuntime.gcTombstoneEnforcementAllowed,
857
+ callSite,
858
+ },
859
+ this.pkg,
860
+ error,
861
+ );
862
+ if (this.throwOnTombstoneUsage) {
863
+ throw error;
864
+ }
865
+ }
866
+ }
867
+
868
+ public getCreateChildSummarizerNodeFn(id: string, createParam: CreateChildSummarizerNodeParam) {
869
+ return (
870
+ summarizeInternal: SummarizeInternalFn,
871
+ getGCDataFn: (fullGC?: boolean) => Promise<IGarbageCollectionData>,
872
+ getBaseGCDetailsFn?: () => Promise<IGarbageCollectionDetailsBase>,
873
+ ) =>
874
+ this.summarizerNode.createChild(
875
+ summarizeInternal,
876
+ id,
877
+ createParam,
878
+ // DDS will not create failure summaries
879
+ { throwOnFailure: true },
880
+ getGCDataFn,
881
+ getBaseGCDetailsFn,
882
+ );
883
+ }
884
+
885
+ public async uploadBlob(blob: ArrayBufferLike): Promise<IFluidHandle<ArrayBufferLike>> {
886
+ return this.containerRuntime.uploadBlob(blob);
887
+ }
822
888
  }
823
889
 
824
890
  export class RemoteFluidDataStoreContext extends FluidDataStoreContext {
825
- private readonly initSnapshotValue: ISnapshotTree | undefined;
826
- private readonly baseGCDetailsP: Promise<IGarbageCollectionDetailsBase>;
827
-
828
- constructor(props: IRemoteFluidDataStoreContextProps) {
829
- super(
830
- props,
831
- true /* existing */,
832
- BindState.Bound,
833
- false /* isLocalDataStore */,
834
- () => {
835
- throw new Error("Already attached");
836
- },
837
- );
838
-
839
- this.initSnapshotValue = props.snapshotTree;
840
- this.baseGCDetailsP = new LazyPromise<IGarbageCollectionDetailsBase>(async () => {
841
- return (await props.getBaseGCDetails()) ?? {};
842
- });
843
-
844
- if (props.snapshotTree !== undefined) {
845
- this.summarizerNode.updateBaseSummaryState(props.snapshotTree);
846
- }
847
- }
848
-
849
- private readonly initialSnapshotDetailsP = new LazyPromise<ISnapshotDetails>(async () => {
850
- let tree = this.initSnapshotValue;
851
- let isRootDataStore = true;
852
-
853
- if (!!tree && tree.blobs[dataStoreAttributesBlobName] !== undefined) {
854
- // Need to get through snapshot and use that to populate extraBlobs
855
- const attributes =
856
- await readAndParse<ReadFluidDataStoreAttributes>(this.storage, tree.blobs[dataStoreAttributesBlobName]);
857
-
858
- let pkgFromSnapshot: string[];
859
- // Use the snapshotFormatVersion to determine how the pkg is encoded in the snapshot.
860
- // For snapshotFormatVersion = "0.1" (1) or above, pkg is jsonified, otherwise it is just a string.
861
- const formatVersion = getAttributesFormatVersion(attributes);
862
- if (formatVersion < 1) {
863
- pkgFromSnapshot = attributes.pkg.startsWith("[\"") && attributes.pkg.endsWith("\"]")
864
- ? JSON.parse(attributes.pkg) as string[]
865
- : [attributes.pkg];
866
- } else {
867
- pkgFromSnapshot = JSON.parse(attributes.pkg) as string[];
868
- }
869
- this.pkg = pkgFromSnapshot;
870
-
871
- /**
872
- * If there is no isRootDataStore in the attributes blob, set it to true. This will ensure that
873
- * data stores in older documents are not garbage collected incorrectly. This may lead to additional
874
- * roots in the document but they won't break.
875
- */
876
- isRootDataStore = attributes.isRootDataStore ?? true;
877
-
878
- if (hasIsolatedChannels(attributes)) {
879
- tree = tree.trees[channelsTreeName];
880
- assert(tree !== undefined,
881
- 0x1fe /* "isolated channels subtree should exist in remote datastore snapshot" */);
882
- }
883
- }
884
-
885
- return {
886
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
887
- pkg: this.pkg!,
888
- isRootDataStore,
889
- snapshot: tree,
890
- };
891
- });
892
-
893
- public async getInitialSnapshotDetails(): Promise<ISnapshotDetails> {
894
- return this.initialSnapshotDetailsP;
895
- }
896
-
897
- public async getBaseGCDetails(): Promise<IGarbageCollectionDetailsBase> {
898
- return this.baseGCDetailsP;
899
- }
900
-
901
- public generateAttachMessage(): IAttachMessage {
902
- throw new Error("Cannot attach remote store");
903
- }
891
+ private readonly initSnapshotValue: ISnapshotTree | undefined;
892
+ private readonly baseGCDetailsP: Promise<IGarbageCollectionDetailsBase>;
893
+
894
+ constructor(props: IRemoteFluidDataStoreContextProps) {
895
+ super(props, true /* existing */, BindState.Bound, false /* isLocalDataStore */, () => {
896
+ throw new Error("Already attached");
897
+ });
898
+
899
+ this.initSnapshotValue = props.snapshotTree;
900
+ this.baseGCDetailsP = new LazyPromise<IGarbageCollectionDetailsBase>(async () => {
901
+ return (await props.getBaseGCDetails()) ?? {};
902
+ });
903
+
904
+ if (props.snapshotTree !== undefined) {
905
+ this.summarizerNode.updateBaseSummaryState(props.snapshotTree);
906
+ }
907
+ }
908
+
909
+ private readonly initialSnapshotDetailsP = new LazyPromise<ISnapshotDetails>(async () => {
910
+ let tree = this.initSnapshotValue;
911
+ let isRootDataStore = true;
912
+
913
+ if (!!tree && tree.blobs[dataStoreAttributesBlobName] !== undefined) {
914
+ // Need to get through snapshot and use that to populate extraBlobs
915
+ const attributes = await readAndParse<ReadFluidDataStoreAttributes>(
916
+ this.storage,
917
+ tree.blobs[dataStoreAttributesBlobName],
918
+ );
919
+
920
+ let pkgFromSnapshot: string[];
921
+ // Use the snapshotFormatVersion to determine how the pkg is encoded in the snapshot.
922
+ // For snapshotFormatVersion = "0.1" (1) or above, pkg is jsonified, otherwise it is just a string.
923
+ const formatVersion = getAttributesFormatVersion(attributes);
924
+ if (formatVersion < 1) {
925
+ pkgFromSnapshot =
926
+ attributes.pkg.startsWith('["') && attributes.pkg.endsWith('"]')
927
+ ? (JSON.parse(attributes.pkg) as string[])
928
+ : [attributes.pkg];
929
+ } else {
930
+ pkgFromSnapshot = JSON.parse(attributes.pkg) as string[];
931
+ }
932
+ this.pkg = pkgFromSnapshot;
933
+
934
+ /**
935
+ * If there is no isRootDataStore in the attributes blob, set it to true. This will ensure that
936
+ * data stores in older documents are not garbage collected incorrectly. This may lead to additional
937
+ * roots in the document but they won't break.
938
+ */
939
+ isRootDataStore = attributes.isRootDataStore ?? true;
940
+
941
+ if (hasIsolatedChannels(attributes)) {
942
+ tree = tree.trees[channelsTreeName];
943
+ assert(
944
+ tree !== undefined,
945
+ 0x1fe /* "isolated channels subtree should exist in remote datastore snapshot" */,
946
+ );
947
+ }
948
+ }
949
+
950
+ return {
951
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
952
+ pkg: this.pkg!,
953
+ isRootDataStore,
954
+ snapshot: tree,
955
+ };
956
+ });
957
+
958
+ public async getInitialSnapshotDetails(): Promise<ISnapshotDetails> {
959
+ return this.initialSnapshotDetailsP;
960
+ }
961
+
962
+ public async getBaseGCDetails(): Promise<IGarbageCollectionDetailsBase> {
963
+ return this.baseGCDetailsP;
964
+ }
965
+
966
+ public generateAttachMessage(): IAttachMessage {
967
+ throw new Error("Cannot attach remote store");
968
+ }
904
969
  }
905
970
 
906
971
  /**
907
972
  * Base class for detached & attached context classes
908
973
  */
909
974
  export class LocalFluidDataStoreContextBase extends FluidDataStoreContext {
910
- private readonly snapshotTree: ISnapshotTree | undefined;
911
- /**
912
- * @deprecated 0.16 Issue #1635, #3631
913
- */
914
- public readonly createProps?: any;
915
-
916
- constructor(props: ILocalFluidDataStoreContextProps) {
917
- super(
918
- props,
919
- props.snapshotTree !== undefined ? true : false /* existing */,
920
- props.snapshotTree ? BindState.Bound : BindState.NotBound,
921
- true /* isLocalDataStore */,
922
- props.makeLocallyVisibleFn,
923
- );
924
-
925
- this.snapshotTree = props.snapshotTree;
926
- if (props.isRootDataStore === true) {
927
- this.setInMemoryRoot();
928
- }
929
- this.createProps = props.createProps;
930
- this.attachListeners();
931
- }
932
-
933
- private attachListeners(): void {
934
- this.once("attaching", () => {
935
- assert(this.attachState === AttachState.Detached, 0x14d /* "Should move from detached to attaching" */);
936
- this._attachState = AttachState.Attaching;
937
- });
938
- this.once("attached", () => {
939
- assert(this.attachState === AttachState.Attaching, 0x14e /* "Should move from attaching to attached" */);
940
- this._attachState = AttachState.Attached;
941
- });
942
- }
943
-
944
- public generateAttachMessage(): IAttachMessage {
945
- assert(this.channel !== undefined, 0x14f /* "There should be a channel when generating attach message" */);
946
- assert(this.pkg !== undefined, 0x150 /* "pkg should be available in local data store context" */);
947
-
948
- const summarizeResult = this.channel.getAttachSummary();
949
-
950
- // Wrap dds summaries in .channels subtree.
951
- wrapSummaryInChannelsTree(summarizeResult);
952
-
953
- // Add data store's attributes to the summary.
954
- const attributes = createAttributes(
955
- this.pkg,
956
- this.isInMemoryRoot(),
957
- );
958
- addBlobToSummary(summarizeResult, dataStoreAttributesBlobName, JSON.stringify(attributes));
959
-
960
- // Attach message needs the summary in ITree format. Convert the ISummaryTree into an ITree.
961
- const snapshot = convertSummaryTreeToITree(summarizeResult.summary);
962
-
963
- const message: IAttachMessage = {
964
- id: this.id,
965
- snapshot,
966
- type: this.pkg[this.pkg.length - 1],
967
- };
968
-
969
- return message;
970
- }
971
-
972
- public async getInitialSnapshotDetails(): Promise<ISnapshotDetails> {
973
- let snapshot = this.snapshotTree;
974
- let attributes: ReadFluidDataStoreAttributes;
975
- let isRootDataStore = false;
976
- if (snapshot !== undefined) {
977
- // Get the dataStore attributes.
978
- // Note: storage can be undefined in special case while detached.
979
- attributes = await getFluidDataStoreAttributes(this.storage, snapshot);
980
- if (hasIsolatedChannels(attributes)) {
981
- snapshot = snapshot.trees[channelsTreeName];
982
- assert(snapshot !== undefined,
983
- 0x1ff /* "isolated channels subtree should exist in local datastore snapshot" */);
984
- }
985
- if (this.pkg === undefined) {
986
- this.pkg = JSON.parse(attributes.pkg) as string[];
987
- // If there is no isRootDataStore in the attributes blob, set it to true. This ensures that data
988
- // stores in older documents are not garbage collected incorrectly. This may lead to additional
989
- // roots in the document but they won't break.
990
- if (attributes.isRootDataStore ?? true) {
991
- isRootDataStore = true;
992
- this.setInMemoryRoot();
993
- }
994
- }
995
- }
996
- assert(this.pkg !== undefined, 0x152 /* "pkg should be available in local data store" */);
997
-
998
- return {
999
- pkg: this.pkg,
1000
- isRootDataStore,
1001
- snapshot,
1002
- };
1003
- }
1004
-
1005
- public async getBaseGCDetails(): Promise<IGarbageCollectionDetailsBase> {
1006
- // Local data store does not have initial summary.
1007
- return {};
1008
- }
975
+ private readonly snapshotTree: ISnapshotTree | undefined;
976
+ /**
977
+ * @deprecated 0.16 Issue #1635, #3631
978
+ */
979
+ public readonly createProps?: any;
980
+
981
+ constructor(props: ILocalFluidDataStoreContextProps) {
982
+ super(
983
+ props,
984
+ props.snapshotTree !== undefined ? true : false /* existing */,
985
+ props.snapshotTree ? BindState.Bound : BindState.NotBound,
986
+ true /* isLocalDataStore */,
987
+ props.makeLocallyVisibleFn,
988
+ );
989
+
990
+ this.snapshotTree = props.snapshotTree;
991
+ if (props.isRootDataStore === true) {
992
+ this.setInMemoryRoot();
993
+ }
994
+ this.createProps = props.createProps;
995
+ this.attachListeners();
996
+ }
997
+
998
+ private attachListeners(): void {
999
+ this.once("attaching", () => {
1000
+ assert(
1001
+ this.attachState === AttachState.Detached,
1002
+ 0x14d /* "Should move from detached to attaching" */,
1003
+ );
1004
+ this._attachState = AttachState.Attaching;
1005
+ });
1006
+ this.once("attached", () => {
1007
+ assert(
1008
+ this.attachState === AttachState.Attaching,
1009
+ 0x14e /* "Should move from attaching to attached" */,
1010
+ );
1011
+ this._attachState = AttachState.Attached;
1012
+ });
1013
+ }
1014
+
1015
+ public generateAttachMessage(): IAttachMessage {
1016
+ assert(
1017
+ this.channel !== undefined,
1018
+ 0x14f /* "There should be a channel when generating attach message" */,
1019
+ );
1020
+ assert(
1021
+ this.pkg !== undefined,
1022
+ 0x150 /* "pkg should be available in local data store context" */,
1023
+ );
1024
+
1025
+ const summarizeResult = this.channel.getAttachSummary();
1026
+
1027
+ // Wrap dds summaries in .channels subtree.
1028
+ wrapSummaryInChannelsTree(summarizeResult);
1029
+
1030
+ // Add data store's attributes to the summary.
1031
+ const attributes = createAttributes(this.pkg, this.isInMemoryRoot());
1032
+ addBlobToSummary(summarizeResult, dataStoreAttributesBlobName, JSON.stringify(attributes));
1033
+
1034
+ // Attach message needs the summary in ITree format. Convert the ISummaryTree into an ITree.
1035
+ const snapshot = convertSummaryTreeToITree(summarizeResult.summary);
1036
+
1037
+ const message: IAttachMessage = {
1038
+ id: this.id,
1039
+ snapshot,
1040
+ type: this.pkg[this.pkg.length - 1],
1041
+ };
1042
+
1043
+ return message;
1044
+ }
1045
+
1046
+ public async getInitialSnapshotDetails(): Promise<ISnapshotDetails> {
1047
+ let snapshot = this.snapshotTree;
1048
+ let attributes: ReadFluidDataStoreAttributes;
1049
+ let isRootDataStore = false;
1050
+ if (snapshot !== undefined) {
1051
+ // Get the dataStore attributes.
1052
+ // Note: storage can be undefined in special case while detached.
1053
+ attributes = await getFluidDataStoreAttributes(this.storage, snapshot);
1054
+ if (hasIsolatedChannels(attributes)) {
1055
+ snapshot = snapshot.trees[channelsTreeName];
1056
+ assert(
1057
+ snapshot !== undefined,
1058
+ 0x1ff /* "isolated channels subtree should exist in local datastore snapshot" */,
1059
+ );
1060
+ }
1061
+ if (this.pkg === undefined) {
1062
+ this.pkg = JSON.parse(attributes.pkg) as string[];
1063
+ // If there is no isRootDataStore in the attributes blob, set it to true. This ensures that data
1064
+ // stores in older documents are not garbage collected incorrectly. This may lead to additional
1065
+ // roots in the document but they won't break.
1066
+ if (attributes.isRootDataStore ?? true) {
1067
+ isRootDataStore = true;
1068
+ this.setInMemoryRoot();
1069
+ }
1070
+ }
1071
+ }
1072
+ assert(this.pkg !== undefined, 0x152 /* "pkg should be available in local data store" */);
1073
+
1074
+ return {
1075
+ pkg: this.pkg,
1076
+ isRootDataStore,
1077
+ snapshot,
1078
+ };
1079
+ }
1080
+
1081
+ public async getBaseGCDetails(): Promise<IGarbageCollectionDetailsBase> {
1082
+ // Local data store does not have initial summary.
1083
+ return {};
1084
+ }
1085
+
1086
+ /**
1087
+ * A context should only be marked as deleted when its a remote context.
1088
+ * Session Expiry at the runtime level should have closed the container creating the local data store context
1089
+ * before delete is even possible. Session Expiry is at 30 days, and sweep is done 36+ days later from the time
1090
+ * it was unreferenced. Thus the sweeping container should have loaded from a snapshot and thus creating a remote
1091
+ * context.
1092
+ */
1093
+ public delete() {
1094
+ // TODO: GC:Validation - potentially prevent this from happening or asserting. Maybe throw here.
1095
+ sendGCUnexpectedUsageEvent(
1096
+ this.mc,
1097
+ {
1098
+ eventName: "GC_Deleted_DataStore_Unexpected_Delete",
1099
+ message: "Unexpected deletion of a local data store context",
1100
+ category: "error",
1101
+ gcTombstoneEnforcementAllowed: undefined,
1102
+ },
1103
+ this.pkg,
1104
+ );
1105
+ super.delete();
1106
+ }
1009
1107
  }
1010
1108
 
1011
1109
  /**
@@ -1015,9 +1113,9 @@ export class LocalFluidDataStoreContextBase extends FluidDataStoreContext {
1015
1113
  * Runtime is created using data store factory that is associated with this context.
1016
1114
  */
1017
1115
  export class LocalFluidDataStoreContext extends LocalFluidDataStoreContextBase {
1018
- constructor(props: ILocalFluidDataStoreContextProps) {
1019
- super(props);
1020
- }
1116
+ constructor(props: ILocalFluidDataStoreContextProps) {
1117
+ super(props);
1118
+ }
1021
1119
  }
1022
1120
 
1023
1121
  /**
@@ -1027,50 +1125,54 @@ export class LocalFluidDataStoreContext extends LocalFluidDataStoreContextBase {
1027
1125
  * Attachment process provides all missing parts - package path, data store runtime, and data store factory
1028
1126
  */
1029
1127
  export class LocalDetachedFluidDataStoreContext
1030
- extends LocalFluidDataStoreContextBase
1031
- implements IFluidDataStoreContextDetached {
1032
- constructor(props: ILocalFluidDataStoreContextProps) {
1033
- super(props);
1034
- this.detachedRuntimeCreation = true;
1035
- }
1036
-
1037
- public async attachRuntime(
1038
- registry: IProvideFluidDataStoreFactory,
1039
- dataStoreChannel: IFluidDataStoreChannel) {
1040
- assert(this.detachedRuntimeCreation, 0x154 /* "runtime creation is already attached" */);
1041
- this.detachedRuntimeCreation = false;
1042
-
1043
- assert(this.channelDeferred === undefined, 0x155 /* "channel deferral is already set" */);
1044
- this.channelDeferred = new Deferred<IFluidDataStoreChannel>();
1045
-
1046
- const factory = registry.IFluidDataStoreFactory;
1047
-
1048
- const entry = await this.factoryFromPackagePath(this.pkg);
1049
- assert(entry.factory === factory, 0x156 /* "Unexpected factory for package path" */);
1050
-
1051
- assert(this.registry === undefined, 0x157 /* "datastore registry already attached" */);
1052
- this.registry = entry.registry;
1053
-
1054
- super.bindRuntime(dataStoreChannel);
1055
-
1056
- // Load the handle to the data store's entryPoint to make sure that for a detached data store, the entryPoint
1057
- // initialization function is called before the data store gets attached and potentially connected to the
1058
- // delta stream, so it gets a chance to do things while the data store is still "purely local".
1059
- // This preserves the behavior from before we introduced entryPoints, where the instantiateDataStore method
1060
- // of data store factories tends to construct the data object (at least kick off an async method that returns
1061
- // it); that code moved to the entryPoint initialization function, so we want to ensure it still executes
1062
- // before the data store is attached.
1063
- await dataStoreChannel.entryPoint?.get();
1064
-
1065
- if (await this.isRoot()) {
1066
- dataStoreChannel.makeVisibleAndAttachGraph();
1067
- }
1068
- }
1069
-
1070
- public async getInitialSnapshotDetails(): Promise<ISnapshotDetails> {
1071
- if (this.detachedRuntimeCreation) {
1072
- throw new Error("Detached Fluid Data Store context can't be realized! Please attach runtime first!");
1073
- }
1074
- return super.getInitialSnapshotDetails();
1075
- }
1128
+ extends LocalFluidDataStoreContextBase
1129
+ implements IFluidDataStoreContextDetached
1130
+ {
1131
+ constructor(props: ILocalFluidDataStoreContextProps) {
1132
+ super(props);
1133
+ this.detachedRuntimeCreation = true;
1134
+ }
1135
+
1136
+ public async attachRuntime(
1137
+ registry: IProvideFluidDataStoreFactory,
1138
+ dataStoreChannel: IFluidDataStoreChannel,
1139
+ ) {
1140
+ assert(this.detachedRuntimeCreation, 0x154 /* "runtime creation is already attached" */);
1141
+ this.detachedRuntimeCreation = false;
1142
+
1143
+ assert(this.channelDeferred === undefined, 0x155 /* "channel deferral is already set" */);
1144
+ this.channelDeferred = new Deferred<IFluidDataStoreChannel>();
1145
+
1146
+ const factory = registry.IFluidDataStoreFactory;
1147
+
1148
+ const entry = await this.factoryFromPackagePath(this.pkg);
1149
+ assert(entry.factory === factory, 0x156 /* "Unexpected factory for package path" */);
1150
+
1151
+ assert(this.registry === undefined, 0x157 /* "datastore registry already attached" */);
1152
+ this.registry = entry.registry;
1153
+
1154
+ super.bindRuntime(dataStoreChannel);
1155
+
1156
+ // Load the handle to the data store's entryPoint to make sure that for a detached data store, the entryPoint
1157
+ // initialization function is called before the data store gets attached and potentially connected to the
1158
+ // delta stream, so it gets a chance to do things while the data store is still "purely local".
1159
+ // This preserves the behavior from before we introduced entryPoints, where the instantiateDataStore method
1160
+ // of data store factories tends to construct the data object (at least kick off an async method that returns
1161
+ // it); that code moved to the entryPoint initialization function, so we want to ensure it still executes
1162
+ // before the data store is attached.
1163
+ await dataStoreChannel.entryPoint?.get();
1164
+
1165
+ if (await this.isRoot()) {
1166
+ dataStoreChannel.makeVisibleAndAttachGraph();
1167
+ }
1168
+ }
1169
+
1170
+ public async getInitialSnapshotDetails(): Promise<ISnapshotDetails> {
1171
+ if (this.detachedRuntimeCreation) {
1172
+ throw new Error(
1173
+ "Detached Fluid Data Store context can't be realized! Please attach runtime first!",
1174
+ );
1175
+ }
1176
+ return super.getInitialSnapshotDetails();
1177
+ }
1076
1178
  }