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