@fluidframework/container-runtime 2.0.0-dev.2.2.0.111723 → 2.0.0-dev.3.1.0.125672

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (365) hide show
  1. package/.eslintrc.js +21 -10
  2. package/.mocharc.js +2 -2
  3. package/api-extractor.json +2 -2
  4. package/dist/batchTracker.d.ts +1 -2
  5. package/dist/batchTracker.d.ts.map +1 -1
  6. package/dist/batchTracker.js +2 -1
  7. package/dist/batchTracker.js.map +1 -1
  8. package/dist/blobManager.d.ts +62 -28
  9. package/dist/blobManager.d.ts.map +1 -1
  10. package/dist/blobManager.js +256 -102
  11. package/dist/blobManager.js.map +1 -1
  12. package/dist/connectionTelemetry.d.ts.map +1 -1
  13. package/dist/connectionTelemetry.js +11 -9
  14. package/dist/connectionTelemetry.js.map +1 -1
  15. package/dist/containerHandleContext.d.ts.map +1 -1
  16. package/dist/containerHandleContext.js +3 -1
  17. package/dist/containerHandleContext.js.map +1 -1
  18. package/dist/containerRuntime.d.ts +110 -78
  19. package/dist/containerRuntime.d.ts.map +1 -1
  20. package/dist/containerRuntime.js +336 -331
  21. package/dist/containerRuntime.js.map +1 -1
  22. package/dist/dataStore.d.ts.map +1 -1
  23. package/dist/dataStore.js +11 -9
  24. package/dist/dataStore.js.map +1 -1
  25. package/dist/dataStoreContext.d.ts +2 -1
  26. package/dist/dataStoreContext.d.ts.map +1 -1
  27. package/dist/dataStoreContext.js +40 -23
  28. package/dist/dataStoreContext.js.map +1 -1
  29. package/dist/dataStoreContexts.d.ts.map +1 -1
  30. package/dist/dataStoreContexts.js +7 -3
  31. package/dist/dataStoreContexts.js.map +1 -1
  32. package/dist/dataStoreRegistry.d.ts.map +1 -1
  33. package/dist/dataStoreRegistry.js +3 -1
  34. package/dist/dataStoreRegistry.js.map +1 -1
  35. package/dist/dataStores.d.ts +12 -9
  36. package/dist/dataStores.d.ts.map +1 -1
  37. package/dist/dataStores.js +69 -46
  38. package/dist/dataStores.js.map +1 -1
  39. package/dist/deltaScheduler.d.ts.map +1 -1
  40. package/dist/deltaScheduler.js +8 -3
  41. package/dist/deltaScheduler.js.map +1 -1
  42. package/dist/garbageCollection.d.ts +57 -42
  43. package/dist/garbageCollection.d.ts.map +1 -1
  44. package/dist/garbageCollection.js +371 -239
  45. package/dist/garbageCollection.js.map +1 -1
  46. package/dist/garbageCollectionConstants.d.ts +23 -0
  47. package/dist/garbageCollectionConstants.d.ts.map +1 -0
  48. package/dist/garbageCollectionConstants.js +36 -0
  49. package/dist/garbageCollectionConstants.js.map +1 -0
  50. package/dist/garbageCollectionHelpers.d.ts +15 -0
  51. package/dist/garbageCollectionHelpers.d.ts.map +1 -0
  52. package/dist/garbageCollectionHelpers.js +27 -0
  53. package/dist/garbageCollectionHelpers.js.map +1 -0
  54. package/dist/gcSweepReadyUsageDetection.d.ts +5 -5
  55. package/dist/gcSweepReadyUsageDetection.d.ts.map +1 -1
  56. package/dist/gcSweepReadyUsageDetection.js +15 -11
  57. package/dist/gcSweepReadyUsageDetection.js.map +1 -1
  58. package/dist/index.d.ts +4 -3
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js +5 -6
  61. package/dist/index.js.map +1 -1
  62. package/dist/opLifecycle/batchManager.d.ts +42 -0
  63. package/dist/opLifecycle/batchManager.d.ts.map +1 -0
  64. package/dist/opLifecycle/batchManager.js +124 -0
  65. package/dist/opLifecycle/batchManager.js.map +1 -0
  66. package/dist/opLifecycle/definitions.d.ts +64 -0
  67. package/dist/opLifecycle/definitions.d.ts.map +1 -0
  68. package/dist/opLifecycle/definitions.js +7 -0
  69. package/dist/opLifecycle/definitions.js.map +1 -0
  70. package/dist/opLifecycle/index.d.ts +12 -0
  71. package/dist/opLifecycle/index.d.ts.map +1 -0
  72. package/dist/opLifecycle/index.js +22 -0
  73. package/dist/opLifecycle/index.js.map +1 -0
  74. package/dist/{opCompressor.d.ts → opLifecycle/opCompressor.d.ts} +3 -3
  75. package/dist/opLifecycle/opCompressor.d.ts.map +1 -0
  76. package/dist/opLifecycle/opCompressor.js +67 -0
  77. package/dist/opLifecycle/opCompressor.js.map +1 -0
  78. package/dist/{opDecompressor.d.ts → opLifecycle/opDecompressor.d.ts} +2 -1
  79. package/dist/opLifecycle/opDecompressor.d.ts.map +1 -0
  80. package/dist/{opDecompressor.js → opLifecycle/opDecompressor.js} +37 -21
  81. package/dist/opLifecycle/opDecompressor.js.map +1 -0
  82. package/dist/opLifecycle/opSplitter.d.ts +49 -0
  83. package/dist/opLifecycle/opSplitter.d.ts.map +1 -0
  84. package/dist/opLifecycle/opSplitter.js +173 -0
  85. package/dist/opLifecycle/opSplitter.js.map +1 -0
  86. package/dist/opLifecycle/outbox.d.ts +52 -0
  87. package/dist/opLifecycle/outbox.d.ts.map +1 -0
  88. package/dist/opLifecycle/outbox.js +164 -0
  89. package/dist/opLifecycle/outbox.js.map +1 -0
  90. package/dist/opLifecycle/remoteMessageProcessor.d.ts +26 -0
  91. package/dist/opLifecycle/remoteMessageProcessor.d.ts.map +1 -0
  92. package/dist/opLifecycle/remoteMessageProcessor.js +96 -0
  93. package/dist/opLifecycle/remoteMessageProcessor.js.map +1 -0
  94. package/dist/opProperties.d.ts.map +1 -1
  95. package/dist/opProperties.js +1 -3
  96. package/dist/opProperties.js.map +1 -1
  97. package/dist/orderedClientElection.d.ts.map +1 -1
  98. package/dist/orderedClientElection.js +10 -4
  99. package/dist/orderedClientElection.js.map +1 -1
  100. package/dist/packageVersion.d.ts +1 -1
  101. package/dist/packageVersion.js +1 -1
  102. package/dist/packageVersion.js.map +1 -1
  103. package/dist/pendingStateManager.d.ts +4 -13
  104. package/dist/pendingStateManager.d.ts.map +1 -1
  105. package/dist/pendingStateManager.js +134 -161
  106. package/dist/pendingStateManager.js.map +1 -1
  107. package/dist/runWhileConnectedCoordinator.d.ts.map +1 -1
  108. package/dist/runWhileConnectedCoordinator.js.map +1 -1
  109. package/dist/runningSummarizer.d.ts.map +1 -1
  110. package/dist/runningSummarizer.js +34 -22
  111. package/dist/runningSummarizer.js.map +1 -1
  112. package/dist/scheduleManager.d.ts +0 -1
  113. package/dist/scheduleManager.d.ts.map +1 -1
  114. package/dist/scheduleManager.js +11 -21
  115. package/dist/scheduleManager.js.map +1 -1
  116. package/dist/serializedSnapshotStorage.d.ts.map +1 -1
  117. package/dist/serializedSnapshotStorage.js +3 -1
  118. package/dist/serializedSnapshotStorage.js.map +1 -1
  119. package/dist/summarizer.d.ts +2 -3
  120. package/dist/summarizer.d.ts.map +1 -1
  121. package/dist/summarizer.js +39 -18
  122. package/dist/summarizer.js.map +1 -1
  123. package/dist/summarizerClientElection.d.ts +1 -2
  124. package/dist/summarizerClientElection.d.ts.map +1 -1
  125. package/dist/summarizerClientElection.js +3 -30
  126. package/dist/summarizerClientElection.js.map +1 -1
  127. package/dist/summarizerHandle.d.ts.map +1 -1
  128. package/dist/summarizerHandle.js.map +1 -1
  129. package/dist/summarizerHeuristics.d.ts.map +1 -1
  130. package/dist/summarizerHeuristics.js +6 -9
  131. package/dist/summarizerHeuristics.js.map +1 -1
  132. package/dist/summarizerTypes.d.ts +22 -25
  133. package/dist/summarizerTypes.d.ts.map +1 -1
  134. package/dist/summarizerTypes.js.map +1 -1
  135. package/dist/summaryCollection.d.ts.map +1 -1
  136. package/dist/summaryCollection.js +18 -8
  137. package/dist/summaryCollection.js.map +1 -1
  138. package/dist/summaryFormat.d.ts.map +1 -1
  139. package/dist/summaryFormat.js +18 -11
  140. package/dist/summaryFormat.js.map +1 -1
  141. package/dist/summaryGenerator.d.ts.map +1 -1
  142. package/dist/summaryGenerator.js +32 -14
  143. package/dist/summaryGenerator.js.map +1 -1
  144. package/dist/summaryManager.d.ts.map +1 -1
  145. package/dist/summaryManager.js +21 -9
  146. package/dist/summaryManager.js.map +1 -1
  147. package/dist/throttler.d.ts +2 -2
  148. package/dist/throttler.d.ts.map +1 -1
  149. package/dist/throttler.js +4 -4
  150. package/dist/throttler.js.map +1 -1
  151. package/garbageCollection.md +15 -2
  152. package/lib/batchTracker.d.ts +1 -2
  153. package/lib/batchTracker.d.ts.map +1 -1
  154. package/lib/batchTracker.js +2 -1
  155. package/lib/batchTracker.js.map +1 -1
  156. package/lib/blobManager.d.ts +62 -28
  157. package/lib/blobManager.d.ts.map +1 -1
  158. package/lib/blobManager.js +259 -105
  159. package/lib/blobManager.js.map +1 -1
  160. package/lib/connectionTelemetry.d.ts.map +1 -1
  161. package/lib/connectionTelemetry.js +11 -9
  162. package/lib/connectionTelemetry.js.map +1 -1
  163. package/lib/containerHandleContext.d.ts.map +1 -1
  164. package/lib/containerHandleContext.js +3 -1
  165. package/lib/containerHandleContext.js.map +1 -1
  166. package/lib/containerRuntime.d.ts +110 -78
  167. package/lib/containerRuntime.d.ts.map +1 -1
  168. package/lib/containerRuntime.js +340 -334
  169. package/lib/containerRuntime.js.map +1 -1
  170. package/lib/dataStore.d.ts.map +1 -1
  171. package/lib/dataStore.js +11 -9
  172. package/lib/dataStore.js.map +1 -1
  173. package/lib/dataStoreContext.d.ts +2 -1
  174. package/lib/dataStoreContext.d.ts.map +1 -1
  175. package/lib/dataStoreContext.js +41 -24
  176. package/lib/dataStoreContext.js.map +1 -1
  177. package/lib/dataStoreContexts.d.ts.map +1 -1
  178. package/lib/dataStoreContexts.js +7 -3
  179. package/lib/dataStoreContexts.js.map +1 -1
  180. package/lib/dataStoreRegistry.d.ts.map +1 -1
  181. package/lib/dataStoreRegistry.js +3 -1
  182. package/lib/dataStoreRegistry.js.map +1 -1
  183. package/lib/dataStores.d.ts +12 -9
  184. package/lib/dataStores.d.ts.map +1 -1
  185. package/lib/dataStores.js +75 -52
  186. package/lib/dataStores.js.map +1 -1
  187. package/lib/deltaScheduler.d.ts.map +1 -1
  188. package/lib/deltaScheduler.js +9 -4
  189. package/lib/deltaScheduler.js.map +1 -1
  190. package/lib/garbageCollection.d.ts +57 -42
  191. package/lib/garbageCollection.d.ts.map +1 -1
  192. package/lib/garbageCollection.js +364 -232
  193. package/lib/garbageCollection.js.map +1 -1
  194. package/lib/garbageCollectionConstants.d.ts +23 -0
  195. package/lib/garbageCollectionConstants.d.ts.map +1 -0
  196. package/lib/garbageCollectionConstants.js +33 -0
  197. package/lib/garbageCollectionConstants.js.map +1 -0
  198. package/lib/garbageCollectionHelpers.d.ts +15 -0
  199. package/lib/garbageCollectionHelpers.d.ts.map +1 -0
  200. package/lib/garbageCollectionHelpers.js +23 -0
  201. package/lib/garbageCollectionHelpers.js.map +1 -0
  202. package/lib/gcSweepReadyUsageDetection.d.ts +5 -5
  203. package/lib/gcSweepReadyUsageDetection.d.ts.map +1 -1
  204. package/lib/gcSweepReadyUsageDetection.js +15 -11
  205. package/lib/gcSweepReadyUsageDetection.js.map +1 -1
  206. package/lib/index.d.ts +4 -3
  207. package/lib/index.d.ts.map +1 -1
  208. package/lib/index.js +3 -3
  209. package/lib/index.js.map +1 -1
  210. package/lib/opLifecycle/batchManager.d.ts +42 -0
  211. package/lib/opLifecycle/batchManager.d.ts.map +1 -0
  212. package/lib/opLifecycle/batchManager.js +120 -0
  213. package/lib/opLifecycle/batchManager.js.map +1 -0
  214. package/lib/opLifecycle/definitions.d.ts +64 -0
  215. package/lib/opLifecycle/definitions.d.ts.map +1 -0
  216. package/lib/opLifecycle/definitions.js +6 -0
  217. package/lib/opLifecycle/definitions.js.map +1 -0
  218. package/lib/opLifecycle/index.d.ts +12 -0
  219. package/lib/opLifecycle/index.d.ts.map +1 -0
  220. package/lib/opLifecycle/index.js +11 -0
  221. package/lib/opLifecycle/index.js.map +1 -0
  222. package/lib/{opCompressor.d.ts → opLifecycle/opCompressor.d.ts} +3 -3
  223. package/lib/opLifecycle/opCompressor.d.ts.map +1 -0
  224. package/lib/opLifecycle/opCompressor.js +63 -0
  225. package/lib/opLifecycle/opCompressor.js.map +1 -0
  226. package/lib/{opDecompressor.d.ts → opLifecycle/opDecompressor.d.ts} +2 -1
  227. package/lib/opLifecycle/opDecompressor.d.ts.map +1 -0
  228. package/lib/{opDecompressor.js → opLifecycle/opDecompressor.js} +37 -21
  229. package/lib/opLifecycle/opDecompressor.js.map +1 -0
  230. package/lib/opLifecycle/opSplitter.d.ts +49 -0
  231. package/lib/opLifecycle/opSplitter.d.ts.map +1 -0
  232. package/lib/opLifecycle/opSplitter.js +168 -0
  233. package/lib/opLifecycle/opSplitter.js.map +1 -0
  234. package/lib/opLifecycle/outbox.d.ts +52 -0
  235. package/lib/opLifecycle/outbox.d.ts.map +1 -0
  236. package/lib/opLifecycle/outbox.js +160 -0
  237. package/lib/opLifecycle/outbox.js.map +1 -0
  238. package/lib/opLifecycle/remoteMessageProcessor.d.ts +26 -0
  239. package/lib/opLifecycle/remoteMessageProcessor.d.ts.map +1 -0
  240. package/lib/opLifecycle/remoteMessageProcessor.js +91 -0
  241. package/lib/opLifecycle/remoteMessageProcessor.js.map +1 -0
  242. package/lib/opProperties.d.ts.map +1 -1
  243. package/lib/opProperties.js +1 -3
  244. package/lib/opProperties.js.map +1 -1
  245. package/lib/orderedClientElection.d.ts.map +1 -1
  246. package/lib/orderedClientElection.js +10 -4
  247. package/lib/orderedClientElection.js.map +1 -1
  248. package/lib/packageVersion.d.ts +1 -1
  249. package/lib/packageVersion.js +1 -1
  250. package/lib/packageVersion.js.map +1 -1
  251. package/lib/pendingStateManager.d.ts +4 -13
  252. package/lib/pendingStateManager.d.ts.map +1 -1
  253. package/lib/pendingStateManager.js +134 -161
  254. package/lib/pendingStateManager.js.map +1 -1
  255. package/lib/runWhileConnectedCoordinator.d.ts.map +1 -1
  256. package/lib/runWhileConnectedCoordinator.js.map +1 -1
  257. package/lib/runningSummarizer.d.ts.map +1 -1
  258. package/lib/runningSummarizer.js +35 -23
  259. package/lib/runningSummarizer.js.map +1 -1
  260. package/lib/scheduleManager.d.ts +0 -1
  261. package/lib/scheduleManager.d.ts.map +1 -1
  262. package/lib/scheduleManager.js +11 -21
  263. package/lib/scheduleManager.js.map +1 -1
  264. package/lib/serializedSnapshotStorage.d.ts.map +1 -1
  265. package/lib/serializedSnapshotStorage.js +3 -1
  266. package/lib/serializedSnapshotStorage.js.map +1 -1
  267. package/lib/summarizer.d.ts +2 -3
  268. package/lib/summarizer.d.ts.map +1 -1
  269. package/lib/summarizer.js +39 -18
  270. package/lib/summarizer.js.map +1 -1
  271. package/lib/summarizerClientElection.d.ts +1 -2
  272. package/lib/summarizerClientElection.d.ts.map +1 -1
  273. package/lib/summarizerClientElection.js +3 -30
  274. package/lib/summarizerClientElection.js.map +1 -1
  275. package/lib/summarizerHandle.d.ts.map +1 -1
  276. package/lib/summarizerHandle.js.map +1 -1
  277. package/lib/summarizerHeuristics.d.ts.map +1 -1
  278. package/lib/summarizerHeuristics.js +6 -9
  279. package/lib/summarizerHeuristics.js.map +1 -1
  280. package/lib/summarizerTypes.d.ts +22 -25
  281. package/lib/summarizerTypes.d.ts.map +1 -1
  282. package/lib/summarizerTypes.js.map +1 -1
  283. package/lib/summaryCollection.d.ts.map +1 -1
  284. package/lib/summaryCollection.js +18 -8
  285. package/lib/summaryCollection.js.map +1 -1
  286. package/lib/summaryFormat.d.ts.map +1 -1
  287. package/lib/summaryFormat.js +20 -13
  288. package/lib/summaryFormat.js.map +1 -1
  289. package/lib/summaryGenerator.d.ts.map +1 -1
  290. package/lib/summaryGenerator.js +32 -14
  291. package/lib/summaryGenerator.js.map +1 -1
  292. package/lib/summaryManager.d.ts.map +1 -1
  293. package/lib/summaryManager.js +21 -9
  294. package/lib/summaryManager.js.map +1 -1
  295. package/lib/throttler.d.ts +2 -2
  296. package/lib/throttler.d.ts.map +1 -1
  297. package/lib/throttler.js +4 -4
  298. package/lib/throttler.js.map +1 -1
  299. package/package.json +28 -38
  300. package/prettier.config.cjs +1 -1
  301. package/src/batchTracker.ts +55 -50
  302. package/src/blobManager.ts +802 -541
  303. package/src/connectionTelemetry.ts +280 -249
  304. package/src/containerHandleContext.ts +27 -29
  305. package/src/containerRuntime.ts +3125 -2982
  306. package/src/dataStore.ts +172 -159
  307. package/src/dataStoreContext.ts +1049 -992
  308. package/src/dataStoreContexts.ts +178 -161
  309. package/src/dataStoreRegistry.ts +25 -20
  310. package/src/dataStores.ts +785 -711
  311. package/src/deltaScheduler.ts +158 -150
  312. package/src/garbageCollection.ts +1797 -1558
  313. package/src/garbageCollectionConstants.ts +38 -0
  314. package/src/garbageCollectionHelpers.ts +37 -0
  315. package/src/gcSweepReadyUsageDetection.ts +90 -84
  316. package/src/index.ts +68 -69
  317. package/src/opLifecycle/batchManager.ts +167 -0
  318. package/src/opLifecycle/definitions.ts +70 -0
  319. package/src/opLifecycle/index.ts +18 -0
  320. package/src/opLifecycle/opCompressor.ts +82 -0
  321. package/src/opLifecycle/opDecompressor.ts +124 -0
  322. package/src/opLifecycle/opSplitter.ts +238 -0
  323. package/src/opLifecycle/outbox.ts +228 -0
  324. package/src/opLifecycle/remoteMessageProcessor.ts +106 -0
  325. package/src/opProperties.ts +11 -9
  326. package/src/orderedClientElection.ts +489 -457
  327. package/src/packageVersion.ts +1 -1
  328. package/src/pendingStateManager.ts +379 -381
  329. package/src/runWhileConnectedCoordinator.ts +78 -71
  330. package/src/runningSummarizer.ts +619 -582
  331. package/src/scheduleManager.ts +299 -280
  332. package/src/serializedSnapshotStorage.ts +116 -111
  333. package/src/summarizer.ts +417 -381
  334. package/src/summarizerClientElection.ts +107 -129
  335. package/src/summarizerHandle.ts +11 -9
  336. package/src/summarizerHeuristics.ts +183 -186
  337. package/src/summarizerTypes.ts +344 -333
  338. package/src/summaryCollection.ts +378 -349
  339. package/src/summaryFormat.ts +146 -127
  340. package/src/summaryGenerator.ts +464 -406
  341. package/src/summaryManager.ts +377 -348
  342. package/src/throttler.ts +131 -122
  343. package/tsconfig.esnext.json +6 -6
  344. package/tsconfig.json +9 -13
  345. package/dist/batchManager.d.ts +0 -42
  346. package/dist/batchManager.d.ts.map +0 -1
  347. package/dist/batchManager.js +0 -83
  348. package/dist/batchManager.js.map +0 -1
  349. package/dist/opCompressor.d.ts.map +0 -1
  350. package/dist/opCompressor.js +0 -50
  351. package/dist/opCompressor.js.map +0 -1
  352. package/dist/opDecompressor.d.ts.map +0 -1
  353. package/dist/opDecompressor.js.map +0 -1
  354. package/lib/batchManager.d.ts +0 -42
  355. package/lib/batchManager.d.ts.map +0 -1
  356. package/lib/batchManager.js +0 -79
  357. package/lib/batchManager.js.map +0 -1
  358. package/lib/opCompressor.d.ts.map +0 -1
  359. package/lib/opCompressor.js +0 -46
  360. package/lib/opCompressor.js.map +0 -1
  361. package/lib/opDecompressor.d.ts.map +0 -1
  362. package/lib/opDecompressor.js.map +0 -1
  363. package/src/batchManager.ts +0 -108
  364. package/src/opCompressor.ts +0 -59
  365. package/src/opDecompressor.ts +0 -82
@@ -6,19 +6,45 @@
6
6
  import { v4 as uuid } from "uuid";
7
7
  import { IFluidHandle, IFluidHandleContext } from "@fluidframework/core-interfaces";
8
8
  import { IDocumentStorageService } from "@fluidframework/driver-definitions";
9
- import { ICreateBlobResponse, ISequencedDocumentMessage, ISnapshotTree } from "@fluidframework/protocol-definitions";
10
- import { generateHandleContextPath, SummaryTreeBuilder } from "@fluidframework/runtime-utils";
11
- import { ITelemetryLogger } from "@fluidframework/common-definitions";
12
- import { assert, bufferToString, Deferred, stringToBuffer, TypedEventEmitter } from "@fluidframework/common-utils";
13
- import { IContainerRuntime, IContainerRuntimeEvents } from "@fluidframework/container-runtime-definitions";
9
+ import {
10
+ ICreateBlobResponse,
11
+ ISequencedDocumentMessage,
12
+ ISnapshotTree,
13
+ } from "@fluidframework/protocol-definitions";
14
+ import {
15
+ createResponseError,
16
+ generateHandleContextPath,
17
+ responseToException,
18
+ SummaryTreeBuilder,
19
+ } from "@fluidframework/runtime-utils";
20
+ import {
21
+ assert,
22
+ bufferToString,
23
+ Deferred,
24
+ stringToBuffer,
25
+ TypedEventEmitter,
26
+ } from "@fluidframework/common-utils";
27
+ import {
28
+ IContainerRuntime,
29
+ IContainerRuntimeEvents,
30
+ } from "@fluidframework/container-runtime-definitions";
14
31
  import { AttachState } from "@fluidframework/container-definitions";
15
- import { ChildLogger, PerformanceEvent } from "@fluidframework/telemetry-utils";
16
32
  import {
17
- IGarbageCollectionData,
18
- ISummaryTreeWithStats,
19
- ITelemetryContext,
33
+ ChildLogger,
34
+ loggerToMonitoringContext,
35
+ MonitoringContext,
36
+ PerformanceEvent,
37
+ } from "@fluidframework/telemetry-utils";
38
+ import {
39
+ IGarbageCollectionData,
40
+ ISummaryTreeWithStats,
41
+ ITelemetryContext,
20
42
  } from "@fluidframework/runtime-definitions";
43
+ import { TombstoneResponseHeaderKey } from "./containerRuntime";
21
44
  import { Throttler, formExponentialFn, IThrottler } from "./throttler";
45
+ import { summarizerClientType } from "./summarizerClientElection";
46
+ import { throwOnTombstoneLoadKey } from "./garbageCollectionConstants";
47
+ import { sendGCUnexpectedUsageEvent } from "./garbageCollectionHelpers";
22
48
 
23
49
  /**
24
50
  * This class represents blob (long string)
@@ -28,564 +54,799 @@ import { Throttler, formExponentialFn, IThrottler } from "./throttler";
28
54
  * and loads blob.
29
55
  */
30
56
  export class BlobHandle implements IFluidHandle<ArrayBufferLike> {
31
- private attached: boolean = false;
57
+ private attached: boolean = false;
32
58
 
33
- public get IFluidHandle(): IFluidHandle { return this; }
59
+ public get IFluidHandle(): IFluidHandle {
60
+ return this;
61
+ }
34
62
 
35
- public get isAttached(): boolean {
36
- return this.attached;
37
- }
63
+ public get isAttached(): boolean {
64
+ return this.attached;
65
+ }
38
66
 
39
- public readonly absolutePath: string;
67
+ public readonly absolutePath: string;
40
68
 
41
- constructor(
42
- public readonly path: string,
43
- public readonly routeContext: IFluidHandleContext,
44
- public get: () => Promise<any>,
45
- ) {
46
- this.absolutePath = generateHandleContextPath(path, this.routeContext);
47
- }
69
+ constructor(
70
+ public readonly path: string,
71
+ public readonly routeContext: IFluidHandleContext,
72
+ public get: () => Promise<any>,
73
+ ) {
74
+ this.absolutePath = generateHandleContextPath(path, this.routeContext);
75
+ }
48
76
 
49
- public attachGraph() {
50
- this.attached = true;
51
- }
77
+ public attachGraph() {
78
+ this.attached = true;
79
+ }
52
80
 
53
- public bind(handle: IFluidHandle) {
54
- throw new Error("Cannot bind to blob handle");
55
- }
81
+ public bind(handle: IFluidHandle) {
82
+ throw new Error("Cannot bind to blob handle");
83
+ }
56
84
  }
57
85
 
58
86
  class CancellableThrottler {
59
- constructor(private readonly throttler: IThrottler) { }
60
- private cancelP = new Deferred<void>();
61
-
62
- public async getDelay(): Promise<void> {
63
- return Promise.race([
64
- this.cancelP.promise,
65
- new Promise<void>((resolve) => setTimeout(resolve, this.throttler.getDelay())),
66
- ]);
67
- }
68
-
69
- public cancel() {
70
- this.cancelP.resolve();
71
- this.cancelP = new Deferred<void>();
72
- }
87
+ constructor(private readonly throttler: IThrottler) {}
88
+ private cancelP = new Deferred<void>();
89
+
90
+ public async getDelay(): Promise<void> {
91
+ return Promise.race([
92
+ this.cancelP.promise,
93
+ new Promise<void>((resolve) => setTimeout(resolve, this.throttler.getDelay())),
94
+ ]);
95
+ }
96
+
97
+ public cancel() {
98
+ this.cancelP.resolve();
99
+ this.cancelP = new Deferred<void>();
100
+ }
73
101
  }
74
102
 
75
103
  /**
76
104
  * Information from a snapshot needed to load BlobManager
77
105
  */
78
106
  export interface IBlobManagerLoadInfo {
79
- ids?: string[];
80
- redirectTable?: [string, string][];
107
+ ids?: string[];
108
+ redirectTable?: [string, string][];
81
109
  }
82
110
 
83
111
  // Restrict the IContainerRuntime interface to the subset required by BlobManager. This helps to make
84
112
  // the contract explicit and reduces the amount of mocking required for tests.
85
- export type IBlobManagerRuntime =
86
- Pick<IContainerRuntime, "attachState" | "connected" | "logger"> & TypedEventEmitter<IContainerRuntimeEvents>;
113
+ export type IBlobManagerRuntime = Pick<
114
+ IContainerRuntime,
115
+ "attachState" | "connected" | "logger" | "clientDetails"
116
+ > &
117
+ TypedEventEmitter<IContainerRuntimeEvents>;
87
118
 
88
119
  // Note that while offline we "submit" an op before uploading the blob, but we always
89
120
  // expect blobs to be uploaded before we actually see the op round-trip
90
121
  enum PendingBlobStatus {
91
- OnlinePendingUpload,
92
- OnlinePendingOp,
93
- OfflinePendingUpload,
94
- OfflinePendingOp,
122
+ OnlinePendingUpload,
123
+ OnlinePendingOp,
124
+ OfflinePendingUpload,
125
+ OfflinePendingOp,
95
126
  }
96
127
 
128
+ type ICreateBlobResponseWithTTL = ICreateBlobResponse & Partial<Record<"minTTLInSeconds", number>>;
129
+
97
130
  interface PendingBlob {
98
- blob: ArrayBufferLike;
99
- status: PendingBlobStatus;
100
- storageId?: string;
101
- handleP: Deferred<IFluidHandle<ArrayBufferLike>>;
102
- uploadP: Promise<ICreateBlobResponse>;
131
+ blob: ArrayBufferLike;
132
+ status: PendingBlobStatus;
133
+ storageId?: string;
134
+ handleP: Deferred<IFluidHandle<ArrayBufferLike>>;
135
+ uploadP: Promise<ICreateBlobResponse>;
136
+ localUploadTime?: number;
137
+ serverUploadTime?: number;
138
+ minTTLInSeconds?: number;
139
+ }
140
+
141
+ export interface IPendingBlobs {
142
+ [id: string]: { blob: string };
143
+ }
144
+
145
+ export interface IBlobManagerEvents {
146
+ (event: "noPendingBlobs", listener: () => void);
103
147
  }
104
148
 
105
- export interface IPendingBlobs { [id: string]: { blob: string; }; }
106
-
107
- export class BlobManager {
108
- public static readonly basePath = "_blobs";
109
- private static readonly redirectTableBlobName = ".redirectTable";
110
- private readonly logger: ITelemetryLogger;
111
-
112
- /**
113
- * Map of local (offline/detached) IDs to storage IDs. Contains identity entries
114
- * (id id) for storage IDs, so all requested IDs should be a key in this map.
115
- * Blobs created while the container is detached are stored in IDetachedBlobStorage
116
- * which gives local IDs; the storage IDs are filled in at attach time.
117
- */
118
- private readonly redirectTable: Map<string, string | undefined>;
119
-
120
- /**
121
- * Blobs which have not been uploaded or for which we have not yet seen a BlobAttach op round-trip.
122
- * Until we see the op round-trip, there is a possibility we may need to re-upload the blob, so
123
- * we must save it. This is true for both the online and offline flow.
124
- */
125
- private readonly pendingBlobs: Map<string, PendingBlob> = new Map();
126
-
127
- /**
128
- * Track ops in flight for online flow. Used to avoid searching pendingBlobs since BlobAttach ops
129
- * don't include local ID in online flow.
130
- */
131
- private readonly opsInFlight: Map<string, string[]> = new Map();
132
-
133
- private readonly retryThrottler = new CancellableThrottler(new Throttler(
134
- 60 * 1000, // 60 sec delay window
135
- 30 * 1000, // 30 sec max delay
136
- // throttling function increases exponentially (0ms, 40ms, 80ms, 160ms, etc)
137
- formExponentialFn({ coefficient: 20, initialDelay: 0 }),
138
- ));
139
-
140
- constructor(
141
- private readonly routeContext: IFluidHandleContext,
142
- snapshot: IBlobManagerLoadInfo,
143
- private readonly getStorage: () => IDocumentStorageService,
144
- /**
145
- * Submit a BlobAttach op. When a blob is uploaded, there is a short grace period before which
146
- * the blob is deleted. The BlobAttach op notifies the server that blob is in use. The server
147
- * will then not delete the blob as long as it is listed as referenced in future summaries.
148
- * The summarizing client will know to include the storage ID in the summary when it sees the op.
149
- *
150
- * The op may also include a local ID to inform all clients of the relation to the storage
151
- * ID, without knowledge of which they cannot request the blob from storage. This is also
152
- * included in the redirect table in the summary.
153
- */
154
- private readonly sendBlobAttachOp: (storageId?: string, localId?: string) => void,
155
- // To be called when a blob node is requested. blobPath is the path of the blob's node in GC's graph. It's
156
- // of the format `/<BlobManager.basePath>/<blobId>`.
157
- private readonly gcNodeUpdated: (blobPath: string) => void,
158
- private readonly runtime: IBlobManagerRuntime,
159
- stashedBlobs: IPendingBlobs = {},
160
- ) {
161
- this.logger = ChildLogger.create(this.runtime.logger, "BlobManager");
162
- this.runtime.on("disconnected", () => this.onDisconnected());
163
- this.redirectTable = this.load(snapshot);
164
-
165
- // Begin uploading stashed blobs from previous container instance
166
- Object.entries(stashedBlobs).forEach(([localId, entry]) => {
167
- const blob = stringToBuffer(entry.blob, "base64");
168
- this.pendingBlobs.set(localId, {
169
- blob,
170
- status: PendingBlobStatus.OfflinePendingUpload,
171
- handleP: new Deferred(),
172
- uploadP: this.uploadBlob(localId, blob),
173
- });
174
- });
175
- }
176
-
177
- private get pendingOfflineUploads() {
178
- return Array.from(this.pendingBlobs.values())
179
- .filter((e) => e.status === PendingBlobStatus.OfflinePendingUpload);
180
- }
181
-
182
- public get hasPendingOfflineUploads(): boolean {
183
- return this.pendingOfflineUploads.length > 0;
184
- }
185
-
186
- /**
187
- * Upload blobs added while offline. This must be completed before connecting and resubmitting ops.
188
- */
189
- public async onConnected() {
190
- this.retryThrottler.cancel();
191
- const pendingUploads = this.pendingOfflineUploads.map(async (e) => e.uploadP);
192
- await PerformanceEvent.timedExecAsync(this.logger, {
193
- eventName: "BlobUploadOnConnected",
194
- count: pendingUploads.length,
195
- }, async () => Promise.all(pendingUploads),
196
- { start: true, end: true },
197
- );
198
- }
199
-
200
- /**
201
- * Transition online blobs waiting for BlobAttach op round-trip since we will not see the op until we are connected
202
- * again
203
- */
204
- private onDisconnected() {
205
- for (const [localId, entry] of this.pendingBlobs) {
206
- if (entry.status === PendingBlobStatus.OnlinePendingOp) {
207
- // This will submit another BlobAttach op for this blob. This is necessary because the one we sent
208
- // already didn't have the local ID.
209
- this.transitionToOffline(localId);
210
- }
211
- }
212
- }
213
-
214
- /**
215
- * For a blobId, returns its path in GC's graph. The node path is of the format `/<BlobManager.basePath>/<blobId>`
216
- * This path must match the path of the blob handle returned by the createBlob API because blobs are marked
217
- * referenced by storing these handles in a referenced DDS.
218
- */
219
- private getBlobGCNodePath(blobId: string) {
220
- return `/${BlobManager.basePath}/${blobId}`;
221
- }
222
-
223
- /**
224
- * Set of actual storage IDs (i.e., IDs that can be requested from storage). This will be empty if the container is
225
- * detached or there are no (non-pending) attachment blobs in the document
226
- */
227
- private get storageIds(): Set<string> {
228
- const ids = new Set<string | undefined>(this.redirectTable.values());
229
-
230
- // If we are detached, we will not have storage IDs, only undefined
231
- const undefinedValueInTable = ids.delete(undefined);
232
-
233
- // For a detached container, entries are inserted into the redirect table with an undefined storage ID.
234
- // For an attached container, entries are inserted w/storage ID after the BlobAttach op round-trips.
235
- assert(!undefinedValueInTable || this.runtime.attachState === AttachState.Detached && ids.size === 0,
236
- 0x382 /* 'redirectTable' must contain only undefined while detached / defined values while attached */);
237
-
238
- return ids as Set<string>;
239
- }
240
-
241
- public async getBlob(blobId: string): Promise<ArrayBufferLike> {
242
- const pending = this.pendingBlobs.get(blobId);
243
- if (pending) {
244
- return pending.blob;
245
- }
246
- let storageId;
247
- if (this.runtime.attachState === AttachState.Detached) {
248
- assert(this.redirectTable.has(blobId), 0x383 /* requesting unknown blobs */);
249
-
250
- // Blobs created while the container is detached are stored in IDetachedBlobStorage.
251
- // The 'IDocumentStorageService.readBlob()' call below will retrieve these via localId.
252
- storageId = blobId;
253
- } else {
254
- storageId = this.redirectTable.get(blobId);
255
- assert(!!storageId, 0x11f /* "requesting unknown blobs" */);
256
- }
257
-
258
- // When a GC-able (not pending) blob is retrieved, let runtime know that the corresponding GC node got updated.
259
- this.gcNodeUpdated(this.getBlobGCNodePath(blobId));
260
-
261
- return PerformanceEvent.timedExecAsync(
262
- this.logger,
263
- { eventName: "AttachmentReadBlob", id: storageId },
264
- async () => {
265
- return this.getStorage().readBlob(storageId);
266
- },
267
- { end: true, cancel: "error" },
268
- );
269
- }
270
-
271
- private getBlobHandle(id: string): IFluidHandle<ArrayBufferLike> {
272
- assert(this.redirectTable.has(id) || this.pendingBlobs.has(id),
273
- 0x384 /* requesting handle for unknown blob */);
274
- return new BlobHandle(
275
- `${BlobManager.basePath}/${id}`,
276
- this.routeContext,
277
- async () => this.getBlob(id),
278
- );
279
- }
280
-
281
- private async createBlobDetached(blob: ArrayBufferLike): Promise<IFluidHandle<ArrayBufferLike>> {
282
- // Blobs created while the container is detached are stored in IDetachedBlobStorage.
283
- // The 'IDocumentStorageService.createBlob()' call below will respond with a localId.
284
- const response = await this.getStorage().createBlob(blob);
285
- this.redirectTable.set(response.id, undefined);
286
- return this.getBlobHandle(response.id);
287
- }
288
-
289
- public async createBlob(blob: ArrayBufferLike): Promise<IFluidHandle<ArrayBufferLike>> {
290
- if (this.runtime.attachState === AttachState.Detached) {
291
- return this.createBlobDetached(blob);
292
- }
293
- if (this.runtime.attachState === AttachState.Attaching) {
294
- // blob upload is not supported in "Attaching" state
295
- this.logger.sendTelemetryEvent({ eventName: "CreateBlobWhileAttaching" });
296
- await new Promise<void>((resolve) => this.runtime.once("attached", resolve));
297
- }
298
- assert(this.runtime.attachState === AttachState.Attached,
299
- 0x385 /* For clarity and paranoid defense against adding future attachment states */);
300
-
301
- // Create a local ID for each blob. This is used to support blobs if/when the client goes
302
- // offline since we don't have the ID from storage yet. If online flow succeeds this won't be used.
303
- const localId = uuid();
304
- const pendingEntry: PendingBlob = {
305
- blob,
306
- status: PendingBlobStatus.OnlinePendingUpload,
307
- handleP: new Deferred(),
308
- uploadP: this.uploadBlob(localId, blob),
309
- };
310
- this.pendingBlobs.set(localId, pendingEntry);
311
-
312
- return pendingEntry.handleP.promise;
313
- }
314
-
315
- private async uploadBlob(localId: string, blob: ArrayBufferLike): Promise<ICreateBlobResponse> {
316
- return PerformanceEvent.timedExecAsync(
317
- this.logger,
318
- { eventName: "createBlob" },
319
- async () => this.getStorage().createBlob(blob),
320
- { end: true, cancel: this.runtime.connected ? "error" : "generic" },
321
- ).then(
322
- (response) => this.onUploadResolve(localId, response),
323
- async (err) => this.onUploadReject(localId, err),
324
- );
325
- }
326
-
327
- private onUploadResolve(localId: string, response: ICreateBlobResponse) {
328
- const entry = this.pendingBlobs.get(localId);
329
- assert(entry?.status === PendingBlobStatus.OnlinePendingUpload ||
330
- entry?.status === PendingBlobStatus.OfflinePendingUpload,
331
- 0x386 /* Must have pending blob entry for uploaded blob */);
332
- entry.storageId = response.id;
333
- if (this.runtime.connected) {
334
- if (entry.status === PendingBlobStatus.OnlinePendingUpload) {
335
- if (this.storageIds.has(response.id)) {
336
- // Storage may dedupe blobs and give us an ID we already know
337
- // no need to submit BlobAttach op in this case
338
- entry.handleP.resolve(this.getBlobHandle(response.id));
339
- this.pendingBlobs.delete(localId);
340
- } else {
341
- // Check for still-pending duplicates too; if an op is already in flight we can wait for that one
342
- if (!this.opsInFlight.has(response.id)) {
343
- this.sendBlobAttachOp(response.id);
344
- }
345
- this.opsInFlight.set(response.id, (this.opsInFlight.get(response.id) ?? []).concat(localId));
346
- entry.status = PendingBlobStatus.OnlinePendingOp;
347
- }
348
- } else if (entry.status === PendingBlobStatus.OfflinePendingUpload) {
349
- // We already submitted a BlobAttach op for this blob when it was transitioned to offline flow
350
- entry.status = PendingBlobStatus.OfflinePendingOp;
351
- }
352
- } else {
353
- // connected to storage but not ordering service?
354
- this.logger.sendTelemetryEvent({ eventName: "BlobUploadSuccessWhileDisconnected" });
355
- if (entry.status === PendingBlobStatus.OnlinePendingUpload) {
356
- this.transitionToOffline(localId);
357
- }
358
- entry.status = PendingBlobStatus.OfflinePendingOp;
359
- }
360
- return response;
361
- }
362
-
363
- private async onUploadReject(localId: string, error) {
364
- const entry = this.pendingBlobs.get(localId);
365
- assert(!!entry, 0x387 /* Must have pending blob entry for blob which failed to upload */);
366
- if (!this.runtime.connected) {
367
- if (entry.status === PendingBlobStatus.OnlinePendingUpload) {
368
- this.transitionToOffline(localId);
369
- }
370
- // we are probably not connected to storage but start another upload request in case we are
371
- entry.uploadP = this.retryThrottler.getDelay().then(async () => this.uploadBlob(localId, entry.blob));
372
- return entry.uploadP;
373
- } else {
374
- entry.handleP.reject(error);
375
- throw error;
376
- }
377
- }
378
-
379
- private transitionToOffline(localId: string) {
380
- assert(!this.runtime.connected, 0x388 /* Must only transition to offline flow while runtime is disconnected */);
381
- const entry = this.pendingBlobs.get(localId);
382
- assert(!!entry, 0x389 /* No pending blob entry */);
383
- assert([PendingBlobStatus.OnlinePendingUpload, PendingBlobStatus.OnlinePendingOp].includes(entry.status),
384
- 0x38a /* Blob must be in online flow to transition to offline flow */);
385
-
386
- entry.status = entry.status === PendingBlobStatus.OnlinePendingUpload
387
- ? PendingBlobStatus.OfflinePendingUpload
388
- : PendingBlobStatus.OfflinePendingOp;
389
-
390
- // Submit a BlobAttach op. It's important we submit this op now before returning the blob handle so the
391
- // BlobAttach op is sequenced prior to any ops referencing the handle. Otherwise an invalid handle could be
392
- // added to the document if the ops are not all successfully submitted upon reconnection.
393
- // storageId may be undefined but since we are not connected we will have a chance to add it when reSubmit()
394
- // is called
395
- this.sendBlobAttachOp(entry.storageId, localId);
396
- entry.handleP.resolve(this.getBlobHandle(localId));
397
- }
398
-
399
- /**
400
- * Resubmit a BlobAttach op. Used to add storage IDs to ops that were
401
- * submitted to runtime while disconnected.
402
- * @param metadata - op metadata containing storage and/or local IDs
403
- */
404
- public reSubmit(metadata: Record<string, unknown> | undefined) {
405
- assert(!!metadata, 0x38b /* Resubmitted ops must have metadata */);
406
- const { blobId, localId }: { blobId?: string; localId?: string; } = metadata;
407
- if (!blobId) {
408
- assert(!!localId, 0x38c /* Submitted BlobAttach ops must have a blobId or localId */);
409
- // We submitted this op while offline. The blob should have been uploaded by now.
410
- const pendingEntry = this.pendingBlobs.get(localId);
411
- assert(pendingEntry?.status === PendingBlobStatus.OfflinePendingOp &&
412
- !!pendingEntry?.storageId, 0x38d /* blob must be uploaded before resubmitting BlobAttach op */);
413
- return this.sendBlobAttachOp(pendingEntry.storageId, localId);
414
- }
415
- return this.sendBlobAttachOp(blobId, localId);
416
- }
417
-
418
- public processBlobAttachOp(message: ISequencedDocumentMessage, local: boolean) {
419
- assert(message?.metadata?.blobId, 0x12a /* "Missing blob id on metadata" */);
420
- if (message.metadata.localId !== undefined) {
421
- this.redirectTable.set(message.metadata.localId, message.metadata.blobId);
422
- }
423
- // set identity (id -> id) entry
424
- this.redirectTable.set(message.metadata.blobId, message.metadata.blobId);
425
-
426
- if (local) {
427
- if (message.metadata.localId === undefined) {
428
- // Since there is no local ID, we know this op was submitted while online.
429
- const waitingBlobs = this.opsInFlight.get(message.metadata.blobId);
430
- assert(!!waitingBlobs, 0x38e /* local online BlobAttach op with no pending blob */);
431
- waitingBlobs.forEach((localId) => {
432
- const pendingBlobEntry = this.pendingBlobs.get(localId);
433
- assert(
434
- pendingBlobEntry !== undefined,
435
- 0x38f, /* local online BlobAttach op with no pending blob entry */
436
- );
437
-
438
- // It's possible we transitioned to offline flow while waiting for this op.
439
- if (pendingBlobEntry.status === PendingBlobStatus.OnlinePendingOp) {
440
- pendingBlobEntry.handleP.resolve(this.getBlobHandle(message.metadata.blobId));
441
- this.pendingBlobs.delete(localId);
442
- }
443
- });
444
- } else {
445
- // Each local ID is unique; get the pending blob entry and delete it
446
- assert(this.pendingBlobs.get(message.metadata.localId)?.status === PendingBlobStatus.OfflinePendingOp,
447
- 0x1f8 /* "local BlobAttach op with no pending blob" */);
448
- this.pendingBlobs.delete(message.metadata.localId);
449
- }
450
- }
451
- }
452
-
453
- /**
454
- * Reads blobs needed to load BlobManager from storage.
455
- * @param blobsTree - Tree containing IDs of previously attached blobs. We
456
- * look for the IDs in the blob entries of the tree since the both the r11s
457
- * and SPO drivers replace the attachment types returned in snapshot() with blobs.
458
- */
459
- public static async load(
460
- blobsTree: ISnapshotTree | undefined,
461
- tryFetchBlob: (id: string) => Promise<[string, string][]>,
462
- ): Promise<IBlobManagerLoadInfo> {
463
- if (!blobsTree) {
464
- return {};
465
- }
466
- let redirectTable;
467
- const tableId = blobsTree.blobs[this.redirectTableBlobName];
468
- if (tableId) {
469
- redirectTable = await tryFetchBlob(tableId);
470
- }
471
- const ids = Object.entries(blobsTree.blobs)
472
- .filter(([k, _]) => k !== this.redirectTableBlobName).map(([_, v]) => v);
473
- return { ids, redirectTable };
474
- }
475
-
476
- /**
477
- * Load a set of previously attached blob IDs and redirect table from a previous snapshot.
478
- */
479
- private load(snapshot: IBlobManagerLoadInfo): Map<string, string | undefined> {
480
- this.logger.sendTelemetryEvent({
481
- eventName: "AttachmentBlobsLoaded",
482
- count: snapshot.ids?.length ?? 0,
483
- redirectTable: snapshot.redirectTable?.length,
484
- });
485
- const table = new Map<string, string | undefined>(snapshot.redirectTable);
486
- if (snapshot.ids) {
487
- const detached = this.runtime.attachState === AttachState.Detached;
488
- // If we are detached, we don't have storage IDs yet, so set to undefined
489
- // Otherwise, set identity (id -> id) entries
490
- snapshot.ids.forEach((entry) => table.set(entry, detached ? undefined : entry));
491
- }
492
- return table;
493
- }
494
-
495
- /**
496
- * Generates data used for garbage collection. Each blob uploaded represents a node in the GC graph as it can be
497
- * individually referenced by storing its handle in a referenced DDS. Returns the list of blob ids as GC nodes.
498
- * @param fullGC - true to bypass optimizations and force full generation of GC data. BlobManager doesn't care
499
- * about this for now because the data is a simple list of blob ids.
500
- */
501
- public getGCData(fullGC: boolean = false): IGarbageCollectionData {
502
- const gcData: IGarbageCollectionData = { gcNodes: {} };
503
- /**
504
- * The node path is of the format `/_blobs/blobId`. This path must match the path of the blob handle returned
505
- * by the createBlob API because blobs are marked referenced by storing these handles in a referenced DDS.
506
- */
507
- this.storageIds.forEach((blobId: string) => {
508
- gcData.gcNodes[this.getBlobGCNodePath(blobId)] = [];
509
- });
510
-
511
- // For some blobs, the handle returned on creation is based off of the localId. So, these
512
- // nodes can be referenced by storing the localId handle. When that happens, the corresponding storageId node
513
- // must also be marked referenced. So, we add a route from the localId node to the storageId node.
514
- // Note that because of de-duping, there can be multiple localIds that all redirect to the same storageId or
515
- // a blob may be referenced via its storageId handle.
516
- for (const [localId, storageId] of this.redirectTable) {
517
- assert(!!storageId, 0x390 /* Must be attached to get GC data */);
518
- // Add node for the localId and add a route to the storageId node. The storageId node will have been
519
- // added above when adding nodes for this.blobIds.
520
- gcData.gcNodes[this.getBlobGCNodePath(localId)] = [this.getBlobGCNodePath(storageId)];
521
- }
522
-
523
- return gcData;
524
- }
525
-
526
- /**
527
- * When running GC in test mode, this is called to delete blobs that are unused.
528
- * @param unusedRoutes - These are the blob node ids that are unused and should be deleted.
529
- */
530
- public deleteUnusedRoutes(unusedRoutes: string[]): void {
531
- // The routes or blob node paths are in the same format as returned in getGCData -
532
- // `/<BlobManager.basePath>/<blobId>`.
533
- for (const route of unusedRoutes) {
534
- const pathParts = route.split("/");
535
- assert(
536
- pathParts.length === 3 && pathParts[1] === BlobManager.basePath,
537
- 0x2d5 /* "Invalid blob node id in unused routes." */,
538
- );
539
- const blobId = pathParts[2];
540
-
541
- // The unused blobId could be a localId. If so, remove it from the redirect table and continue. The
542
- // corresponding storageId may still be used either directly or via other localIds.
543
- if (this.redirectTable?.has(blobId)) {
544
- this.redirectTable.delete(blobId);
545
- continue;
546
- }
547
- }
548
- }
549
-
550
- public summarize(telemetryContext?: ITelemetryContext): ISummaryTreeWithStats {
551
- // if storageIds is empty, it means we are detached and have only local IDs, or that there are no blobs attached
552
- const blobIds = this.storageIds.size > 0 ? Array.from(this.storageIds) : Array.from(this.redirectTable.keys());
553
- const builder = new SummaryTreeBuilder();
554
- blobIds.forEach((blobId) => {
555
- builder.addAttachment(blobId);
556
- });
557
-
558
- // Any non-identity entries in the table need to be saved in the summary
559
- if (this.redirectTable.size > blobIds.length) {
560
- builder.addBlob(
561
- BlobManager.redirectTableBlobName,
562
- // filter out identity entries
563
- JSON.stringify(Array.from(this.redirectTable.entries())
564
- .filter(([localId, storageId]) => localId !== storageId)),
565
- );
566
- }
567
-
568
- return builder.getSummaryTree();
569
- }
570
-
571
- public setRedirectTable(table: Map<string, string>) {
572
- assert(this.runtime.attachState === AttachState.Detached,
573
- 0x252 /* "redirect table can only be set in detached container" */);
574
- assert(this.redirectTable.size === table.size,
575
- 0x391 /* Redirect table size must match BlobManager's local ID count */);
576
- for (const [localId, storageId] of table) {
577
- assert(this.redirectTable.has(localId), 0x254 /* "unrecognized id in redirect table" */);
578
- this.redirectTable.set(localId, storageId);
579
- // set identity (id -> id) entry
580
- this.redirectTable.set(storageId, storageId);
581
- }
582
- }
583
-
584
- public getPendingBlobs(): IPendingBlobs {
585
- const blobs = {};
586
- for (const [key, entry] of this.pendingBlobs) {
587
- blobs[key] = { blob: bufferToString(entry.blob, "base64") };
588
- }
589
- return blobs;
590
- }
149
+ export class BlobManager extends TypedEventEmitter<IBlobManagerEvents> {
150
+ public static readonly basePath = "_blobs";
151
+ private static readonly redirectTableBlobName = ".redirectTable";
152
+ private readonly mc: MonitoringContext;
153
+
154
+ /**
155
+ * Map of local IDs to storage IDs. Contains identity entries (id → id) for storage IDs. All requested IDs should
156
+ * be a key in this map. Blobs created while the container is detached are stored in IDetachedBlobStorage which
157
+ * gives local IDs; the storage IDs are filled in at attach time.
158
+ * Note: It contains mappings from all clients, i.e., from remote clients as well. local ID comes from the client
159
+ * that uploaded the blob but its mapping to storage ID is needed in all clients in order to retrieve the blob.
160
+ */
161
+ private readonly redirectTable: Map<string, string | undefined>;
162
+
163
+ /**
164
+ * Blobs which have not been uploaded or for which we have not yet seen a BlobAttach op round-trip.
165
+ * Until we see the op round-trip, there is a possibility we may need to re-upload the blob, so
166
+ * we must save it. This is true for both the online and offline flow.
167
+ */
168
+ private readonly pendingBlobs: Map<string, PendingBlob> = new Map();
169
+
170
+ /**
171
+ * Track ops in flight for online flow. This is used for optimizations where if we receive an ack for a storage ID,
172
+ * we can resolve all pending blobs with the same storage ID even though they may have different local IDs. That's
173
+ * because we know that the server will not delete the blob corresponding to that storage ID.
174
+ */
175
+ private readonly opsInFlight: Map<string, string[]> = new Map();
176
+
177
+ private readonly retryThrottler = new CancellableThrottler(
178
+ new Throttler(
179
+ 60 * 1000, // 60 sec delay window
180
+ 30 * 1000, // 30 sec max delay
181
+ // throttling function increases exponentially (0ms, 40ms, 80ms, 160ms, etc)
182
+ formExponentialFn({ coefficient: 20, initialDelay: 0 }),
183
+ ),
184
+ );
185
+
186
+ /** If true, throw an error when a tombstone attachment blob is retrieved. */
187
+ private readonly throwOnTombstoneLoad: boolean;
188
+ /**
189
+ * This stores IDs of tombstoned blobs.
190
+ * Tombstone is a temporary feature that imitates a blob getting swept by garbage collection.
191
+ */
192
+ private readonly tombstonedBlobs: Set<string> = new Set();
193
+
194
+ constructor(
195
+ private readonly routeContext: IFluidHandleContext,
196
+ snapshot: IBlobManagerLoadInfo,
197
+ private readonly getStorage: () => IDocumentStorageService,
198
+ /**
199
+ * Submit a BlobAttach op. When a blob is uploaded, there is a short grace period before which the blob is
200
+ * deleted. The BlobAttach op notifies the server that blob is in use. The server will then not delete the
201
+ * the blob as long as it is listed as referenced in future summaries. The summarizing client will know to
202
+ * include the storage ID in the summary when it sees the op.
203
+ *
204
+ * The op will also include a local ID to inform all clients of the relation to the storage ID, without
205
+ * knowledge of which they cannot request the blob from storage. It's important that this op is sequenced
206
+ * before any ops that reference the local ID, otherwise, an invalid handle could be added to the document.
207
+ */
208
+ private readonly sendBlobAttachOp: (localId: string, storageId?: string) => void,
209
+ // Called when a blob node is requested. blobPath is the path of the blob's node in GC's graph.
210
+ // blobPath's format - `/<BlobManager.basePath>/<blobId>`.
211
+ private readonly blobRequested: (blobPath: string) => void,
212
+ // Called when a reference is added to a blob. For instance, when creating a localId / storageId to storageId
213
+ // mapping in the redirect table.
214
+ // Node path formats - `/<BlobManager.basePath>/<blobId>`.
215
+ private readonly addedBlobReference: (fromNodePath: string, toNodePath: string) => void,
216
+ // Called to check if a blob has been deleted by GC.
217
+ // blobPath's format - `/<BlobManager.basePath>/<blobId>`.
218
+ private readonly isBlobDeleted: (blobPath: string) => boolean,
219
+ private readonly runtime: IBlobManagerRuntime,
220
+ stashedBlobs: IPendingBlobs = {},
221
+ private readonly getCurrentReferenceTimestampMs: () => number | undefined,
222
+ ) {
223
+ super();
224
+ this.mc = loggerToMonitoringContext(ChildLogger.create(this.runtime.logger, "BlobManager"));
225
+ // Read the feature flag that tells whether to throw when a tombstone blob is requested.
226
+ this.throwOnTombstoneLoad =
227
+ this.mc.config.getBoolean(throwOnTombstoneLoadKey) === true &&
228
+ this.runtime.clientDetails.type !== summarizerClientType;
229
+
230
+ this.runtime.on("disconnected", () => this.onDisconnected());
231
+ this.redirectTable = this.load(snapshot);
232
+
233
+ // Begin uploading stashed blobs from previous container instance
234
+ Object.entries(stashedBlobs).forEach(([localId, entry]) => {
235
+ const blob = stringToBuffer(entry.blob, "base64");
236
+ this.pendingBlobs.set(localId, {
237
+ blob,
238
+ status: PendingBlobStatus.OfflinePendingUpload,
239
+ handleP: new Deferred(),
240
+ uploadP: this.uploadBlob(localId, blob),
241
+ });
242
+ });
243
+ }
244
+
245
+ private get pendingOfflineUploads() {
246
+ return Array.from(this.pendingBlobs.values()).filter(
247
+ (e) => e.status === PendingBlobStatus.OfflinePendingUpload,
248
+ );
249
+ }
250
+
251
+ public get hasPendingOfflineUploads(): boolean {
252
+ return this.pendingOfflineUploads.length > 0;
253
+ }
254
+
255
+ public get hasPendingBlobs(): boolean {
256
+ return (
257
+ (this.runtime.attachState !== AttachState.Attached && this.redirectTable.size > 0) ||
258
+ this.pendingBlobs.size > 0
259
+ );
260
+ }
261
+
262
+ /**
263
+ * Upload blobs added while offline. This must be completed before connecting and resubmitting ops.
264
+ */
265
+ public async onConnected() {
266
+ this.retryThrottler.cancel();
267
+ const pendingUploads = this.pendingOfflineUploads.map(async (e) => e.uploadP);
268
+ await PerformanceEvent.timedExecAsync(
269
+ this.mc.logger,
270
+ {
271
+ eventName: "BlobUploadOnConnected",
272
+ count: pendingUploads.length,
273
+ },
274
+ async () => Promise.all(pendingUploads),
275
+ { start: true, end: true },
276
+ );
277
+ }
278
+
279
+ /**
280
+ * Transition online blobs waiting for BlobAttach op round-trip since we will not see the op until we are connected
281
+ * again
282
+ */
283
+ private onDisconnected() {
284
+ for (const [localId, entry] of this.pendingBlobs) {
285
+ if (entry.status === PendingBlobStatus.OnlinePendingOp) {
286
+ // This will submit another BlobAttach op for this blob. This is necessary because the one we sent
287
+ // already didn't have the local ID.
288
+ this.transitionToOffline(localId);
289
+ }
290
+ }
291
+ }
292
+
293
+ /**
294
+ * For a blobId, returns its path in GC's graph. The node path is of the format `/<BlobManager.basePath>/<blobId>`
295
+ * This path must match the path of the blob handle returned by the createBlob API because blobs are marked
296
+ * referenced by storing these handles in a referenced DDS.
297
+ */
298
+ private getBlobGCNodePath(blobId: string) {
299
+ return `/${BlobManager.basePath}/${blobId}`;
300
+ }
301
+
302
+ /**
303
+ * Set of actual storage IDs (i.e., IDs that can be requested from storage). This will be empty if the container is
304
+ * detached or there are no (non-pending) attachment blobs in the document
305
+ */
306
+ private get storageIds(): Set<string> {
307
+ const ids = new Set<string | undefined>(this.redirectTable.values());
308
+
309
+ // If we are detached, we will not have storage IDs, only undefined
310
+ const undefinedValueInTable = ids.delete(undefined);
311
+
312
+ // For a detached container, entries are inserted into the redirect table with an undefined storage ID.
313
+ // For an attached container, entries are inserted w/storage ID after the BlobAttach op round-trips.
314
+ assert(
315
+ !undefinedValueInTable ||
316
+ (this.runtime.attachState === AttachState.Detached && ids.size === 0),
317
+ 0x382 /* 'redirectTable' must contain only undefined while detached / defined values while attached */,
318
+ );
319
+
320
+ return ids as Set<string>;
321
+ }
322
+
323
+ public async getBlob(blobId: string): Promise<ArrayBufferLike> {
324
+ // Verify that the blob is valid, i.e., it has not been garbage collected. If it is, this will throw an error,
325
+ // failing the call.
326
+ this.verifyBlobValidity(blobId);
327
+
328
+ const pending = this.pendingBlobs.get(blobId);
329
+ if (pending) {
330
+ return pending.blob;
331
+ }
332
+ let storageId: string;
333
+ if (this.runtime.attachState === AttachState.Detached) {
334
+ assert(this.redirectTable.has(blobId), 0x383 /* requesting unknown blobs */);
335
+
336
+ // Blobs created while the container is detached are stored in IDetachedBlobStorage.
337
+ // The 'IDocumentStorageService.readBlob()' call below will retrieve these via localId.
338
+ storageId = blobId;
339
+ } else {
340
+ const attachedStorageId = this.redirectTable.get(blobId);
341
+ assert(!!attachedStorageId, 0x11f /* "requesting unknown blobs" */);
342
+ storageId = attachedStorageId;
343
+ }
344
+
345
+ // Let runtime know that the corresponding GC node was requested.
346
+ this.blobRequested(this.getBlobGCNodePath(blobId));
347
+
348
+ return PerformanceEvent.timedExecAsync(
349
+ this.mc.logger,
350
+ { eventName: "AttachmentReadBlob", id: storageId },
351
+ async () => {
352
+ return this.getStorage().readBlob(storageId);
353
+ },
354
+ { end: true, cancel: "error" },
355
+ );
356
+ }
357
+
358
+ private getBlobHandle(id: string): IFluidHandle<ArrayBufferLike> {
359
+ assert(
360
+ this.redirectTable.has(id) || this.pendingBlobs.has(id),
361
+ 0x384 /* requesting handle for unknown blob */,
362
+ );
363
+ return new BlobHandle(`${BlobManager.basePath}/${id}`, this.routeContext, async () =>
364
+ this.getBlob(id),
365
+ );
366
+ }
367
+
368
+ private async createBlobDetached(
369
+ blob: ArrayBufferLike,
370
+ ): Promise<IFluidHandle<ArrayBufferLike>> {
371
+ // Blobs created while the container is detached are stored in IDetachedBlobStorage.
372
+ // The 'IDocumentStorageService.createBlob()' call below will respond with a localId.
373
+ const response = await this.getStorage().createBlob(blob);
374
+ this.setRedirection(response.id, undefined);
375
+ return this.getBlobHandle(response.id);
376
+ }
377
+
378
+ public async createBlob(blob: ArrayBufferLike): Promise<IFluidHandle<ArrayBufferLike>> {
379
+ if (this.runtime.attachState === AttachState.Detached) {
380
+ return this.createBlobDetached(blob);
381
+ }
382
+ if (this.runtime.attachState === AttachState.Attaching) {
383
+ // blob upload is not supported in "Attaching" state
384
+ this.mc.logger.sendTelemetryEvent({ eventName: "CreateBlobWhileAttaching" });
385
+ await new Promise<void>((resolve) => this.runtime.once("attached", resolve));
386
+ }
387
+ assert(
388
+ this.runtime.attachState === AttachState.Attached,
389
+ 0x385 /* For clarity and paranoid defense against adding future attachment states */,
390
+ );
391
+
392
+ // Create a local ID for the blob. After uploading it to storage and before returning it, a local ID to
393
+ // storage ID mapping is created.
394
+ const localId = uuid();
395
+ const pendingEntry: PendingBlob = {
396
+ blob,
397
+ status: PendingBlobStatus.OnlinePendingUpload,
398
+ handleP: new Deferred(),
399
+ uploadP: this.uploadBlob(localId, blob),
400
+ };
401
+ this.pendingBlobs.set(localId, pendingEntry);
402
+
403
+ return pendingEntry.handleP.promise;
404
+ }
405
+
406
+ private async uploadBlob(localId: string, blob: ArrayBufferLike): Promise<ICreateBlobResponse> {
407
+ return PerformanceEvent.timedExecAsync(
408
+ this.mc.logger,
409
+ { eventName: "createBlob" },
410
+ async () => this.getStorage().createBlob(blob),
411
+ { end: true, cancel: this.runtime.connected ? "error" : "generic" },
412
+ ).then(
413
+ (response) => this.onUploadResolve(localId, response),
414
+ async (err) => this.onUploadReject(localId, err),
415
+ );
416
+ }
417
+
418
+ /**
419
+ * Set up a mapping in the redirect table from fromId to toId. Also, notify the runtime that a reference is added
420
+ * which is required for GC.
421
+ */
422
+ private setRedirection(fromId: string, toId: string | undefined) {
423
+ this.redirectTable.set(fromId, toId);
424
+ // Notify runtime of a reference added if toId is not undefined. It can be undefined when a blob is uploaded in
425
+ // detached mode. In this case, the entry will be updated when the blob is updated.
426
+ if (toId !== undefined) {
427
+ this.addedBlobReference(this.getBlobGCNodePath(fromId), this.getBlobGCNodePath(toId));
428
+ }
429
+ }
430
+
431
+ private deleteAndEmitsIfEmpty(id: string) {
432
+ if (this.pendingBlobs.has(id)) {
433
+ this.pendingBlobs.delete(id);
434
+ if (!this.hasPendingBlobs) {
435
+ this.emit("noPendingBlobs");
436
+ }
437
+ }
438
+ }
439
+
440
+ private onUploadResolve(localId: string, response: ICreateBlobResponseWithTTL) {
441
+ const entry = this.pendingBlobs.get(localId);
442
+ assert(
443
+ entry?.status === PendingBlobStatus.OnlinePendingUpload ||
444
+ entry?.status === PendingBlobStatus.OfflinePendingUpload,
445
+ 0x386 /* Must have pending blob entry for uploaded blob */,
446
+ );
447
+ entry.storageId = response.id;
448
+ entry.localUploadTime = Date.now();
449
+ entry.minTTLInSeconds = response.minTTLInSeconds;
450
+ entry.serverUploadTime = this.getCurrentReferenceTimestampMs();
451
+ if (this.runtime.connected) {
452
+ if (entry.status === PendingBlobStatus.OnlinePendingUpload) {
453
+ // Send a blob attach op. This serves two purposes:
454
+ // 1. If its a new blob, i.e., it isn't de-duped, the server will keep the blob alive if it sees this op
455
+ // until its storage ID is added to the next summary.
456
+ // 2. It will create a local ID to storage ID mapping in all clients which is needed to retrieve the
457
+ // blob from the server via the storage ID.
458
+ this.logTimeInfo(entry, "sendBlobAttachResolveTTL");
459
+ this.sendBlobAttachOp(localId, response.id);
460
+ if (this.storageIds.has(response.id)) {
461
+ // The blob is de-duped. Set up a local ID to storage ID mapping and return the blob. Since this is
462
+ // an existing blob, we don't have to wait for the op to be ack'd since this step has already
463
+ // happened before and so, the server won't delete it.
464
+ this.setRedirection(localId, response.id);
465
+ entry.handleP.resolve(this.getBlobHandle(localId));
466
+ this.deleteAndEmitsIfEmpty(localId);
467
+ } else {
468
+ // If there is already an op for this storage ID, append the local ID to the list. Once any op for
469
+ // this storage ID is ack'd, all pending blobs for it can be resolved since the op will keep the
470
+ // blob alive in storage.
471
+ this.opsInFlight.set(
472
+ response.id,
473
+ (this.opsInFlight.get(response.id) ?? []).concat(localId),
474
+ );
475
+ entry.status = PendingBlobStatus.OnlinePendingOp;
476
+ }
477
+ } else if (entry.status === PendingBlobStatus.OfflinePendingUpload) {
478
+ // We already submitted a BlobAttach op for this blob when it was transitioned to offline flow
479
+ entry.status = PendingBlobStatus.OfflinePendingOp;
480
+ }
481
+ } else {
482
+ // connected to storage but not ordering service?
483
+ this.mc.logger.sendTelemetryEvent({ eventName: "BlobUploadSuccessWhileDisconnected" });
484
+ if (entry.status === PendingBlobStatus.OnlinePendingUpload) {
485
+ this.transitionToOffline(localId);
486
+ }
487
+ entry.status = PendingBlobStatus.OfflinePendingOp;
488
+ }
489
+ return response;
490
+ }
491
+
492
+ private async onUploadReject(localId: string, error) {
493
+ const entry = this.pendingBlobs.get(localId);
494
+ assert(!!entry, 0x387 /* Must have pending blob entry for blob which failed to upload */);
495
+ if (!this.runtime.connected) {
496
+ if (entry.status === PendingBlobStatus.OnlinePendingUpload) {
497
+ this.transitionToOffline(localId);
498
+ }
499
+ // we are probably not connected to storage but start another upload request in case we are
500
+ entry.uploadP = this.retryThrottler
501
+ .getDelay()
502
+ .then(async () => this.uploadBlob(localId, entry.blob));
503
+ return entry.uploadP;
504
+ } else {
505
+ entry.handleP.reject(error);
506
+ throw error;
507
+ }
508
+ }
509
+
510
+ private transitionToOffline(localId: string) {
511
+ assert(
512
+ !this.runtime.connected,
513
+ 0x388 /* Must only transition to offline flow while runtime is disconnected */,
514
+ );
515
+ const entry = this.pendingBlobs.get(localId);
516
+ assert(!!entry, 0x389 /* No pending blob entry */);
517
+ assert(
518
+ [PendingBlobStatus.OnlinePendingUpload, PendingBlobStatus.OnlinePendingOp].includes(
519
+ entry.status,
520
+ ),
521
+ 0x38a /* Blob must be in online flow to transition to offline flow */,
522
+ );
523
+
524
+ /**
525
+ * If we haven't already submitted a BlobAttach op for this entry, send it before returning the blob handle.
526
+ * This will make sure that the BlobAttach op is sequenced prior to any ops referencing the handle. Otherwise,
527
+ * an invalid handle could be added to the document.
528
+ * storageId may be undefined but since we are not connected we will have a chance to add it when reSubmit()
529
+ * is called on reconnection.
530
+ */
531
+ if (entry.status !== PendingBlobStatus.OnlinePendingOp) {
532
+ this.logTimeInfo(entry, "sendBlobAttachTransitionOfflineTTL");
533
+ this.sendBlobAttachOp(localId, entry.storageId);
534
+ }
535
+
536
+ entry.status =
537
+ entry.status === PendingBlobStatus.OnlinePendingUpload
538
+ ? PendingBlobStatus.OfflinePendingUpload
539
+ : PendingBlobStatus.OfflinePendingOp;
540
+
541
+ entry.handleP.resolve(this.getBlobHandle(localId));
542
+ }
543
+
544
+ /**
545
+ * Resubmit a BlobAttach op. Used to add storage IDs to ops that were
546
+ * submitted to runtime while disconnected.
547
+ * @param metadata - op metadata containing storage and/or local IDs
548
+ */
549
+ public reSubmit(metadata: Record<string, unknown> | undefined) {
550
+ assert(!!metadata, 0x38b /* Resubmitted ops must have metadata */);
551
+ const { localId, blobId }: { localId?: string; blobId?: string } = metadata;
552
+ assert(localId !== undefined, 0x50d /* local ID not available on reSubmit */);
553
+ const pendingEntry = this.pendingBlobs.get(localId);
554
+ if (pendingEntry) {
555
+ this.logTimeInfo(pendingEntry, "sendBlobAttachResubmitTTL");
556
+ }
557
+ if (!blobId) {
558
+ // We submitted this op while offline. The blob should have been uploaded by now.
559
+ assert(
560
+ pendingEntry?.status === PendingBlobStatus.OfflinePendingOp &&
561
+ !!pendingEntry?.storageId,
562
+ 0x38d /* blob must be uploaded before resubmitting BlobAttach op */,
563
+ );
564
+ return this.sendBlobAttachOp(localId, pendingEntry.storageId);
565
+ }
566
+ return this.sendBlobAttachOp(localId, blobId);
567
+ }
568
+
569
+ private logTimeInfo(pendingEntry: PendingBlob, eventName: string) {
570
+ let timeLapseSinceLocalUpload: number = 0;
571
+ let timeLapseSinceServerUpload: number = 0;
572
+ let expiredUsingLocalTime;
573
+ let expiredUsingServerTime;
574
+ if (pendingEntry.localUploadTime) {
575
+ timeLapseSinceLocalUpload = (Date.now() - pendingEntry.localUploadTime) / 1000;
576
+ expiredUsingLocalTime =
577
+ (pendingEntry.minTTLInSeconds ?? 0) - timeLapseSinceLocalUpload < 0 ? true : false;
578
+ }
579
+ if (pendingEntry.serverUploadTime) {
580
+ timeLapseSinceServerUpload = (Date.now() - pendingEntry.serverUploadTime) / 1000;
581
+ expiredUsingServerTime =
582
+ (pendingEntry.minTTLInSeconds ?? 0) - timeLapseSinceServerUpload < 0 ? true : false;
583
+ }
584
+ this.mc.logger.sendTelemetryEvent({
585
+ eventName,
586
+ entryStatus: pendingEntry.status,
587
+ timeLapseSinceLocalUpload,
588
+ timeLapseSinceServerUpload,
589
+ minTTLInSeconds: pendingEntry.minTTLInSeconds,
590
+ expiredUsingLocalTime,
591
+ expiredUsingServerTime,
592
+ });
593
+ }
594
+
595
+ public processBlobAttachOp(message: ISequencedDocumentMessage, local: boolean) {
596
+ const localId = message.metadata?.localId;
597
+ const blobId = message.metadata?.blobId;
598
+ assert(blobId !== undefined, 0x12a /* "Missing blob id on metadata" */);
599
+
600
+ // Set up a mapping from local ID to storage ID. This is crucial since without this the blob cannot be
601
+ // requested from the server.
602
+ // Note: The check for undefined is needed for back-compat when localId was not part of the BlobAttach op that
603
+ // was sent when online.
604
+ if (localId !== undefined) {
605
+ this.setRedirection(localId, blobId);
606
+ }
607
+ // set identity (id -> id) entry
608
+ this.setRedirection(blobId, blobId);
609
+
610
+ if (local) {
611
+ assert(localId !== undefined, 0x50e /* local ID not present in blob attach message */);
612
+ const waitingBlobs = this.opsInFlight.get(blobId);
613
+ if (waitingBlobs !== undefined) {
614
+ // For each op corresponding to this storage ID that we are waiting for, resolve the pending blob.
615
+ // This is safe because the server will keep the blob alive and the op containing the local ID to
616
+ // storage ID is already in flight and any op containing this local ID will be sequenced after that.
617
+ waitingBlobs.forEach((pendingLocalId) => {
618
+ const pendingBlobEntry = this.pendingBlobs.get(pendingLocalId);
619
+ assert(
620
+ pendingBlobEntry !== undefined,
621
+ 0x38f /* local online BlobAttach op with no pending blob entry */,
622
+ );
623
+
624
+ // It's possible we transitioned to offline flow while waiting for this op.
625
+ if (pendingBlobEntry.status === PendingBlobStatus.OnlinePendingOp) {
626
+ this.setRedirection(pendingLocalId, blobId);
627
+ pendingBlobEntry.handleP.resolve(this.getBlobHandle(pendingLocalId));
628
+ this.deleteAndEmitsIfEmpty(pendingLocalId);
629
+ }
630
+ });
631
+ this.opsInFlight.delete(blobId);
632
+ }
633
+ // For blobs that were transitioned to offline flow while waiting for this op, the entry should be deleted.
634
+ this.deleteAndEmitsIfEmpty(localId);
635
+ }
636
+ }
637
+
638
+ /**
639
+ * Reads blobs needed to load BlobManager from storage.
640
+ * @param blobsTree - Tree containing IDs of previously attached blobs. We
641
+ * look for the IDs in the blob entries of the tree since the both the r11s
642
+ * and SPO drivers replace the attachment types returned in snapshot() with blobs.
643
+ */
644
+ public static async load(
645
+ blobsTree: ISnapshotTree | undefined,
646
+ tryFetchBlob: (id: string) => Promise<[string, string][]>,
647
+ ): Promise<IBlobManagerLoadInfo> {
648
+ if (!blobsTree) {
649
+ return {};
650
+ }
651
+ let redirectTable;
652
+ const tableId = blobsTree.blobs[this.redirectTableBlobName];
653
+ if (tableId) {
654
+ redirectTable = await tryFetchBlob(tableId);
655
+ }
656
+ const ids = Object.entries(blobsTree.blobs)
657
+ .filter(([k, _]) => k !== this.redirectTableBlobName)
658
+ .map(([_, v]) => v);
659
+ return { ids, redirectTable };
660
+ }
661
+
662
+ /**
663
+ * Load a set of previously attached blob IDs and redirect table from a previous snapshot.
664
+ */
665
+ private load(snapshot: IBlobManagerLoadInfo): Map<string, string | undefined> {
666
+ this.mc.logger.sendTelemetryEvent({
667
+ eventName: "AttachmentBlobsLoaded",
668
+ count: snapshot.ids?.length ?? 0,
669
+ redirectTable: snapshot.redirectTable?.length,
670
+ });
671
+ const table = new Map<string, string | undefined>(snapshot.redirectTable);
672
+ if (snapshot.ids) {
673
+ const detached = this.runtime.attachState === AttachState.Detached;
674
+ // If we are detached, we don't have storage IDs yet, so set to undefined
675
+ // Otherwise, set identity (id -> id) entries
676
+ snapshot.ids.forEach((entry) => table.set(entry, detached ? undefined : entry));
677
+ }
678
+ return table;
679
+ }
680
+
681
+ /**
682
+ * Generates data used for garbage collection. Each blob uploaded represents a node in the GC graph as it can be
683
+ * individually referenced by storing its handle in a referenced DDS. Returns the list of blob ids as GC nodes.
684
+ * @param fullGC - true to bypass optimizations and force full generation of GC data. BlobManager doesn't care
685
+ * about this for now because the data is a simple list of blob ids.
686
+ */
687
+ public getGCData(fullGC: boolean = false): IGarbageCollectionData {
688
+ const gcData: IGarbageCollectionData = { gcNodes: {} };
689
+ for (const [localId, storageId] of this.redirectTable) {
690
+ assert(!!storageId, 0x390 /* Must be attached to get GC data */);
691
+ gcData.gcNodes[this.getBlobGCNodePath(localId)] = [this.getBlobGCNodePath(storageId)];
692
+ }
693
+ return gcData;
694
+ }
695
+
696
+ /**
697
+ * This is called to update blobs whose routes are unused. The unused blobs are deleted.
698
+ * @param unusedRoutes - The routes of the blob nodes that are unused.
699
+ */
700
+ public updateUnusedRoutes(unusedRoutes: string[]): void {
701
+ // The routes or blob node paths are in the same format as returned in getGCData -
702
+ // `/<BlobManager.basePath>/<blobId>`.
703
+ for (const route of unusedRoutes) {
704
+ const pathParts = route.split("/");
705
+ assert(
706
+ pathParts.length === 3 && pathParts[1] === BlobManager.basePath,
707
+ 0x2d5 /* "Invalid blob node id in unused routes." */,
708
+ );
709
+ const blobId = pathParts[2];
710
+ this.redirectTable.delete(blobId);
711
+ }
712
+ }
713
+
714
+ /**
715
+ * This is called to update blobs whose routes are tombstones. Tombstoned blobs enable testing scenarios with
716
+ * accessing deleted content without actually deleting content from summaries.
717
+ * @param tombstonedRoutes - The routes of blob nodes that are tombstones.
718
+ */
719
+ public updateTombstonedRoutes(tombstonedRoutes: string[]) {
720
+ const tombstonedBlobsSet: Set<string> = new Set();
721
+ // The routes or blob node paths are in the same format as returned in getGCData -
722
+ // `/<BlobManager.basePath>/<blobId>`.
723
+ for (const route of tombstonedRoutes) {
724
+ const pathParts = route.split("/");
725
+ assert(
726
+ pathParts.length === 3 && pathParts[1] === BlobManager.basePath,
727
+ 0x50f /* Invalid blob node id in tombstoned routes. */,
728
+ );
729
+ tombstonedBlobsSet.add(pathParts[2]);
730
+ }
731
+
732
+ // Remove blobs from the tombstone list that were tombstoned but aren't anymore as per the tombstoneRoutes.
733
+ for (const blobId of this.tombstonedBlobs) {
734
+ if (!tombstonedBlobsSet.has(blobId)) {
735
+ this.tombstonedBlobs.delete(blobId);
736
+ }
737
+ }
738
+
739
+ // Mark blobs that are now tombstoned by adding them to the tombstone list.
740
+ for (const blobId of tombstonedBlobsSet) {
741
+ this.tombstonedBlobs.add(blobId);
742
+ }
743
+ }
744
+
745
+ /**
746
+ * Verifies that the blob with given id is valid, i.e., it has not been garbage collected. If the blob is GC'd,
747
+ * log an error and throw if necessary.
748
+ */
749
+ private verifyBlobValidity(blobId: string) {
750
+ /**
751
+ * A blob can be in one of the following states:
752
+ * 1. "deleted" - It has been deleted by garbage collection sweep phase.
753
+ * 2. "tombstoned" - It is ready for deletion but sweep phase isn't enabled and tombstone feature is enabled.
754
+ * 3. "valid" - It has not been deleted or tombstoned.
755
+ */
756
+ let state: "valid" | "tombstoned" | "deleted" = "valid";
757
+ if (this.isBlobDeleted(this.getBlobGCNodePath(blobId))) {
758
+ state = "deleted";
759
+ } else if (this.tombstonedBlobs.has(blobId)) {
760
+ state = "tombstoned";
761
+ }
762
+
763
+ if (state === "valid") {
764
+ return;
765
+ }
766
+
767
+ // If the blob is deleted or throw on tombstone load is enabled, throw an error which will fail any attempt
768
+ // to load the blob.
769
+ const shouldFail = state === "deleted" || this.throwOnTombstoneLoad;
770
+ const request = { url: blobId };
771
+ const error = responseToException(
772
+ createResponseError(
773
+ 404,
774
+ "Blob was deleted",
775
+ request,
776
+ state === "tombstoned" ? { [TombstoneResponseHeaderKey]: true } : undefined,
777
+ ),
778
+ request,
779
+ );
780
+ sendGCUnexpectedUsageEvent(
781
+ this.mc,
782
+ {
783
+ eventName:
784
+ state === "tombstoned"
785
+ ? "GC_Tombstone_Blob_Requested"
786
+ : "GC_Deleted_Blob_Requested",
787
+ category: shouldFail ? "error" : "generic",
788
+ isSummarizerClient: this.runtime.clientDetails.type === summarizerClientType,
789
+ },
790
+ [BlobManager.basePath],
791
+ error,
792
+ );
793
+ if (shouldFail) {
794
+ throw error;
795
+ }
796
+ }
797
+
798
+ public summarize(telemetryContext?: ITelemetryContext): ISummaryTreeWithStats {
799
+ // if storageIds is empty, it means we are detached and have only local IDs, or that there are no blobs attached
800
+ const blobIds =
801
+ this.storageIds.size > 0
802
+ ? Array.from(this.storageIds)
803
+ : Array.from(this.redirectTable.keys());
804
+ const builder = new SummaryTreeBuilder();
805
+ blobIds.forEach((blobId) => {
806
+ builder.addAttachment(blobId);
807
+ });
808
+
809
+ // Any non-identity entries in the table need to be saved in the summary
810
+ if (this.redirectTable.size > blobIds.length) {
811
+ builder.addBlob(
812
+ BlobManager.redirectTableBlobName,
813
+ // filter out identity entries
814
+ JSON.stringify(
815
+ Array.from(this.redirectTable.entries()).filter(
816
+ ([localId, storageId]) => localId !== storageId,
817
+ ),
818
+ ),
819
+ );
820
+ }
821
+
822
+ return builder.getSummaryTree();
823
+ }
824
+
825
+ public setRedirectTable(table: Map<string, string>) {
826
+ assert(
827
+ this.runtime.attachState === AttachState.Detached,
828
+ 0x252 /* "redirect table can only be set in detached container" */,
829
+ );
830
+ assert(
831
+ this.redirectTable.size === table.size,
832
+ 0x391 /* Redirect table size must match BlobManager's local ID count */,
833
+ );
834
+ for (const [localId, storageId] of table) {
835
+ assert(
836
+ this.redirectTable.has(localId),
837
+ 0x254 /* "unrecognized id in redirect table" */,
838
+ );
839
+ this.setRedirection(localId, storageId);
840
+ // set identity (id -> id) entry
841
+ this.setRedirection(storageId, storageId);
842
+ }
843
+ }
844
+
845
+ public getPendingBlobs(): IPendingBlobs {
846
+ const blobs = {};
847
+ for (const [key, entry] of this.pendingBlobs) {
848
+ blobs[key] = { blob: bufferToString(entry.blob, "base64") };
849
+ }
850
+ return blobs;
851
+ }
591
852
  }