public-response-cache-adapter.ts (1986 lines) and download-delivery-adapter.ts (1491 lines) mixed the facade with codecs and validators. Moved verbatim: - cache-storage/public-cache-codec.ts: manifest normalization and canonical digest input, marker/active-pointer validation, bounded control JSON, owned cache names, CacheValidationFailure -> Result mapping. - cache-storage/public-cache-response-validation.ts: response admission (status, directives, Content-Type, Vary, bounded body, digest). - browser-files/download-input-validation.ts: request snapshot, input/limit checks, presigned and browser-managed capability validation, handoff target. The adapters drop to 1164 and 1157 lines. Two non-verbatim edits: validateDownloadInput takes a structural DownloadInputValidationOptions instead of DownloadDeliveryAdapterOptions (no import cycle), and readBodyBounded races reads on the kernel createAbortableOperation instead of its own abort listener. Moving it out of a primitive-importing file would otherwise have raised the hand-rolled abort ratchet to 20/19; the abort outcome (ABORTED, reader cancelled) is unchanged. Verified: characterization tests added first and passing before the move (cache manifest/response/control-JSON failure codes, lookup abort during a pending body read; download input validation codes); a line diff confirms the moved code is verbatim apart from the two edits above. Inventory 139/139, lane gates, check:browser-file-storage-boundaries pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1165 lines
37 KiB
TypeScript
1165 lines
37 KiB
TypeScript
import type {
|
|
CachedPublicResponse,
|
|
PublicCacheAsset,
|
|
PublicCacheCleanupReport,
|
|
PublicCacheInspection,
|
|
PublicCacheReleaseManifest,
|
|
PublicCacheReleaseSummary,
|
|
PublicResponseCache,
|
|
} from "../../application/ports/browser-file-storage/cache-storage-ports.ts";
|
|
import type {
|
|
BrowserDataFailure,
|
|
BrowserDataOperation,
|
|
BrowserDataResult,
|
|
ByteSource,
|
|
} from "../../application/ports/browser-file-storage/shared.ts";
|
|
import {
|
|
abortedResult,
|
|
browserDataFailure,
|
|
browserDataSuccess,
|
|
} from "../browser-file-storage/result.ts";
|
|
import { createAbortableOperation } from "../platform/abortable-operation.ts";
|
|
import {
|
|
cacheByteBucket,
|
|
cacheEntryBucket,
|
|
observePublicCacheSafely,
|
|
resolvePublicCachePolicy,
|
|
type PublicCacheRuntimePolicy,
|
|
type PublicCacheSafeObserver,
|
|
} from "./public-cache-policy.ts";
|
|
import {
|
|
CacheValidationFailure,
|
|
MAX_CONTROL_JSON_BYTES,
|
|
SHA256_HEX,
|
|
activePointerRequest,
|
|
asFailure,
|
|
assetKey,
|
|
canonicalManifest,
|
|
controlCacheName,
|
|
exceptionFailure,
|
|
isActivePointer,
|
|
isReleaseMarker,
|
|
jsonResponse,
|
|
markerRequest,
|
|
normalizeAndVerifyManifest,
|
|
normalizeAssets,
|
|
normalizeLookupRequest,
|
|
readBoundedJson,
|
|
releaseCacheName,
|
|
sha256Hex,
|
|
validationFailure,
|
|
type ActiveReleasePointer,
|
|
type BrowserFailureResult,
|
|
type NormalizedAsset,
|
|
type NormalizedReleaseManifest,
|
|
type PublicCacheCryptoFacade,
|
|
type ReleaseMarker,
|
|
} from "./public-cache-codec.ts";
|
|
import {
|
|
createNativeRequest,
|
|
readAndValidateResponse,
|
|
} from "./public-cache-response-validation.ts";
|
|
|
|
export interface PublicCacheMutationLock {
|
|
run<Value>(
|
|
signal: AbortSignal | undefined,
|
|
task: () => Promise<Value>,
|
|
): Promise<Value>;
|
|
}
|
|
|
|
export type PublicResponseCacheDependencies = Readonly<{
|
|
cacheStorage?: CacheStorage;
|
|
fetcher?: (request: Request) => Promise<Response>;
|
|
crypto: Crypto;
|
|
mutationLock?: PublicCacheMutationLock;
|
|
policy: PublicCacheRuntimePolicy;
|
|
now?: () => number;
|
|
observer?: PublicCacheSafeObserver;
|
|
}>;
|
|
|
|
type PublicCacheFacade = Readonly<{
|
|
match(request: Request): Promise<Response | undefined>;
|
|
put(request: Request, response: Response): Promise<void>;
|
|
}>;
|
|
|
|
type PublicCacheStorageFacade = Readonly<{
|
|
open(name: string): Promise<PublicCacheFacade>;
|
|
keys(): Promise<string[]>;
|
|
delete(name: string): Promise<boolean>;
|
|
}>;
|
|
|
|
type PublicResponseCacheDependencySnapshot = Readonly<{
|
|
cacheStorage?: PublicCacheStorageFacade;
|
|
fetcher?: (request: Request) => Promise<Response>;
|
|
crypto: PublicCacheCryptoFacade;
|
|
mutationLock?: PublicCacheMutationLock;
|
|
observer?: PublicCacheSafeObserver;
|
|
}>;
|
|
|
|
/**
|
|
* Q-6.2-6. A lookup-ready view of a verified marker. The cache name already
|
|
* encodes the manifest digest and the digest binds every asset field, so a
|
|
* marker verified once for a key stays valid for that key.
|
|
*/
|
|
type VerifiedLookupMarker = Readonly<{
|
|
key: string;
|
|
assetsByKey: ReadonlyMap<string, NormalizedAsset>;
|
|
}>;
|
|
|
|
type LockManagerLike = {
|
|
request<Value>(
|
|
name: string,
|
|
options: Readonly<{ mode: "exclusive"; signal?: AbortSignal }>,
|
|
callback: (lock: unknown) => Promise<Value>,
|
|
): Promise<Value>;
|
|
};
|
|
|
|
function snapshotPublicCacheDependencies(
|
|
dependencies: PublicResponseCacheDependencies,
|
|
): PublicResponseCacheDependencySnapshot {
|
|
const fetcher = dependencies.fetcher;
|
|
const observer = dependencies.observer;
|
|
if (
|
|
(fetcher !== undefined && typeof fetcher !== "function") ||
|
|
(observer !== undefined && typeof observer !== "function")
|
|
) {
|
|
throw new TypeError("Public cache runtime dependency is invalid.");
|
|
}
|
|
return Object.freeze({
|
|
cacheStorage: snapshotCacheStorage(dependencies.cacheStorage),
|
|
fetcher,
|
|
crypto: snapshotCacheCrypto(dependencies.crypto),
|
|
mutationLock: snapshotMutationLock(dependencies.mutationLock),
|
|
observer,
|
|
});
|
|
}
|
|
|
|
function snapshotCacheStorage(
|
|
cacheStorage: CacheStorage | undefined,
|
|
): PublicCacheStorageFacade | undefined {
|
|
if (!cacheStorage) return undefined;
|
|
const open = cacheStorage.open;
|
|
const keys = cacheStorage.keys;
|
|
const deleteCache = cacheStorage.delete;
|
|
if (
|
|
typeof open !== "function" ||
|
|
typeof keys !== "function" ||
|
|
typeof deleteCache !== "function"
|
|
) {
|
|
throw new TypeError("Public cache storage capability is invalid.");
|
|
}
|
|
return Object.freeze({
|
|
async open(name: string): Promise<PublicCacheFacade> {
|
|
const cache = await open.call(cacheStorage, name);
|
|
return snapshotCache(cache);
|
|
},
|
|
keys: keys.bind(cacheStorage),
|
|
delete: deleteCache.bind(cacheStorage),
|
|
});
|
|
}
|
|
|
|
function snapshotCache(cache: Cache): PublicCacheFacade {
|
|
const match = cache.match;
|
|
const put = cache.put;
|
|
if (typeof match !== "function" || typeof put !== "function") {
|
|
throw new TypeError("Public cache capability is invalid.");
|
|
}
|
|
return Object.freeze({
|
|
match: match.bind(cache),
|
|
put: put.bind(cache),
|
|
});
|
|
}
|
|
|
|
function snapshotCacheCrypto(crypto: Crypto): PublicCacheCryptoFacade {
|
|
const subtle = crypto?.subtle;
|
|
const digest = subtle?.digest;
|
|
if (typeof digest !== "function") {
|
|
throw new TypeError("Public cache crypto capability is invalid.");
|
|
}
|
|
return Object.freeze({
|
|
async digestSha256(bytes: Uint8Array): Promise<ArrayBuffer> {
|
|
return await digest.call(
|
|
subtle,
|
|
"SHA-256",
|
|
Uint8Array.from(bytes),
|
|
);
|
|
},
|
|
});
|
|
}
|
|
|
|
function snapshotMutationLock(
|
|
lock: PublicCacheMutationLock | undefined,
|
|
): PublicCacheMutationLock | undefined {
|
|
if (!lock) return undefined;
|
|
const run = lock.run;
|
|
if (typeof run !== "function") {
|
|
throw new TypeError("Public cache mutation lock is invalid.");
|
|
}
|
|
return Object.freeze({
|
|
async run<Value>(
|
|
signal: AbortSignal | undefined,
|
|
task: () => Promise<Value>,
|
|
): Promise<Value> {
|
|
return await (run.call(lock, signal, task) as Promise<Value>);
|
|
},
|
|
});
|
|
}
|
|
|
|
export function createPublicResponseCacheAdapter(
|
|
inputDependencies: PublicResponseCacheDependencies,
|
|
): PublicResponseCache {
|
|
const dependencies = snapshotPublicCacheDependencies(inputDependencies);
|
|
const policy = resolvePublicCachePolicy(inputDependencies.policy);
|
|
const now = inputDependencies.now ?? Date.now;
|
|
// ponytail: one slot for the active release only; a rollback re-verifies.
|
|
let verifiedLookupMarker: VerifiedLookupMarker | undefined;
|
|
|
|
const responses: PublicResponseCache["responses"] = Object.freeze({
|
|
async matchActiveExact(
|
|
request: Parameters<
|
|
PublicResponseCache["responses"]["matchActiveExact"]
|
|
>[0],
|
|
) {
|
|
const signal = request.signal;
|
|
const aborted = abortedResult(signal, "CACHE_LOOKUP");
|
|
if (aborted) return aborted;
|
|
if (!dependencies.cacheStorage) {
|
|
return unsupported("CACHE_LOOKUP", "RETRY");
|
|
}
|
|
let assetRequest: NormalizedAsset;
|
|
try {
|
|
assetRequest = normalizeLookupRequest(
|
|
request.absoluteUrl,
|
|
request.requestHeaders,
|
|
policy,
|
|
);
|
|
} catch (error) {
|
|
return validationFailure(error, "CACHE_LOOKUP");
|
|
}
|
|
observePublicCacheSafely(dependencies.observer, {
|
|
operation: "CACHE_LOOKUP",
|
|
outcome: "STARTED",
|
|
});
|
|
|
|
try {
|
|
const pointerResult = await readActivePointer(
|
|
dependencies.cacheStorage,
|
|
policy,
|
|
);
|
|
if (!pointerResult.ok) {
|
|
return observeFailure(pointerResult, dependencies.observer);
|
|
}
|
|
if (!pointerResult.value) {
|
|
observePublicCacheSafely(dependencies.observer, {
|
|
operation: "CACHE_LOOKUP",
|
|
outcome: "SUCCEEDED",
|
|
});
|
|
return browserDataSuccess(null);
|
|
}
|
|
const pointer = pointerResult.value;
|
|
const names = await dependencies.cacheStorage.keys();
|
|
if (!names.includes(pointer.candidateCacheName)) {
|
|
return observeFailure(
|
|
browserDataFailure("STORAGE_EVICTED", "CACHE_LOOKUP", {
|
|
recovery: "REHYDRATE",
|
|
}),
|
|
dependencies.observer,
|
|
pointer.releaseRegistryId,
|
|
);
|
|
}
|
|
const cache = await dependencies.cacheStorage.open(
|
|
pointer.candidateCacheName,
|
|
);
|
|
const markerKey = `${pointer.candidateCacheName}\n${pointer.manifestDigestHex}`;
|
|
let verified =
|
|
verifiedLookupMarker?.key === markerKey
|
|
? verifiedLookupMarker
|
|
: undefined;
|
|
if (!verified) {
|
|
const markerResult = await readMarker(
|
|
cache,
|
|
policy,
|
|
dependencies.crypto,
|
|
);
|
|
if (!markerResult.ok) {
|
|
return observeFailure(
|
|
markerResult,
|
|
dependencies.observer,
|
|
pointer.releaseRegistryId,
|
|
);
|
|
}
|
|
const marker = markerResult.value;
|
|
if (
|
|
!marker ||
|
|
marker.releaseRegistryId !== pointer.releaseRegistryId ||
|
|
marker.manifestDigestHex !== pointer.manifestDigestHex
|
|
) {
|
|
return observeFailure(
|
|
browserDataFailure("INTEGRITY_FAILED", "CACHE_LOOKUP", {
|
|
recovery: "REHYDRATE",
|
|
}),
|
|
dependencies.observer,
|
|
pointer.releaseRegistryId,
|
|
);
|
|
}
|
|
verified = Object.freeze({
|
|
key: markerKey,
|
|
assetsByKey: new Map(
|
|
marker.assets.map((asset) => [assetKey(asset), asset]),
|
|
),
|
|
});
|
|
verifiedLookupMarker = verified;
|
|
}
|
|
const manifestAsset = verified.assetsByKey.get(
|
|
assetKey(assetRequest),
|
|
);
|
|
if (!manifestAsset) {
|
|
observePublicCacheSafely(dependencies.observer, {
|
|
operation: "CACHE_LOOKUP",
|
|
outcome: "SUCCEEDED",
|
|
releaseRegistryId: pointer.releaseRegistryId,
|
|
});
|
|
return browserDataSuccess(null);
|
|
}
|
|
|
|
const nativeRequest = createNativeRequest(manifestAsset);
|
|
// Exact Cache.match defaults are intentional. ignoreSearch,
|
|
// ignoreMethod and ignoreVary are never enabled.
|
|
const cached = await cache.match(nativeRequest);
|
|
if (!cached) {
|
|
return observeFailure(
|
|
browserDataFailure("STORAGE_EVICTED", "CACHE_LOOKUP", {
|
|
recovery: "REHYDRATE",
|
|
}),
|
|
dependencies.observer,
|
|
pointer.releaseRegistryId,
|
|
);
|
|
}
|
|
const read = await readAndValidateResponse(
|
|
cached,
|
|
manifestAsset,
|
|
policy,
|
|
dependencies.crypto,
|
|
signal,
|
|
);
|
|
if (!read.ok) {
|
|
return observeFailure(
|
|
rebaseFailure(read.error, "CACHE_LOOKUP"),
|
|
dependencies.observer,
|
|
pointer.releaseRegistryId,
|
|
manifestAsset.expectedByteLength,
|
|
);
|
|
}
|
|
const body = byteSourceFrom(read.value.bytes);
|
|
const response: CachedPublicResponse = Object.freeze({
|
|
status: 200,
|
|
headers: read.value.headers,
|
|
body,
|
|
integrity: Object.freeze({
|
|
algorithm: "SHA-256",
|
|
digestHex: manifestAsset.digestHex,
|
|
}),
|
|
});
|
|
observePublicCacheSafely(dependencies.observer, {
|
|
operation: "CACHE_LOOKUP",
|
|
outcome: "SUCCEEDED",
|
|
releaseRegistryId: pointer.releaseRegistryId,
|
|
byteBucket: cacheByteBucket(manifestAsset.expectedByteLength),
|
|
});
|
|
return browserDataSuccess(response);
|
|
} catch (error) {
|
|
return observeFailure(
|
|
exceptionFailure(error, "CACHE_LOOKUP"),
|
|
dependencies.observer,
|
|
);
|
|
}
|
|
},
|
|
});
|
|
|
|
const admin: PublicResponseCache["admin"] = Object.freeze({
|
|
async stageRelease(
|
|
manifest: PublicCacheReleaseManifest,
|
|
options: NonNullable<
|
|
Parameters<PublicResponseCache["admin"]["stageRelease"]>[1]
|
|
> = {},
|
|
) {
|
|
const signal = options.signal;
|
|
const aborted = abortedResult(signal, "CACHE_STAGE");
|
|
if (aborted) return aborted;
|
|
const availability = stageAvailability(dependencies);
|
|
if (availability) return availability;
|
|
|
|
let normalized: NormalizedReleaseManifest;
|
|
try {
|
|
normalized = await normalizeAndVerifyManifest(
|
|
manifest,
|
|
policy,
|
|
dependencies.crypto,
|
|
);
|
|
} catch (error) {
|
|
return validationFailure(error, "CACHE_STAGE");
|
|
}
|
|
observePublicCacheSafely(dependencies.observer, {
|
|
operation: "CACHE_STAGE",
|
|
outcome: "STARTED",
|
|
releaseRegistryId: normalized.releaseRegistryId,
|
|
entryBucket: cacheEntryBucket(normalized.assets.length),
|
|
});
|
|
|
|
// NS-08. One owner covers the whole staging body. Handing the signal to
|
|
// each `Request` only asked a cooperative fetch to stop: a stream or a
|
|
// digest that ignored it kept the mutation lock and, worse, could finish
|
|
// after the abort had already ended the operation and still write both the
|
|
// asset and the marker, publishing a release nobody was waiting for.
|
|
const owner = createAbortableOperation({ signal });
|
|
const ownedStep = async <Value>(
|
|
task: Promise<Value>,
|
|
compensate?: (value: Value) => void,
|
|
): Promise<Value> => {
|
|
const raced = await owner.race(task, compensate);
|
|
if (raced.kind === "REJECTED") throw raced.reason;
|
|
if (raced.kind !== "VALUE") {
|
|
throw new CacheValidationFailure("ABORTED");
|
|
}
|
|
return raced.value;
|
|
};
|
|
const assertOwned = (): void => {
|
|
if (owner.terminal() !== null) {
|
|
throw new CacheValidationFailure("ABORTED");
|
|
}
|
|
};
|
|
|
|
try {
|
|
const result = await dependencies.mutationLock!.run(
|
|
signal,
|
|
async () => {
|
|
assertOwned();
|
|
const cacheName = releaseCacheName(
|
|
policy,
|
|
normalized.releaseRegistryId,
|
|
normalized.manifestDigestHex,
|
|
);
|
|
const existingNames = await ownedStep(
|
|
Promise.resolve(dependencies.cacheStorage!.keys()),
|
|
);
|
|
// STO-RR-05. A candidate this call did not create may be the one
|
|
// currently serving traffic, so nothing about it is deleted before
|
|
// a replacement has been fetched and verified.
|
|
const preExistingCandidate = existingNames.includes(cacheName);
|
|
if (preExistingCandidate) {
|
|
const existing = await dependencies.cacheStorage!.open(cacheName);
|
|
const marker = await readMarker(
|
|
existing,
|
|
policy,
|
|
dependencies.crypto,
|
|
);
|
|
if (!marker.ok && marker.error.code !== "CORRUPT_DATA") {
|
|
// STO-RR-04. A marker that could not be read is unknown, not
|
|
// damaged. Treating a transient storage error as proof of
|
|
// corruption would delete a healthy active release.
|
|
return rebaseFailure(marker.error, "CACHE_STAGE");
|
|
}
|
|
if (
|
|
marker.ok &&
|
|
marker.value &&
|
|
marker.value.releaseRegistryId ===
|
|
normalized.releaseRegistryId &&
|
|
marker.value.manifestDigestHex ===
|
|
normalized.manifestDigestHex &&
|
|
marker.value.entryCount === normalized.assets.length
|
|
) {
|
|
// STO-04. The marker is a claim that staging completed, not
|
|
// evidence that every entry still exists and matches. Browser
|
|
// eviction, manual deletion and partial corruption all leave the
|
|
// marker intact, so the candidate is re-verified before reuse.
|
|
const verified = await verifyReleaseCandidate(
|
|
existing,
|
|
marker.value.assets,
|
|
policy,
|
|
dependencies.crypto,
|
|
signal,
|
|
);
|
|
if (verified.kind === "VERIFIED") {
|
|
return browserDataSuccess(summaryFromMarker(marker.value));
|
|
}
|
|
if (verified.kind === "UNKNOWN") {
|
|
// Abort or an unreadable candidate is never stage success and
|
|
// never silently deletes an owned candidate.
|
|
return verified.failure;
|
|
}
|
|
}
|
|
}
|
|
|
|
const cache = await ownedStep(
|
|
Promise.resolve(dependencies.cacheStorage!.open(cacheName)),
|
|
);
|
|
try {
|
|
let totalBytes = 0;
|
|
for (const asset of normalized.assets) {
|
|
assertOwned();
|
|
const cacheRequest = createNativeRequest(asset);
|
|
const networkRequest = createNativeRequest(
|
|
asset,
|
|
owner.signal,
|
|
);
|
|
const response = await ownedStep(
|
|
Promise.resolve(dependencies.fetcher!(networkRequest)),
|
|
// A response that arrives after the owner ended is released
|
|
// rather than read.
|
|
(late) => {
|
|
void late.body?.cancel().catch(() => undefined);
|
|
},
|
|
);
|
|
const read = await ownedStep(
|
|
readAndValidateResponse(
|
|
response,
|
|
asset,
|
|
policy,
|
|
dependencies.crypto,
|
|
owner.signal,
|
|
),
|
|
);
|
|
if (!read.ok) throw new CacheValidationFailure(read.error.code);
|
|
assertOwned();
|
|
totalBytes += read.value.bytes.byteLength;
|
|
if (totalBytes > policy.maxReleaseBytes) {
|
|
throw new CacheValidationFailure("LIMIT_EXCEEDED");
|
|
}
|
|
await ownedStep(
|
|
Promise.resolve(
|
|
cache.put(
|
|
cacheRequest,
|
|
new Response(Uint8Array.from(read.value.bytes), {
|
|
status: 200,
|
|
headers: read.value.headers.map(
|
|
([name, value]) => [name, value],
|
|
),
|
|
}),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
assertOwned();
|
|
|
|
const marker: ReleaseMarker = Object.freeze({
|
|
schemaVersion: 1,
|
|
verified: true,
|
|
releaseRegistryId: normalized.releaseRegistryId,
|
|
manifestDigestHex: normalized.manifestDigestHex,
|
|
entryCount: normalized.assets.length,
|
|
totalBytes,
|
|
stagedAtEpochMs: now(),
|
|
assets: normalized.assets,
|
|
});
|
|
await ownedStep(
|
|
Promise.resolve(
|
|
cache.put(markerRequest(policy), jsonResponse(marker)),
|
|
),
|
|
);
|
|
// The marker is the activation record, so it is only a success
|
|
// once this call still owns the operation that wrote it.
|
|
assertOwned();
|
|
return browserDataSuccess(summaryFromMarker(marker));
|
|
} catch (error) {
|
|
// STO-RR-05. Only a candidate this call created is removed. A
|
|
// repair that failed part-way leaves every entry it did replace
|
|
// and every entry it never touched in place, so the release that
|
|
// was serving traffic before still is.
|
|
if (!preExistingCandidate) {
|
|
await dependencies.cacheStorage!.delete(cacheName);
|
|
}
|
|
throw error;
|
|
}
|
|
},
|
|
);
|
|
if (!result.ok) {
|
|
return observeFailure(
|
|
result,
|
|
dependencies.observer,
|
|
normalized.releaseRegistryId,
|
|
);
|
|
}
|
|
observePublicCacheSafely(dependencies.observer, {
|
|
operation: "CACHE_STAGE",
|
|
outcome: "SUCCEEDED",
|
|
releaseRegistryId: normalized.releaseRegistryId,
|
|
entryBucket: cacheEntryBucket(result.value.entryCount),
|
|
byteBucket: cacheByteBucket(result.value.totalBytes),
|
|
});
|
|
return result;
|
|
} catch (error) {
|
|
return observeFailure(
|
|
exceptionFailure(error, "CACHE_STAGE"),
|
|
dependencies.observer,
|
|
normalized.releaseRegistryId,
|
|
);
|
|
} finally {
|
|
owner.close();
|
|
}
|
|
},
|
|
|
|
async activateRelease(
|
|
releaseRegistryId: string,
|
|
manifestDigestHex: string,
|
|
options: NonNullable<
|
|
Parameters<PublicResponseCache["admin"]["activateRelease"]>[2]
|
|
> = {},
|
|
) {
|
|
const signal = options.signal;
|
|
const aborted = abortedResult(signal, "CACHE_ACTIVATE");
|
|
if (aborted) return aborted;
|
|
const availability = localMutationAvailability(
|
|
dependencies,
|
|
"CACHE_ACTIVATE",
|
|
);
|
|
if (availability) return availability;
|
|
if (
|
|
!policy.isReleaseRegistryIdAllowed(releaseRegistryId) ||
|
|
!SHA256_HEX.test(manifestDigestHex)
|
|
) {
|
|
return browserDataFailure("INVALID_INPUT", "CACHE_ACTIVATE");
|
|
}
|
|
observePublicCacheSafely(dependencies.observer, {
|
|
operation: "CACHE_ACTIVATE",
|
|
outcome: "STARTED",
|
|
releaseRegistryId,
|
|
});
|
|
|
|
try {
|
|
const result = await dependencies.mutationLock!.run(
|
|
signal,
|
|
async () => {
|
|
const cacheName = releaseCacheName(
|
|
policy,
|
|
releaseRegistryId,
|
|
manifestDigestHex,
|
|
);
|
|
const names = await dependencies.cacheStorage!.keys();
|
|
if (!names.includes(cacheName)) {
|
|
return browserDataFailure("NOT_FOUND", "CACHE_ACTIVATE", {
|
|
recovery: "REHYDRATE",
|
|
});
|
|
}
|
|
const cache = await dependencies.cacheStorage!.open(cacheName);
|
|
const markerResult = await readMarker(
|
|
cache,
|
|
policy,
|
|
dependencies.crypto,
|
|
);
|
|
if (!markerResult.ok) {
|
|
return rebaseFailure(markerResult.error, "CACHE_ACTIVATE");
|
|
}
|
|
const marker = markerResult.value;
|
|
if (
|
|
!marker ||
|
|
marker.releaseRegistryId !== releaseRegistryId ||
|
|
marker.manifestDigestHex !== manifestDigestHex
|
|
) {
|
|
return browserDataFailure(
|
|
"INTEGRITY_FAILED",
|
|
"CACHE_ACTIVATE",
|
|
{ recovery: "REHYDRATE" },
|
|
);
|
|
}
|
|
|
|
const candidate = await verifyReleaseCandidate(
|
|
cache,
|
|
marker.assets,
|
|
policy,
|
|
dependencies.crypto,
|
|
signal,
|
|
);
|
|
if (candidate.kind === "UNKNOWN") {
|
|
return rebaseFailure(
|
|
candidate.failure.error,
|
|
"CACHE_ACTIVATE",
|
|
);
|
|
}
|
|
if (candidate.kind === "REPAIRABLE") {
|
|
return browserDataFailure(
|
|
"INTEGRITY_FAILED",
|
|
"CACHE_ACTIVATE",
|
|
{ recovery: "REHYDRATE" },
|
|
);
|
|
}
|
|
|
|
const previousPointer = await readActivePointer(
|
|
dependencies.cacheStorage!,
|
|
policy,
|
|
);
|
|
if (!previousPointer.ok) {
|
|
return rebaseFailure(
|
|
previousPointer.error,
|
|
"CACHE_ACTIVATE",
|
|
);
|
|
}
|
|
const rollbackCandidateCacheNames = [
|
|
...(previousPointer.value
|
|
? [
|
|
previousPointer.value.candidateCacheName,
|
|
...previousPointer.value
|
|
.rollbackCandidateCacheNames,
|
|
]
|
|
: []),
|
|
]
|
|
.filter(
|
|
(name, index, all) =>
|
|
name !== cacheName && all.indexOf(name) === index,
|
|
)
|
|
.slice(0, policy.retainedPreviousReleaseCount);
|
|
const pointer: ActiveReleasePointer = Object.freeze({
|
|
schemaVersion: 1,
|
|
releaseRegistryId,
|
|
manifestDigestHex,
|
|
candidateCacheName: cacheName,
|
|
rollbackCandidateCacheNames: Object.freeze(
|
|
rollbackCandidateCacheNames,
|
|
),
|
|
activatedAtEpochMs: now(),
|
|
});
|
|
const control = await dependencies.cacheStorage!.open(
|
|
controlCacheName(policy),
|
|
);
|
|
await control.put(
|
|
activePointerRequest(policy),
|
|
jsonResponse(pointer),
|
|
);
|
|
return browserDataSuccess(summaryFromMarker(marker));
|
|
},
|
|
);
|
|
if (!result.ok) {
|
|
return observeFailure(
|
|
result,
|
|
dependencies.observer,
|
|
releaseRegistryId,
|
|
);
|
|
}
|
|
observePublicCacheSafely(dependencies.observer, {
|
|
operation: "CACHE_ACTIVATE",
|
|
outcome: "SUCCEEDED",
|
|
releaseRegistryId,
|
|
entryBucket: cacheEntryBucket(result.value.entryCount),
|
|
byteBucket: cacheByteBucket(result.value.totalBytes),
|
|
});
|
|
return result;
|
|
} catch (error) {
|
|
return observeFailure(
|
|
exceptionFailure(error, "CACHE_ACTIVATE"),
|
|
dependencies.observer,
|
|
releaseRegistryId,
|
|
);
|
|
}
|
|
},
|
|
|
|
async cleanupOwned(
|
|
request: NonNullable<
|
|
Parameters<PublicResponseCache["admin"]["cleanupOwned"]>[0]
|
|
> = {},
|
|
) {
|
|
const signal = request.signal;
|
|
const aborted = abortedResult(signal, "CACHE_DELETE");
|
|
if (aborted) return aborted;
|
|
const availability = localMutationAvailability(
|
|
dependencies,
|
|
"CACHE_DELETE",
|
|
);
|
|
if (availability) return availability;
|
|
observePublicCacheSafely(dependencies.observer, {
|
|
operation: "CACHE_DELETE",
|
|
outcome: "STARTED",
|
|
});
|
|
|
|
try {
|
|
const result = await dependencies.mutationLock!.run(
|
|
signal,
|
|
async () => {
|
|
const pointer = await readActivePointer(
|
|
dependencies.cacheStorage!,
|
|
policy,
|
|
);
|
|
if (!pointer.ok) {
|
|
return rebaseFailure(pointer.error, "CACHE_DELETE");
|
|
}
|
|
const names = await dependencies.cacheStorage!.keys();
|
|
const ownedNames = names.filter((name) =>
|
|
name.startsWith(policy.ownedCachePrefix),
|
|
);
|
|
let deleted = 0;
|
|
let retained = 0;
|
|
const lifecycleRetainedNames = new Set([
|
|
...(pointer.value
|
|
? [
|
|
pointer.value.candidateCacheName,
|
|
...pointer.value.rollbackCandidateCacheNames,
|
|
]
|
|
: []),
|
|
]);
|
|
for (const name of ownedNames) {
|
|
if (signal?.aborted) {
|
|
return browserDataFailure("ABORTED", "CACHE_DELETE");
|
|
}
|
|
if (
|
|
name === controlCacheName(policy) ||
|
|
lifecycleRetainedNames.has(name)
|
|
) {
|
|
retained += 1;
|
|
continue;
|
|
}
|
|
if (await dependencies.cacheStorage!.delete(name)) {
|
|
deleted += 1;
|
|
}
|
|
}
|
|
const report: PublicCacheCleanupReport = Object.freeze({
|
|
inspectedOwnedCaches: ownedNames.length,
|
|
deletedOwnedCaches: deleted,
|
|
retainedOwnedCaches: retained,
|
|
});
|
|
return browserDataSuccess(report);
|
|
},
|
|
);
|
|
if (!result.ok) {
|
|
return observeFailure(result, dependencies.observer);
|
|
}
|
|
observePublicCacheSafely(dependencies.observer, {
|
|
operation: "CACHE_DELETE",
|
|
outcome: "SUCCEEDED",
|
|
entryBucket: cacheEntryBucket(
|
|
result.value.inspectedOwnedCaches,
|
|
),
|
|
});
|
|
return result;
|
|
} catch (error) {
|
|
return observeFailure(
|
|
exceptionFailure(error, "CACHE_DELETE"),
|
|
dependencies.observer,
|
|
);
|
|
}
|
|
},
|
|
|
|
async inspect() {
|
|
if (!dependencies.cacheStorage) {
|
|
return unsupported("CACHE_LOOKUP", "RETRY");
|
|
}
|
|
try {
|
|
const names = await dependencies.cacheStorage.keys();
|
|
const owned = names.filter((name) =>
|
|
name.startsWith(policy.ownedCachePrefix),
|
|
);
|
|
const pointer = await readActivePointer(
|
|
dependencies.cacheStorage,
|
|
policy,
|
|
);
|
|
if (!pointer.ok) return pointer;
|
|
|
|
const candidates: PublicCacheInspection["releaseCandidates"][number][] =
|
|
[];
|
|
let unreadableOwnedCacheCount = 0;
|
|
for (const name of owned) {
|
|
if (name === controlCacheName(policy)) continue;
|
|
const cache = await dependencies.cacheStorage.open(name);
|
|
const marker = await readMarker(
|
|
cache,
|
|
policy,
|
|
dependencies.crypto,
|
|
);
|
|
if (!marker.ok || !marker.value) {
|
|
unreadableOwnedCacheCount += 1;
|
|
continue;
|
|
}
|
|
candidates.push(
|
|
Object.freeze({
|
|
releaseRegistryId: marker.value.releaseRegistryId,
|
|
verified: true,
|
|
entryCount: marker.value.entryCount,
|
|
}),
|
|
);
|
|
}
|
|
return browserDataSuccess<PublicCacheInspection>(
|
|
Object.freeze({
|
|
activeReleaseRegistryId:
|
|
pointer.value?.releaseRegistryId ?? null,
|
|
ownedCacheCount: owned.length,
|
|
unreadableOwnedCacheCount,
|
|
releaseCandidates: Object.freeze(candidates),
|
|
}),
|
|
);
|
|
} catch (error) {
|
|
return exceptionFailure(error, "CACHE_LOOKUP");
|
|
}
|
|
},
|
|
});
|
|
|
|
return Object.freeze({ responses, admin });
|
|
}
|
|
|
|
export function createPublicCacheWebLock(
|
|
lockManager: LockManager,
|
|
lockName: string,
|
|
): PublicCacheMutationLock {
|
|
if (lockName.length === 0) {
|
|
throw new TypeError("Public cache mutation lock name is required.");
|
|
}
|
|
const manager = lockManager as unknown as LockManagerLike;
|
|
return Object.freeze({
|
|
async run<Value>(
|
|
signal: AbortSignal | undefined,
|
|
task: () => Promise<Value>,
|
|
): Promise<Value> {
|
|
if (signal?.aborted) {
|
|
throw new DOMException("The operation was aborted.", "AbortError");
|
|
}
|
|
return await manager.request(
|
|
lockName,
|
|
{ mode: "exclusive", signal },
|
|
async (lock) => {
|
|
if (!lock) throw new CacheValidationFailure("BLOCKED");
|
|
return await task();
|
|
},
|
|
);
|
|
},
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Build tooling and tests can use this helper to produce the exact digest
|
|
* accepted by stageRelease.
|
|
*/
|
|
export async function computePublicCacheManifestDigestHex(
|
|
crypto: Crypto,
|
|
releaseRegistryId: string,
|
|
assets: readonly PublicCacheAsset[],
|
|
policyInput: PublicCacheRuntimePolicy,
|
|
): Promise<string> {
|
|
const policy = resolvePublicCachePolicy(policyInput);
|
|
const cryptoSnapshot = snapshotCacheCrypto(crypto);
|
|
if (!policy.isReleaseRegistryIdAllowed(releaseRegistryId)) {
|
|
throw new TypeError("Public cache release registry ID is invalid.");
|
|
}
|
|
const normalized = normalizeAssets(assets, policy);
|
|
return await sha256Hex(
|
|
cryptoSnapshot,
|
|
new TextEncoder().encode(
|
|
canonicalManifest(releaseRegistryId, normalized),
|
|
),
|
|
);
|
|
}
|
|
|
|
async function readMarker(
|
|
cache: PublicCacheFacade,
|
|
policy: PublicCacheRuntimePolicy,
|
|
crypto: PublicCacheCryptoFacade,
|
|
): Promise<BrowserDataResult<ReleaseMarker | null>> {
|
|
try {
|
|
const response = await cache.match(markerRequest(policy));
|
|
if (!response) return browserDataSuccess(null);
|
|
const value = await readBoundedJson(response, MAX_CONTROL_JSON_BYTES);
|
|
if (!isReleaseMarker(value, policy)) {
|
|
return browserDataFailure("CORRUPT_DATA", "CACHE_LOOKUP", {
|
|
recovery: "REHYDRATE",
|
|
});
|
|
}
|
|
const computedDigest = await sha256Hex(
|
|
crypto,
|
|
new TextEncoder().encode(
|
|
canonicalManifest(value.releaseRegistryId, value.assets),
|
|
),
|
|
);
|
|
if (
|
|
value.entryCount !== value.assets.length ||
|
|
value.totalBytes !==
|
|
value.assets.reduce(
|
|
(total, asset) => total + asset.expectedByteLength,
|
|
0,
|
|
) ||
|
|
computedDigest !== value.manifestDigestHex
|
|
) {
|
|
return browserDataFailure("CORRUPT_DATA", "CACHE_LOOKUP", {
|
|
recovery: "REHYDRATE",
|
|
});
|
|
}
|
|
return browserDataSuccess(value);
|
|
} catch (error) {
|
|
return exceptionFailure(error, "CACHE_LOOKUP");
|
|
}
|
|
}
|
|
|
|
async function readActivePointer(
|
|
cacheStorage: PublicCacheStorageFacade,
|
|
policy: PublicCacheRuntimePolicy,
|
|
): Promise<BrowserDataResult<ActiveReleasePointer | null>> {
|
|
try {
|
|
const name = controlCacheName(policy);
|
|
if (!(await cacheStorage.keys()).includes(name)) {
|
|
return browserDataSuccess(null);
|
|
}
|
|
const cache = await cacheStorage.open(name);
|
|
const response = await cache.match(activePointerRequest(policy));
|
|
if (!response) return browserDataSuccess(null);
|
|
const value = await readBoundedJson(response, MAX_CONTROL_JSON_BYTES);
|
|
if (!isActivePointer(value, policy)) {
|
|
return browserDataFailure("CORRUPT_DATA", "CACHE_LOOKUP", {
|
|
recovery: "REHYDRATE",
|
|
});
|
|
}
|
|
return browserDataSuccess(value);
|
|
} catch (error) {
|
|
return exceptionFailure(error, "CACHE_LOOKUP");
|
|
}
|
|
}
|
|
|
|
function byteSourceFrom(bytes: Uint8Array): ByteSource {
|
|
const stored = Uint8Array.from(bytes);
|
|
return Object.freeze({
|
|
byteLength: stored.byteLength,
|
|
async *stream(signal: AbortSignal) {
|
|
if (signal.aborted) {
|
|
yield browserDataFailure("ABORTED", "CACHE_LOOKUP");
|
|
return;
|
|
}
|
|
yield browserDataSuccess(Uint8Array.from(stored));
|
|
},
|
|
});
|
|
}
|
|
|
|
function summaryFromMarker(
|
|
marker: ReleaseMarker,
|
|
): PublicCacheReleaseSummary {
|
|
return Object.freeze({
|
|
releaseRegistryId: marker.releaseRegistryId,
|
|
entryCount: marker.entryCount,
|
|
totalBytes: marker.totalBytes,
|
|
stagedAtEpochMs: marker.stagedAtEpochMs,
|
|
});
|
|
}
|
|
|
|
type ReleaseCandidateVerdict =
|
|
| Readonly<{ kind: "VERIFIED" }>
|
|
/** An exact, owned entry is missing or no longer matches the manifest. */
|
|
| Readonly<{ kind: "REPAIRABLE" }>
|
|
/** Abort or an unreadable candidate: never success, never a silent delete. */
|
|
| Readonly<{ kind: "UNKNOWN"; failure: BrowserFailureResult }>;
|
|
|
|
/**
|
|
* STO-04. The single verification authority shared by the stage fast path and
|
|
* activation, so "the marker says it is staged" can never stand in for "every
|
|
* entry is present and matches".
|
|
*/
|
|
async function verifyReleaseCandidate(
|
|
cache: Readonly<{ match(request: Request): Promise<Response | undefined> }>,
|
|
assets: readonly NormalizedAsset[],
|
|
policy: PublicCacheRuntimePolicy,
|
|
crypto: Readonly<{
|
|
digestSha256(bytes: Uint8Array): Promise<ArrayBuffer>;
|
|
}>,
|
|
signal: AbortSignal | undefined,
|
|
): Promise<ReleaseCandidateVerdict> {
|
|
for (const asset of assets) {
|
|
if (signal?.aborted) {
|
|
return Object.freeze({
|
|
kind: "UNKNOWN" as const,
|
|
failure: asFailure(
|
|
browserDataFailure("ABORTED", "CACHE_ACTIVATE"),
|
|
),
|
|
});
|
|
}
|
|
let cached: Response | undefined;
|
|
try {
|
|
cached = await cache.match(createNativeRequest(asset));
|
|
} catch {
|
|
return Object.freeze({
|
|
kind: "UNKNOWN" as const,
|
|
failure: asFailure(
|
|
browserDataFailure("UNAVAILABLE", "CACHE_ACTIVATE", {
|
|
retryable: true,
|
|
recovery: "RETRY",
|
|
}),
|
|
),
|
|
});
|
|
}
|
|
if (!cached) return Object.freeze({ kind: "REPAIRABLE" as const });
|
|
const verified = await readAndValidateResponse(
|
|
cached,
|
|
asset,
|
|
policy,
|
|
crypto,
|
|
signal,
|
|
);
|
|
if (!verified.ok) {
|
|
return verified.error.code === "ABORTED"
|
|
? Object.freeze({
|
|
kind: "UNKNOWN" as const,
|
|
failure: asFailure(verified),
|
|
})
|
|
: Object.freeze({ kind: "REPAIRABLE" as const });
|
|
}
|
|
}
|
|
return Object.freeze({ kind: "VERIFIED" as const });
|
|
}
|
|
|
|
/**
|
|
* STO-05. Staging is the only operation that reaches the network, so it is the
|
|
* only one that requires a fetcher.
|
|
*/
|
|
function stageAvailability(
|
|
dependencies: PublicResponseCacheDependencySnapshot,
|
|
): BrowserFailureResult | null {
|
|
return dependencies.cacheStorage &&
|
|
dependencies.fetcher &&
|
|
dependencies.mutationLock
|
|
? null
|
|
: unsupported("CACHE_STAGE", "ONLINE_ONLY");
|
|
}
|
|
|
|
/**
|
|
* Activation, rollback and cleanup are local Cache Storage mutations. Requiring
|
|
* a fetcher would block an offline rollback or a quota-recovery cleanup that
|
|
* needs no network at all.
|
|
*/
|
|
function localMutationAvailability(
|
|
dependencies: PublicResponseCacheDependencySnapshot,
|
|
operation: "CACHE_ACTIVATE" | "CACHE_DELETE",
|
|
): BrowserFailureResult | null {
|
|
return dependencies.cacheStorage && dependencies.mutationLock
|
|
? null
|
|
: unsupported(operation, "RETRY");
|
|
}
|
|
|
|
function unsupported(
|
|
operation: BrowserDataOperation,
|
|
recovery: "ONLINE_ONLY" | "RETRY",
|
|
): BrowserFailureResult {
|
|
return asFailure(
|
|
browserDataFailure("UNSUPPORTED", operation, { recovery }),
|
|
);
|
|
}
|
|
|
|
function rebaseFailure(
|
|
failure: BrowserDataFailure,
|
|
operation: BrowserDataOperation,
|
|
): BrowserFailureResult {
|
|
return {
|
|
ok: false,
|
|
error: Object.freeze({ ...failure, operation }),
|
|
};
|
|
}
|
|
|
|
function observeFailure(
|
|
result: BrowserDataResult<unknown>,
|
|
observer: PublicCacheSafeObserver | undefined,
|
|
releaseRegistryId?: string,
|
|
byteLength?: number,
|
|
): BrowserFailureResult {
|
|
if (result.ok) {
|
|
throw new TypeError("Expected a public cache failure result.");
|
|
}
|
|
observePublicCacheSafely(observer, {
|
|
operation: result.error.operation,
|
|
outcome: "FAILED",
|
|
failureCode: result.error.code,
|
|
releaseRegistryId,
|
|
byteBucket:
|
|
byteLength === undefined ? undefined : cacheByteBucket(byteLength),
|
|
});
|
|
return result;
|
|
}
|