@fluidframework/container-runtime 1.2.2 → 2.0.0-internal.1.0.0.82159

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 (135) hide show
  1. package/dist/blobManager.d.ts +81 -25
  2. package/dist/blobManager.d.ts.map +1 -1
  3. package/dist/blobManager.js +301 -100
  4. package/dist/blobManager.js.map +1 -1
  5. package/dist/containerRuntime.d.ts +65 -11
  6. package/dist/containerRuntime.d.ts.map +1 -1
  7. package/dist/containerRuntime.js +101 -82
  8. package/dist/containerRuntime.js.map +1 -1
  9. package/dist/dataStore.d.ts +1 -1
  10. package/dist/dataStore.d.ts.map +1 -1
  11. package/dist/dataStore.js +32 -26
  12. package/dist/dataStore.js.map +1 -1
  13. package/dist/dataStoreContext.d.ts +3 -4
  14. package/dist/dataStoreContext.d.ts.map +1 -1
  15. package/dist/dataStoreContext.js +16 -23
  16. package/dist/dataStoreContext.js.map +1 -1
  17. package/dist/dataStores.d.ts +5 -2
  18. package/dist/dataStores.d.ts.map +1 -1
  19. package/dist/dataStores.js +11 -3
  20. package/dist/dataStores.js.map +1 -1
  21. package/dist/garbageCollection.d.ts.map +1 -1
  22. package/dist/garbageCollection.js +17 -12
  23. package/dist/garbageCollection.js.map +1 -1
  24. package/dist/opProperties.d.ts +7 -0
  25. package/dist/opProperties.d.ts.map +1 -0
  26. package/dist/opProperties.js +20 -0
  27. package/dist/opProperties.js.map +1 -0
  28. package/dist/packageVersion.d.ts +1 -1
  29. package/dist/packageVersion.d.ts.map +1 -1
  30. package/dist/packageVersion.js +1 -1
  31. package/dist/packageVersion.js.map +1 -1
  32. package/dist/runningSummarizer.d.ts +14 -4
  33. package/dist/runningSummarizer.d.ts.map +1 -1
  34. package/dist/runningSummarizer.js +68 -26
  35. package/dist/runningSummarizer.js.map +1 -1
  36. package/dist/summarizer.d.ts +0 -2
  37. package/dist/summarizer.d.ts.map +1 -1
  38. package/dist/summarizer.js +1 -12
  39. package/dist/summarizer.js.map +1 -1
  40. package/dist/summarizerHeuristics.d.ts +26 -4
  41. package/dist/summarizerHeuristics.d.ts.map +1 -1
  42. package/dist/summarizerHeuristics.js +95 -18
  43. package/dist/summarizerHeuristics.js.map +1 -1
  44. package/dist/summarizerTypes.d.ts +30 -10
  45. package/dist/summarizerTypes.d.ts.map +1 -1
  46. package/dist/summarizerTypes.js.map +1 -1
  47. package/dist/summaryCollection.js +1 -1
  48. package/dist/summaryCollection.js.map +1 -1
  49. package/dist/summaryFormat.d.ts +0 -5
  50. package/dist/summaryFormat.d.ts.map +1 -1
  51. package/dist/summaryFormat.js.map +1 -1
  52. package/dist/summaryGenerator.d.ts +1 -0
  53. package/dist/summaryGenerator.d.ts.map +1 -1
  54. package/dist/summaryGenerator.js +11 -9
  55. package/dist/summaryGenerator.js.map +1 -1
  56. package/lib/blobManager.d.ts +81 -25
  57. package/lib/blobManager.d.ts.map +1 -1
  58. package/lib/blobManager.js +302 -101
  59. package/lib/blobManager.js.map +1 -1
  60. package/lib/containerRuntime.d.ts +65 -11
  61. package/lib/containerRuntime.d.ts.map +1 -1
  62. package/lib/containerRuntime.js +103 -84
  63. package/lib/containerRuntime.js.map +1 -1
  64. package/lib/dataStore.d.ts +1 -1
  65. package/lib/dataStore.d.ts.map +1 -1
  66. package/lib/dataStore.js +32 -26
  67. package/lib/dataStore.js.map +1 -1
  68. package/lib/dataStoreContext.d.ts +3 -4
  69. package/lib/dataStoreContext.d.ts.map +1 -1
  70. package/lib/dataStoreContext.js +17 -24
  71. package/lib/dataStoreContext.js.map +1 -1
  72. package/lib/dataStores.d.ts +5 -2
  73. package/lib/dataStores.d.ts.map +1 -1
  74. package/lib/dataStores.js +11 -3
  75. package/lib/dataStores.js.map +1 -1
  76. package/lib/garbageCollection.d.ts.map +1 -1
  77. package/lib/garbageCollection.js +17 -12
  78. package/lib/garbageCollection.js.map +1 -1
  79. package/lib/opProperties.d.ts +7 -0
  80. package/lib/opProperties.d.ts.map +1 -0
  81. package/lib/opProperties.js +16 -0
  82. package/lib/opProperties.js.map +1 -0
  83. package/lib/packageVersion.d.ts +1 -1
  84. package/lib/packageVersion.d.ts.map +1 -1
  85. package/lib/packageVersion.js +1 -1
  86. package/lib/packageVersion.js.map +1 -1
  87. package/lib/runningSummarizer.d.ts +14 -4
  88. package/lib/runningSummarizer.d.ts.map +1 -1
  89. package/lib/runningSummarizer.js +68 -26
  90. package/lib/runningSummarizer.js.map +1 -1
  91. package/lib/summarizer.d.ts +0 -2
  92. package/lib/summarizer.d.ts.map +1 -1
  93. package/lib/summarizer.js +1 -12
  94. package/lib/summarizer.js.map +1 -1
  95. package/lib/summarizerHeuristics.d.ts +26 -4
  96. package/lib/summarizerHeuristics.d.ts.map +1 -1
  97. package/lib/summarizerHeuristics.js +95 -18
  98. package/lib/summarizerHeuristics.js.map +1 -1
  99. package/lib/summarizerTypes.d.ts +30 -10
  100. package/lib/summarizerTypes.d.ts.map +1 -1
  101. package/lib/summarizerTypes.js.map +1 -1
  102. package/lib/summaryCollection.js +1 -1
  103. package/lib/summaryCollection.js.map +1 -1
  104. package/lib/summaryFormat.d.ts +0 -5
  105. package/lib/summaryFormat.d.ts.map +1 -1
  106. package/lib/summaryFormat.js.map +1 -1
  107. package/lib/summaryGenerator.d.ts +1 -0
  108. package/lib/summaryGenerator.d.ts.map +1 -1
  109. package/lib/summaryGenerator.js +11 -9
  110. package/lib/summaryGenerator.js.map +1 -1
  111. package/package.json +45 -20
  112. package/src/blobManager.ts +360 -119
  113. package/src/containerRuntime.ts +203 -103
  114. package/src/dataStore.ts +53 -38
  115. package/src/dataStoreContext.ts +16 -23
  116. package/src/dataStores.ts +14 -3
  117. package/src/garbageCollection.ts +13 -7
  118. package/src/opProperties.ts +19 -0
  119. package/src/packageVersion.ts +1 -1
  120. package/src/runningSummarizer.ts +75 -22
  121. package/src/summarizer.ts +1 -18
  122. package/src/summarizerHeuristics.ts +133 -19
  123. package/src/summarizerTypes.ts +37 -10
  124. package/src/summaryCollection.ts +1 -1
  125. package/src/summaryFormat.ts +0 -6
  126. package/src/summaryGenerator.ts +40 -22
  127. package/dist/opTelemetry.d.ts +0 -22
  128. package/dist/opTelemetry.d.ts.map +0 -1
  129. package/dist/opTelemetry.js +0 -59
  130. package/dist/opTelemetry.js.map +0 -1
  131. package/lib/opTelemetry.d.ts +0 -22
  132. package/lib/opTelemetry.d.ts.map +0 -1
  133. package/lib/opTelemetry.js +0 -55
  134. package/lib/opTelemetry.js.map +0 -1
  135. 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
7
  import { assert, Deferred } 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,101 @@ 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) {
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
- }
57
- });
58
- this.load(snapshot);
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);
59
101
  }
60
- hasBlob(id) {
61
- return this.blobIds.has(id) || this.detachedBlobIds.has(id);
102
+ get pendingOfflineUploads() {
103
+ return Array.from(this.pendingBlobs.values())
104
+ .filter((e) => e.status === PendingBlobStatus.OfflinePendingUpload);
105
+ }
106
+ get hasPendingOfflineUploads() {
107
+ return this.pendingOfflineUploads.length > 0;
108
+ }
109
+ /**
110
+ * Upload blobs added while offline. This must be completed before connecting and resubmitting ops.
111
+ */
112
+ async onConnected() {
113
+ this.retryThrottler.cancel();
114
+ const pendingUploads = this.pendingOfflineUploads.map(async (e) => e.uploadP);
115
+ await PerformanceEvent.timedExecAsync(this.logger, {
116
+ eventName: "BlobUploadOnConnected",
117
+ count: pendingUploads.length,
118
+ }, async () => Promise.all(pendingUploads), { start: true, end: true });
119
+ }
120
+ /**
121
+ * Transition online blobs waiting for BlobAttach op round-trip since we will not see the op until we are connected
122
+ * again
123
+ */
124
+ onDisconnected() {
125
+ for (const [localId, entry] of this.pendingBlobs) {
126
+ if (entry.status === PendingBlobStatus.OnlinePendingOp) {
127
+ // This will submit another BlobAttach op for this blob. This is necessary because the one we sent
128
+ // already didn't have the local ID.
129
+ this.transitionToOffline(localId);
130
+ }
131
+ }
62
132
  }
63
133
  /**
64
134
  * For a blobId, returns its path in GC's graph. The node path is of the format `/<BlobManager.basePath>/<blobId>`
@@ -68,61 +138,200 @@ export class BlobManager {
68
138
  getBlobGCNodePath(blobId) {
69
139
  return `/${BlobManager.basePath}/${blobId}`;
70
140
  }
141
+ /**
142
+ * Set of actual storage IDs (i.e., IDs that can be requested from storage). This will be empty if the container is
143
+ * detached or there are no (non-pending) attachment blobs in the document
144
+ */
145
+ get storageIds() {
146
+ const ids = new Set(this.redirectTable.values());
147
+ // If we are detached, we will not have storage IDs, only undefined
148
+ const undefinedValueInTable = ids.delete(undefined);
149
+ // For a detached container, entries are inserted into the redirect table with an undefined storage ID.
150
+ // For an attached container, entries are inserted w/storage ID after the BlobAttach op round-trips.
151
+ assert(!undefinedValueInTable || this.runtime.attachState === AttachState.Detached && ids.size === 0, "'redirectTable' must contain only undefined while detached / defined values while attached");
152
+ return ids;
153
+ }
71
154
  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.
155
+ const pending = this.pendingBlobs.get(blobId);
156
+ if (pending) {
157
+ return pending.blob;
158
+ }
159
+ let storageId;
160
+ if (this.runtime.attachState === AttachState.Detached) {
161
+ assert(this.redirectTable.has(blobId), "requesting unknown blobs");
162
+ // Blobs created while the container is detached are stored in IDetachedBlobStorage.
163
+ // The 'IDocumentStorageService.readBlob()' call below will retrieve these via localId.
164
+ storageId = blobId;
165
+ }
166
+ else {
167
+ storageId = this.redirectTable.get(blobId);
168
+ assert(!!storageId, 0x11f /* "requesting unknown blobs" */);
169
+ }
170
+ // When a GC-able (not pending) blob is retrieved, let runtime know that the corresponding GC node got updated.
76
171
  this.gcNodeUpdated(this.getBlobGCNodePath(blobId));
77
- return new BlobHandle(`${BlobManager.basePath}/${storageId}`, this.routeContext, async () => PerformanceEvent.timedExecAsync(this.logger, { eventName: "AttachmentReadBlob", id: storageId }, async () => {
172
+ return PerformanceEvent.timedExecAsync(this.logger, { eventName: "AttachmentReadBlob", id: storageId }, async () => {
78
173
  return this.getStorage().readBlob(storageId);
79
- }, { end: true, cancel: "error" }));
174
+ }, { end: true, cancel: "error" });
175
+ }
176
+ getBlobHandle(id) {
177
+ assert(this.redirectTable.has(id) || this.pendingBlobs.has(id), "requesting handle for unknown blob");
178
+ return new BlobHandle(`${BlobManager.basePath}/${id}`, this.routeContext, async () => this.getBlob(id));
179
+ }
180
+ async createBlobDetached(blob) {
181
+ // Blobs created while the container is detached are stored in IDetachedBlobStorage.
182
+ // The 'IDocumentStorageService.createBlob()' call below will respond with a localId.
183
+ const response = await this.getStorage().createBlob(blob);
184
+ this.redirectTable.set(response.id, undefined);
185
+ return this.getBlobHandle(response.id);
80
186
  }
81
187
  async createBlob(blob) {
82
- var _a, _b;
188
+ if (this.runtime.attachState === AttachState.Detached) {
189
+ return this.createBlobDetached(blob);
190
+ }
83
191
  if (this.runtime.attachState === AttachState.Attaching) {
84
192
  // blob upload is not supported in "Attaching" state
85
193
  this.logger.sendTelemetryEvent({ eventName: "CreateBlobWhileAttaching" });
86
194
  await new Promise((resolve) => this.runtime.once("attached", resolve));
87
195
  }
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;
196
+ assert(this.runtime.attachState === AttachState.Attached, "For clarity and paranoid defense against adding future attachment states");
197
+ // Create a local ID for each blob. This is used to support blobs if/when the client goes
198
+ // offline since we don't have the ID from storage yet. If online flow succeeds this won't be used.
199
+ const localId = uuid();
200
+ const pendingEntry = {
201
+ blob,
202
+ status: PendingBlobStatus.OnlinePendingUpload,
203
+ handleP: new Deferred(),
204
+ uploadP: this.uploadBlob(localId, blob),
205
+ };
206
+ this.pendingBlobs.set(localId, pendingEntry);
207
+ return pendingEntry.handleP.promise;
208
+ }
209
+ async uploadBlob(localId, blob) {
210
+ 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));
211
+ }
212
+ onUploadResolve(localId, response) {
213
+ var _a;
214
+ const entry = this.pendingBlobs.get(localId);
215
+ assert((entry === null || entry === void 0 ? void 0 : entry.status) === PendingBlobStatus.OnlinePendingUpload ||
216
+ (entry === null || entry === void 0 ? void 0 : entry.status) === PendingBlobStatus.OfflinePendingUpload, "Must have pending blob entry for uploaded blob");
217
+ entry.storageId = response.id;
218
+ if (this.runtime.connected) {
219
+ if (entry.status === PendingBlobStatus.OnlinePendingUpload) {
220
+ if (this.storageIds.has(response.id)) {
221
+ // Storage may dedupe blobs and give us an ID we already know
222
+ // no need to submit BlobAttach op in this case
223
+ entry.handleP.resolve(this.getBlobHandle(response.id));
224
+ this.pendingBlobs.delete(localId);
225
+ }
226
+ else {
227
+ // Check for still-pending duplicates too; if an op is already in flight we can wait for that one
228
+ if (!this.opsInFlight.has(response.id)) {
229
+ this.sendBlobAttachOp(response.id);
230
+ }
231
+ this.opsInFlight.set(response.id, ((_a = this.opsInFlight.get(response.id)) !== null && _a !== void 0 ? _a : []).concat(localId));
232
+ entry.status = PendingBlobStatus.OnlinePendingOp;
233
+ }
234
+ }
235
+ else if (entry.status === PendingBlobStatus.OfflinePendingUpload) {
236
+ // We already submitted a BlobAttach op for this blob when it was transitioned to offline flow
237
+ entry.status = PendingBlobStatus.OfflinePendingOp;
238
+ }
102
239
  }
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);
240
+ else {
241
+ // connected to storage but not ordering service?
242
+ this.logger.sendTelemetryEvent({ eventName: "BlobUploadSuccessWhileDisconnected" });
243
+ if (entry.status === PendingBlobStatus.OnlinePendingUpload) {
244
+ this.transitionToOffline(localId);
245
+ }
246
+ entry.status = PendingBlobStatus.OfflinePendingOp;
106
247
  }
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);
248
+ return response;
249
+ }
250
+ async onUploadReject(localId, error) {
251
+ const entry = this.pendingBlobs.get(localId);
252
+ assert(!!entry, "Must have pending blob entry for blob which failed to upload");
253
+ if (!this.runtime.connected) {
254
+ if (entry.status === PendingBlobStatus.OnlinePendingUpload) {
255
+ this.transitionToOffline(localId);
256
+ }
257
+ // we are probably not connected to storage but start another upload request in case we are
258
+ entry.uploadP = this.retryThrottler.getDelay().then(async () => this.uploadBlob(localId, entry.blob));
259
+ return entry.uploadP;
260
+ }
261
+ else {
262
+ entry.handleP.reject(error);
263
+ throw error;
264
+ }
265
+ }
266
+ transitionToOffline(localId) {
267
+ assert(!this.runtime.connected, "Must only transition to offline flow while runtime is disconnected");
268
+ const entry = this.pendingBlobs.get(localId);
269
+ assert(!!entry, "No pending blob entry");
270
+ assert([PendingBlobStatus.OnlinePendingUpload, PendingBlobStatus.OnlinePendingOp].includes(entry.status), "Blob must be in online flow to transition to offline flow");
271
+ entry.status = entry.status === PendingBlobStatus.OnlinePendingUpload
272
+ ? PendingBlobStatus.OfflinePendingUpload
273
+ : PendingBlobStatus.OfflinePendingOp;
274
+ // Submit a BlobAttach op. It's important we submit this op now before returning the blob handle so the
275
+ // BlobAttach op is sequenced prior to any ops referencing the handle. Otherwise an invalid handle could be
276
+ // added to the document if the ops are not all successfully submitted upon reconnection.
277
+ // storageId may be undefined but since we are not connected we will have a chance to add it when reSubmit()
278
+ // is called
279
+ this.sendBlobAttachOp(entry.storageId, localId);
280
+ entry.handleP.resolve(this.getBlobHandle(localId));
281
+ }
282
+ /**
283
+ * Resubmit a BlobAttach op. Used to add storage IDs to ops that were
284
+ * submitted to runtime while disconnected.
285
+ * @param metadata - op metadata containing storage and/or local IDs
286
+ */
287
+ reSubmit(metadata) {
288
+ assert(!!metadata, "Resubmitted ops must have metadata");
289
+ const { blobId, localId } = metadata;
290
+ if (!blobId) {
291
+ assert(!!localId, "Submitted BlobAttach ops must have a blobId or localId");
292
+ // We submitted this op while offline. The blob should have been uploaded by now.
293
+ const pendingEntry = this.pendingBlobs.get(localId);
294
+ assert((pendingEntry === null || pendingEntry === void 0 ? void 0 : pendingEntry.status) === PendingBlobStatus.OfflinePendingOp &&
295
+ !!(pendingEntry === null || pendingEntry === void 0 ? void 0 : pendingEntry.storageId), "blob must be uploaded before resubmitting BlobAttach op");
296
+ return this.sendBlobAttachOp(pendingEntry.storageId, localId);
112
297
  }
113
- return handle;
298
+ return this.sendBlobAttachOp(blobId, localId);
114
299
  }
115
- processBlobAttachOp(blobId, local) {
300
+ processBlobAttachOp(message, local) {
301
+ var _a, _b;
302
+ 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" */);
303
+ if (message.metadata.localId !== undefined) {
304
+ this.redirectTable.set(message.metadata.localId, message.metadata.blobId);
305
+ }
306
+ // set identity (id -> id) entry
307
+ this.redirectTable.set(message.metadata.blobId, message.metadata.blobId);
116
308
  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);
309
+ if (message.metadata.localId === undefined) {
310
+ // Since there is no local ID, we know this op was submitted while online.
311
+ const waitingBlobs = this.opsInFlight.get(message.metadata.blobId);
312
+ assert(!!waitingBlobs, "local online BlobAttach op with no pending blob");
313
+ waitingBlobs.forEach((localId) => {
314
+ const pendingBlobEntry = this.pendingBlobs.get(localId);
315
+ assert(pendingBlobEntry !== undefined, "local online BlobAttach op with no pending blob entry");
316
+ // It's possible we transitioned to offline flow while waiting for this op.
317
+ if (pendingBlobEntry.status === PendingBlobStatus.OnlinePendingOp) {
318
+ pendingBlobEntry.handleP.resolve(this.getBlobHandle(message.metadata.blobId));
319
+ this.pendingBlobs.delete(localId);
320
+ }
321
+ });
322
+ }
323
+ else {
324
+ // Each local ID is unique; get the pending blob entry and delete it
325
+ 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" */);
326
+ this.pendingBlobs.delete(message.metadata.localId);
327
+ }
121
328
  }
122
- this.blobIds.add(blobId);
123
329
  }
124
330
  /**
125
331
  * Reads blobs needed to load BlobManager from storage.
332
+ * @param blobsTree - Tree containing IDs of previously attached blobs. We
333
+ * look for the IDs in the blob entries of the tree since the both the r11s
334
+ * and SPO drivers replace the attachment types returned in snapshot() with blobs.
126
335
  */
127
336
  static async load(blobsTree, tryFetchBlob) {
128
337
  if (!blobsTree) {
@@ -138,33 +347,23 @@ export class BlobManager {
138
347
  return { ids, redirectTable };
139
348
  }
140
349
  /**
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.
350
+ * Load a set of previously attached blob IDs and redirect table from a previous snapshot.
153
351
  */
154
352
  load(snapshot) {
155
353
  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
354
  this.logger.sendTelemetryEvent({
164
355
  eventName: "AttachmentBlobsLoaded",
165
356
  count: (_b = (_a = snapshot.ids) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0,
166
357
  redirectTable: (_c = snapshot.redirectTable) === null || _c === void 0 ? void 0 : _c.length,
167
358
  });
359
+ const table = new Map(snapshot.redirectTable);
360
+ if (snapshot.ids) {
361
+ const detached = this.runtime.attachState === AttachState.Detached;
362
+ // If we are detached, we don't have storage IDs yet, so set to undefined
363
+ // Otherwise, set identity (id -> id) entries
364
+ snapshot.ids.forEach((entry) => table.set(entry, detached ? undefined : entry));
365
+ }
366
+ return table;
168
367
  }
169
368
  /**
170
369
  * Generates data used for garbage collection. Each blob uploaded represents a node in the GC graph as it can be
@@ -174,22 +373,23 @@ export class BlobManager {
174
373
  */
175
374
  getGCData(fullGC = false) {
176
375
  const gcData = { gcNodes: {} };
177
- this.blobIds.forEach((blobId) => {
376
+ /**
377
+ * The node path is of the format `/_blobs/blobId`. This path must match the path of the blob handle returned
378
+ * by the createBlob API because blobs are marked referenced by storing these handles in a referenced DDS.
379
+ */
380
+ this.storageIds.forEach((blobId) => {
178
381
  gcData.gcNodes[this.getBlobGCNodePath(blobId)] = [];
179
382
  });
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
- }
383
+ // For some blobs, the handle returned on creation is based off of the localId. So, these
384
+ // nodes can be referenced by storing the localId handle. When that happens, the corresponding storageId node
385
+ // must also be marked referenced. So, we add a route from the localId node to the storageId node.
386
+ // Note that because of de-duping, there can be multiple localIds that all redirect to the same storageId or
387
+ // a blob may be referenced via its storageId handle.
388
+ for (const [localId, storageId] of this.redirectTable) {
389
+ assert(!!storageId, "Must be attached to get GC data");
390
+ // Add node for the localId and add a route to the storageId node. The storageId node will have been
391
+ // added above when adding nodes for this.blobIds.
392
+ gcData.gcNodes[this.getBlobGCNodePath(localId)] = [this.getBlobGCNodePath(storageId)];
193
393
  }
194
394
  return gcData;
195
395
  }
@@ -211,32 +411,33 @@ export class BlobManager {
211
411
  this.redirectTable.delete(blobId);
212
412
  continue;
213
413
  }
214
- this.blobIds.delete(blobId);
215
414
  }
216
415
  }
217
416
  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;
417
+ // if storageIds is empty, it means we are detached and have only local IDs, or that there are no blobs attached
418
+ const blobIds = this.storageIds.size > 0 ? Array.from(this.storageIds) : Array.from(this.redirectTable.keys());
222
419
  const builder = new SummaryTreeBuilder();
223
420
  blobIds.forEach((blobId) => {
224
421
  builder.addAttachment(blobId);
225
422
  });
226
- if (this.redirectTable && this.redirectTable.size > 0) {
227
- builder.addBlob(BlobManager.redirectTableBlobName, JSON.stringify(Array.from(this.redirectTable.entries())));
423
+ // Any non-identity entries in the table need to be saved in the summary
424
+ if (this.redirectTable.size > blobIds.length) {
425
+ builder.addBlob(BlobManager.redirectTableBlobName,
426
+ // filter out identity entries
427
+ JSON.stringify(Array.from(this.redirectTable.entries())
428
+ .filter(([localId, storageId]) => localId !== storageId)));
228
429
  }
229
430
  return builder.getSummaryTree();
230
431
  }
231
432
  setRedirectTable(table) {
232
433
  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" */);
434
+ assert(this.redirectTable.size === table.size, "Redirect table size must match BlobManager's local ID count");
234
435
  for (const [localId, storageId] of table) {
235
- assert(this.detachedBlobIds.delete(localId), 0x254 /* "unrecognized id in redirect table" */);
236
- this.blobIds.add(storageId);
436
+ assert(this.redirectTable.has(localId), 0x254 /* "unrecognized id in redirect table" */);
437
+ this.redirectTable.set(localId, storageId);
438
+ // set identity (id -> id) entry
439
+ this.redirectTable.set(storageId, storageId);
237
440
  }
238
- assert(this.detachedBlobIds.size === 0, 0x255 /* "detached blob id absent in redirect table" */);
239
- this.redirectTable = table;
240
441
  }
241
442
  }
242
443
  BlobManager.basePath = "_blobs";