Files
clean-architecture-frontend…/src/adapters/platform/indexeddb-connection.ts
T
DongHyeonkaandClaude Opus 5.5 3e37fbf0ed fix(storage): delete a partition's IndexedDB dataset when an authorized purge cannot open it (05-03)
LOGOUT and ACCOUNT_DELETION purged row by row and so needed an open that a
corrupt budget or binding row always rejected, leaving personal rows on the
device. After authority approval, a purge that finds the dataset rejected by
admission now deletes that partition's own database and reports it; healthy
datasets and other partitions are untouched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 22:24:55 +09:00

702 lines
24 KiB
TypeScript

/**
* IDB-X-01. Shared IndexedDB connection mechanics.
*
* Four adapters independently reimplemented "turn an open request into a
* promise, hold a blocked deadline, route upgrade/error/success, close a
* connection that arrives after the caller gave up, and drop the cached handle
* when the browser takes it away". Only the mechanics are shared here. Database
* naming, schema, migrations, governance binding and the failure taxonomy stay
* with each subsystem, so this module imports none of them and is not a
* generic storage layer.
*
* The `IDBFactory` is a required parameter rather than a read of
* `globalThis.indexedDB`. `eslint.config.ts:40-63` bans that property on every
* browser root and `eslint.config.ts:519-530` grants the owned-adapter escape
* hatch to `src/adapters/platform/browser-lifecycle.ts` as a single file, not
* to this folder. Requiring the factory is also what all four callers already
* do, so nothing in eslint.config.ts has to change.
*
* What this module owns: event wiring, the settle-once latch, the blocked
* deadline and the cached-handle lifecycle. What it must never own: database
* names, schemas, migrations, governance bindings, codecs, byte budgets,
* retention, idempotency receipts, failure code tables, operation labels,
* observation event shapes, durability defaults and budget criteria. Wanting to
* move one of those in here is the signal to stop.
*/
import type { Result } from "../../contracts/result.ts";
import type { AbortTimerSnapshot } from "./abortable-operation.ts";
/**
* Everything that can end an IndexedDB operation without the caller getting a
* value. The kernel reports the cause; the caller's `translate` turns it into
* that subsystem's failure code.
*
* This union is the extension point. `abortable-operation.ts:11` baked a closed
* three-member `AbortTerminalReason` into its return type, so http v3 needed
* five owners and could not use the kernel at all. Here the owner vocabulary is
* never in a return type: adding a member is a compile error in every
* `translate` (they are total functions over the union) rather than a silent
* behavior change, and no consumer has to fork.
*/
export type IndexedDbFailureCause =
/** A native throw or a `request.error` / `transaction.error`. */
| Readonly<{ kind: "NATIVE_EXCEPTION"; error: unknown }>
/** `onblocked` fired and no deadline was configured. */
| Readonly<{ kind: "BLOCKED"; oldVersion: number; newVersion: number | null }>
/** `onblocked` fired and the configured deadline then elapsed. */
| Readonly<{ kind: "BLOCKED_DEADLINE" }>
/** The caller's own `AbortSignal` fired. */
| Readonly<{ kind: "CALLER_ABORT" }>
/** The connection handle was closed, which is not the caller aborting. */
| Readonly<{ kind: "CLOSED" }>
/** `upgrade` returned `REJECTED`, or a version change happened unexpectedly. */
| Readonly<{
kind: "UPGRADE_REJECTED";
oldVersion: number;
newVersion: number | null;
detail?: unknown;
}>
/** `admit` returned `REJECT`. `detail` is opaque to the kernel. */
| Readonly<{ kind: "ADMISSION_REJECTED"; detail?: unknown }>
/** A transaction completed without `succeed()` ever being called. */
| Readonly<{ kind: "NO_VALUE_PRODUCED" }>
/**
* No `IDBFactory`, or a required `IDBKeyRange` the caller did not supply.
* The kernel never raises this itself — the factory is a required parameter,
* so the condition can only exist before the kernel is called. It is part of
* the vocabulary so a caller that resolves those globals has one place to
* name the failure instead of a second taxonomy beside `translate`.
*/
| Readonly<{ kind: "UNSUPPORTED" }>;
/**
* Turns a cause into this subsystem's failure value. Built per call site so the
* kernel never learns an operation label or a failure code; a caller that needs
* `INDEXEDDB_READ` and one that needs `UPLOAD_RECONCILE` differ only here.
*/
export type IndexedDbTranslate<Failure> = (
cause: IndexedDbFailureCause,
) => Failure;
export type IndexedDbUpgradeContext = Readonly<{
database: IDBDatabase;
transaction: IDBTransaction;
oldVersion: number;
/** Never `null`: a null `newVersion` is reported as `UPGRADE_REJECTED` before `upgrade` runs. */
newVersion: number;
}>;
/**
* `REJECTED` aborts the versionchange transaction, so a schema change can never
* commit under a rejected policy. A throw from `upgrade` is equivalent to
* `REJECTED` with the thrown value as `detail`.
*/
export type IndexedDbUpgradeOutcome =
| Readonly<{ kind: "APPLIED" }>
| Readonly<{ kind: "REJECTED"; detail?: unknown }>;
/**
* Post-open validation. It runs after `onsuccess` and may be asynchronous, so
* store/index assertions and governance reads both fit. A rejected or failed
* admission closes the connection before the caller ever sees it.
*/
export type IndexedDbAdmission =
| Readonly<{ kind: "ADMIT" }>
| Readonly<{ kind: "REJECT"; detail?: unknown }>
| Readonly<{ kind: "FAIL"; cause: IndexedDbFailureCause }>;
export type IndexedDbOpenInput<Failure> = Readonly<{
/** Required. See the module comment for why this is not read from a global. */
factory: IDBFactory;
databaseName: string;
/** Omit to open whatever version exists. */
version?: number;
translate: IndexedDbTranslate<Failure>;
/**
* Called inside the versionchange transaction. Omitting it means any upgrade
* is unexpected and the open fails with `UPGRADE_REJECTED` — which is what
* `indexeddb-maintenance.ts:477-484` does by hand today.
*/
upgrade?: (context: IndexedDbUpgradeContext) => IndexedDbUpgradeOutcome;
/** Post-open validation. Omitting it admits every successful open. */
admit?: (
database: IDBDatabase,
) => IndexedDbAdmission | Promise<IndexedDbAdmission>;
/** Aborts a pending upgrade transaction and settles with `CALLER_ABORT`. */
signal?: AbortSignal;
/**
* `undefined` or `0`: the `onblocked` event itself is terminal and settles
* with `BLOCKED` (maintenance's behavior). A positive value waits that long
* before settling with `BLOCKED_DEADLINE` (runtime/opfs/checkpoint).
*/
blockedTimeoutMs?: number;
/**
* Required when `blockedTimeoutMs` is positive. Build it with
* `snapshotAbortTimers` from `./abortable-operation.ts`, which binds the
* callables once so replacing a method after composition cannot change how an
* open already in flight is bounded.
*/
timers?: AbortTimerSnapshot;
/** Observation only; it cannot change the outcome and its throw is swallowed. */
onBlocked?: (
event: Readonly<{ oldVersion: number; newVersion: number | null }>,
) => void;
}>;
export type IndexedDbConnection<Failure> = Readonly<{
/**
* Single-flight: concurrent callers share one in-flight open, and a cached
* live connection is returned without touching the factory.
*/
acquire(signal?: AbortSignal): Promise<Result<IDBDatabase, Failure>>;
/** The cached connection, or `null` while none is live. Live accessor, not a snapshot. */
current(): IDBDatabase | null;
/**
* Idempotent. Closes the cached connection and settles any in-flight open
* with `CLOSED` — not `CALLER_ABORT`, because the two have different codes in
* `indexeddb-runtime.ts` (`L743` resolves UNAVAILABLE while `L676` resolves
* ABORTED), and collapsing them would change one of them.
*/
close(): void;
isClosed(): boolean;
}>;
export type IndexedDbConnectionInput<Failure> = Readonly<{
/**
* How to produce a connection. Normally a closure over
* `openIndexedDbDatabase`. It is a seam rather than a fixed body so a caller
* can retry, decorate or fake the open without faking an `IDBFactory`.
*/
open: (
signal: AbortSignal | undefined,
) => Promise<Result<IDBDatabase, Failure>>;
translate: IndexedDbTranslate<Failure>;
/**
* Fired after the handle has already dropped its cached connection, so a
* listener cannot keep a connection the browser is taking back. The next
* `acquire()` opens again.
*/
onVersionChange?: (event: IDBVersionChangeEvent) => void;
/** `onclose`: the browser closed the connection without a version change. */
onForcedClose?: () => void;
}>;
export type IndexedDbDeleteOutcome =
| Readonly<{ kind: "DELETED" }>
/**
* The request is still live in the browser. It is not a failure and it is not
* "not applied": `deleteDatabase` cannot be cancelled after dispatch, so the
* effect is unknown. `indexeddb-checkpoint-store.ts:449-462` makes the same
* distinction and its comment explains why.
*/
| Readonly<{ kind: "BLOCKED_DEADLINE" }>;
export type IndexedDbDeleteInput<Failure> = Readonly<{
factory: IDBFactory;
databaseName: string;
translate: IndexedDbTranslate<Failure>;
blockedTimeoutMs?: number;
timers?: AbortTimerSnapshot;
/**
* Called exactly once when the native request truly settles, success or
* error — never on a blocked deadline. The caller uses it to release a
* pending-deletion registration; the kernel does not own such a registry
* because whether a realm may recreate the database is the caller's policy.
*/
onSettled?: () => void;
}>;
function succeeded<Value, Failure>(value: Value): Result<Value, Failure> {
return Object.freeze({ ok: true as const, value });
}
function failed<Value, Failure>(error: Failure): Result<Value, Failure> {
return Object.freeze({ ok: false as const, error });
}
/**
* A connection that lost a race is closed, never leaked. The close itself is
* best effort: a handle the browser already tore down cannot be closed again,
* and that must not replace the outcome the caller was given.
*/
function closeQuietly(database: IDBDatabase): void {
try {
database.close();
} catch {
// A connection that cannot be closed is already gone.
}
}
/**
* A positive deadline with no scheduler leaves the open unbounded, which is the
* same class of configuration defect `assertBoundedCapacity` and
* `snapshotAbortTimers` reject at construction rather than at runtime. It is a
* throw instead of a `Failure` because no `translate` could describe it without
* the caller first deciding it is acceptable to run unbounded.
*/
function assertBlockedDeadline(
blockedTimeoutMs: number | undefined,
timers: AbortTimerSnapshot | undefined,
): boolean {
const bounded =
blockedTimeoutMs !== undefined &&
Number.isFinite(blockedTimeoutMs) &&
blockedTimeoutMs > 0;
if (bounded && !timers) {
throw new TypeError(
"A positive blockedTimeoutMs requires a timer snapshot.",
);
}
return bounded;
}
/**
* Settles exactly once. A connection that arrives after the settle — a late
* `onsuccess`, a rejected admission, an abort — is closed rather than leaked.
*/
export function openIndexedDbDatabase<Failure>(
input: IndexedDbOpenInput<Failure>,
): Promise<Result<IDBDatabase, Failure>> {
const { factory, databaseName, translate } = input;
const bounded = assertBlockedDeadline(input.blockedTimeoutMs, input.timers);
if (input.signal?.aborted) {
return Promise.resolve(failed(translate({ kind: "CALLER_ABORT" })));
}
return new Promise<Result<IDBDatabase, Failure>>((resolve) => {
let settled = false;
let blockedTimer: unknown;
let blockedTimerSet = false;
let upgradeRejection: IndexedDbFailureCause | null = null;
const settle = (result: Result<IDBDatabase, Failure>) => {
if (settled) {
if (result.ok) closeQuietly(result.value);
return;
}
settled = true;
if (blockedTimerSet) {
blockedTimerSet = false;
try {
input.timers?.clearTimer(blockedTimer);
} catch {
// A throwing scheduler cannot keep the open unresolved.
}
}
try {
input.signal?.removeEventListener("abort", onCallerAbort);
} catch {
// A hostile signal facade cannot block cleanup.
}
resolve(result);
};
const settleFailure = (cause: IndexedDbFailureCause) => {
settle(failed(translate(cause)));
};
let request: IDBOpenDBRequest;
try {
request =
input.version === undefined
? factory.open(databaseName)
: factory.open(databaseName, input.version);
} catch (error) {
settleFailure({ kind: "NATIVE_EXCEPTION", error });
return;
}
/**
* An upgrade transaction is the only cancellable part of an open request:
* aborting it makes the request fail through `onerror`, and there is no
* other way to stop a dispatched open.
*/
const abortUpgrade = () => {
try {
request.transaction?.abort();
} catch {
// The request's own error path owns whatever happens next.
}
};
function onCallerAbort(): void {
abortUpgrade();
settleFailure({ kind: "CALLER_ABORT" });
}
input.signal?.addEventListener("abort", onCallerAbort, { once: true });
request.onupgradeneeded = (event) => {
const transaction = request.transaction;
const oldVersion = event.oldVersion;
const newVersion = event.newVersion;
// A null `newVersion` means a delete is in progress, and no `upgrade`
// policy can be applied to a schema that is going away. It is reported
// before the callback runs so a caller never sees a half-open upgrade.
// Q-6.5-10. An open that already settled (caller abort, BLOCKED, close)
// must not commit a migration behind its caller's back either.
if (settled || !transaction || newVersion === null || !input.upgrade) {
upgradeRejection = { kind: "UPGRADE_REJECTED", oldVersion, newVersion };
abortUpgrade();
return;
}
let outcome: IndexedDbUpgradeOutcome;
try {
outcome = input.upgrade({
database: request.result,
transaction,
oldVersion,
newVersion,
});
} catch (error) {
outcome = { kind: "REJECTED", detail: error };
}
if (outcome.kind === "APPLIED") return;
upgradeRejection = {
kind: "UPGRADE_REJECTED",
oldVersion,
newVersion,
detail: outcome.detail,
};
abortUpgrade();
};
request.onblocked = (event) => {
const blocked = Object.freeze({
oldVersion: event.oldVersion,
newVersion: event.newVersion,
});
if (input.onBlocked) {
try {
input.onBlocked(blocked);
} catch {
// Observation cannot change the outcome.
}
}
if (!bounded) {
settleFailure({ kind: "BLOCKED", ...blocked });
return;
}
if (blockedTimerSet || settled) return;
try {
blockedTimer = input.timers?.setTimer(() => {
settleFailure({ kind: "BLOCKED_DEADLINE" });
}, input.blockedTimeoutMs as number);
blockedTimerSet = true;
} catch {
// A scheduler that cannot install the deadline leaves the open
// unbounded, so the deadline is treated as already elapsed.
settleFailure({ kind: "BLOCKED_DEADLINE" });
}
};
request.onerror = () => {
settleFailure(
upgradeRejection ?? { kind: "NATIVE_EXCEPTION", error: request.error },
);
};
const routeAdmission = (
database: IDBDatabase,
admission: IndexedDbAdmission,
) => {
if (settled) {
closeQuietly(database);
return;
}
if (admission.kind === "ADMIT") {
settle(succeeded(database));
return;
}
// A connection the caller will never see is closed before the failure is
// reported, so a rejected admission cannot leak a live handle.
closeQuietly(database);
settleFailure(
admission.kind === "REJECT"
? { kind: "ADMISSION_REJECTED", detail: admission.detail }
: admission.cause,
);
};
request.onsuccess = () => {
const database = request.result;
if (settled) {
closeQuietly(database);
return;
}
if (!input.admit) {
settle(succeeded(database));
return;
}
let admission: IndexedDbAdmission | Promise<IndexedDbAdmission>;
try {
admission = input.admit(database);
} catch (error) {
closeQuietly(database);
settleFailure({ kind: "NATIVE_EXCEPTION", error });
return;
}
void Promise.resolve(admission).then(
(resolved) => routeAdmission(database, resolved),
(error: unknown) => {
closeQuietly(database);
settleFailure({ kind: "NATIVE_EXCEPTION", error });
},
);
};
});
}
export function createIndexedDbConnection<Failure>(
input: IndexedDbConnectionInput<Failure>,
): IndexedDbConnection<Failure> {
let connection: IDBDatabase | null = null;
let attempt: Promise<Result<IDBDatabase, Failure>> | null = null;
let controller: AbortController | null = null;
let closed = false;
const closeWaiters = new Set<() => void>();
/**
* The browser is taking the connection back. The cached handle is dropped
* before the subsystem is told, so a notification callback cannot hand out a
* connection that is already gone. The next `acquire()` opens again.
*/
const invalidate = (database: IDBDatabase, notify: () => void) => {
if (connection !== database) return;
connection = null;
try {
notify();
} catch {
// Losing the connection is independent from announcing it.
}
};
const adopt = (database: IDBDatabase): IDBDatabase => {
database.onversionchange = (event) => {
// The connection has to go for the other context's upgrade to proceed,
// so it is closed here rather than left to a listener's discretion.
closeQuietly(database);
invalidate(database, () => input.onVersionChange?.(event));
};
database.onclose = () => {
// `onclose` means the browser already tore the connection down, so there
// is nothing left to close — only a cached handle to drop.
invalidate(database, () => input.onForcedClose?.());
};
return database;
};
const start = (): Promise<Result<IDBDatabase, Failure>> => {
const openController = new AbortController();
controller = openController;
const started = input.open(openController.signal).then(
(result) => {
if (attempt === started) {
attempt = null;
controller = null;
}
if (!result.ok) return result;
if (closed) {
// The handle was closed while the open was in flight; the connection
// that arrived belongs to nobody.
closeQuietly(result.value);
return result;
}
connection = adopt(result.value);
return result;
},
(error: unknown) => {
if (attempt === started) {
attempt = null;
controller = null;
}
return failed<IDBDatabase, Failure>(
input.translate({ kind: "NATIVE_EXCEPTION", error }),
);
},
);
attempt = started;
return started;
};
return Object.freeze({
acquire(signal) {
if (closed) {
return Promise.resolve(
failed<IDBDatabase, Failure>(input.translate({ kind: "CLOSED" })),
);
}
if (signal?.aborted) {
return Promise.resolve(
failed<IDBDatabase, Failure>(
input.translate({ kind: "CALLER_ABORT" }),
),
);
}
const live = connection;
if (live) return Promise.resolve(succeeded<IDBDatabase, Failure>(live));
const shared = attempt ?? start();
// The shared open is not cancelled by one caller giving up: another
// caller may still want the connection, and the request cannot be
// un-dispatched anyway.
return new Promise<Result<IDBDatabase, Failure>>((resolve) => {
let callerSettled = false;
const finishCaller = (result: Result<IDBDatabase, Failure>) => {
if (callerSettled) return;
callerSettled = true;
try {
signal?.removeEventListener("abort", onAbort);
} catch {
// A hostile signal facade cannot block cleanup.
}
resolve(result);
};
function onAbort(): void {
finishCaller(
failed(input.translate({ kind: "CALLER_ABORT" })),
);
}
function onClose(): void {
finishCaller(failed(input.translate({ kind: "CLOSED" })));
}
signal?.addEventListener("abort", onAbort, { once: true });
closeWaiters.add(onClose);
void shared.then(
(result) => {
closeWaiters.delete(onClose);
// A handle closed mid-open reports CLOSED even if the open itself
// succeeded: the connection is already gone.
finishCaller(
closed
? failed(input.translate({ kind: "CLOSED" }))
: result,
);
},
() => {
closeWaiters.delete(onClose);
finishCaller(failed(input.translate({ kind: "CLOSED" })));
},
);
});
},
current: () => connection,
close() {
if (closed) return;
closed = true;
const live = connection;
connection = null;
if (live) closeQuietly(live);
// Cancelling the in-flight open aborts a pending upgrade transaction, so
// a closed handle does not leave a versionchange transaction running.
try {
controller?.abort();
} catch {
// A cancelled open still reports CLOSED to its waiters below.
}
controller = null;
for (const waiter of [...closeWaiters]) {
closeWaiters.delete(waiter);
waiter();
}
},
isClosed: () => closed,
});
}
/**
* In this module because it is the same `IDBOpenDBRequest` state machine as
* `openIndexedDbDatabase`. Two callers delete a database:
* `indexeddb-checkpoint-store.ts`, and the IndexedDB runtime's authorized
* LOGOUT/ACCOUNT_DELETION purge when its dataset fails admission. Leaving it out would leave a third hand-written copy of
* the settle-once blocked-deadline latch eight lines away from the kernel's.
*
* There is deliberately no `signal`: the request cannot be cancelled after
* dispatch, so reporting ABORTED while the deletion may still commit would be a
* lie. Callers check their signal before calling.
*/
export function deleteIndexedDbDatabase<Failure>(
input: IndexedDbDeleteInput<Failure>,
): Promise<Result<IndexedDbDeleteOutcome, Failure>> {
const { factory, databaseName, translate } = input;
const bounded = assertBlockedDeadline(input.blockedTimeoutMs, input.timers);
return new Promise<Result<IndexedDbDeleteOutcome, Failure>>((resolve) => {
let settled = false;
let notified = false;
let blockedTimer: unknown;
let blockedTimerSet = false;
/**
* Independent of `settle`: a blocked deadline resolves the caller while the
* request is still live, and the registration must be released when the
* request actually lands, not when the caller stopped waiting.
*/
const notifySettled = () => {
if (notified) return;
notified = true;
try {
input.onSettled?.();
} catch {
// Releasing a registration cannot change the deletion outcome.
}
};
const settle = (result: Result<IndexedDbDeleteOutcome, Failure>) => {
if (settled) return;
settled = true;
if (blockedTimerSet) {
blockedTimerSet = false;
try {
input.timers?.clearTimer(blockedTimer);
} catch {
// A throwing scheduler cannot keep the deletion unresolved.
}
}
resolve(result);
};
let request: IDBOpenDBRequest;
try {
request = factory.deleteDatabase(databaseName);
} catch (error) {
notifySettled();
settle(failed(translate({ kind: "NATIVE_EXCEPTION", error })));
return;
}
request.onsuccess = () => {
notifySettled();
settle(succeeded({ kind: "DELETED" as const }));
};
request.onerror = () => {
notifySettled();
settle(
failed(translate({ kind: "NATIVE_EXCEPTION", error: request.error })),
);
};
request.onblocked = (event) => {
if (!bounded) {
settle(
failed(
translate({
kind: "BLOCKED",
oldVersion: event.oldVersion,
newVersion: event.newVersion,
}),
),
);
return;
}
if (blockedTimerSet || settled) return;
try {
blockedTimer = input.timers?.setTimer(() => {
settle(succeeded({ kind: "BLOCKED_DEADLINE" as const }));
}, input.blockedTimeoutMs as number);
blockedTimerSet = true;
} catch {
settle(succeeded({ kind: "BLOCKED_DEADLINE" as const }));
}
};
});
}