@fluidframework/container-runtime 2.0.0-internal.3.0.0 → 2.0.0-internal.3.1.0

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