@fluidframework/container-runtime 2.0.0-internal.3.0.5 → 2.0.0-internal.3.1.1

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