@fluidframework/container-runtime 1.3.0 → 2.0.0-dev.1.4.5.105745

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 (222) hide show
  1. package/.eslintrc.js +8 -22
  2. package/.mocharc.js +12 -0
  3. package/dist/batchManager.d.ts +37 -0
  4. package/dist/batchManager.d.ts.map +1 -0
  5. package/dist/batchManager.js +73 -0
  6. package/dist/batchManager.js.map +1 -0
  7. package/dist/batchTracker.d.ts +1 -2
  8. package/dist/batchTracker.d.ts.map +1 -1
  9. package/dist/batchTracker.js +2 -3
  10. package/dist/batchTracker.js.map +1 -1
  11. package/dist/blobManager.d.ts +87 -25
  12. package/dist/blobManager.d.ts.map +1 -1
  13. package/dist/blobManager.js +317 -99
  14. package/dist/blobManager.js.map +1 -1
  15. package/dist/containerRuntime.d.ts +110 -125
  16. package/dist/containerRuntime.d.ts.map +1 -1
  17. package/dist/containerRuntime.js +360 -549
  18. package/dist/containerRuntime.js.map +1 -1
  19. package/dist/dataStore.js +29 -24
  20. package/dist/dataStore.js.map +1 -1
  21. package/dist/dataStoreContext.d.ts +20 -14
  22. package/dist/dataStoreContext.d.ts.map +1 -1
  23. package/dist/dataStoreContext.js +49 -58
  24. package/dist/dataStoreContext.js.map +1 -1
  25. package/dist/dataStores.d.ts +12 -5
  26. package/dist/dataStores.d.ts.map +1 -1
  27. package/dist/dataStores.js +21 -20
  28. package/dist/dataStores.js.map +1 -1
  29. package/dist/deltaScheduler.d.ts +6 -4
  30. package/dist/deltaScheduler.d.ts.map +1 -1
  31. package/dist/deltaScheduler.js +6 -4
  32. package/dist/deltaScheduler.js.map +1 -1
  33. package/dist/garbageCollection.d.ts +74 -14
  34. package/dist/garbageCollection.d.ts.map +1 -1
  35. package/dist/garbageCollection.js +248 -169
  36. package/dist/garbageCollection.js.map +1 -1
  37. package/dist/gcSweepReadyUsageDetection.d.ts +53 -0
  38. package/dist/gcSweepReadyUsageDetection.d.ts.map +1 -0
  39. package/dist/gcSweepReadyUsageDetection.js +135 -0
  40. package/dist/gcSweepReadyUsageDetection.js.map +1 -0
  41. package/dist/index.d.ts +2 -1
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +3 -2
  44. package/dist/index.js.map +1 -1
  45. package/dist/opProperties.d.ts +7 -0
  46. package/dist/opProperties.d.ts.map +1 -0
  47. package/dist/opProperties.js +20 -0
  48. package/dist/opProperties.js.map +1 -0
  49. package/dist/orderedClientElection.d.ts +28 -10
  50. package/dist/orderedClientElection.d.ts.map +1 -1
  51. package/dist/orderedClientElection.js +14 -4
  52. package/dist/orderedClientElection.js.map +1 -1
  53. package/dist/packageVersion.d.ts +1 -1
  54. package/dist/packageVersion.d.ts.map +1 -1
  55. package/dist/packageVersion.js +1 -1
  56. package/dist/packageVersion.js.map +1 -1
  57. package/dist/pendingStateManager.d.ts +0 -11
  58. package/dist/pendingStateManager.d.ts.map +1 -1
  59. package/dist/pendingStateManager.js +24 -46
  60. package/dist/pendingStateManager.js.map +1 -1
  61. package/dist/runningSummarizer.d.ts +14 -4
  62. package/dist/runningSummarizer.d.ts.map +1 -1
  63. package/dist/runningSummarizer.js +69 -27
  64. package/dist/runningSummarizer.js.map +1 -1
  65. package/dist/scheduleManager.d.ts +31 -0
  66. package/dist/scheduleManager.d.ts.map +1 -0
  67. package/dist/scheduleManager.js +243 -0
  68. package/dist/scheduleManager.js.map +1 -0
  69. package/dist/summarizer.d.ts +0 -2
  70. package/dist/summarizer.d.ts.map +1 -1
  71. package/dist/summarizer.js +1 -12
  72. package/dist/summarizer.js.map +1 -1
  73. package/dist/summarizerHeuristics.d.ts +26 -4
  74. package/dist/summarizerHeuristics.d.ts.map +1 -1
  75. package/dist/summarizerHeuristics.js +98 -18
  76. package/dist/summarizerHeuristics.js.map +1 -1
  77. package/dist/summarizerTypes.d.ts +45 -18
  78. package/dist/summarizerTypes.d.ts.map +1 -1
  79. package/dist/summarizerTypes.js +1 -1
  80. package/dist/summarizerTypes.js.map +1 -1
  81. package/dist/summaryCollection.d.ts +1 -0
  82. package/dist/summaryCollection.d.ts.map +1 -1
  83. package/dist/summaryCollection.js +31 -15
  84. package/dist/summaryCollection.js.map +1 -1
  85. package/dist/summaryFormat.d.ts +0 -5
  86. package/dist/summaryFormat.d.ts.map +1 -1
  87. package/dist/summaryFormat.js.map +1 -1
  88. package/dist/summaryGenerator.d.ts +1 -0
  89. package/dist/summaryGenerator.d.ts.map +1 -1
  90. package/dist/summaryGenerator.js +11 -9
  91. package/dist/summaryGenerator.js.map +1 -1
  92. package/dist/summaryManager.d.ts +2 -2
  93. package/dist/summaryManager.d.ts.map +1 -1
  94. package/dist/summaryManager.js +22 -7
  95. package/dist/summaryManager.js.map +1 -1
  96. package/lib/batchManager.d.ts +37 -0
  97. package/lib/batchManager.d.ts.map +1 -0
  98. package/lib/batchManager.js +69 -0
  99. package/lib/batchManager.js.map +1 -0
  100. package/lib/batchTracker.d.ts +1 -2
  101. package/lib/batchTracker.d.ts.map +1 -1
  102. package/lib/batchTracker.js +2 -3
  103. package/lib/batchTracker.js.map +1 -1
  104. package/lib/blobManager.d.ts +87 -25
  105. package/lib/blobManager.d.ts.map +1 -1
  106. package/lib/blobManager.js +319 -101
  107. package/lib/blobManager.js.map +1 -1
  108. package/lib/containerRuntime.d.ts +110 -125
  109. package/lib/containerRuntime.d.ts.map +1 -1
  110. package/lib/containerRuntime.js +366 -554
  111. package/lib/containerRuntime.js.map +1 -1
  112. package/lib/dataStore.js +29 -24
  113. package/lib/dataStore.js.map +1 -1
  114. package/lib/dataStoreContext.d.ts +20 -14
  115. package/lib/dataStoreContext.d.ts.map +1 -1
  116. package/lib/dataStoreContext.js +46 -55
  117. package/lib/dataStoreContext.js.map +1 -1
  118. package/lib/dataStores.d.ts +12 -5
  119. package/lib/dataStores.d.ts.map +1 -1
  120. package/lib/dataStores.js +21 -20
  121. package/lib/dataStores.js.map +1 -1
  122. package/lib/deltaScheduler.d.ts +6 -4
  123. package/lib/deltaScheduler.d.ts.map +1 -1
  124. package/lib/deltaScheduler.js +6 -4
  125. package/lib/deltaScheduler.js.map +1 -1
  126. package/lib/garbageCollection.d.ts +74 -14
  127. package/lib/garbageCollection.d.ts.map +1 -1
  128. package/lib/garbageCollection.js +237 -159
  129. package/lib/garbageCollection.js.map +1 -1
  130. package/lib/gcSweepReadyUsageDetection.d.ts +53 -0
  131. package/lib/gcSweepReadyUsageDetection.d.ts.map +1 -0
  132. package/lib/gcSweepReadyUsageDetection.js +130 -0
  133. package/lib/gcSweepReadyUsageDetection.js.map +1 -0
  134. package/lib/index.d.ts +2 -1
  135. package/lib/index.d.ts.map +1 -1
  136. package/lib/index.js +2 -1
  137. package/lib/index.js.map +1 -1
  138. package/lib/opProperties.d.ts +7 -0
  139. package/lib/opProperties.d.ts.map +1 -0
  140. package/lib/opProperties.js +16 -0
  141. package/lib/opProperties.js.map +1 -0
  142. package/lib/orderedClientElection.d.ts +28 -10
  143. package/lib/orderedClientElection.d.ts.map +1 -1
  144. package/lib/orderedClientElection.js +14 -4
  145. package/lib/orderedClientElection.js.map +1 -1
  146. package/lib/packageVersion.d.ts +1 -1
  147. package/lib/packageVersion.d.ts.map +1 -1
  148. package/lib/packageVersion.js +1 -1
  149. package/lib/packageVersion.js.map +1 -1
  150. package/lib/pendingStateManager.d.ts +0 -11
  151. package/lib/pendingStateManager.d.ts.map +1 -1
  152. package/lib/pendingStateManager.js +24 -46
  153. package/lib/pendingStateManager.js.map +1 -1
  154. package/lib/runningSummarizer.d.ts +14 -4
  155. package/lib/runningSummarizer.d.ts.map +1 -1
  156. package/lib/runningSummarizer.js +69 -27
  157. package/lib/runningSummarizer.js.map +1 -1
  158. package/lib/scheduleManager.d.ts +31 -0
  159. package/lib/scheduleManager.d.ts.map +1 -0
  160. package/lib/scheduleManager.js +239 -0
  161. package/lib/scheduleManager.js.map +1 -0
  162. package/lib/summarizer.d.ts +0 -2
  163. package/lib/summarizer.d.ts.map +1 -1
  164. package/lib/summarizer.js +1 -12
  165. package/lib/summarizer.js.map +1 -1
  166. package/lib/summarizerHeuristics.d.ts +26 -4
  167. package/lib/summarizerHeuristics.d.ts.map +1 -1
  168. package/lib/summarizerHeuristics.js +98 -18
  169. package/lib/summarizerHeuristics.js.map +1 -1
  170. package/lib/summarizerTypes.d.ts +45 -18
  171. package/lib/summarizerTypes.d.ts.map +1 -1
  172. package/lib/summarizerTypes.js +1 -1
  173. package/lib/summarizerTypes.js.map +1 -1
  174. package/lib/summaryCollection.d.ts +1 -0
  175. package/lib/summaryCollection.d.ts.map +1 -1
  176. package/lib/summaryCollection.js +31 -15
  177. package/lib/summaryCollection.js.map +1 -1
  178. package/lib/summaryFormat.d.ts +0 -5
  179. package/lib/summaryFormat.d.ts.map +1 -1
  180. package/lib/summaryFormat.js.map +1 -1
  181. package/lib/summaryGenerator.d.ts +1 -0
  182. package/lib/summaryGenerator.d.ts.map +1 -1
  183. package/lib/summaryGenerator.js +11 -9
  184. package/lib/summaryGenerator.js.map +1 -1
  185. package/lib/summaryManager.d.ts +2 -2
  186. package/lib/summaryManager.d.ts.map +1 -1
  187. package/lib/summaryManager.js +22 -7
  188. package/lib/summaryManager.js.map +1 -1
  189. package/package.json +68 -25
  190. package/src/batchManager.ts +91 -0
  191. package/src/batchTracker.ts +2 -3
  192. package/src/blobManager.ts +385 -118
  193. package/src/containerRuntime.ts +523 -732
  194. package/src/dataStore.ts +49 -37
  195. package/src/dataStoreContext.ts +44 -56
  196. package/src/dataStores.ts +34 -30
  197. package/src/deltaScheduler.ts +6 -4
  198. package/src/garbageCollection.ts +296 -205
  199. package/src/gcSweepReadyUsageDetection.ts +147 -0
  200. package/src/index.ts +1 -2
  201. package/src/opProperties.ts +19 -0
  202. package/src/orderedClientElection.ts +31 -10
  203. package/src/packageVersion.ts +1 -1
  204. package/src/pendingStateManager.ts +27 -59
  205. package/src/runningSummarizer.ts +76 -23
  206. package/src/scheduleManager.ts +314 -0
  207. package/src/summarizer.ts +1 -18
  208. package/src/summarizerHeuristics.ts +136 -19
  209. package/src/summarizerTypes.ts +53 -18
  210. package/src/summaryCollection.ts +33 -18
  211. package/src/summaryFormat.ts +0 -6
  212. package/src/summaryGenerator.ts +40 -22
  213. package/src/summaryManager.ts +22 -7
  214. package/dist/opTelemetry.d.ts +0 -22
  215. package/dist/opTelemetry.d.ts.map +0 -1
  216. package/dist/opTelemetry.js +0 -59
  217. package/dist/opTelemetry.js.map +0 -1
  218. package/lib/opTelemetry.d.ts +0 -22
  219. package/lib/opTelemetry.d.ts.map +0 -1
  220. package/lib/opTelemetry.js +0 -55
  221. package/lib/opTelemetry.js.map +0 -1
  222. package/src/opTelemetry.ts +0 -71
@@ -2,10 +2,12 @@
2
2
  * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
3
  * Licensed under the MIT License.
4
4
  */
5
+ import { v4 as uuid } from "uuid";
5
6
  import { generateHandleContextPath, SummaryTreeBuilder } from "@fluidframework/runtime-utils";
6
- import { assert, Deferred } from "@fluidframework/common-utils";
7
+ import { assert, bufferToString, Deferred, stringToBuffer } from "@fluidframework/common-utils";
7
8
  import { AttachState } from "@fluidframework/container-definitions";
8
- import { PerformanceEvent } from "@fluidframework/telemetry-utils";
9
+ import { ChildLogger, PerformanceEvent } from "@fluidframework/telemetry-utils";
10
+ import { Throttler, formExponentialFn } from "./throttler";
9
11
  /**
10
12
  * This class represents blob (long string)
11
13
  * This object is used only when creating (writing) new blob and serialization purposes.
@@ -32,33 +34,111 @@ export class BlobHandle {
32
34
  throw new Error("Cannot bind to blob handle");
33
35
  }
34
36
  }
37
+ class CancellableThrottler {
38
+ constructor(throttler) {
39
+ this.throttler = throttler;
40
+ this.cancelP = new Deferred();
41
+ }
42
+ async getDelay() {
43
+ return Promise.race([
44
+ this.cancelP.promise,
45
+ new Promise((resolve) => setTimeout(resolve, this.throttler.getDelay())),
46
+ ]);
47
+ }
48
+ cancel() {
49
+ this.cancelP.resolve();
50
+ this.cancelP = new Deferred();
51
+ }
52
+ }
53
+ // Note that while offline we "submit" an op before uploading the blob, but we always
54
+ // expect blobs to be uploaded before we actually see the op round-trip
55
+ var PendingBlobStatus;
56
+ (function (PendingBlobStatus) {
57
+ PendingBlobStatus[PendingBlobStatus["OnlinePendingUpload"] = 0] = "OnlinePendingUpload";
58
+ PendingBlobStatus[PendingBlobStatus["OnlinePendingOp"] = 1] = "OnlinePendingOp";
59
+ PendingBlobStatus[PendingBlobStatus["OfflinePendingUpload"] = 2] = "OfflinePendingUpload";
60
+ PendingBlobStatus[PendingBlobStatus["OfflinePendingOp"] = 3] = "OfflinePendingOp";
61
+ })(PendingBlobStatus || (PendingBlobStatus = {}));
35
62
  export class BlobManager {
36
- constructor(routeContext, snapshot, getStorage, attachBlobCallback,
63
+ constructor(routeContext, snapshot, getStorage,
64
+ /**
65
+ * Submit a BlobAttach op. When a blob is uploaded, there is a short grace period before which
66
+ * the blob is deleted. The BlobAttach op notifies the server that blob is in use. The server
67
+ * will then not delete the blob as long as it is listed as referenced in future summaries.
68
+ * The summarizing client will know to include the storage ID in the summary when it sees the op.
69
+ *
70
+ * The op may also include a local ID to inform all clients of the relation to the storage
71
+ * ID, without knowledge of which they cannot request the blob from storage. This is also
72
+ * included in the redirect table in the summary.
73
+ */
74
+ sendBlobAttachOp,
37
75
  // To be called when a blob node is requested. blobPath is the path of the blob's node in GC's graph. It's
38
76
  // of the format `/<BlobManager.basePath>/<blobId>`.
39
- gcNodeUpdated, runtime, logger) {
77
+ gcNodeUpdated, runtime, stashedBlobs = {}) {
40
78
  this.routeContext = routeContext;
41
79
  this.getStorage = getStorage;
42
- this.attachBlobCallback = attachBlobCallback;
80
+ this.sendBlobAttachOp = sendBlobAttachOp;
43
81
  this.gcNodeUpdated = gcNodeUpdated;
44
82
  this.runtime = runtime;
45
- this.logger = logger;
46
- // uploaded blob IDs
47
- this.blobIds = new Set();
48
- // blobs for which upload is pending. maps to a promise that will resolve once the blob has been uploaded and a
49
- // BlobAttach op has round-tripped.
50
- this.pendingBlobIds = new Map();
51
- // blobs uploaded while detached; cleared upon attach
52
- this.detachedBlobIds = new Set();
53
- this.runtime.once("dispose", () => {
54
- for (const promise of this.pendingBlobIds.values()) {
55
- promise.reject(new Error("runtime disposed while blobAttach op in flight"));
56
- }
83
+ /**
84
+ * Blobs which have not been uploaded or for which we have not yet seen a BlobAttach op round-trip.
85
+ * Until we see the op round-trip, there is a possibility we may need to re-upload the blob, so
86
+ * we must save it. This is true for both the online and offline flow.
87
+ */
88
+ this.pendingBlobs = new Map();
89
+ /**
90
+ * Track ops in flight for online flow. Used to avoid searching pendingBlobs since BlobAttach ops
91
+ * don't include local ID in online flow.
92
+ */
93
+ this.opsInFlight = new Map();
94
+ this.retryThrottler = new CancellableThrottler(new Throttler(60 * 1000, // 60 sec delay window
95
+ 30 * 1000, // 30 sec max delay
96
+ // throttling function increases exponentially (0ms, 40ms, 80ms, 160ms, etc)
97
+ formExponentialFn({ coefficient: 20, initialDelay: 0 })));
98
+ this.logger = ChildLogger.create(this.runtime.logger, "BlobManager");
99
+ this.runtime.on("disconnected", () => this.onDisconnected());
100
+ this.redirectTable = this.load(snapshot);
101
+ // Begin uploading stashed blobs from previous container instance
102
+ Object.entries(stashedBlobs).forEach(([localId, entry]) => {
103
+ const blob = stringToBuffer(entry.blob, "base64");
104
+ this.pendingBlobs.set(localId, {
105
+ blob,
106
+ status: PendingBlobStatus.OfflinePendingUpload,
107
+ handleP: new Deferred(),
108
+ uploadP: this.uploadBlob(localId, blob),
109
+ });
57
110
  });
58
- this.load(snapshot);
59
111
  }
60
- hasBlob(id) {
61
- return this.blobIds.has(id) || this.detachedBlobIds.has(id);
112
+ get pendingOfflineUploads() {
113
+ return Array.from(this.pendingBlobs.values())
114
+ .filter((e) => e.status === PendingBlobStatus.OfflinePendingUpload);
115
+ }
116
+ get hasPendingOfflineUploads() {
117
+ return this.pendingOfflineUploads.length > 0;
118
+ }
119
+ /**
120
+ * Upload blobs added while offline. This must be completed before connecting and resubmitting ops.
121
+ */
122
+ async onConnected() {
123
+ this.retryThrottler.cancel();
124
+ const pendingUploads = this.pendingOfflineUploads.map(async (e) => e.uploadP);
125
+ await PerformanceEvent.timedExecAsync(this.logger, {
126
+ eventName: "BlobUploadOnConnected",
127
+ count: pendingUploads.length,
128
+ }, async () => Promise.all(pendingUploads), { start: true, end: true });
129
+ }
130
+ /**
131
+ * Transition online blobs waiting for BlobAttach op round-trip since we will not see the op until we are connected
132
+ * again
133
+ */
134
+ onDisconnected() {
135
+ for (const [localId, entry] of this.pendingBlobs) {
136
+ if (entry.status === PendingBlobStatus.OnlinePendingOp) {
137
+ // This will submit another BlobAttach op for this blob. This is necessary because the one we sent
138
+ // already didn't have the local ID.
139
+ this.transitionToOffline(localId);
140
+ }
141
+ }
62
142
  }
63
143
  /**
64
144
  * For a blobId, returns its path in GC's graph. The node path is of the format `/<BlobManager.basePath>/<blobId>`
@@ -68,61 +148,200 @@ export class BlobManager {
68
148
  getBlobGCNodePath(blobId) {
69
149
  return `/${BlobManager.basePath}/${blobId}`;
70
150
  }
151
+ /**
152
+ * Set of actual storage IDs (i.e., IDs that can be requested from storage). This will be empty if the container is
153
+ * detached or there are no (non-pending) attachment blobs in the document
154
+ */
155
+ get storageIds() {
156
+ const ids = new Set(this.redirectTable.values());
157
+ // If we are detached, we will not have storage IDs, only undefined
158
+ const undefinedValueInTable = ids.delete(undefined);
159
+ // For a detached container, entries are inserted into the redirect table with an undefined storage ID.
160
+ // For an attached container, entries are inserted w/storage ID after the BlobAttach op round-trips.
161
+ assert(!undefinedValueInTable || this.runtime.attachState === AttachState.Detached && ids.size === 0, 0x382 /* 'redirectTable' must contain only undefined while detached / defined values while attached */);
162
+ return ids;
163
+ }
71
164
  async getBlob(blobId) {
72
- var _a, _b;
73
- const storageId = (_b = (_a = this.redirectTable) === null || _a === void 0 ? void 0 : _a.get(blobId)) !== null && _b !== void 0 ? _b : blobId;
74
- assert(this.hasBlob(storageId), 0x11f /* "requesting unknown blobs" */);
75
- // When this blob is retrieved, let the container runtime know that the corresponding GC node got updated.
165
+ const pending = this.pendingBlobs.get(blobId);
166
+ if (pending) {
167
+ return pending.blob;
168
+ }
169
+ let storageId;
170
+ if (this.runtime.attachState === AttachState.Detached) {
171
+ assert(this.redirectTable.has(blobId), 0x383 /* requesting unknown blobs */);
172
+ // Blobs created while the container is detached are stored in IDetachedBlobStorage.
173
+ // The 'IDocumentStorageService.readBlob()' call below will retrieve these via localId.
174
+ storageId = blobId;
175
+ }
176
+ else {
177
+ storageId = this.redirectTable.get(blobId);
178
+ assert(!!storageId, 0x11f /* "requesting unknown blobs" */);
179
+ }
180
+ // When a GC-able (not pending) blob is retrieved, let runtime know that the corresponding GC node got updated.
76
181
  this.gcNodeUpdated(this.getBlobGCNodePath(blobId));
77
- return new BlobHandle(`${BlobManager.basePath}/${storageId}`, this.routeContext, async () => PerformanceEvent.timedExecAsync(this.logger, { eventName: "AttachmentReadBlob", id: storageId }, async () => {
182
+ return PerformanceEvent.timedExecAsync(this.logger, { eventName: "AttachmentReadBlob", id: storageId }, async () => {
78
183
  return this.getStorage().readBlob(storageId);
79
- }, { end: true, cancel: "error" }));
184
+ }, { end: true, cancel: "error" });
185
+ }
186
+ getBlobHandle(id) {
187
+ assert(this.redirectTable.has(id) || this.pendingBlobs.has(id), 0x384 /* requesting handle for unknown blob */);
188
+ return new BlobHandle(`${BlobManager.basePath}/${id}`, this.routeContext, async () => this.getBlob(id));
189
+ }
190
+ async createBlobDetached(blob) {
191
+ // Blobs created while the container is detached are stored in IDetachedBlobStorage.
192
+ // The 'IDocumentStorageService.createBlob()' call below will respond with a localId.
193
+ const response = await this.getStorage().createBlob(blob);
194
+ this.redirectTable.set(response.id, undefined);
195
+ return this.getBlobHandle(response.id);
80
196
  }
81
197
  async createBlob(blob) {
82
- var _a, _b;
198
+ if (this.runtime.attachState === AttachState.Detached) {
199
+ return this.createBlobDetached(blob);
200
+ }
83
201
  if (this.runtime.attachState === AttachState.Attaching) {
84
202
  // blob upload is not supported in "Attaching" state
85
203
  this.logger.sendTelemetryEvent({ eventName: "CreateBlobWhileAttaching" });
86
204
  await new Promise((resolve) => this.runtime.once("attached", resolve));
87
205
  }
88
- if (!this.runtime.connected && this.runtime.attachState === AttachState.Attached) {
89
- // see https://github.com/microsoft/FluidFramework/issues/8246
90
- // Avoid getting storage if we are offline since it might be undefined. In the future we will return
91
- // handles immediately while offline
92
- await new Promise((resolve) => this.runtime.once("connected", resolve));
93
- }
94
- const response = await PerformanceEvent.timedExecAsync(this.logger, { eventName: "createBlob" }, async () => this.getStorage().createBlob(blob), { end: true, cancel: "error" });
95
- const handle = new BlobHandle(`${BlobManager.basePath}/${response.id}`, this.routeContext,
96
- // get() should go through BlobManager.getBlob() so handles created while detached can be redirected
97
- // to the correct storage id after they are uploaded
98
- async () => this.getBlob(response.id).then(async (h) => h.get()));
99
- if (this.runtime.attachState === AttachState.Detached) {
100
- this.detachedBlobIds.add(response.id);
101
- return handle;
206
+ assert(this.runtime.attachState === AttachState.Attached, 0x385 /* For clarity and paranoid defense against adding future attachment states */);
207
+ // Create a local ID for each blob. This is used to support blobs if/when the client goes
208
+ // offline since we don't have the ID from storage yet. If online flow succeeds this won't be used.
209
+ const localId = uuid();
210
+ const pendingEntry = {
211
+ blob,
212
+ status: PendingBlobStatus.OnlinePendingUpload,
213
+ handleP: new Deferred(),
214
+ uploadP: this.uploadBlob(localId, blob),
215
+ };
216
+ this.pendingBlobs.set(localId, pendingEntry);
217
+ return pendingEntry.handleP.promise;
218
+ }
219
+ async uploadBlob(localId, blob) {
220
+ return PerformanceEvent.timedExecAsync(this.logger, { eventName: "createBlob" }, async () => this.getStorage().createBlob(blob), { end: true, cancel: this.runtime.connected ? "error" : "generic" }).then((response) => this.onUploadResolve(localId, response), async (err) => this.onUploadReject(localId, err));
221
+ }
222
+ onUploadResolve(localId, response) {
223
+ var _a;
224
+ const entry = this.pendingBlobs.get(localId);
225
+ assert((entry === null || entry === void 0 ? void 0 : entry.status) === PendingBlobStatus.OnlinePendingUpload ||
226
+ (entry === null || entry === void 0 ? void 0 : entry.status) === PendingBlobStatus.OfflinePendingUpload, 0x386 /* Must have pending blob entry for uploaded blob */);
227
+ entry.storageId = response.id;
228
+ if (this.runtime.connected) {
229
+ if (entry.status === PendingBlobStatus.OnlinePendingUpload) {
230
+ if (this.storageIds.has(response.id)) {
231
+ // Storage may dedupe blobs and give us an ID we already know
232
+ // no need to submit BlobAttach op in this case
233
+ entry.handleP.resolve(this.getBlobHandle(response.id));
234
+ this.pendingBlobs.delete(localId);
235
+ }
236
+ else {
237
+ // Check for still-pending duplicates too; if an op is already in flight we can wait for that one
238
+ if (!this.opsInFlight.has(response.id)) {
239
+ this.sendBlobAttachOp(response.id);
240
+ }
241
+ this.opsInFlight.set(response.id, ((_a = this.opsInFlight.get(response.id)) !== null && _a !== void 0 ? _a : []).concat(localId));
242
+ entry.status = PendingBlobStatus.OnlinePendingOp;
243
+ }
244
+ }
245
+ else if (entry.status === PendingBlobStatus.OfflinePendingUpload) {
246
+ // We already submitted a BlobAttach op for this blob when it was transitioned to offline flow
247
+ entry.status = PendingBlobStatus.OfflinePendingOp;
248
+ }
102
249
  }
103
- // Note - server will de-dup blobs, so we might get existing blobId!
104
- if (this.pendingBlobIds.has(response.id)) {
105
- await ((_a = this.pendingBlobIds.get(response.id)) === null || _a === void 0 ? void 0 : _a.promise);
250
+ else {
251
+ // connected to storage but not ordering service?
252
+ this.logger.sendTelemetryEvent({ eventName: "BlobUploadSuccessWhileDisconnected" });
253
+ if (entry.status === PendingBlobStatus.OnlinePendingUpload) {
254
+ this.transitionToOffline(localId);
255
+ }
256
+ entry.status = PendingBlobStatus.OfflinePendingOp;
106
257
  }
107
- else if (!this.blobIds.has(response.id)) {
108
- this.pendingBlobIds.set(response.id, new Deferred());
109
- // send blob attach op and wait until we see it to return the handle
110
- this.attachBlobCallback(response.id);
111
- await ((_b = this.pendingBlobIds.get(response.id)) === null || _b === void 0 ? void 0 : _b.promise);
258
+ return response;
259
+ }
260
+ async onUploadReject(localId, error) {
261
+ const entry = this.pendingBlobs.get(localId);
262
+ assert(!!entry, 0x387 /* Must have pending blob entry for blob which failed to upload */);
263
+ if (!this.runtime.connected) {
264
+ if (entry.status === PendingBlobStatus.OnlinePendingUpload) {
265
+ this.transitionToOffline(localId);
266
+ }
267
+ // we are probably not connected to storage but start another upload request in case we are
268
+ entry.uploadP = this.retryThrottler.getDelay().then(async () => this.uploadBlob(localId, entry.blob));
269
+ return entry.uploadP;
112
270
  }
113
- return handle;
271
+ else {
272
+ entry.handleP.reject(error);
273
+ throw error;
274
+ }
275
+ }
276
+ transitionToOffline(localId) {
277
+ assert(!this.runtime.connected, 0x388 /* Must only transition to offline flow while runtime is disconnected */);
278
+ const entry = this.pendingBlobs.get(localId);
279
+ assert(!!entry, 0x389 /* No pending blob entry */);
280
+ assert([PendingBlobStatus.OnlinePendingUpload, PendingBlobStatus.OnlinePendingOp].includes(entry.status), 0x38a /* Blob must be in online flow to transition to offline flow */);
281
+ entry.status = entry.status === PendingBlobStatus.OnlinePendingUpload
282
+ ? PendingBlobStatus.OfflinePendingUpload
283
+ : PendingBlobStatus.OfflinePendingOp;
284
+ // Submit a BlobAttach op. It's important we submit this op now before returning the blob handle so the
285
+ // BlobAttach op is sequenced prior to any ops referencing the handle. Otherwise an invalid handle could be
286
+ // added to the document if the ops are not all successfully submitted upon reconnection.
287
+ // storageId may be undefined but since we are not connected we will have a chance to add it when reSubmit()
288
+ // is called
289
+ this.sendBlobAttachOp(entry.storageId, localId);
290
+ entry.handleP.resolve(this.getBlobHandle(localId));
291
+ }
292
+ /**
293
+ * Resubmit a BlobAttach op. Used to add storage IDs to ops that were
294
+ * submitted to runtime while disconnected.
295
+ * @param metadata - op metadata containing storage and/or local IDs
296
+ */
297
+ reSubmit(metadata) {
298
+ assert(!!metadata, 0x38b /* Resubmitted ops must have metadata */);
299
+ const { blobId, localId } = metadata;
300
+ if (!blobId) {
301
+ assert(!!localId, 0x38c /* Submitted BlobAttach ops must have a blobId or localId */);
302
+ // We submitted this op while offline. The blob should have been uploaded by now.
303
+ const pendingEntry = this.pendingBlobs.get(localId);
304
+ assert((pendingEntry === null || pendingEntry === void 0 ? void 0 : pendingEntry.status) === PendingBlobStatus.OfflinePendingOp &&
305
+ !!(pendingEntry === null || pendingEntry === void 0 ? void 0 : pendingEntry.storageId), 0x38d /* blob must be uploaded before resubmitting BlobAttach op */);
306
+ return this.sendBlobAttachOp(pendingEntry.storageId, localId);
307
+ }
308
+ return this.sendBlobAttachOp(blobId, localId);
114
309
  }
115
- processBlobAttachOp(blobId, local) {
310
+ processBlobAttachOp(message, local) {
311
+ var _a, _b;
312
+ assert((_a = message === null || message === void 0 ? void 0 : message.metadata) === null || _a === void 0 ? void 0 : _a.blobId, 0x12a /* "Missing blob id on metadata" */);
313
+ if (message.metadata.localId !== undefined) {
314
+ this.redirectTable.set(message.metadata.localId, message.metadata.blobId);
315
+ }
316
+ // set identity (id -> id) entry
317
+ this.redirectTable.set(message.metadata.blobId, message.metadata.blobId);
116
318
  if (local) {
117
- const pendingBlobP = this.pendingBlobIds.get(blobId);
118
- assert(pendingBlobP !== undefined, 0x1f8 /* "local BlobAttach op with no pending blob" */);
119
- pendingBlobP.resolve();
120
- this.pendingBlobIds.delete(blobId);
319
+ if (message.metadata.localId === undefined) {
320
+ // Since there is no local ID, we know this op was submitted while online.
321
+ const waitingBlobs = this.opsInFlight.get(message.metadata.blobId);
322
+ assert(!!waitingBlobs, 0x38e /* local online BlobAttach op with no pending blob */);
323
+ waitingBlobs.forEach((localId) => {
324
+ const pendingBlobEntry = this.pendingBlobs.get(localId);
325
+ assert(pendingBlobEntry !== undefined, 0x38f);
326
+ // It's possible we transitioned to offline flow while waiting for this op.
327
+ if (pendingBlobEntry.status === PendingBlobStatus.OnlinePendingOp) {
328
+ pendingBlobEntry.handleP.resolve(this.getBlobHandle(message.metadata.blobId));
329
+ this.pendingBlobs.delete(localId);
330
+ }
331
+ });
332
+ }
333
+ else {
334
+ // Each local ID is unique; get the pending blob entry and delete it
335
+ assert(((_b = this.pendingBlobs.get(message.metadata.localId)) === null || _b === void 0 ? void 0 : _b.status) === PendingBlobStatus.OfflinePendingOp, 0x1f8 /* "local BlobAttach op with no pending blob" */);
336
+ this.pendingBlobs.delete(message.metadata.localId);
337
+ }
121
338
  }
122
- this.blobIds.add(blobId);
123
339
  }
124
340
  /**
125
341
  * Reads blobs needed to load BlobManager from storage.
342
+ * @param blobsTree - Tree containing IDs of previously attached blobs. We
343
+ * look for the IDs in the blob entries of the tree since the both the r11s
344
+ * and SPO drivers replace the attachment types returned in snapshot() with blobs.
126
345
  */
127
346
  static async load(blobsTree, tryFetchBlob) {
128
347
  if (!blobsTree) {
@@ -138,33 +357,23 @@ export class BlobManager {
138
357
  return { ids, redirectTable };
139
358
  }
140
359
  /**
141
- * Load a set of previously attached blob IDs from a previous snapshot. Note
142
- * that BlobManager tracking and reporting attached blobs is a temporary
143
- * solution since storage expects attached blobs to be reported and any that
144
- * are not reported as attached may be GCed. In the future attached blob
145
- * IDs will be collected at summarization time, and runtime will not care
146
- * about the existence or specific formatting of this tree in returned
147
- * snapshots.
148
- *
149
- * @param blobsTree - Tree containing IDs of previously attached blobs. This
150
- * corresponds to snapshot() below. We look for the IDs in the blob entries
151
- * of the tree since the both the r11s and SPO drivers replace the
152
- * attachment types returned in snapshot() with blobs.
360
+ * Load a set of previously attached blob IDs and redirect table from a previous snapshot.
153
361
  */
154
362
  load(snapshot) {
155
363
  var _a, _b, _c;
156
- if (snapshot.ids) {
157
- const detached = this.runtime.attachState === AttachState.Detached;
158
- snapshot.ids.map((entry) => detached ? this.detachedBlobIds.add(entry) : this.blobIds.add(entry));
159
- }
160
- if (snapshot.redirectTable) {
161
- this.redirectTable = new Map(snapshot.redirectTable);
162
- }
163
364
  this.logger.sendTelemetryEvent({
164
365
  eventName: "AttachmentBlobsLoaded",
165
366
  count: (_b = (_a = snapshot.ids) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0,
166
367
  redirectTable: (_c = snapshot.redirectTable) === null || _c === void 0 ? void 0 : _c.length,
167
368
  });
369
+ const table = new Map(snapshot.redirectTable);
370
+ if (snapshot.ids) {
371
+ const detached = this.runtime.attachState === AttachState.Detached;
372
+ // If we are detached, we don't have storage IDs yet, so set to undefined
373
+ // Otherwise, set identity (id -> id) entries
374
+ snapshot.ids.forEach((entry) => table.set(entry, detached ? undefined : entry));
375
+ }
376
+ return table;
168
377
  }
169
378
  /**
170
379
  * Generates data used for garbage collection. Each blob uploaded represents a node in the GC graph as it can be
@@ -174,22 +383,23 @@ export class BlobManager {
174
383
  */
175
384
  getGCData(fullGC = false) {
176
385
  const gcData = { gcNodes: {} };
177
- this.blobIds.forEach((blobId) => {
386
+ /**
387
+ * The node path is of the format `/_blobs/blobId`. This path must match the path of the blob handle returned
388
+ * by the createBlob API because blobs are marked referenced by storing these handles in a referenced DDS.
389
+ */
390
+ this.storageIds.forEach((blobId) => {
178
391
  gcData.gcNodes[this.getBlobGCNodePath(blobId)] = [];
179
392
  });
180
- /**
181
- * For all blobs in the redirect table, the handle returned on creation is based off of the localId. So, these
182
- * nodes can be referenced by storing the localId handle. When that happens, the corresponding storageId node
183
- * must also be marked referenced. So, we add a route from the localId node to the storageId node.
184
- * Note that because of de-duping, there can be multiple localIds that all redirect to the same storageId or
185
- * a blob may be referenced via its storageId handle.
186
- */
187
- if (this.redirectTable !== undefined) {
188
- for (const [localId, storageId] of this.redirectTable) {
189
- // Add node for the localId and add a route to the storageId node. The storageId node will have been
190
- // added above when adding nodes for this.blobIds.
191
- gcData.gcNodes[this.getBlobGCNodePath(localId)] = [this.getBlobGCNodePath(storageId)];
192
- }
393
+ // For some blobs, the handle returned on creation is based off of the localId. So, these
394
+ // nodes can be referenced by storing the localId handle. When that happens, the corresponding storageId node
395
+ // must also be marked referenced. So, we add a route from the localId node to the storageId node.
396
+ // Note that because of de-duping, there can be multiple localIds that all redirect to the same storageId or
397
+ // a blob may be referenced via its storageId handle.
398
+ for (const [localId, storageId] of this.redirectTable) {
399
+ assert(!!storageId, 0x390 /* Must be attached to get GC data */);
400
+ // Add node for the localId and add a route to the storageId node. The storageId node will have been
401
+ // added above when adding nodes for this.blobIds.
402
+ gcData.gcNodes[this.getBlobGCNodePath(localId)] = [this.getBlobGCNodePath(storageId)];
193
403
  }
194
404
  return gcData;
195
405
  }
@@ -211,32 +421,40 @@ export class BlobManager {
211
421
  this.redirectTable.delete(blobId);
212
422
  continue;
213
423
  }
214
- this.blobIds.delete(blobId);
215
424
  }
216
425
  }
217
426
  summarize(telemetryContext) {
218
- // If we have a redirect table it means the container is about to transition to "Attaching" state, so we need
219
- // to return an actual snapshot containing all the real storage IDs we know about.
220
- const attachingOrAttached = !!this.redirectTable || this.runtime.attachState !== AttachState.Detached;
221
- const blobIds = attachingOrAttached ? this.blobIds : this.detachedBlobIds;
427
+ // if storageIds is empty, it means we are detached and have only local IDs, or that there are no blobs attached
428
+ const blobIds = this.storageIds.size > 0 ? Array.from(this.storageIds) : Array.from(this.redirectTable.keys());
222
429
  const builder = new SummaryTreeBuilder();
223
430
  blobIds.forEach((blobId) => {
224
431
  builder.addAttachment(blobId);
225
432
  });
226
- if (this.redirectTable && this.redirectTable.size > 0) {
227
- builder.addBlob(BlobManager.redirectTableBlobName, JSON.stringify(Array.from(this.redirectTable.entries())));
433
+ // Any non-identity entries in the table need to be saved in the summary
434
+ if (this.redirectTable.size > blobIds.length) {
435
+ builder.addBlob(BlobManager.redirectTableBlobName,
436
+ // filter out identity entries
437
+ JSON.stringify(Array.from(this.redirectTable.entries())
438
+ .filter(([localId, storageId]) => localId !== storageId)));
228
439
  }
229
440
  return builder.getSummaryTree();
230
441
  }
231
442
  setRedirectTable(table) {
232
443
  assert(this.runtime.attachState === AttachState.Detached, 0x252 /* "redirect table can only be set in detached container" */);
233
- assert(!this.redirectTable, 0x253 /* "redirect table already exists" */);
444
+ assert(this.redirectTable.size === table.size, 0x391 /* Redirect table size must match BlobManager's local ID count */);
234
445
  for (const [localId, storageId] of table) {
235
- assert(this.detachedBlobIds.delete(localId), 0x254 /* "unrecognized id in redirect table" */);
236
- this.blobIds.add(storageId);
446
+ assert(this.redirectTable.has(localId), 0x254 /* "unrecognized id in redirect table" */);
447
+ this.redirectTable.set(localId, storageId);
448
+ // set identity (id -> id) entry
449
+ this.redirectTable.set(storageId, storageId);
450
+ }
451
+ }
452
+ getPendingBlobs() {
453
+ const blobs = {};
454
+ for (const [key, entry] of this.pendingBlobs) {
455
+ blobs[key] = { blob: bufferToString(entry.blob, "base64") };
237
456
  }
238
- assert(this.detachedBlobIds.size === 0, 0x255 /* "detached blob id absent in redirect table" */);
239
- this.redirectTable = table;
457
+ return blobs;
240
458
  }
241
459
  }
242
460
  BlobManager.basePath = "_blobs";