@fluidframework/container-runtime 2.63.0-359734 → 2.63.0-359962

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.
@@ -28,12 +28,14 @@ class BlobHandle extends internal_3.FluidHandleBase {
28
28
  return (this._events ??= (0, client_utils_1.createEmitter)());
29
29
  }
30
30
  get payloadState() {
31
- return this._state;
31
+ return this._payloadState;
32
32
  }
33
33
  get payloadShareError() {
34
34
  return this._payloadShareError;
35
35
  }
36
- constructor(path, routeContext, get, payloadPending, onAttachGraph) {
36
+ constructor(path, routeContext,
37
+ // TODO: just take the blob rather than a get function?
38
+ get, payloadPending, onAttachGraph) {
37
39
  super();
38
40
  this.path = path;
39
41
  this.routeContext = routeContext;
@@ -41,15 +43,15 @@ class BlobHandle extends internal_3.FluidHandleBase {
41
43
  this.payloadPending = payloadPending;
42
44
  this.onAttachGraph = onAttachGraph;
43
45
  this.attached = false;
44
- this._state = "pending";
45
46
  this.notifyShared = () => {
46
- this._state = "shared";
47
+ this._payloadState = "shared";
47
48
  this._events?.emit("payloadShared");
48
49
  };
49
50
  this.notifyFailed = (error) => {
50
51
  this._payloadShareError = error;
51
52
  this._events?.emit("payloadShareFailed", error);
52
53
  };
54
+ this._payloadState = payloadPending ? "pending" : "shared";
53
55
  this.absolutePath = (0, internal_3.generateHandleContextPath)(path, this.routeContext);
54
56
  }
55
57
  attachGraph() {
@@ -60,20 +62,201 @@ class BlobHandle extends internal_3.FluidHandleBase {
60
62
  }
61
63
  }
62
64
  exports.BlobHandle = BlobHandle;
65
+ /**
66
+ * Check if for a given uploaded or attaching blob, the TTL is too close to expiry to safely attempt
67
+ * an attach. Currently using a heuristic of half the TTL duration having passed since upload.
68
+ */
69
+ const isTTLTooCloseToExpiry = (blobRecord) => blobRecord.minTTLInSeconds !== undefined &&
70
+ Date.now() - blobRecord.uploadTime > (blobRecord.minTTLInSeconds / 2) * 1000;
71
+ const createAbortError = () => new internal_4.LoggingError("uploadBlob aborted");
63
72
  exports.blobManagerBasePath = "_blobs";
64
73
  class BlobManager {
65
74
  constructor(props) {
66
75
  this.internalEvents = (0, client_utils_1.createEmitter)();
67
76
  /**
68
- * Blobs which we have not yet seen a BlobAttach op round-trip and not yet attached to a DDS.
77
+ * The localBlobCache has a dual role of caching locally-created blobs, as well as tracking their state as they
78
+ * are shared. Keys are localIds.
79
+ */
80
+ this.localBlobCache = new Map();
81
+ /**
82
+ * Blobs with an attached handle that have not finished blob-attaching are the set we need to provide from
83
+ * getPendingState(). This stores their local IDs, and then we can look them up against the localBlobCache.
69
84
  */
70
- this.pendingBlobs = new Map();
85
+ this.pendingBlobsWithAttachedHandles = new Set();
71
86
  /**
72
- * Track ops in flight for online flow. This is used for optimizations where if we receive an ack for a storage ID,
73
- * we can resolve all pending blobs with the same storage ID even though they may have different local IDs. That's
74
- * because we know that the server will not delete the blob corresponding to that storage ID.
87
+ * Local IDs for any pending blobs we loaded with and have not yet started the upload/attach flow for.
75
88
  */
76
- this.opsInFlight = new Map();
89
+ this.pendingOnlyLocalIds = new Set();
90
+ /**
91
+ * Upload and attach the localBlobCache entry for the given localId.
92
+ *
93
+ * Expects the localBlobCache entry for the given localId to be in either localOnly or uploaded state
94
+ * when called. Returns a promise that resolves when the blob completes uploading and attaching, or else
95
+ * rejects if an error is encountered or the signal is aborted.
96
+ */
97
+ this.uploadAndAttach = async (localId, signal) => {
98
+ if (signal?.aborted === true) {
99
+ this.localBlobCache.delete(localId);
100
+ this.pendingBlobsWithAttachedHandles.delete(localId);
101
+ throw createAbortError();
102
+ }
103
+ const localBlobRecordInitial = this.localBlobCache.get(localId);
104
+ (0, internal_2.assert)(localBlobRecordInitial?.state === "localOnly" ||
105
+ localBlobRecordInitial?.state === "uploaded", "Expect uploadAndAttach to be called with either localOnly or uploaded state");
106
+ const { blob } = localBlobRecordInitial;
107
+ /**
108
+ * Expects the localBlobCache entry for the given localId to be in either localOnly or uploaded state
109
+ * when called. Returns a promise that resolves when the blob is in uploaded or attached state, or else
110
+ * rejects on error during upload or if the signal is aborted.
111
+ *
112
+ * Most of the time this should be expected to exit in uploaded state, but if we are loading from pending
113
+ * state we may see an attach op from the client that generated the pending state, which can complete the
114
+ * attach while the upload is outstanding.
115
+ */
116
+ const ensureUploaded = async () => {
117
+ const localBlobRecord = this.localBlobCache.get(localId);
118
+ if (localBlobRecord?.state === "uploaded") {
119
+ // In normal creation flows, the blob will be in localOnly state here. But in the case of loading
120
+ // with pending state we can call it with an uploaded-but-not-attached blob. Start the upload
121
+ // flow only if it's localOnly.
122
+ return;
123
+ }
124
+ (0, internal_2.assert)(localBlobRecord?.state === "localOnly", "Attempting to upload from unexpected state");
125
+ this.localBlobCache.set(localId, { state: "uploading", blob });
126
+ await new Promise((resolve, reject) => {
127
+ // If we eventually have driver-level support for abort, then this can simplify a bit as we won't
128
+ // need to track upload completion and abort separately. Until then, we need to handle the case that
129
+ // the upload continues and settles after becoming irrelevant due to signal abort or blob attach.
130
+ let uploadHasBecomeIrrelevant = false;
131
+ const onSignalAbort = () => {
132
+ removeListeners();
133
+ uploadHasBecomeIrrelevant = true;
134
+ this.localBlobCache.delete(localId);
135
+ this.pendingBlobsWithAttachedHandles.delete(localId);
136
+ reject(createAbortError());
137
+ };
138
+ const onProcessedBlobAttach = (_localId, _storageId) => {
139
+ if (_localId === localId) {
140
+ removeListeners();
141
+ uploadHasBecomeIrrelevant = true;
142
+ resolve();
143
+ }
144
+ };
145
+ const removeListeners = () => {
146
+ this.internalEvents.off("processedBlobAttach", onProcessedBlobAttach);
147
+ signal?.removeEventListener("abort", onSignalAbort);
148
+ };
149
+ this.internalEvents.on("processedBlobAttach", onProcessedBlobAttach);
150
+ signal?.addEventListener("abort", onSignalAbort);
151
+ this.storage
152
+ .createBlob(blob)
153
+ .then((createBlobResponse) => {
154
+ if (!uploadHasBecomeIrrelevant) {
155
+ removeListeners();
156
+ this.localBlobCache.set(localId, {
157
+ state: "uploaded",
158
+ blob,
159
+ storageId: createBlobResponse.id,
160
+ uploadTime: Date.now(),
161
+ minTTLInSeconds: createBlobResponse.minTTLInSeconds,
162
+ });
163
+ resolve();
164
+ }
165
+ })
166
+ .catch((error) => {
167
+ if (!uploadHasBecomeIrrelevant) {
168
+ removeListeners();
169
+ // If the storage call errors, we can't recover. Reject to throw back to the caller.
170
+ this.localBlobCache.delete(localId);
171
+ this.pendingBlobsWithAttachedHandles.delete(localId);
172
+ reject(error);
173
+ }
174
+ });
175
+ });
176
+ };
177
+ /**
178
+ * Expects the localBlobCache entry for the given localId to be in uploaded or attached state when called.
179
+ * Returns a promise that resolves to true if the blob is successfully attached, or false if it cannot be
180
+ * attached and the upload flow needs to be restarted from the top (currently only if the TTL expires before
181
+ * attach can be completed). In the latter case, the localBlobRecord will also be reset to localOnly state.
182
+ * The promise rejects if the signal is aborted.
183
+ */
184
+ const tryAttach = async () => {
185
+ const localBlobRecord = this.localBlobCache.get(localId);
186
+ if (localBlobRecord?.state === "attached") {
187
+ // In normal creation flows, the blob will be in uploaded state here. But if we are loading from pending
188
+ // state and see an attach op from the client that generated the pending state, we may have reached
189
+ // attached state in the middle of the upload attempt. In that case there's no more work to do and we
190
+ // can just return.
191
+ return true;
192
+ }
193
+ (0, internal_2.assert)(localBlobRecord?.state === "uploaded", "Attempting to attach from unexpected state");
194
+ // If we just uploaded the blob TTL really shouldn't be expired at this location. But if we loaded from
195
+ // pending state, the upload may have happened some time far in the past and could be expired here.
196
+ if (isTTLTooCloseToExpiry(localBlobRecord)) {
197
+ // If the TTL is expired, we assume it's gone from the storage and so is effectively localOnly again.
198
+ // Then when we re-enter the loop, we'll re-upload it.
199
+ this.localBlobCache.set(localId, { state: "localOnly", blob });
200
+ // Emitting here isn't really necessary since the only listener would be attached below. Including here
201
+ // for completeness though, in case we add other listeners in the future.
202
+ this.internalEvents.emit("blobExpired", localId);
203
+ return false;
204
+ }
205
+ else {
206
+ this.localBlobCache.set(localId, {
207
+ ...localBlobRecord,
208
+ state: "attaching",
209
+ });
210
+ // Send and await a blob attach op. This serves two purposes:
211
+ // 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
212
+ // until its storage ID is added to the next summary.
213
+ // 2. It will create a local ID to storage ID mapping in all clients which is needed to retrieve the
214
+ // blob from the server via the storage ID.
215
+ return new Promise((resolve, reject) => {
216
+ const onProcessedBlobAttach = (_localId, _storageId) => {
217
+ if (_localId === localId) {
218
+ removeListeners();
219
+ resolve(true);
220
+ }
221
+ };
222
+ // Although we already checked for TTL expiry above, the op we're about to send may later be asked
223
+ // to resubmit. Before we resubmit, we check again for TTL expiry - this listener is how we learn if
224
+ // we discovered expiry in the resubmit flow.
225
+ const onBlobExpired = (_localId) => {
226
+ if (_localId === localId) {
227
+ removeListeners();
228
+ resolve(false);
229
+ }
230
+ };
231
+ const onSignalAbort = () => {
232
+ removeListeners();
233
+ this.localBlobCache.delete(localId);
234
+ this.pendingBlobsWithAttachedHandles.delete(localId);
235
+ reject(createAbortError());
236
+ };
237
+ const removeListeners = () => {
238
+ this.internalEvents.off("processedBlobAttach", onProcessedBlobAttach);
239
+ this.internalEvents.off("blobExpired", onBlobExpired);
240
+ signal?.removeEventListener("abort", onSignalAbort);
241
+ };
242
+ this.internalEvents.on("processedBlobAttach", onProcessedBlobAttach);
243
+ this.internalEvents.on("blobExpired", onBlobExpired);
244
+ signal?.addEventListener("abort", onSignalAbort);
245
+ this.sendBlobAttachOp(localId, localBlobRecord.storageId);
246
+ });
247
+ }
248
+ };
249
+ let attachCompleted = false;
250
+ while (!attachCompleted) {
251
+ await ensureUploaded();
252
+ attachCompleted = await tryAttach();
253
+ // If something stopped the attach from completing successfully (currently just TTL expiry),
254
+ // we expect that the blob was already updated to reflect the updated state (i.e. back to localOnly)
255
+ // and we'll try the loop again from the top.
256
+ }
257
+ // When the blob successfully attaches, the localBlobRecord will have been updated to attached state
258
+ // at the time we processed the op, so there's nothing else to do here.
259
+ };
77
260
  /**
78
261
  * Called in detached state just prior to attaching, this will update the redirect table by
79
262
  * converting the pseudo storage IDs into real storage IDs using the provided detachedStorageTable.
@@ -93,14 +276,27 @@ class BlobManager {
93
276
  for (const [localId, detachedStorageId] of redirectTableEntries) {
94
277
  const newStorageId = detachedStorageTable.get(detachedStorageId);
95
278
  (0, internal_2.assert)(newStorageId !== undefined, 0xc53 /* Couldn't find a matching storage ID */);
96
- this.setRedirection(localId, newStorageId);
279
+ this.redirectTable.set(localId, newStorageId);
97
280
  // set identity (id -> id) entry
98
- this.setRedirection(newStorageId, newStorageId);
281
+ this.redirectTable.set(newStorageId, newStorageId);
99
282
  }
100
283
  };
101
- const { routeContext, blobManagerLoadInfo, storage, sendBlobAttachOp, blobRequested, isBlobDeleted, runtime, localIdGenerator, createBlobPayloadPending, } = props;
284
+ /**
285
+ * Upload and attach any pending blobs that the BlobManager was loaded with that have not already
286
+ * been attached in the meantime.
287
+ * @returns A promise that resolves when all the uploads and attaches have completed, or rejects
288
+ * if any of them fail.
289
+ */
290
+ this.sharePendingBlobs = async () => {
291
+ const localIdsToUpload = [...this.pendingOnlyLocalIds];
292
+ this.pendingOnlyLocalIds.clear();
293
+ // TODO: Determine if Promise.all is ergonomic at the callsite. Would Promise.allSettled be better?
294
+ await Promise.all(localIdsToUpload.map(async (localId) => this.uploadAndAttach(localId)));
295
+ };
296
+ const { routeContext, blobManagerLoadInfo, storage, sendBlobAttachOp, blobRequested, isBlobDeleted, runtime, pendingBlobs, localIdGenerator, createBlobPayloadPending, } = props;
102
297
  this.routeContext = routeContext;
103
298
  this.storage = storage;
299
+ this.sendBlobAttachOp = sendBlobAttachOp;
104
300
  this.blobRequested = blobRequested;
105
301
  this.isBlobDeleted = isBlobDeleted;
106
302
  this.runtime = runtime;
@@ -111,44 +307,30 @@ class BlobManager {
111
307
  namespace: "BlobManager",
112
308
  });
113
309
  this.redirectTable = (0, blobManagerSnapSum_js_1.toRedirectTable)(blobManagerLoadInfo, this.mc.logger);
114
- this.sendBlobAttachOp = (localId, storageId) => {
115
- const pendingEntry = this.pendingBlobs.get(localId);
116
- (0, internal_2.assert)(pendingEntry !== undefined, 0x725 /* Must have pending blob entry for upcoming op */);
117
- if (pendingEntry?.uploadTime !== undefined &&
118
- pendingEntry?.minTTLInSeconds !== undefined) {
119
- const secondsSinceUpload = (Date.now() - pendingEntry.uploadTime) / 1000;
120
- const expired = pendingEntry.minTTLInSeconds - secondsSinceUpload < 0;
121
- this.mc.logger.sendTelemetryEvent({
122
- eventName: "sendBlobAttach",
123
- secondsSinceUpload,
124
- minTTLInSeconds: pendingEntry.minTTLInSeconds,
125
- expired,
126
- });
127
- if (expired) {
128
- // reupload blob and reset previous fields
129
- this.pendingBlobs.set(localId, {
130
- ...pendingEntry,
131
- storageId: undefined,
132
- uploadTime: undefined,
133
- minTTLInSeconds: undefined,
134
- opsent: false,
135
- uploadP: this.uploadBlob(localId, pendingEntry.blob),
136
- });
137
- return;
138
- }
310
+ // We populate the localBlobCache with any pending blobs we are provided, which makes them available
311
+ // to access even though they are not shared yet. However, we don't start the share flow until it is
312
+ // explicitly invoked via sharePendingBlobs() in case we are loaded in a frozen container.
313
+ if (pendingBlobs !== undefined) {
314
+ for (const [localId, serializableBlobRecord] of Object.entries(pendingBlobs)) {
315
+ (0, internal_2.assert)(!this.redirectTable.has(localId), "Pending blob already in redirect table");
316
+ const localBlobRecord = {
317
+ ...serializableBlobRecord,
318
+ blob: (0, client_utils_1.stringToBuffer)(serializableBlobRecord.blob, "base64"),
319
+ };
320
+ this.localBlobCache.set(localId, localBlobRecord);
321
+ // Since we received these blobs from pending state, we'll assume they were only added to the
322
+ // pending state at generation time because their handles were attached. We add them back here
323
+ // in case we need to round-trip them back out again due to another getPendingBlobs() call.
324
+ this.pendingBlobsWithAttachedHandles.add(localId);
325
+ this.pendingOnlyLocalIds.add(localId);
139
326
  }
140
- pendingEntry.opsent = true;
141
- sendBlobAttachOp(localId, storageId);
142
- };
143
- }
144
- createAbortError(pending) {
145
- return new internal_4.LoggingError("uploadBlob aborted", {
146
- acked: pending?.acked,
147
- uploadTime: pending?.uploadTime,
148
- });
327
+ }
149
328
  }
329
+ /**
330
+ * Returns whether a blob with the given localId can be retrieved by the BlobManager via getBlob().
331
+ */
150
332
  hasBlob(localId) {
151
- return this.redirectTable.get(localId) !== undefined;
333
+ return this.redirectTable.has(localId) || this.localBlobCache.has(localId);
152
334
  }
153
335
  /**
154
336
  * Lookup the blob storage ID for a given local blob id.
@@ -181,15 +363,16 @@ class BlobManager {
181
363
  // Note that this will throw if the blob is inactive or tombstoned and throwing on incorrect usage
182
364
  // is configured.
183
365
  this.blobRequested((0, exports.getGCNodePathFromLocalId)(localId));
184
- const pending = this.pendingBlobs.get(localId);
185
- if (pending) {
186
- return pending.blob;
366
+ const localBlobRecord = this.localBlobCache.get(localId);
367
+ if (localBlobRecord !== undefined) {
368
+ return localBlobRecord.blob;
187
369
  }
188
370
  let storageId = this.redirectTable.get(localId);
189
371
  if (storageId === undefined) {
190
372
  // Only blob handles explicitly marked with pending payload are permitted to exist without
191
373
  // yet knowing their storage id. Otherwise they must already be associated with a storage id.
192
- // Handles for detached blobs are not payload pending.
374
+ // Handles for detached blobs are not payload pending, though they should also always be present
375
+ // in the localBlobCache and therefore should never need to refer to storage.
193
376
  (0, internal_2.assert)(payloadPending, 0x11f /* "requesting unknown blobs" */);
194
377
  // If we didn't find it in the redirectTable and it's payloadPending, assume the attach op is coming
195
378
  // eventually and wait. We do this even if the local client doesn't have the blob payloadPending flag
@@ -217,33 +400,15 @@ class BlobManager {
217
400
  });
218
401
  }, { end: true, cancel: "error" });
219
402
  }
220
- getBlobHandle(localId) {
221
- (0, internal_2.assert)(this.redirectTable.has(localId) || this.pendingBlobs.has(localId), 0x384 /* requesting handle for unknown blob */);
222
- const pending = this.pendingBlobs.get(localId);
223
- // Create a callback function for once the handle has been attached
224
- const callback = pending
225
- ? () => {
226
- pending.attached = true;
227
- // Notify listeners (e.g. serialization process) that handle has been attached
228
- this.internalEvents.emit("handleAttached", pending);
229
- this.deletePendingBlobMaybe(localId);
230
- }
231
- : undefined;
232
- return new BlobHandle((0, exports.getGCNodePathFromLocalId)(localId), this.routeContext, async () => this.getBlob(localId, false), false, // payloadPending
233
- callback);
234
- }
235
- async createBlobDetached(blob) {
236
- const localId = this.localIdGenerator();
237
- // Blobs created while the container is detached are stored in IDetachedBlobStorage.
238
- // The 'IContainerStorageService.createBlob()' call below will respond with a pseudo storage ID.
239
- // That pseudo storage ID will be replaced with the real storage ID at attach time.
240
- const { id: detachedStorageId } = await this.storage.createBlob(blob);
241
- this.setRedirection(localId, detachedStorageId);
242
- return this.getBlobHandle(localId);
403
+ getNonPayloadPendingBlobHandle(localId) {
404
+ const localBlobRecord = this.localBlobCache.get(localId);
405
+ (0, internal_2.assert)(localBlobRecord !== undefined, 0x384 /* requesting handle for unknown blob */);
406
+ (0, internal_2.assert)(localBlobRecord.state === "attached", "Expected blob to be attached");
407
+ return new BlobHandle((0, exports.getGCNodePathFromLocalId)(localId), this.routeContext, async () => this.getBlob(localId, false), false);
243
408
  }
244
409
  async createBlob(blob, signal) {
245
410
  if (this.runtime.attachState === internal_1.AttachState.Detached) {
246
- return this.createBlobDetached(blob);
411
+ return this.createBlobDetached(blob, signal);
247
412
  }
248
413
  if (this.runtime.attachState === internal_1.AttachState.Attaching) {
249
414
  // blob upload is not supported in "Attaching" state
@@ -252,177 +417,46 @@ class BlobManager {
252
417
  }
253
418
  (0, internal_2.assert)(this.runtime.attachState === internal_1.AttachState.Attached, 0x385 /* For clarity and paranoid defense against adding future attachment states */);
254
419
  return this.createBlobPayloadPending
255
- ? this.createBlobWithPayloadPending(blob)
420
+ ? this.createBlobWithPayloadPending(blob, signal)
256
421
  : this.createBlobLegacy(blob, signal);
257
422
  }
258
- async createBlobLegacy(blob, signal) {
423
+ async createBlobDetached(blob, signal) {
259
424
  if (signal?.aborted === true) {
260
- throw this.createAbortError();
425
+ throw createAbortError();
261
426
  }
262
- // Create a local ID for the blob. After uploading it to storage and before returning it, a local ID to
263
- // storage ID mapping is created.
264
427
  const localId = this.localIdGenerator();
265
- const pendingEntry = {
266
- blob,
267
- handleP: new internal_2.Deferred(),
268
- uploadP: this.uploadBlob(localId, blob),
269
- attached: false,
270
- acked: false,
271
- abortSignal: signal,
272
- opsent: false,
273
- };
274
- this.pendingBlobs.set(localId, pendingEntry);
275
- const abortListener = () => {
276
- if (pendingEntry.acked !== true) {
277
- pendingEntry.handleP.reject(this.createAbortError(pendingEntry));
278
- }
279
- };
280
- signal?.addEventListener("abort", abortListener, { once: true });
281
- return pendingEntry.handleP.promise.finally(() => {
282
- signal?.removeEventListener("abort", abortListener);
283
- });
428
+ this.localBlobCache.set(localId, { state: "uploading", blob });
429
+ // Blobs created while the container is detached are stored in IDetachedBlobStorage.
430
+ // The 'IContainerStorageService.createBlob()' call below will respond with a pseudo storage ID.
431
+ // That pseudo storage ID will be replaced with the real storage ID at attach time.
432
+ const { id: detachedStorageId } = await this.storage.createBlob(blob);
433
+ // From the perspective of the BlobManager, the blob is now fully attached. The actual
434
+ // upload/attach process at container attach time is treated as opaque to this tracking.
435
+ this.localBlobCache.set(localId, { state: "attached", blob });
436
+ this.redirectTable.set(localId, detachedStorageId);
437
+ return this.getNonPayloadPendingBlobHandle(localId);
284
438
  }
285
- createBlobWithPayloadPending(blob) {
439
+ async createBlobLegacy(blob, signal) {
286
440
  const localId = this.localIdGenerator();
441
+ this.localBlobCache.set(localId, { state: "localOnly", blob });
442
+ await this.uploadAndAttach(localId, signal);
443
+ return this.getNonPayloadPendingBlobHandle(localId);
444
+ }
445
+ createBlobWithPayloadPending(blob, signal) {
446
+ const localId = this.localIdGenerator();
447
+ this.localBlobCache.set(localId, { state: "localOnly", blob });
287
448
  const blobHandle = new BlobHandle((0, exports.getGCNodePathFromLocalId)(localId), this.routeContext, async () => blob, true, // payloadPending
288
449
  () => {
289
- const pendingEntry = {
290
- blob,
291
- handleP: new internal_2.Deferred(),
292
- uploadP: this.uploadBlob(localId, blob),
293
- attached: true,
294
- acked: false,
295
- opsent: false,
296
- };
297
- this.pendingBlobs.set(localId, pendingEntry);
450
+ this.pendingBlobsWithAttachedHandles.add(localId);
451
+ const uploadAndAttachP = this.uploadAndAttach(localId, signal);
452
+ uploadAndAttachP.then(blobHandle.notifyShared).catch((error) => {
453
+ // TODO: notifyShared won't fail directly, but it emits an event to the customer.
454
+ // Consider what to do if the customer's code throws. reportError is nice.
455
+ });
456
+ uploadAndAttachP.catch(blobHandle.notifyFailed);
298
457
  });
299
- const onProcessedBlobAttach = (_localId, _storageId) => {
300
- if (_localId === localId) {
301
- this.internalEvents.off("processedBlobAttach", onProcessedBlobAttach);
302
- blobHandle.notifyShared();
303
- }
304
- };
305
- this.internalEvents.on("processedBlobAttach", onProcessedBlobAttach);
306
- const onUploadFailed = (_localId, error) => {
307
- if (_localId === localId) {
308
- this.internalEvents.off("uploadFailed", onUploadFailed);
309
- blobHandle.notifyFailed(error);
310
- }
311
- };
312
- this.internalEvents.on("uploadFailed", onUploadFailed);
313
458
  return blobHandle;
314
459
  }
315
- /**
316
- * Upload a blob to the storage service.
317
- * @returns A promise that resolves when the upload is complete and a blob attach op has been sent (but not ack'd).
318
- *
319
- * @privateRemarks This method must not reject, as there is no error handling for it in current tracking.
320
- */
321
- async uploadBlob(localId, blob) {
322
- let response;
323
- try {
324
- response = await this.storage.createBlob(blob);
325
- }
326
- catch (error) {
327
- const entry = this.pendingBlobs.get(localId);
328
- this.mc.logger.sendTelemetryEvent({
329
- eventName: "UploadBlobReject",
330
- // TODO: better typing
331
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any
332
- error: error,
333
- message: entry === undefined ? "Missing pendingBlob" : undefined,
334
- localId,
335
- });
336
- // We probably should assert the pendingBlobs entry here, but we don't currently have any error handling
337
- // for the uploadP - a promise rejection would be unhandled anyway. For now we can detect this with the
338
- // message on the UploadBlobReject telemetry.
339
- if (entry !== undefined) {
340
- entry.handleP.reject(error);
341
- this.deletePendingBlob(localId);
342
- }
343
- this.internalEvents.emit("uploadFailed", localId, error);
344
- return;
345
- }
346
- try {
347
- this.onUploadResolve(localId, response);
348
- }
349
- catch (error) {
350
- this.mc.logger.sendTelemetryEvent({
351
- eventName: "OnUploadResolveError",
352
- // TODO: better typing
353
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any
354
- error: error,
355
- localId,
356
- });
357
- }
358
- }
359
- /**
360
- * Set up a mapping in the redirect table from fromId to toId. Also, notify the runtime that a reference is added
361
- * which is required for GC.
362
- */
363
- setRedirection(fromId, toId) {
364
- this.redirectTable.set(fromId, toId);
365
- }
366
- deletePendingBlobMaybe(localId) {
367
- if (this.pendingBlobs.has(localId)) {
368
- const entry = this.pendingBlobs.get(localId);
369
- if (entry?.attached === true && entry?.acked === true) {
370
- this.deletePendingBlob(localId);
371
- }
372
- }
373
- }
374
- deletePendingBlob(id) {
375
- this.pendingBlobs.delete(id);
376
- }
377
- onUploadResolve(localId, response) {
378
- const entry = this.pendingBlobs.get(localId);
379
- (0, internal_2.assert)(entry !== undefined, 0x6c8 /* pending blob entry not found for uploaded blob */);
380
- if (entry.abortSignal?.aborted === true && entry.opsent !== true) {
381
- this.mc.logger.sendTelemetryEvent({
382
- eventName: "BlobAborted",
383
- localId,
384
- });
385
- this.deletePendingBlob(localId);
386
- return;
387
- }
388
- (0, internal_2.assert)(entry.storageId === undefined, 0x386 /* Must have pending blob entry for uploaded blob */);
389
- entry.storageId = response.id;
390
- entry.uploadTime = Date.now();
391
- entry.minTTLInSeconds = response.minTTLInSeconds;
392
- // Send a blob attach op. This serves two purposes:
393
- // 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
394
- // until its storage ID is added to the next summary.
395
- // 2. It will create a local ID to storage ID mapping in all clients which is needed to retrieve the
396
- // blob from the server via the storage ID.
397
- if (entry.opsent !== true) {
398
- this.sendBlobAttachOp(localId, response.id);
399
- }
400
- const storageIds = (0, blobManagerSnapSum_js_1.getStorageIds)(this.redirectTable);
401
- if (storageIds.has(response.id)) {
402
- // The blob is de-duped. Set up a local ID to storage ID mapping and return the blob. Since this is
403
- // an existing blob, we don't have to wait for the op to be ack'd since this step has already
404
- // happened before and so, the server won't delete it.
405
- this.setRedirection(localId, response.id);
406
- const blobHandle = this.getBlobHandle(localId);
407
- blobHandle.notifyShared();
408
- entry.handleP.resolve(blobHandle);
409
- this.deletePendingBlobMaybe(localId);
410
- }
411
- else {
412
- // If there is already an op for this storage ID, append the local ID to the list. Once any op for
413
- // this storage ID is ack'd, all pending blobs for it can be resolved since the op will keep the
414
- // blob alive in storage.
415
- let setForRemoteId = this.opsInFlight.get(response.id);
416
- if (setForRemoteId === undefined) {
417
- setForRemoteId = new Set();
418
- this.opsInFlight.set(response.id, setForRemoteId);
419
- }
420
- // seeing the same localId twice can happen if a blob is being reuploaded and stashed.
421
- // TODO: review stashing logic and see if we can avoid this, as well in tests.
422
- setForRemoteId.add(localId);
423
- }
424
- return response;
425
- }
426
460
  /**
427
461
  * Resubmit a BlobAttach op. Used to add storage IDs to ops that were
428
462
  * submitted to runtime while disconnected.
@@ -431,54 +465,47 @@ class BlobManager {
431
465
  reSubmit(metadata) {
432
466
  (0, internal_2.assert)((0, metadata_js_1.isBlobMetadata)(metadata), 0xc01 /* Expected blob metadata for a BlobAttach op */);
433
467
  const { localId, blobId: storageId } = metadata;
434
- // Any blob that we're actively trying to advance to attached state must have a
435
- // pendingBlobs entry. Decline to resubmit for anything else.
436
- // For example, we might be asked to resubmit stashed ops for blobs that never had
437
- // their handle attached - these won't have a pendingBlobs entry and we shouldn't
438
- // try to attach them since they won't be accessible to the customer and would just
439
- // be considered garbage immediately.
440
- if (this.pendingBlobs.has(localId)) {
441
- this.sendBlobAttachOp(localId, storageId);
468
+ // Any blob that we're actively trying to advance to attached state must be in attaching state.
469
+ // Decline to resubmit for anything else.
470
+ // For example, we might be asked to resubmit stashed ops for blobs that never had their handle
471
+ // attached - these won't have a localBlobCache entry because we filter them out when generating
472
+ // pending state. We shouldn't try to attach them since they won't be accessible to the customer
473
+ // and would just be considered garbage immediately.
474
+ // TODO: Is it possible that we'd be asked to resubmit for a pending blob before we call sharePendingBlobs?
475
+ const localBlobRecord = this.localBlobCache.get(localId);
476
+ if (localBlobRecord?.state === "attaching") {
477
+ // If the TTL is expired, we assume it's gone from the storage and so is effectively localOnly again.
478
+ if (isTTLTooCloseToExpiry(localBlobRecord)) {
479
+ this.localBlobCache.set(localId, { state: "localOnly", blob: localBlobRecord.blob });
480
+ this.internalEvents.emit("blobExpired", localId);
481
+ }
482
+ else {
483
+ this.sendBlobAttachOp(localId, storageId);
484
+ }
442
485
  }
443
486
  }
444
487
  processBlobAttachMessage(message, local) {
445
488
  (0, internal_2.assert)((0, metadata_js_1.isBlobMetadata)(message.metadata), 0xc02 /* Expected blob metadata for a BlobAttach op */);
446
489
  const { localId, blobId: storageId } = message.metadata;
447
- const pendingEntry = this.pendingBlobs.get(localId);
448
- if (pendingEntry?.abortSignal?.aborted === true) {
449
- this.deletePendingBlob(localId);
450
- return;
490
+ const maybeLocalBlobRecord = this.localBlobCache.get(localId);
491
+ if (maybeLocalBlobRecord !== undefined) {
492
+ const attachedBlobRecord = {
493
+ state: "attached",
494
+ blob: maybeLocalBlobRecord.blob,
495
+ };
496
+ // Processing a blob attach op is authoritative and may stomp on any existing state. Other
497
+ // callsites that update localBlobCache entries must take proper caution to handle the case
498
+ // that a blob attach op is processed concurrently.
499
+ this.localBlobCache.set(localId, attachedBlobRecord);
500
+ // Note there may or may not be an entry in pendingBlobsWithAttachedHandles for this localId,
501
+ // in particular for the non-payloadPending case since we should be reaching this point
502
+ // before even returning a handle to the caller.
503
+ this.pendingBlobsWithAttachedHandles.delete(localId);
504
+ this.pendingOnlyLocalIds.delete(localId);
451
505
  }
452
- this.setRedirection(localId, storageId);
506
+ this.redirectTable.set(localId, storageId);
453
507
  // set identity (id -> id) entry
454
- this.setRedirection(storageId, storageId);
455
- if (local) {
456
- const waitingBlobs = this.opsInFlight.get(storageId);
457
- if (waitingBlobs !== undefined) {
458
- // For each op corresponding to this storage ID that we are waiting for, resolve the pending blob.
459
- // This is safe because the server will keep the blob alive and the op containing the local ID to
460
- // storage ID is already in flight and any op containing this local ID will be sequenced after that.
461
- for (const pendingLocalId of waitingBlobs) {
462
- const entry = this.pendingBlobs.get(pendingLocalId);
463
- (0, internal_2.assert)(entry !== undefined, 0x38f /* local online BlobAttach op with no pending blob entry */);
464
- this.setRedirection(pendingLocalId, storageId);
465
- entry.acked = true;
466
- const blobHandle = this.getBlobHandle(pendingLocalId);
467
- blobHandle.notifyShared();
468
- entry.handleP.resolve(blobHandle);
469
- this.deletePendingBlobMaybe(pendingLocalId);
470
- }
471
- this.opsInFlight.delete(storageId);
472
- }
473
- const localEntry = this.pendingBlobs.get(localId);
474
- if (localEntry) {
475
- localEntry.acked = true;
476
- const blobHandle = this.getBlobHandle(localId);
477
- blobHandle.notifyShared();
478
- localEntry.handleP.resolve(blobHandle);
479
- this.deletePendingBlobMaybe(localId);
480
- }
481
- }
508
+ this.redirectTable.set(storageId, storageId);
482
509
  this.internalEvents.emit("processedBlobAttach", localId, storageId);
483
510
  }
484
511
  summarize(telemetryContext) {
@@ -503,18 +530,9 @@ class BlobManager {
503
530
  }
504
531
  return gcData;
505
532
  }
506
- /**
507
- * Delete attachment blobs that are sweep ready.
508
- * @param sweepReadyBlobRoutes - The routes of blobs that are sweep ready and should be deleted. These routes will
509
- * be based off of local ids.
510
- * @returns The routes of blobs that were deleted.
511
- */
512
- deleteSweepReadyNodes(sweepReadyBlobRoutes) {
513
- this.deleteBlobsFromRedirectTable(sweepReadyBlobRoutes);
514
- return [...sweepReadyBlobRoutes];
515
- }
516
533
  /**
517
534
  * Delete blobs with the given routes from the redirect table.
535
+ * @returns The routes of blobs that were deleted.
518
536
  *
519
537
  * @remarks
520
538
  * The routes are GC nodes paths of format -`/<blobManagerBasePath>/<localId>`.
@@ -529,11 +547,11 @@ class BlobManager {
529
547
  * will ensure we don't create an attachment blob for them at the next summary. The service would then delete them
530
548
  * some time in the future.
531
549
  */
532
- deleteBlobsFromRedirectTable(blobRoutes) {
550
+ deleteSweepReadyNodes(sweepReadyBlobRoutes) {
533
551
  // maybeUnusedStorageIds is used to compute the set of storage IDs that *used to have a local ID*, but that
534
552
  // local ID is being deleted.
535
553
  const maybeUnusedStorageIds = new Set();
536
- for (const route of blobRoutes) {
554
+ for (const route of sweepReadyBlobRoutes) {
537
555
  const localId = getLocalIdFromGCNodePath(route);
538
556
  // If the blob hasn't already been deleted, log an error because this should never happen.
539
557
  // If the blob has already been deleted, log a telemetry event. This can happen because multiple GC
@@ -567,6 +585,7 @@ class BlobManager {
567
585
  for (const storageId of maybeUnusedStorageIds) {
568
586
  this.redirectTable.delete(storageId);
569
587
  }
588
+ return [...sweepReadyBlobRoutes];
570
589
  }
571
590
  /**
572
591
  * Verifies that the blob with given id is not deleted, i.e., it has not been garbage collected. If the blob is GC'd,
@@ -589,28 +608,31 @@ class BlobManager {
589
608
  * To be used in getPendingLocalState flow. Get a serializable record of the blobs that are
590
609
  * pending upload and/or their BlobAttach op, which can be given to a new BlobManager to
591
610
  * resume work.
592
- *
593
- * @privateRemarks
594
- * For now, we don't track any pending blobs since the getPendingBlobs flow doesn't enable
595
- * restoring to a state where an accessible handle has been stored by the customer (and we'll
596
- * just drop any BlobAttach ops on the ground during reSubmit). However, once we add support
597
- * for payload-pending handles, this will return the blobs associated with those handles.
598
611
  */
599
612
  getPendingBlobs() {
600
- return undefined;
601
- }
602
- /**
603
- * Part of container serialization when imminent closure is enabled (Currently when calling closeAndGetPendingLocalState).
604
- * This asynchronous function resolves all pending createBlob calls and waits for each blob
605
- * to be attached. It will also send BlobAttach ops for each pending blob that hasn't sent it
606
- * yet so that serialized container can resubmit them when rehydrated.
607
- *
608
- * @param stopBlobAttachingSignal - Optional signal to abort the blob attaching process.
609
- * @returns - A promise that resolves with the details of the attached blobs,
610
- * or undefined if no blobs were processed.
611
- */
612
- async attachAndGetPendingBlobs(stopBlobAttachingSignal) {
613
- throw new internal_4.UsageError("attachAndGetPendingBlobs is no longer supported");
613
+ const pendingBlobs = {};
614
+ for (const localId of this.pendingBlobsWithAttachedHandles) {
615
+ const localBlobRecord = this.localBlobCache.get(localId);
616
+ (0, internal_2.assert)(localBlobRecord !== undefined, "Pending blob must be in local cache");
617
+ (0, internal_2.assert)(localBlobRecord.state === "uploading" ||
618
+ localBlobRecord.state === "uploaded" ||
619
+ localBlobRecord.state === "attaching", "Pending blob must be in uploading, uploaded, or attaching state");
620
+ // We treat blobs in both uploaded and attaching state as just being uploaded, to distrust
621
+ // whether we expect to see any ack for a BlobAttach op. We just remain prepared to handle
622
+ // a BlobAttach op for it if we do see one after loading from pending state.
623
+ pendingBlobs[localId] =
624
+ localBlobRecord.state === "uploading"
625
+ ? {
626
+ state: "localOnly",
627
+ blob: (0, client_utils_1.bufferToString)(localBlobRecord.blob, "base64"),
628
+ }
629
+ : {
630
+ ...localBlobRecord,
631
+ state: "uploaded",
632
+ blob: (0, client_utils_1.bufferToString)(localBlobRecord.blob, "base64"),
633
+ };
634
+ }
635
+ return Object.keys(pendingBlobs).length > 0 ? pendingBlobs : undefined;
614
636
  }
615
637
  }
616
638
  exports.BlobManager = BlobManager;