perf(file-transfer): fold duplicated local helpers into one per module (Q-B)

- browser-file-picker: the native and enhanced pickers carried two copies of
  the same selection observation (#finishObservation / #observe); one
  module-level observeSelection replaces both.
- indexeddb-checkpoint-store: read / compareAndSwap / remove /
  removeUnreadable each repeated acquire -> transaction -> get -> onerror;
  withCheckpointRow does that once and hands the row to the operation, still
  inside the same transaction. deleteCheckpointRow shares the delete tail.
- resumable-upload-runtime: the four checkpoint removals that remap to
  UPLOAD_RECONCILE go through removeCheckpoint.
- image-cdn-runtime: the verification deadline reuses
  combineImageRuntimeAbortSignals instead of a second listener loop; the
  verifier-coverage check throws its TypeError from one place; the registry
  id pattern is one constant instead of three inline literals.
- presigned executor / capability provider: reuse checkpoint-schema's
  SHA256_HEX and isSafeUploadReceiptToken instead of equal local patterns.

file-transfer reference runtime: 54754 -> 54562 gzip bytes (budget 54600).
Other reference runtimes unchanged.

Verified: check:architecture, check:types:app, check:types:test, lint,
test:unit, test:component, check:adapter-inventory, build,
check:optional-recipes (file-transfer 54562/54600, offline-indexeddb
35854/36000, realtime 39685/40000, service-worker-pwa 9500/10000),
test:recipes, check:types:recipes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-24 14:49:19 +09:00
co-authored by Claude Opus 5.5
parent 834308c29b
commit e96f78b8e0
6 changed files with 249 additions and 251 deletions
@@ -207,23 +207,25 @@ export class NativeInputFilePicker implements DisposableFilePicker {
try {
request = snapshotSelectionRequest(input);
} catch {
return this.#finishObservation(
return observeSelection(
this.#observer,
browserDataFailure("INVALID_INPUT", "FILE_SELECT"),
);
}
if (this.#disposed) {
return this.#finishObservation(
return observeSelection(
this.#observer,
browserDataFailure("UNAVAILABLE", "FILE_SELECT"),
);
}
const cancelled = abortedResult(request.signal, "FILE_SELECT");
if (cancelled) return this.#finishObservation(cancelled);
if (cancelled) return observeSelection(this.#observer, cancelled);
const resolvedPolicy = this.#resolveSelection(
request.policy,
request.limits,
);
if (!resolvedPolicy.ok) {
return this.#finishObservation(resolvedPolicy);
return observeSelection(this.#observer, resolvedPolicy);
}
const policy = resolvedPolicy.value;
if (
@@ -232,17 +234,20 @@ export class NativeInputFilePicker implements DisposableFilePicker {
this.#inputEvents.getAttribute,
)
) {
return this.#finishObservation(
return observeSelection(
this.#observer,
browserDataFailure("INVALID_INPUT", "FILE_SELECT"),
);
}
if (this.#pending) {
return this.#finishObservation(
return observeSelection(
this.#observer,
browserDataFailure("BLOCKED", "FILE_SELECT"),
);
}
if (this.#userActivation && !this.#userActivation.isActive) {
return this.#finishObservation(
return observeSelection(
this.#observer,
browserDataFailure("PERMISSION_DENIED", "FILE_SELECT"),
);
}
@@ -344,9 +349,10 @@ export class NativeInputFilePicker implements DisposableFilePicker {
}
},
);
return this.#finishObservation(result);
return observeSelection(this.#observer, result);
} catch (error) {
return this.#finishObservation(
return observeSelection(
this.#observer,
mapBrowserDataException(error, "FILE_SELECT"),
);
} finally {
@@ -368,33 +374,6 @@ export class NativeInputFilePicker implements DisposableFilePicker {
// Some test doubles or constrained DOM hosts expose a readonly value.
}
}
#finishObservation(
result: BrowserDataResult<FileSelectionOutcome>,
): BrowserDataResult<FileSelectionOutcome> {
if (result.ok) {
const dismissed = result.value.kind === "DISMISSED";
const bytes =
result.value.kind === "SELECTED"
? result.value.files.reduce(
(total, candidate) => total + candidate.sizeBytes,
0,
)
: null;
observeBrowserFile(this.#observer, {
operation: "FILE_SELECT",
outcome: dismissed ? "DISMISSED" : "SUCCESS",
byteBucket: byteBucket(bytes),
});
} else {
observeBrowserFile(this.#observer, {
operation: "FILE_SELECT",
outcome: "FAILED",
failureCode: result.error.code,
});
}
return result;
}
}
export type SystemOpenPickerAcceptType = Readonly<{
@@ -472,30 +451,36 @@ export class EnhancedFilePicker implements DisposableFilePicker {
try {
request = snapshotSelectionRequest(input);
} catch {
return this.#observe(
return observeSelection(
this.#observer,
browserDataFailure("INVALID_INPUT", "FILE_SELECT"),
);
}
if (this.#disposed) {
return this.#observe(
return observeSelection(
this.#observer,
browserDataFailure("UNAVAILABLE", "FILE_SELECT"),
);
}
const cancelled = abortedResult(request.signal, "FILE_SELECT");
if (cancelled) return this.#observe(cancelled);
if (cancelled) return observeSelection(this.#observer, cancelled);
const resolvedPolicy = this.#resolveSelection(
request.policy,
request.limits,
);
if (!resolvedPolicy.ok) return this.#observe(resolvedPolicy);
if (!resolvedPolicy.ok) {
return observeSelection(this.#observer, resolvedPolicy);
}
const policy = resolvedPolicy.value;
if (this.#pending) {
return this.#observe(
return observeSelection(
this.#observer,
browserDataFailure("BLOCKED", "FILE_SELECT"),
);
}
if (this.#userActivation && !this.#userActivation.isActive) {
return this.#observe(
return observeSelection(
this.#observer,
browserDataFailure("PERMISSION_DENIED", "FILE_SELECT"),
);
}
@@ -511,9 +496,10 @@ export class EnhancedFilePicker implements DisposableFilePicker {
request.signal,
);
const aborted = abortedResult(request.signal, "FILE_SELECT");
if (aborted) return this.#observe(aborted);
if (aborted) return observeSelection(this.#observer, aborted);
if (handles.length === 0) {
return this.#observe(
return observeSelection(
this.#observer,
browserDataSuccess(
Object.freeze({ kind: "DISMISSED" as const }),
),
@@ -524,7 +510,8 @@ export class EnhancedFilePicker implements DisposableFilePicker {
policy,
request.signal ?? new AbortController().signal,
);
return this.#observe(
return observeSelection(
this.#observer,
captured.ok
? browserDataSuccess(
Object.freeze({
@@ -536,20 +523,23 @@ export class EnhancedFilePicker implements DisposableFilePicker {
);
} catch (error) {
if (error instanceof PickerDisposedError) {
return this.#observe(
return observeSelection(
this.#observer,
browserDataFailure("ABORTED", "FILE_SELECT"),
);
}
if (error instanceof DOMException && error.name === "AbortError") {
const aborted = abortedResult(input.signal, "FILE_SELECT");
if (aborted) return this.#observe(aborted);
return this.#observe(
if (aborted) return observeSelection(this.#observer, aborted);
return observeSelection(
this.#observer,
browserDataSuccess(
Object.freeze({ kind: "DISMISSED" as const }),
),
);
}
return this.#observe(
return observeSelection(
this.#observer,
mapBrowserDataException(error, "FILE_SELECT"),
);
} finally {
@@ -601,34 +591,36 @@ export class EnhancedFilePicker implements DisposableFilePicker {
);
});
}
}
#observe(
result: BrowserDataResult<FileSelectionOutcome>,
): BrowserDataResult<FileSelectionOutcome> {
if (!result.ok) {
observeBrowserFile(this.#observer, {
operation: "FILE_SELECT",
outcome: "FAILED",
failureCode: result.error.code,
});
} else if (result.value.kind === "DISMISSED") {
observeBrowserFile(this.#observer, {
operation: "FILE_SELECT",
outcome: "DISMISSED",
});
} else {
const bytes = result.value.files.reduce(
(total, file) => total + file.sizeBytes,
0,
);
observeBrowserFile(this.#observer, {
operation: "FILE_SELECT",
outcome: "SUCCESS",
byteBucket: byteBucket(bytes),
});
}
return result;
/** One observation per terminal selection result, shared by both pickers. */
function observeSelection(
observer: BrowserFileObserver | undefined,
result: BrowserDataResult<FileSelectionOutcome>,
): BrowserDataResult<FileSelectionOutcome> {
if (!result.ok) {
observeBrowserFile(observer, {
operation: "FILE_SELECT",
outcome: "FAILED",
failureCode: result.error.code,
});
} else if (result.value.kind === "DISMISSED") {
observeBrowserFile(observer, {
operation: "FILE_SELECT",
outcome: "DISMISSED",
});
} else {
const bytes = result.value.files.reduce(
(total, file) => total + file.sizeBytes,
0,
);
observeBrowserFile(observer, {
operation: "FILE_SELECT",
outcome: "SUCCESS",
byteBucket: byteBucket(bytes),
});
}
return result;
}
function pickerAcceptValue(
@@ -71,6 +71,7 @@ type IssuedDescriptorSnapshot = BackendIssuedImageAsset;
const OPAQUE_TOKEN = /^[A-Za-z0-9_-]{8,128}$/u;
const SIGNATURE = /^[A-Za-z0-9_-]{16,512}$/u;
const SHA256_HEX = /^[a-f0-9]{64}$/u;
const REGISTRY_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
const PUBLIC_DESCRIPTOR_KEYS = Object.freeze([
"kind",
"originKey",
@@ -145,19 +146,18 @@ export function createImageCdnRuntime(
dependencies.capabilityVerifier,
);
if (dependencies.capabilityVerifier) {
let covered = false;
try {
if (
!verifyCapability ||
!acceptsCapabilityKey ||
[...capabilityPolicy.acceptedKeyIds].some(
(keyId) => acceptsCapabilityKey(keyId) !== true,
)
) {
throw new TypeError(
"Image capability verifier registry does not cover policy keys.",
covered =
!!verifyCapability &&
!!acceptsCapabilityKey &&
[...capabilityPolicy.acceptedKeyIds].every(
(keyId) => acceptsCapabilityKey(keyId) === true,
);
}
} catch {
// A throwing registry covers nothing.
}
if (!covered) {
throw new TypeError(
"Image capability verifier registry does not cover policy keys.",
);
@@ -943,17 +943,11 @@ function snapshotIssuedDescriptor(
allowedPresetBindingIds.some(
(bindingId) =>
typeof bindingId !== "string" ||
!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(
bindingId,
),
!REGISTRY_ID.test(bindingId),
) ||
snapshot.signature.algorithm !== "ECDSA_P256_SHA256" ||
!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(
snapshot.issuer,
) ||
!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(
snapshot.signature.keyId,
) ||
!REGISTRY_ID.test(snapshot.issuer) ||
!REGISTRY_ID.test(snapshot.signature.keyId) ||
!SHA256_HEX.test(
snapshot.signature.capabilityBindingDigestHex,
) ||
@@ -1062,34 +1056,25 @@ function createCapabilityVerificationDeadline(
timeoutMs: number,
scheduler: ImageCapabilityVerificationScheduler,
): ImageCapabilityVerificationDeadline {
const controller = new AbortController();
let released = false;
const abortListeners = new Map<AbortSignal, () => void>();
const activeSignals = signals.filter(
(signal): signal is AbortSignal => signal !== undefined,
const scope = combineImageRuntimeAbortSignals(
signals.filter(
(signal): signal is AbortSignal => signal !== undefined,
),
);
for (const signal of new Set(activeSignals)) {
const onAbort = () => controller.abort(signal.reason);
abortListeners.set(signal, onAbort);
signal.addEventListener("abort", onAbort, { once: true });
if (signal.aborted) onAbort();
}
let released = false;
let timeoutHandle: unknown;
try {
timeoutHandle = scheduler.setTimeout(() => {
if (released) return;
controller.abort(capabilityVerificationAbortException());
scope.abort(capabilityVerificationAbortException());
}, timeoutMs);
} catch (error) {
for (const [signal, onAbort] of abortListeners) {
signal.removeEventListener("abort", onAbort);
}
scope.release();
throw error;
}
return Object.freeze({
signal: controller.signal,
signal: scope.signal,
release() {
if (released) return;
released = true;
@@ -1098,10 +1083,7 @@ function createCapabilityVerificationDeadline(
} catch {
// Scheduler cleanup cannot alter an already closed adapter result.
}
for (const [signal, onAbort] of abortListeners) {
signal.removeEventListener("abort", onAbort);
}
abortListeners.clear();
scope.release();
},
});
}
@@ -1139,7 +1121,11 @@ function awaitImageRuntimeAbort<Value>(
function combineImageRuntimeAbortSignals(
signals: readonly AbortSignal[],
): Readonly<{ signal: AbortSignal; release(): void }> {
): Readonly<{
signal: AbortSignal;
abort(reason: unknown): void;
release(): void;
}> {
const controller = new AbortController();
const abortListeners = new Map<AbortSignal, () => void>();
for (const signal of new Set(signals)) {
@@ -1151,6 +1137,7 @@ function combineImageRuntimeAbortSignals(
let released = false;
return Object.freeze({
signal: controller.signal,
abort: (reason: unknown) => controller.abort(reason),
release() {
if (released) return;
released = true;
@@ -39,9 +39,11 @@ import {
statusFailure,
transferFailure,
} from "./http-common.ts";
import { SAFE_TRANSFER_ID } from "../resumable-upload/checkpoint-schema.ts";
import {
SAFE_TRANSFER_ID,
SHA256_HEX as SHA256,
} from "../resumable-upload/checkpoint-schema.ts";
const SHA256 = /^[a-f0-9]{64}$/;
const MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/;
const HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
const QUERY_NAME = /^[A-Za-z0-9_.~-]{1,128}$/;
@@ -46,10 +46,11 @@ import {
transferFailure,
type PresignedAbortScope,
} from "./http-common.ts";
import { SAFE_TRANSFER_ID } from "../resumable-upload/checkpoint-schema.ts";
const SHA256 = /^[a-f0-9]{64}$/;
const RECEIPT_TOKEN = /^[A-Za-z0-9][A-Za-z0-9._~:+/=-]{0,511}$/;
import {
isSafeUploadReceiptToken,
SAFE_TRANSFER_ID,
SHA256_HEX as SHA256,
} from "../resumable-upload/checkpoint-schema.ts";
type Scheduler = Readonly<{
setTimeout(callback: () => void, milliseconds: number): unknown;
@@ -1004,9 +1005,7 @@ function normalizeReceiptToken(value: string | null): string | null {
trimmed.endsWith("\"")
? trimmed.slice(1, -1)
: trimmed;
return RECEIPT_TOKEN.test(unquoted) && !unquoted.includes("://")
? unquoted
: null;
return isSafeUploadReceiptToken(unquoted) ? unquoted : null;
}
function responseUrlMatches(
@@ -285,6 +285,35 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
}),
});
/**
* Every store operation reads the row it guards inside the same transaction
* it may then write in, so the guard and the write cannot interleave with
* another context.
*/
async function withCheckpointRow<Value>(
uploadKey: string,
mode: "readonly" | "readwrite",
signal: AbortSignal | undefined,
onRow: (
row: unknown,
store: IDBObjectStore,
context: CheckpointTransactionContext<Value>,
) => void,
): Promise<BrowserDataResult<Value>> {
const opened = await connection.acquire(signal);
if (!opened.ok) return opened;
return await runCheckpointTransaction<Value>(
opened.value,
mode,
signal,
(nativeStore, context) => {
const request = nativeStore.get(uploadKey);
request.onerror = () => context.fail(mappedFailure(request.error));
request.onsuccess = () => onRow(request.result, nativeStore, context);
},
);
}
const storeValue: ResumableUploadCheckpointStore = {
async read(
uploadKey: string,
@@ -295,32 +324,22 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
if (!SAFE_UPLOAD_KEY.test(uploadKey)) {
return browserDataFailure("INVALID_INPUT", OPERATION);
}
const opened = await connection.acquire(signal);
if (!opened.ok) return opened;
return await runCheckpointTransaction<
ResumableUploadCheckpoint | null
>(
opened.value,
return await withCheckpointRow<ResumableUploadCheckpoint | null>(
uploadKey,
"readonly",
signal,
(nativeStore, context) => {
const request = nativeStore.get(uploadKey);
request.onerror = () => context.fail(mappedFailure(request.error));
request.onsuccess = () => {
if (request.result === undefined) {
context.succeed(null);
return;
}
if (!isResumableUploadCheckpoint(request.result)) {
context.fail(
checkpointFailure("CORRUPT_DATA", { recovery: "RECONCILE" }),
);
return;
}
context.succeed(
snapshotCheckpoint(request.result),
(row, _nativeStore, context) => {
if (row === undefined) {
context.succeed(null);
return;
}
if (!isResumableUploadCheckpoint(row)) {
context.fail(
checkpointFailure("CORRUPT_DATA", { recovery: "RECONCILE" }),
);
};
return;
}
context.succeed(snapshotCheckpoint(row));
},
);
},
@@ -345,32 +364,25 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
) {
return browserDataFailure("INVALID_INPUT", OPERATION);
}
const opened = await connection.acquire(inputValue.signal);
if (!opened.ok) return opened;
return await runCheckpointTransaction<ResumableUploadCheckpoint>(
opened.value,
return await withCheckpointRow<ResumableUploadCheckpoint>(
checkpoint.uploadKey,
"readwrite",
inputValue.signal,
(nativeStore, context) => {
const request = nativeStore.get(checkpoint.uploadKey);
request.onerror = () => context.fail(mappedFailure(request.error));
request.onsuccess = () => {
const current = request.result;
if (
(expectedRevision === null && current !== undefined) ||
(expectedRevision !== null &&
(!isResumableUploadCheckpoint(current) ||
current.revision !== expectedRevision))
) {
context.fail(
checkpointFailure("CONFLICT", { recovery: "RECONCILE" }),
);
return;
}
const put = nativeStore.put(checkpoint);
put.onerror = () => context.fail(mappedFailure(put.error));
put.onsuccess = () => context.succeed(checkpoint);
};
(current, nativeStore, context) => {
if (
(expectedRevision === null && current !== undefined) ||
(expectedRevision !== null &&
(!isResumableUploadCheckpoint(current) ||
current.revision !== expectedRevision))
) {
context.fail(
checkpointFailure("CONFLICT", { recovery: "RECONCILE" }),
);
return;
}
const put = nativeStore.put(checkpoint);
put.onerror = () => context.fail(mappedFailure(put.error));
put.onsuccess = () => context.succeed(checkpoint);
},
);
},
@@ -387,30 +399,21 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
) {
return browserDataFailure("INVALID_INPUT", OPERATION);
}
const opened = await connection.acquire(inputValue.signal);
if (!opened.ok) return opened;
return await runCheckpointTransaction<void>(
opened.value,
return await withCheckpointRow<void>(
inputValue.uploadKey,
"readwrite",
inputValue.signal,
(nativeStore, context) => {
const request = nativeStore.get(inputValue.uploadKey);
request.onerror = () => context.fail(mappedFailure(request.error));
request.onsuccess = () => {
if (
!isResumableUploadCheckpoint(request.result) ||
request.result.revision !== inputValue.expectedRevision
) {
context.fail(
checkpointFailure("CONFLICT", { recovery: "RECONCILE" }),
);
return;
}
const deletion = nativeStore.delete(inputValue.uploadKey);
deletion.onerror = () =>
context.fail(mappedFailure(deletion.error));
deletion.onsuccess = () => context.succeed(undefined);
};
(row, nativeStore, context) => {
if (
!isResumableUploadCheckpoint(row) ||
row.revision !== inputValue.expectedRevision
) {
context.fail(
checkpointFailure("CONFLICT", { recovery: "RECONCILE" }),
);
return;
}
deleteCheckpointRow(nativeStore, inputValue.uploadKey, context);
},
);
},
@@ -423,33 +426,24 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
if (!SAFE_UPLOAD_KEY.test(inputValue.uploadKey)) {
return browserDataFailure("INVALID_INPUT", OPERATION);
}
const opened = await connection.acquire(inputValue.signal);
if (!opened.ok) return opened;
return await runCheckpointTransaction<void>(
opened.value,
return await withCheckpointRow<void>(
inputValue.uploadKey,
"readwrite",
inputValue.signal,
(nativeStore, context) => {
const request = nativeStore.get(inputValue.uploadKey);
request.onerror = () => context.fail(mappedFailure(request.error));
request.onsuccess = () => {
// Checked in the same transaction as the delete, so a row another
// context rewrote as a valid checkpoint is never dropped.
if (request.result === undefined) {
context.succeed(undefined);
return;
}
if (isResumableUploadCheckpoint(request.result)) {
context.fail(
checkpointFailure("CONFLICT", { recovery: "RECONCILE" }),
);
return;
}
const deletion = nativeStore.delete(inputValue.uploadKey);
deletion.onerror = () =>
context.fail(mappedFailure(deletion.error));
deletion.onsuccess = () => context.succeed(undefined);
};
(row, nativeStore, context) => {
// Checked in the same transaction as the delete, so a row another
// context rewrote as a valid checkpoint is never dropped.
if (row === undefined) {
context.succeed(undefined);
return;
}
if (isResumableUploadCheckpoint(row)) {
context.fail(
checkpointFailure("CONFLICT", { recovery: "RECONCILE" }),
);
return;
}
deleteCheckpointRow(nativeStore, inputValue.uploadKey, context);
},
);
},
@@ -516,6 +510,21 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
return Object.freeze({ store, admin });
}
type CheckpointTransactionContext<Value> = Readonly<{
succeed(value: Value): void;
fail(failure: BrowserDataFailure): void;
}>;
function deleteCheckpointRow(
store: IDBObjectStore,
uploadKey: string,
context: CheckpointTransactionContext<void>,
): void {
const deletion = store.delete(uploadKey);
deletion.onerror = () => context.fail(mappedFailure(deletion.error));
deletion.onsuccess = () => context.succeed(undefined);
}
/**
* `durability` is deliberately `undefined` rather than `"default"`: that opens
* the transaction with no options bag at all, which is what checkpoint writes
@@ -533,10 +542,7 @@ async function runCheckpointTransaction<Value>(
signal: AbortSignal | undefined,
execute: (
store: IDBObjectStore,
context: Readonly<{
succeed(value: Value): void;
fail(failure: BrowserDataFailure): void;
}>,
context: CheckpointTransactionContext<Value>,
) => void,
): Promise<BrowserDataResult<Value>> {
return await runIndexedDbTransaction<Value, BrowserDataFailure>({
@@ -424,14 +424,12 @@ async function executeUpload<Capability>(
return browserDataSuccess(reconciled.value.upload);
}
if (reconciled.value.kind !== "ACTIVE") {
const removed = await dependencies.checkpoints.remove({
uploadKey: transferred.value.uploadKey,
expectedRevision: transferred.value.revision,
signal: request.signal,
});
if (!removed.ok) {
return remapResult(removed, "UPLOAD_RECONCILE");
}
const removed = await removeCheckpoint(
dependencies,
transferred.value,
request.signal,
);
if (!removed.ok) return removed;
return browserDataFailure("EXPIRED_RESOURCE", "UPLOAD_SESSION", {
recovery: "RESTART",
});
@@ -492,14 +490,12 @@ async function resolveActiveSession<Capability>(
return browserDataSuccess(reconciled.value);
}
if (restartIndex === 1) {
const removed = await dependencies.checkpoints.remove({
uploadKey: checkpoint.uploadKey,
expectedRevision: checkpoint.revision,
signal: request.signal,
});
if (!removed.ok) {
return remapResult(removed, "UPLOAD_RECONCILE");
}
const removed = await removeCheckpoint(
dependencies,
checkpoint,
request.signal,
);
if (!removed.ok) return removed;
break;
}
const replaced = await createUploadSession(
@@ -559,12 +555,12 @@ async function reconcileActiveCheckpoint<Capability>(
);
if (!status.ok) return status;
if (status.value.state === "QUARANTINED") {
const removed = await dependencies.checkpoints.remove({
uploadKey: checkpoint.uploadKey,
expectedRevision: checkpoint.revision,
signal: request.signal,
});
if (!removed.ok) return remapResult(removed, "UPLOAD_RECONCILE");
const removed = await removeCheckpoint(
dependencies,
checkpoint,
request.signal,
);
if (!removed.ok) return removed;
return browserDataSuccess(
Object.freeze({
kind: "COMPLETED" as const,
@@ -1096,12 +1092,12 @@ async function completeUpload<Capability>(
{ recovery: "RECONCILE" },
);
}
const removed = await dependencies.checkpoints.remove({
uploadKey: checkpoint.uploadKey,
expectedRevision: checkpoint.revision,
signal: request.signal,
});
if (!removed.ok) return remapResult(removed, "UPLOAD_RECONCILE");
const removed = await removeCheckpoint(
dependencies,
checkpoint,
request.signal,
);
if (!removed.ok) return removed;
return browserDataSuccess(
quarantinedOutcome(value.resourceId, sessionFromCheckpoint(checkpoint), false),
);
@@ -1217,6 +1213,22 @@ async function executeAbort<Capability>(
return browserDataSuccess(Object.freeze({ state }));
}
/** Drops the durable checkpoint a finished or dead session no longer needs. */
async function removeCheckpoint<Capability>(
dependencies: RuntimeDependencies<Capability>,
checkpoint: ResumableUploadCheckpoint,
signal: AbortSignal,
): Promise<BrowserDataResult<void>> {
return remapResult(
await dependencies.checkpoints.remove({
uploadKey: checkpoint.uploadKey,
expectedRevision: checkpoint.revision,
signal,
}),
"UPLOAD_RECONCILE",
);
}
async function callWithRetry<Capability, Value>(
dependencies: RuntimeDependencies<Capability>,
operation: BrowserDataOperation,