@fluidframework/container-runtime 2.0.0-dev.2.3.0.115467 → 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 (340) 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 +53 -34
  9. package/dist/blobManager.d.ts.map +1 -1
  10. package/dist/blobManager.js +236 -124
  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 +95 -46
  19. package/dist/containerRuntime.d.ts.map +1 -1
  20. package/dist/containerRuntime.js +288 -135
  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 +38 -21
  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 +68 -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 +50 -26
  43. package/dist/garbageCollection.d.ts.map +1 -1
  44. package/dist/garbageCollection.js +348 -196
  45. package/dist/garbageCollection.js.map +1 -1
  46. package/dist/garbageCollectionConstants.d.ts +7 -3
  47. package/dist/garbageCollectionConstants.d.ts.map +1 -1
  48. package/dist/garbageCollectionConstants.js +10 -8
  49. package/dist/garbageCollectionConstants.js.map +1 -1
  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 +14 -10
  57. package/dist/gcSweepReadyUsageDetection.js.map +1 -1
  58. package/dist/index.d.ts +3 -4
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js +3 -5
  61. package/dist/index.js.map +1 -1
  62. package/dist/opLifecycle/batchManager.d.ts +13 -1
  63. package/dist/opLifecycle/batchManager.d.ts.map +1 -1
  64. package/dist/opLifecycle/batchManager.js +48 -7
  65. package/dist/opLifecycle/batchManager.js.map +1 -1
  66. package/dist/opLifecycle/definitions.d.ts +25 -1
  67. package/dist/opLifecycle/definitions.d.ts.map +1 -1
  68. package/dist/opLifecycle/definitions.js.map +1 -1
  69. package/dist/opLifecycle/index.d.ts +2 -2
  70. package/dist/opLifecycle/index.d.ts.map +1 -1
  71. package/dist/opLifecycle/index.js +2 -1
  72. package/dist/opLifecycle/index.js.map +1 -1
  73. package/dist/opLifecycle/opCompressor.d.ts +1 -1
  74. package/dist/opLifecycle/opCompressor.d.ts.map +1 -1
  75. package/dist/opLifecycle/opCompressor.js +24 -10
  76. package/dist/opLifecycle/opCompressor.js.map +1 -1
  77. package/dist/opLifecycle/opDecompressor.d.ts +2 -1
  78. package/dist/opLifecycle/opDecompressor.d.ts.map +1 -1
  79. package/dist/opLifecycle/opDecompressor.js +33 -17
  80. package/dist/opLifecycle/opDecompressor.js.map +1 -1
  81. package/dist/opLifecycle/opSplitter.d.ts +34 -2
  82. package/dist/opLifecycle/opSplitter.d.ts.map +1 -1
  83. package/dist/opLifecycle/opSplitter.js +117 -5
  84. package/dist/opLifecycle/opSplitter.js.map +1 -1
  85. package/dist/opLifecycle/outbox.d.ts +5 -0
  86. package/dist/opLifecycle/outbox.d.ts.map +1 -1
  87. package/dist/opLifecycle/outbox.js +38 -27
  88. package/dist/opLifecycle/outbox.js.map +1 -1
  89. package/dist/opLifecycle/remoteMessageProcessor.d.ts.map +1 -1
  90. package/dist/opLifecycle/remoteMessageProcessor.js +17 -2
  91. package/dist/opLifecycle/remoteMessageProcessor.js.map +1 -1
  92. package/dist/opProperties.d.ts.map +1 -1
  93. package/dist/opProperties.js +1 -3
  94. package/dist/opProperties.js.map +1 -1
  95. package/dist/orderedClientElection.d.ts.map +1 -1
  96. package/dist/orderedClientElection.js +10 -4
  97. package/dist/orderedClientElection.js.map +1 -1
  98. package/dist/packageVersion.d.ts +1 -1
  99. package/dist/packageVersion.js +1 -1
  100. package/dist/packageVersion.js.map +1 -1
  101. package/dist/pendingStateManager.d.ts +4 -13
  102. package/dist/pendingStateManager.d.ts.map +1 -1
  103. package/dist/pendingStateManager.js +134 -161
  104. package/dist/pendingStateManager.js.map +1 -1
  105. package/dist/runWhileConnectedCoordinator.d.ts.map +1 -1
  106. package/dist/runWhileConnectedCoordinator.js.map +1 -1
  107. package/dist/runningSummarizer.d.ts.map +1 -1
  108. package/dist/runningSummarizer.js +34 -22
  109. package/dist/runningSummarizer.js.map +1 -1
  110. package/dist/scheduleManager.d.ts +0 -1
  111. package/dist/scheduleManager.d.ts.map +1 -1
  112. package/dist/scheduleManager.js +11 -21
  113. package/dist/scheduleManager.js.map +1 -1
  114. package/dist/serializedSnapshotStorage.d.ts.map +1 -1
  115. package/dist/serializedSnapshotStorage.js +3 -1
  116. package/dist/serializedSnapshotStorage.js.map +1 -1
  117. package/dist/summarizer.d.ts +2 -3
  118. package/dist/summarizer.d.ts.map +1 -1
  119. package/dist/summarizer.js +39 -18
  120. package/dist/summarizer.js.map +1 -1
  121. package/dist/summarizerClientElection.d.ts +1 -2
  122. package/dist/summarizerClientElection.d.ts.map +1 -1
  123. package/dist/summarizerClientElection.js +3 -30
  124. package/dist/summarizerClientElection.js.map +1 -1
  125. package/dist/summarizerHandle.d.ts.map +1 -1
  126. package/dist/summarizerHandle.js.map +1 -1
  127. package/dist/summarizerHeuristics.d.ts.map +1 -1
  128. package/dist/summarizerHeuristics.js +6 -9
  129. package/dist/summarizerHeuristics.js.map +1 -1
  130. package/dist/summarizerTypes.d.ts +22 -25
  131. package/dist/summarizerTypes.d.ts.map +1 -1
  132. package/dist/summarizerTypes.js.map +1 -1
  133. package/dist/summaryCollection.d.ts.map +1 -1
  134. package/dist/summaryCollection.js +18 -8
  135. package/dist/summaryCollection.js.map +1 -1
  136. package/dist/summaryFormat.d.ts.map +1 -1
  137. package/dist/summaryFormat.js +18 -11
  138. package/dist/summaryFormat.js.map +1 -1
  139. package/dist/summaryGenerator.d.ts.map +1 -1
  140. package/dist/summaryGenerator.js +32 -14
  141. package/dist/summaryGenerator.js.map +1 -1
  142. package/dist/summaryManager.d.ts.map +1 -1
  143. package/dist/summaryManager.js +21 -9
  144. package/dist/summaryManager.js.map +1 -1
  145. package/dist/throttler.d.ts +2 -2
  146. package/dist/throttler.d.ts.map +1 -1
  147. package/dist/throttler.js +4 -4
  148. package/dist/throttler.js.map +1 -1
  149. package/garbageCollection.md +15 -2
  150. package/lib/batchTracker.d.ts +1 -2
  151. package/lib/batchTracker.d.ts.map +1 -1
  152. package/lib/batchTracker.js +2 -1
  153. package/lib/batchTracker.js.map +1 -1
  154. package/lib/blobManager.d.ts +53 -34
  155. package/lib/blobManager.d.ts.map +1 -1
  156. package/lib/blobManager.js +239 -127
  157. package/lib/blobManager.js.map +1 -1
  158. package/lib/connectionTelemetry.d.ts.map +1 -1
  159. package/lib/connectionTelemetry.js +11 -9
  160. package/lib/connectionTelemetry.js.map +1 -1
  161. package/lib/containerHandleContext.d.ts.map +1 -1
  162. package/lib/containerHandleContext.js +3 -1
  163. package/lib/containerHandleContext.js.map +1 -1
  164. package/lib/containerRuntime.d.ts +95 -46
  165. package/lib/containerRuntime.d.ts.map +1 -1
  166. package/lib/containerRuntime.js +291 -138
  167. package/lib/containerRuntime.js.map +1 -1
  168. package/lib/dataStore.d.ts.map +1 -1
  169. package/lib/dataStore.js +11 -9
  170. package/lib/dataStore.js.map +1 -1
  171. package/lib/dataStoreContext.d.ts +2 -1
  172. package/lib/dataStoreContext.d.ts.map +1 -1
  173. package/lib/dataStoreContext.js +40 -23
  174. package/lib/dataStoreContext.js.map +1 -1
  175. package/lib/dataStoreContexts.d.ts.map +1 -1
  176. package/lib/dataStoreContexts.js +7 -3
  177. package/lib/dataStoreContexts.js.map +1 -1
  178. package/lib/dataStoreRegistry.d.ts.map +1 -1
  179. package/lib/dataStoreRegistry.js +3 -1
  180. package/lib/dataStoreRegistry.js.map +1 -1
  181. package/lib/dataStores.d.ts +12 -9
  182. package/lib/dataStores.d.ts.map +1 -1
  183. package/lib/dataStores.js +74 -52
  184. package/lib/dataStores.js.map +1 -1
  185. package/lib/deltaScheduler.d.ts.map +1 -1
  186. package/lib/deltaScheduler.js +9 -4
  187. package/lib/deltaScheduler.js.map +1 -1
  188. package/lib/garbageCollection.d.ts +50 -26
  189. package/lib/garbageCollection.d.ts.map +1 -1
  190. package/lib/garbageCollection.js +347 -195
  191. package/lib/garbageCollection.js.map +1 -1
  192. package/lib/garbageCollectionConstants.d.ts +7 -3
  193. package/lib/garbageCollectionConstants.d.ts.map +1 -1
  194. package/lib/garbageCollectionConstants.js +9 -7
  195. package/lib/garbageCollectionConstants.js.map +1 -1
  196. package/lib/garbageCollectionHelpers.d.ts +15 -0
  197. package/lib/garbageCollectionHelpers.d.ts.map +1 -0
  198. package/lib/garbageCollectionHelpers.js +23 -0
  199. package/lib/garbageCollectionHelpers.js.map +1 -0
  200. package/lib/gcSweepReadyUsageDetection.d.ts +5 -5
  201. package/lib/gcSweepReadyUsageDetection.d.ts.map +1 -1
  202. package/lib/gcSweepReadyUsageDetection.js +14 -10
  203. package/lib/gcSweepReadyUsageDetection.js.map +1 -1
  204. package/lib/index.d.ts +3 -4
  205. package/lib/index.d.ts.map +1 -1
  206. package/lib/index.js +2 -3
  207. package/lib/index.js.map +1 -1
  208. package/lib/opLifecycle/batchManager.d.ts +13 -1
  209. package/lib/opLifecycle/batchManager.d.ts.map +1 -1
  210. package/lib/opLifecycle/batchManager.js +48 -7
  211. package/lib/opLifecycle/batchManager.js.map +1 -1
  212. package/lib/opLifecycle/definitions.d.ts +25 -1
  213. package/lib/opLifecycle/definitions.d.ts.map +1 -1
  214. package/lib/opLifecycle/definitions.js.map +1 -1
  215. package/lib/opLifecycle/index.d.ts +2 -2
  216. package/lib/opLifecycle/index.d.ts.map +1 -1
  217. package/lib/opLifecycle/index.js +1 -1
  218. package/lib/opLifecycle/index.js.map +1 -1
  219. package/lib/opLifecycle/opCompressor.d.ts +1 -1
  220. package/lib/opLifecycle/opCompressor.d.ts.map +1 -1
  221. package/lib/opLifecycle/opCompressor.js +24 -10
  222. package/lib/opLifecycle/opCompressor.js.map +1 -1
  223. package/lib/opLifecycle/opDecompressor.d.ts +2 -1
  224. package/lib/opLifecycle/opDecompressor.d.ts.map +1 -1
  225. package/lib/opLifecycle/opDecompressor.js +33 -17
  226. package/lib/opLifecycle/opDecompressor.js.map +1 -1
  227. package/lib/opLifecycle/opSplitter.d.ts +34 -2
  228. package/lib/opLifecycle/opSplitter.d.ts.map +1 -1
  229. package/lib/opLifecycle/opSplitter.js +116 -5
  230. package/lib/opLifecycle/opSplitter.js.map +1 -1
  231. package/lib/opLifecycle/outbox.d.ts +5 -0
  232. package/lib/opLifecycle/outbox.d.ts.map +1 -1
  233. package/lib/opLifecycle/outbox.js +38 -27
  234. package/lib/opLifecycle/outbox.js.map +1 -1
  235. package/lib/opLifecycle/remoteMessageProcessor.d.ts.map +1 -1
  236. package/lib/opLifecycle/remoteMessageProcessor.js +17 -2
  237. package/lib/opLifecycle/remoteMessageProcessor.js.map +1 -1
  238. package/lib/opProperties.d.ts.map +1 -1
  239. package/lib/opProperties.js +1 -3
  240. package/lib/opProperties.js.map +1 -1
  241. package/lib/orderedClientElection.d.ts.map +1 -1
  242. package/lib/orderedClientElection.js +10 -4
  243. package/lib/orderedClientElection.js.map +1 -1
  244. package/lib/packageVersion.d.ts +1 -1
  245. package/lib/packageVersion.js +1 -1
  246. package/lib/packageVersion.js.map +1 -1
  247. package/lib/pendingStateManager.d.ts +4 -13
  248. package/lib/pendingStateManager.d.ts.map +1 -1
  249. package/lib/pendingStateManager.js +134 -161
  250. package/lib/pendingStateManager.js.map +1 -1
  251. package/lib/runWhileConnectedCoordinator.d.ts.map +1 -1
  252. package/lib/runWhileConnectedCoordinator.js.map +1 -1
  253. package/lib/runningSummarizer.d.ts.map +1 -1
  254. package/lib/runningSummarizer.js +35 -23
  255. package/lib/runningSummarizer.js.map +1 -1
  256. package/lib/scheduleManager.d.ts +0 -1
  257. package/lib/scheduleManager.d.ts.map +1 -1
  258. package/lib/scheduleManager.js +11 -21
  259. package/lib/scheduleManager.js.map +1 -1
  260. package/lib/serializedSnapshotStorage.d.ts.map +1 -1
  261. package/lib/serializedSnapshotStorage.js +3 -1
  262. package/lib/serializedSnapshotStorage.js.map +1 -1
  263. package/lib/summarizer.d.ts +2 -3
  264. package/lib/summarizer.d.ts.map +1 -1
  265. package/lib/summarizer.js +39 -18
  266. package/lib/summarizer.js.map +1 -1
  267. package/lib/summarizerClientElection.d.ts +1 -2
  268. package/lib/summarizerClientElection.d.ts.map +1 -1
  269. package/lib/summarizerClientElection.js +3 -30
  270. package/lib/summarizerClientElection.js.map +1 -1
  271. package/lib/summarizerHandle.d.ts.map +1 -1
  272. package/lib/summarizerHandle.js.map +1 -1
  273. package/lib/summarizerHeuristics.d.ts.map +1 -1
  274. package/lib/summarizerHeuristics.js +6 -9
  275. package/lib/summarizerHeuristics.js.map +1 -1
  276. package/lib/summarizerTypes.d.ts +22 -25
  277. package/lib/summarizerTypes.d.ts.map +1 -1
  278. package/lib/summarizerTypes.js.map +1 -1
  279. package/lib/summaryCollection.d.ts.map +1 -1
  280. package/lib/summaryCollection.js +18 -8
  281. package/lib/summaryCollection.js.map +1 -1
  282. package/lib/summaryFormat.d.ts.map +1 -1
  283. package/lib/summaryFormat.js +20 -13
  284. package/lib/summaryFormat.js.map +1 -1
  285. package/lib/summaryGenerator.d.ts.map +1 -1
  286. package/lib/summaryGenerator.js +32 -14
  287. package/lib/summaryGenerator.js.map +1 -1
  288. package/lib/summaryManager.d.ts.map +1 -1
  289. package/lib/summaryManager.js +21 -9
  290. package/lib/summaryManager.js.map +1 -1
  291. package/lib/throttler.d.ts +2 -2
  292. package/lib/throttler.d.ts.map +1 -1
  293. package/lib/throttler.js +4 -4
  294. package/lib/throttler.js.map +1 -1
  295. package/package.json +27 -24
  296. package/prettier.config.cjs +1 -1
  297. package/src/batchTracker.ts +55 -50
  298. package/src/blobManager.ts +799 -593
  299. package/src/connectionTelemetry.ts +280 -249
  300. package/src/containerHandleContext.ts +27 -29
  301. package/src/containerRuntime.ts +3123 -2793
  302. package/src/dataStore.ts +172 -159
  303. package/src/dataStoreContext.ts +1048 -991
  304. package/src/dataStoreContexts.ts +178 -161
  305. package/src/dataStoreRegistry.ts +25 -20
  306. package/src/dataStores.ts +784 -711
  307. package/src/deltaScheduler.ts +158 -150
  308. package/src/garbageCollection.ts +1795 -1546
  309. package/src/garbageCollectionConstants.ts +10 -7
  310. package/src/garbageCollectionHelpers.ts +37 -0
  311. package/src/gcSweepReadyUsageDetection.ts +89 -83
  312. package/src/index.ts +67 -69
  313. package/src/opLifecycle/batchManager.ts +148 -86
  314. package/src/opLifecycle/definitions.ts +45 -19
  315. package/src/opLifecycle/index.ts +6 -5
  316. package/src/opLifecycle/opCompressor.ts +57 -39
  317. package/src/opLifecycle/opDecompressor.ts +104 -64
  318. package/src/opLifecycle/opSplitter.ts +226 -66
  319. package/src/opLifecycle/outbox.ts +206 -182
  320. package/src/opLifecycle/remoteMessageProcessor.ts +63 -47
  321. package/src/opProperties.ts +11 -9
  322. package/src/orderedClientElection.ts +489 -457
  323. package/src/packageVersion.ts +1 -1
  324. package/src/pendingStateManager.ts +379 -381
  325. package/src/runWhileConnectedCoordinator.ts +78 -71
  326. package/src/runningSummarizer.ts +619 -582
  327. package/src/scheduleManager.ts +299 -280
  328. package/src/serializedSnapshotStorage.ts +116 -111
  329. package/src/summarizer.ts +417 -381
  330. package/src/summarizerClientElection.ts +107 -129
  331. package/src/summarizerHandle.ts +11 -9
  332. package/src/summarizerHeuristics.ts +183 -186
  333. package/src/summarizerTypes.ts +344 -333
  334. package/src/summaryCollection.ts +378 -349
  335. package/src/summaryFormat.ts +146 -127
  336. package/src/summaryGenerator.ts +464 -406
  337. package/src/summaryManager.ts +377 -348
  338. package/src/throttler.ts +131 -122
  339. package/tsconfig.esnext.json +6 -6
  340. package/tsconfig.json +9 -13
@@ -6,25 +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
9
  import {
11
- createResponseError,
12
- generateHandleContextPath,
13
- responseToException,
14
- SummaryTreeBuilder,
10
+ ICreateBlobResponse,
11
+ ISequencedDocumentMessage,
12
+ ISnapshotTree,
13
+ } from "@fluidframework/protocol-definitions";
14
+ import {
15
+ createResponseError,
16
+ generateHandleContextPath,
17
+ responseToException,
18
+ SummaryTreeBuilder,
15
19
  } from "@fluidframework/runtime-utils";
16
- import { assert, bufferToString, Deferred, stringToBuffer, TypedEventEmitter } from "@fluidframework/common-utils";
17
- import { IContainerRuntime, IContainerRuntimeEvents } from "@fluidframework/container-runtime-definitions";
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";
18
31
  import { AttachState } from "@fluidframework/container-definitions";
19
- import { ChildLogger, loggerToMonitoringContext, MonitoringContext, PerformanceEvent } from "@fluidframework/telemetry-utils";
20
32
  import {
21
- IGarbageCollectionData,
22
- ISummaryTreeWithStats,
23
- ITelemetryContext,
33
+ ChildLogger,
34
+ loggerToMonitoringContext,
35
+ MonitoringContext,
36
+ PerformanceEvent,
37
+ } from "@fluidframework/telemetry-utils";
38
+ import {
39
+ IGarbageCollectionData,
40
+ ISummaryTreeWithStats,
41
+ ITelemetryContext,
24
42
  } from "@fluidframework/runtime-definitions";
43
+ import { TombstoneResponseHeaderKey } from "./containerRuntime";
25
44
  import { Throttler, formExponentialFn, IThrottler } from "./throttler";
26
45
  import { summarizerClientType } from "./summarizerClientElection";
27
- import { throwOnTombstoneUsageKey } from "./garbageCollectionConstants";
46
+ import { throwOnTombstoneLoadKey } from "./garbageCollectionConstants";
47
+ import { sendGCUnexpectedUsageEvent } from "./garbageCollectionHelpers";
28
48
 
29
49
  /**
30
50
  * This class represents blob (long string)
@@ -34,613 +54,799 @@ import { throwOnTombstoneUsageKey } from "./garbageCollectionConstants";
34
54
  * and loads blob.
35
55
  */
36
56
  export class BlobHandle implements IFluidHandle<ArrayBufferLike> {
37
- private attached: boolean = false;
57
+ private attached: boolean = false;
38
58
 
39
- public get IFluidHandle(): IFluidHandle { return this; }
59
+ public get IFluidHandle(): IFluidHandle {
60
+ return this;
61
+ }
40
62
 
41
- public get isAttached(): boolean {
42
- return this.attached;
43
- }
63
+ public get isAttached(): boolean {
64
+ return this.attached;
65
+ }
44
66
 
45
- public readonly absolutePath: string;
67
+ public readonly absolutePath: string;
46
68
 
47
- constructor(
48
- public readonly path: string,
49
- public readonly routeContext: IFluidHandleContext,
50
- public get: () => Promise<any>,
51
- ) {
52
- this.absolutePath = generateHandleContextPath(path, this.routeContext);
53
- }
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
+ }
54
76
 
55
- public attachGraph() {
56
- this.attached = true;
57
- }
77
+ public attachGraph() {
78
+ this.attached = true;
79
+ }
58
80
 
59
- public bind(handle: IFluidHandle) {
60
- throw new Error("Cannot bind to blob handle");
61
- }
81
+ public bind(handle: IFluidHandle) {
82
+ throw new Error("Cannot bind to blob handle");
83
+ }
62
84
  }
63
85
 
64
86
  class CancellableThrottler {
65
- constructor(private readonly throttler: IThrottler) { }
66
- private cancelP = new Deferred<void>();
67
-
68
- public async getDelay(): Promise<void> {
69
- return Promise.race([
70
- this.cancelP.promise,
71
- new Promise<void>((resolve) => setTimeout(resolve, this.throttler.getDelay())),
72
- ]);
73
- }
74
-
75
- public cancel() {
76
- this.cancelP.resolve();
77
- this.cancelP = new Deferred<void>();
78
- }
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
+ }
79
101
  }
80
102
 
81
103
  /**
82
104
  * Information from a snapshot needed to load BlobManager
83
105
  */
84
106
  export interface IBlobManagerLoadInfo {
85
- ids?: string[];
86
- redirectTable?: [string, string][];
107
+ ids?: string[];
108
+ redirectTable?: [string, string][];
87
109
  }
88
110
 
89
111
  // Restrict the IContainerRuntime interface to the subset required by BlobManager. This helps to make
90
112
  // the contract explicit and reduces the amount of mocking required for tests.
91
- export type IBlobManagerRuntime =
92
- Pick<IContainerRuntime, "attachState" | "connected" | "logger" | "clientDetails"> & TypedEventEmitter<IContainerRuntimeEvents>;
113
+ export type IBlobManagerRuntime = Pick<
114
+ IContainerRuntime,
115
+ "attachState" | "connected" | "logger" | "clientDetails"
116
+ > &
117
+ TypedEventEmitter<IContainerRuntimeEvents>;
93
118
 
94
119
  // Note that while offline we "submit" an op before uploading the blob, but we always
95
120
  // expect blobs to be uploaded before we actually see the op round-trip
96
121
  enum PendingBlobStatus {
97
- OnlinePendingUpload,
98
- OnlinePendingOp,
99
- OfflinePendingUpload,
100
- OfflinePendingOp,
122
+ OnlinePendingUpload,
123
+ OnlinePendingOp,
124
+ OfflinePendingUpload,
125
+ OfflinePendingOp,
101
126
  }
102
127
 
128
+ type ICreateBlobResponseWithTTL = ICreateBlobResponse & Partial<Record<"minTTLInSeconds", number>>;
129
+
103
130
  interface PendingBlob {
104
- blob: ArrayBufferLike;
105
- status: PendingBlobStatus;
106
- storageId?: string;
107
- handleP: Deferred<IFluidHandle<ArrayBufferLike>>;
108
- 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);
109
147
  }
110
148
 
111
- export interface IPendingBlobs { [id: string]: { blob: string; }; }
112
-
113
- export class BlobManager {
114
- public static readonly basePath = "_blobs";
115
- private static readonly redirectTableBlobName = ".redirectTable";
116
- private readonly mc: MonitoringContext;
117
-
118
- /**
119
- * Map of local (offline/detached) IDs to storage IDs. Contains identity entries
120
- * (id id) for storage IDs, so all requested IDs should be a key in this map.
121
- * Blobs created while the container is detached are stored in IDetachedBlobStorage
122
- * which gives local IDs; the storage IDs are filled in at attach time.
123
- */
124
- private readonly redirectTable: Map<string, string | undefined>;
125
-
126
- /**
127
- * Blobs which have not been uploaded or for which we have not yet seen a BlobAttach op round-trip.
128
- * Until we see the op round-trip, there is a possibility we may need to re-upload the blob, so
129
- * we must save it. This is true for both the online and offline flow.
130
- */
131
- private readonly pendingBlobs: Map<string, PendingBlob> = new Map();
132
-
133
- /**
134
- * Track ops in flight for online flow. Used to avoid searching pendingBlobs since BlobAttach ops
135
- * don't include local ID in online flow.
136
- */
137
- private readonly opsInFlight: Map<string, string[]> = new Map();
138
-
139
- private readonly retryThrottler = new CancellableThrottler(new Throttler(
140
- 60 * 1000, // 60 sec delay window
141
- 30 * 1000, // 30 sec max delay
142
- // throttling function increases exponentially (0ms, 40ms, 80ms, 160ms, etc)
143
- formExponentialFn({ coefficient: 20, initialDelay: 0 }),
144
- ));
145
-
146
- /** If true, throw an error when a tombstone attachment blob is retrieved. */
147
- private readonly throwOnTombstoneUsage: boolean;
148
- /**
149
- * This stores ides of tombstoned blobs.
150
- * Tombstone is a temporary feature that imitates a blob getting swept by garbage collection.
151
- */
152
- private readonly tombstonedBlobs: Set<string> = new Set();
153
-
154
- constructor(
155
- private readonly routeContext: IFluidHandleContext,
156
- snapshot: IBlobManagerLoadInfo,
157
- private readonly getStorage: () => IDocumentStorageService,
158
- /**
159
- * Submit a BlobAttach op. When a blob is uploaded, there is a short grace period before which
160
- * the blob is deleted. The BlobAttach op notifies the server that blob is in use. The server
161
- * will then not delete the blob as long as it is listed as referenced in future summaries.
162
- * The summarizing client will know to include the storage ID in the summary when it sees the op.
163
- *
164
- * The op may also include a local ID to inform all clients of the relation to the storage
165
- * ID, without knowledge of which they cannot request the blob from storage. This is also
166
- * included in the redirect table in the summary.
167
- */
168
- private readonly sendBlobAttachOp: (storageId?: string, localId?: string) => void,
169
- // To be called when a blob node is requested. blobPath is the path of the blob's node in GC's graph. It's
170
- // of the format `/<BlobManager.basePath>/<blobId>`.
171
- private readonly gcNodeUpdated: (blobPath: string) => void,
172
- private readonly runtime: IBlobManagerRuntime,
173
- stashedBlobs: IPendingBlobs = {},
174
- ) {
175
- this.mc = loggerToMonitoringContext(ChildLogger.create(this.runtime.logger, "BlobManager"));
176
- // Read the feature flag that tells whether to throw when a tombstone blob is requested.
177
- this.throwOnTombstoneUsage =
178
- this.mc.config.getBoolean(throwOnTombstoneUsageKey) === true &&
179
- this.runtime.clientDetails.type !== summarizerClientType;
180
-
181
- this.runtime.on("disconnected", () => this.onDisconnected());
182
- this.redirectTable = this.load(snapshot);
183
-
184
- // Begin uploading stashed blobs from previous container instance
185
- Object.entries(stashedBlobs).forEach(([localId, entry]) => {
186
- const blob = stringToBuffer(entry.blob, "base64");
187
- this.pendingBlobs.set(localId, {
188
- blob,
189
- status: PendingBlobStatus.OfflinePendingUpload,
190
- handleP: new Deferred(),
191
- uploadP: this.uploadBlob(localId, blob),
192
- });
193
- });
194
- }
195
-
196
- private get pendingOfflineUploads() {
197
- return Array.from(this.pendingBlobs.values())
198
- .filter((e) => e.status === PendingBlobStatus.OfflinePendingUpload);
199
- }
200
-
201
- public get hasPendingOfflineUploads(): boolean {
202
- return this.pendingOfflineUploads.length > 0;
203
- }
204
-
205
- /**
206
- * Upload blobs added while offline. This must be completed before connecting and resubmitting ops.
207
- */
208
- public async onConnected() {
209
- this.retryThrottler.cancel();
210
- const pendingUploads = this.pendingOfflineUploads.map(async (e) => e.uploadP);
211
- await PerformanceEvent.timedExecAsync(this.mc.logger, {
212
- eventName: "BlobUploadOnConnected",
213
- count: pendingUploads.length,
214
- }, async () => Promise.all(pendingUploads),
215
- { start: true, end: true },
216
- );
217
- }
218
-
219
- /**
220
- * Transition online blobs waiting for BlobAttach op round-trip since we will not see the op until we are connected
221
- * again
222
- */
223
- private onDisconnected() {
224
- for (const [localId, entry] of this.pendingBlobs) {
225
- if (entry.status === PendingBlobStatus.OnlinePendingOp) {
226
- // This will submit another BlobAttach op for this blob. This is necessary because the one we sent
227
- // already didn't have the local ID.
228
- this.transitionToOffline(localId);
229
- }
230
- }
231
- }
232
-
233
- /**
234
- * For a blobId, returns its path in GC's graph. The node path is of the format `/<BlobManager.basePath>/<blobId>`
235
- * This path must match the path of the blob handle returned by the createBlob API because blobs are marked
236
- * referenced by storing these handles in a referenced DDS.
237
- */
238
- private getBlobGCNodePath(blobId: string) {
239
- return `/${BlobManager.basePath}/${blobId}`;
240
- }
241
-
242
- /**
243
- * Set of actual storage IDs (i.e., IDs that can be requested from storage). This will be empty if the container is
244
- * detached or there are no (non-pending) attachment blobs in the document
245
- */
246
- private get storageIds(): Set<string> {
247
- const ids = new Set<string | undefined>(this.redirectTable.values());
248
-
249
- // If we are detached, we will not have storage IDs, only undefined
250
- const undefinedValueInTable = ids.delete(undefined);
251
-
252
- // For a detached container, entries are inserted into the redirect table with an undefined storage ID.
253
- // For an attached container, entries are inserted w/storage ID after the BlobAttach op round-trips.
254
- assert(!undefinedValueInTable || this.runtime.attachState === AttachState.Detached && ids.size === 0,
255
- 0x382 /* 'redirectTable' must contain only undefined while detached / defined values while attached */);
256
-
257
- return ids as Set<string>;
258
- }
259
-
260
- public async getBlob(blobId: string): Promise<ArrayBufferLike> {
261
- const request = { url: blobId };
262
- if (this.tombstonedBlobs.has(blobId) ) {
263
- const error = responseToException(createResponseError(404, "Blob removed by gc", request), request);
264
- this.mc.logger.sendErrorEvent({
265
- eventName: "GC_Tombstone_Blob_Requested",
266
- url: request.url,
267
- }, error);
268
- if (this.throwOnTombstoneUsage) {
269
- throw error;
270
- }
271
- }
272
-
273
- const pending = this.pendingBlobs.get(blobId);
274
- if (pending) {
275
- return pending.blob;
276
- }
277
- let storageId;
278
- if (this.runtime.attachState === AttachState.Detached) {
279
- assert(this.redirectTable.has(blobId), 0x383 /* requesting unknown blobs */);
280
-
281
- // Blobs created while the container is detached are stored in IDetachedBlobStorage.
282
- // The 'IDocumentStorageService.readBlob()' call below will retrieve these via localId.
283
- storageId = blobId;
284
- } else {
285
- storageId = this.redirectTable.get(blobId);
286
- assert(!!storageId, 0x11f /* "requesting unknown blobs" */);
287
- }
288
-
289
- // When a GC-able (not pending) blob is retrieved, let runtime know that the corresponding GC node got updated.
290
- this.gcNodeUpdated(this.getBlobGCNodePath(blobId));
291
-
292
- return PerformanceEvent.timedExecAsync(
293
- this.mc.logger,
294
- { eventName: "AttachmentReadBlob", id: storageId },
295
- async () => {
296
- return this.getStorage().readBlob(storageId);
297
- },
298
- { end: true, cancel: "error" },
299
- );
300
- }
301
-
302
- private getBlobHandle(id: string): IFluidHandle<ArrayBufferLike> {
303
- assert(this.redirectTable.has(id) || this.pendingBlobs.has(id),
304
- 0x384 /* requesting handle for unknown blob */);
305
- return new BlobHandle(
306
- `${BlobManager.basePath}/${id}`,
307
- this.routeContext,
308
- async () => this.getBlob(id),
309
- );
310
- }
311
-
312
- private async createBlobDetached(blob: ArrayBufferLike): Promise<IFluidHandle<ArrayBufferLike>> {
313
- // Blobs created while the container is detached are stored in IDetachedBlobStorage.
314
- // The 'IDocumentStorageService.createBlob()' call below will respond with a localId.
315
- const response = await this.getStorage().createBlob(blob);
316
- this.redirectTable.set(response.id, undefined);
317
- return this.getBlobHandle(response.id);
318
- }
319
-
320
- public async createBlob(blob: ArrayBufferLike): Promise<IFluidHandle<ArrayBufferLike>> {
321
- if (this.runtime.attachState === AttachState.Detached) {
322
- return this.createBlobDetached(blob);
323
- }
324
- if (this.runtime.attachState === AttachState.Attaching) {
325
- // blob upload is not supported in "Attaching" state
326
- this.mc.logger.sendTelemetryEvent({ eventName: "CreateBlobWhileAttaching" });
327
- await new Promise<void>((resolve) => this.runtime.once("attached", resolve));
328
- }
329
- assert(this.runtime.attachState === AttachState.Attached,
330
- 0x385 /* For clarity and paranoid defense against adding future attachment states */);
331
-
332
- // Create a local ID for each blob. This is used to support blobs if/when the client goes
333
- // offline since we don't have the ID from storage yet. If online flow succeeds this won't be used.
334
- const localId = uuid();
335
- const pendingEntry: PendingBlob = {
336
- blob,
337
- status: PendingBlobStatus.OnlinePendingUpload,
338
- handleP: new Deferred(),
339
- uploadP: this.uploadBlob(localId, blob),
340
- };
341
- this.pendingBlobs.set(localId, pendingEntry);
342
-
343
- return pendingEntry.handleP.promise;
344
- }
345
-
346
- private async uploadBlob(localId: string, blob: ArrayBufferLike): Promise<ICreateBlobResponse> {
347
- return PerformanceEvent.timedExecAsync(
348
- this.mc.logger,
349
- { eventName: "createBlob" },
350
- async () => this.getStorage().createBlob(blob),
351
- { end: true, cancel: this.runtime.connected ? "error" : "generic" },
352
- ).then(
353
- (response) => this.onUploadResolve(localId, response),
354
- async (err) => this.onUploadReject(localId, err),
355
- );
356
- }
357
-
358
- private onUploadResolve(localId: string, response: ICreateBlobResponse) {
359
- const entry = this.pendingBlobs.get(localId);
360
- assert(entry?.status === PendingBlobStatus.OnlinePendingUpload ||
361
- entry?.status === PendingBlobStatus.OfflinePendingUpload,
362
- 0x386 /* Must have pending blob entry for uploaded blob */);
363
- entry.storageId = response.id;
364
- if (this.runtime.connected) {
365
- if (entry.status === PendingBlobStatus.OnlinePendingUpload) {
366
- if (this.storageIds.has(response.id)) {
367
- // Storage may dedupe blobs and give us an ID we already know
368
- // no need to submit BlobAttach op in this case
369
- entry.handleP.resolve(this.getBlobHandle(response.id));
370
- this.pendingBlobs.delete(localId);
371
- } else {
372
- // Check for still-pending duplicates too; if an op is already in flight we can wait for that one
373
- if (!this.opsInFlight.has(response.id)) {
374
- this.sendBlobAttachOp(response.id);
375
- }
376
- this.opsInFlight.set(response.id, (this.opsInFlight.get(response.id) ?? []).concat(localId));
377
- entry.status = PendingBlobStatus.OnlinePendingOp;
378
- }
379
- } else if (entry.status === PendingBlobStatus.OfflinePendingUpload) {
380
- // We already submitted a BlobAttach op for this blob when it was transitioned to offline flow
381
- entry.status = PendingBlobStatus.OfflinePendingOp;
382
- }
383
- } else {
384
- // connected to storage but not ordering service?
385
- this.mc.logger.sendTelemetryEvent({ eventName: "BlobUploadSuccessWhileDisconnected" });
386
- if (entry.status === PendingBlobStatus.OnlinePendingUpload) {
387
- this.transitionToOffline(localId);
388
- }
389
- entry.status = PendingBlobStatus.OfflinePendingOp;
390
- }
391
- return response;
392
- }
393
-
394
- private async onUploadReject(localId: string, error) {
395
- const entry = this.pendingBlobs.get(localId);
396
- assert(!!entry, 0x387 /* Must have pending blob entry for blob which failed to upload */);
397
- if (!this.runtime.connected) {
398
- if (entry.status === PendingBlobStatus.OnlinePendingUpload) {
399
- this.transitionToOffline(localId);
400
- }
401
- // we are probably not connected to storage but start another upload request in case we are
402
- entry.uploadP = this.retryThrottler.getDelay().then(async () => this.uploadBlob(localId, entry.blob));
403
- return entry.uploadP;
404
- } else {
405
- entry.handleP.reject(error);
406
- throw error;
407
- }
408
- }
409
-
410
- private transitionToOffline(localId: string) {
411
- assert(!this.runtime.connected, 0x388 /* Must only transition to offline flow while runtime is disconnected */);
412
- const entry = this.pendingBlobs.get(localId);
413
- assert(!!entry, 0x389 /* No pending blob entry */);
414
- assert([PendingBlobStatus.OnlinePendingUpload, PendingBlobStatus.OnlinePendingOp].includes(entry.status),
415
- 0x38a /* Blob must be in online flow to transition to offline flow */);
416
-
417
- entry.status = entry.status === PendingBlobStatus.OnlinePendingUpload
418
- ? PendingBlobStatus.OfflinePendingUpload
419
- : PendingBlobStatus.OfflinePendingOp;
420
-
421
- // Submit a BlobAttach op. It's important we submit this op now before returning the blob handle so the
422
- // BlobAttach op is sequenced prior to any ops referencing the handle. Otherwise an invalid handle could be
423
- // added to the document if the ops are not all successfully submitted upon reconnection.
424
- // storageId may be undefined but since we are not connected we will have a chance to add it when reSubmit()
425
- // is called
426
- this.sendBlobAttachOp(entry.storageId, localId);
427
- entry.handleP.resolve(this.getBlobHandle(localId));
428
- }
429
-
430
- /**
431
- * Resubmit a BlobAttach op. Used to add storage IDs to ops that were
432
- * submitted to runtime while disconnected.
433
- * @param metadata - op metadata containing storage and/or local IDs
434
- */
435
- public reSubmit(metadata: Record<string, unknown> | undefined) {
436
- assert(!!metadata, 0x38b /* Resubmitted ops must have metadata */);
437
- const { blobId, localId }: { blobId?: string; localId?: string; } = metadata;
438
- if (!blobId) {
439
- assert(!!localId, 0x38c /* Submitted BlobAttach ops must have a blobId or localId */);
440
- // We submitted this op while offline. The blob should have been uploaded by now.
441
- const pendingEntry = this.pendingBlobs.get(localId);
442
- assert(pendingEntry?.status === PendingBlobStatus.OfflinePendingOp &&
443
- !!pendingEntry?.storageId, 0x38d /* blob must be uploaded before resubmitting BlobAttach op */);
444
- return this.sendBlobAttachOp(pendingEntry.storageId, localId);
445
- }
446
- return this.sendBlobAttachOp(blobId, localId);
447
- }
448
-
449
- public processBlobAttachOp(message: ISequencedDocumentMessage, local: boolean) {
450
- assert(message?.metadata?.blobId, 0x12a /* "Missing blob id on metadata" */);
451
- if (message.metadata.localId !== undefined) {
452
- this.redirectTable.set(message.metadata.localId, message.metadata.blobId);
453
- }
454
- // set identity (id -> id) entry
455
- this.redirectTable.set(message.metadata.blobId, message.metadata.blobId);
456
-
457
- if (local) {
458
- if (message.metadata.localId === undefined) {
459
- // Since there is no local ID, we know this op was submitted while online.
460
- const waitingBlobs = this.opsInFlight.get(message.metadata.blobId);
461
- assert(!!waitingBlobs, 0x38e /* local online BlobAttach op with no pending blob */);
462
- waitingBlobs.forEach((localId) => {
463
- const pendingBlobEntry = this.pendingBlobs.get(localId);
464
- assert(
465
- pendingBlobEntry !== undefined,
466
- 0x38f, /* local online BlobAttach op with no pending blob entry */
467
- );
468
-
469
- // It's possible we transitioned to offline flow while waiting for this op.
470
- if (pendingBlobEntry.status === PendingBlobStatus.OnlinePendingOp) {
471
- pendingBlobEntry.handleP.resolve(this.getBlobHandle(message.metadata.blobId));
472
- this.pendingBlobs.delete(localId);
473
- }
474
- });
475
- } else {
476
- // Each local ID is unique; get the pending blob entry and delete it
477
- assert(this.pendingBlobs.get(message.metadata.localId)?.status === PendingBlobStatus.OfflinePendingOp,
478
- 0x1f8 /* "local BlobAttach op with no pending blob" */);
479
- this.pendingBlobs.delete(message.metadata.localId);
480
- }
481
- }
482
- }
483
-
484
- /**
485
- * Reads blobs needed to load BlobManager from storage.
486
- * @param blobsTree - Tree containing IDs of previously attached blobs. We
487
- * look for the IDs in the blob entries of the tree since the both the r11s
488
- * and SPO drivers replace the attachment types returned in snapshot() with blobs.
489
- */
490
- public static async load(
491
- blobsTree: ISnapshotTree | undefined,
492
- tryFetchBlob: (id: string) => Promise<[string, string][]>,
493
- ): Promise<IBlobManagerLoadInfo> {
494
- if (!blobsTree) {
495
- return {};
496
- }
497
- let redirectTable;
498
- const tableId = blobsTree.blobs[this.redirectTableBlobName];
499
- if (tableId) {
500
- redirectTable = await tryFetchBlob(tableId);
501
- }
502
- const ids = Object.entries(blobsTree.blobs)
503
- .filter(([k, _]) => k !== this.redirectTableBlobName).map(([_, v]) => v);
504
- return { ids, redirectTable };
505
- }
506
-
507
- /**
508
- * Load a set of previously attached blob IDs and redirect table from a previous snapshot.
509
- */
510
- private load(snapshot: IBlobManagerLoadInfo): Map<string, string | undefined> {
511
- this.mc.logger.sendTelemetryEvent({
512
- eventName: "AttachmentBlobsLoaded",
513
- count: snapshot.ids?.length ?? 0,
514
- redirectTable: snapshot.redirectTable?.length,
515
- });
516
- const table = new Map<string, string | undefined>(snapshot.redirectTable);
517
- if (snapshot.ids) {
518
- const detached = this.runtime.attachState === AttachState.Detached;
519
- // If we are detached, we don't have storage IDs yet, so set to undefined
520
- // Otherwise, set identity (id -> id) entries
521
- snapshot.ids.forEach((entry) => table.set(entry, detached ? undefined : entry));
522
- }
523
- return table;
524
- }
525
-
526
- /**
527
- * Generates data used for garbage collection. Each blob uploaded represents a node in the GC graph as it can be
528
- * individually referenced by storing its handle in a referenced DDS. Returns the list of blob ids as GC nodes.
529
- * @param fullGC - true to bypass optimizations and force full generation of GC data. BlobManager doesn't care
530
- * about this for now because the data is a simple list of blob ids.
531
- */
532
- public getGCData(fullGC: boolean = false): IGarbageCollectionData {
533
- const gcData: IGarbageCollectionData = { gcNodes: {} };
534
- /**
535
- * The node path is of the format `/_blobs/blobId`. This path must match the path of the blob handle returned
536
- * by the createBlob API because blobs are marked referenced by storing these handles in a referenced DDS.
537
- */
538
- this.storageIds.forEach((blobId: string) => {
539
- gcData.gcNodes[this.getBlobGCNodePath(blobId)] = [];
540
- });
541
-
542
- // For some blobs, the handle returned on creation is based off of the localId. So, these
543
- // nodes can be referenced by storing the localId handle. When that happens, the corresponding storageId node
544
- // must also be marked referenced. So, we add a route from the localId node to the storageId node.
545
- // Note that because of de-duping, there can be multiple localIds that all redirect to the same storageId or
546
- // a blob may be referenced via its storageId handle.
547
- for (const [localId, storageId] of this.redirectTable) {
548
- assert(!!storageId, 0x390 /* Must be attached to get GC data */);
549
- // Add node for the localId and add a route to the storageId node. The storageId node will have been
550
- // added above when adding nodes for this.blobIds.
551
- gcData.gcNodes[this.getBlobGCNodePath(localId)] = [this.getBlobGCNodePath(storageId)];
552
- }
553
-
554
- return gcData;
555
- }
556
-
557
- /**
558
- * This is called to update blobs whose routes are used. The used blobs are removed from the tombstone list.
559
- * @param usedRoutes - The routes of the blob nodes that are used.
560
- */
561
- public updateUsedRoutes(usedRoutes: string[]) {
562
- // The routes or blob node paths are in the same format as returned in getGCData -
563
- // `/<BlobManager.basePath>/<blobId>`.
564
- for (const route of usedRoutes) {
565
- const pathParts = route.split("/");
566
- assert(
567
- pathParts.length === 3 && pathParts[1] === BlobManager.basePath,
568
- 0x4bc /* Invalid blob node id in used routes. */,
569
- );
570
- const blobId = pathParts[2];
571
- // Un-tombstone the blob if it was marked tombstone.
572
- this.tombstonedBlobs.delete(blobId);
573
- }
574
- }
575
-
576
- /**
577
- * This is called to update blobs whose routes are unused. The unused blobs are either deleted or marked as
578
- * tombstones.
579
- * @param unusedRoutes - The routes of the blob nodes that are unused.
580
- * @param tombstone - if true, the objects corresponding to unused routes are marked tombstones. Otherwise, they
581
- * are deleted.
582
- */
583
- public updateUnusedRoutes(unusedRoutes: string[], tombstone: boolean): void {
584
- // The routes or blob node paths are in the same format as returned in getGCData -
585
- // `/<BlobManager.basePath>/<blobId>`.
586
- for (const route of unusedRoutes) {
587
- const pathParts = route.split("/");
588
- assert(
589
- pathParts.length === 3 && pathParts[1] === BlobManager.basePath,
590
- 0x2d5 /* "Invalid blob node id in unused routes." */,
591
- );
592
- const blobId = pathParts[2];
593
-
594
- if (tombstone) {
595
- // If tombstone is set, add this blob to the tombstone list.
596
- this.tombstonedBlobs.add(blobId);
597
- } else {
598
- // The unused blobId could be a localId. If so, remove it from the redirect table and continue. The
599
- // corresponding storageId may still be used either directly or via other localIds.
600
- this.redirectTable.delete(blobId);
601
- }
602
- }
603
- }
604
-
605
- public summarize(telemetryContext?: ITelemetryContext): ISummaryTreeWithStats {
606
- // if storageIds is empty, it means we are detached and have only local IDs, or that there are no blobs attached
607
- const blobIds = this.storageIds.size > 0 ? Array.from(this.storageIds) : Array.from(this.redirectTable.keys());
608
- const builder = new SummaryTreeBuilder();
609
- blobIds.forEach((blobId) => {
610
- builder.addAttachment(blobId);
611
- });
612
-
613
- // Any non-identity entries in the table need to be saved in the summary
614
- if (this.redirectTable.size > blobIds.length) {
615
- builder.addBlob(
616
- BlobManager.redirectTableBlobName,
617
- // filter out identity entries
618
- JSON.stringify(Array.from(this.redirectTable.entries())
619
- .filter(([localId, storageId]) => localId !== storageId)),
620
- );
621
- }
622
-
623
- return builder.getSummaryTree();
624
- }
625
-
626
- public setRedirectTable(table: Map<string, string>) {
627
- assert(this.runtime.attachState === AttachState.Detached,
628
- 0x252 /* "redirect table can only be set in detached container" */);
629
- assert(this.redirectTable.size === table.size,
630
- 0x391 /* Redirect table size must match BlobManager's local ID count */);
631
- for (const [localId, storageId] of table) {
632
- assert(this.redirectTable.has(localId), 0x254 /* "unrecognized id in redirect table" */);
633
- this.redirectTable.set(localId, storageId);
634
- // set identity (id -> id) entry
635
- this.redirectTable.set(storageId, storageId);
636
- }
637
- }
638
-
639
- public getPendingBlobs(): IPendingBlobs {
640
- const blobs = {};
641
- for (const [key, entry] of this.pendingBlobs) {
642
- blobs[key] = { blob: bufferToString(entry.blob, "base64") };
643
- }
644
- return blobs;
645
- }
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
+ }
646
852
  }