@fluidframework/container-runtime 2.0.0-internal.3.0.2 → 2.0.0-internal.3.2.0

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