문제: 승인된 LOGOUT·ACCOUNT_DELETION purge는 객체 목록을 읽고, 하나씩 지우고, 마지막에 journal 행을 한 번 센 뒤 0이면 chunk sweep으로 끝나 `chunkSweep: "COMPLETED"`를 돌려준다. 목록과 세기는 각각 한 순간만 본다. - 다른 탭이 새 객체를 put하는 중이면 purge의 remove가 그 put이 쥔 origin lease를 기다린다. partition에 객체가 3개 이상이면 그 put은 목록 뒤에 commit하고 세기 전에 complete까지 끝난다. 목록에도 행 수에도 없어 sweep이 그 chunk를 건너뛰고, 계정 삭제 뒤에도 파일이 읽힌다 (리뷰 실험 Y1b 메모리 20/20, Chromium 6/6). 저장소 테스트는 객체 0~1개로만 돌아서 이 틈을 놓쳤다. - FILES_READY에서 멈춘 put의 행이 `logicalKey`를 잃으면 세지 못한다. staging receipt가 chunk를 sweep에서 지켜 purge마다 COMPLETED인데 receipt·chunk·manifest가 남는다(Y2). 고른 방법: 마지막 객체까지 돈 purge는 sweep 대신 늘 partition 삭제로 끝낸다(리뷰 2.1절 (d')). exclusive partition lock이 그때 진행 중인 put·delete를 모두 기다린 뒤 디렉터리 전체(staging 포함)와 그 partition 행을 지우므로 두 경우를 함께 막는다. 객체 순회는 `removedObjects`· `releasedBytes` 보고와 예산 단위 진행을 위해 남긴다. 예산이나 다른 탭의 변경(CONFLICT) 때문에 끝까지 돌지 못한 호출은 지금처럼 `moreObjectsAvailable: true`를 돌려주고, 그때만 journal 행을 세서 끝나지 않은 행이 있으면 바로 partition을 지운다(2026-11-03 05-01 그대로). purge 성공 report는 이제 `partitionDeleted`와 `moreObjectsAvailable` 중 정확히 하나를 가진다(walk 뒤 abort도 more로 보고). 버린 대안: - (a) sweep 뒤에 다시 세고 committed 객체를 한 번 더 본다: ①만 막고 ②가 남는다. 다시 볼 때 정책상 남겨야 할 객체를 가려내려면 목록을 끝까지 다시 읽어야 한다. - (b)+(a): 둘 다 막지만 판단 조건이 일곱 개가 된다. - 세기를 아예 없애기: 예산에 걸린 호출의 crash 행 처리가 다음 호출로 밀린다. 지금 동작을 바꿀 이유가 없어 남겼다. 위험·한계: - 모든 승인 purge가 다른 탭의 진행 중 put을 기다린다(지금까지는 끝나지 않은 행이 있을 때만). 기다림 상한은 `mutationLockWaitTimeoutMs` (1103/05-02)이고 abort로 멈출 수 있다. - 같은 partition에 LOGOUT 때 남겨야 하는 객체가 섞이면 이 방법은 맞지 않는다. 지금 정책 검사는 OPAQUE_PARTITION이면 LOGOUT·ACCOUNT_DELETION 모두 purge만 허용해 그런 객체가 생기지 않는다. - port의 `chunkSweep`은 아무도 채우지 않는다. 읽는 코드가 깨지지 않게 타입은 남기고 `@deprecated`로 적었다. - recipe fake의 purge도 늘 `partitionDeleted`다. - `logicalKey`를 잃은 행 자체는 여전히 남는다(05-03 설계). 그 bytes는 이제 남지 않는다. - Firefox·WebKit에서 Y1은 돌리지 않았다. browser spec은 객체 0·3개 두 경우로 늘렸다. 검증: desktop batch에서 확인 - node scripts/run-vitest.ts run tests/unit/opfs-worker-runtime.test.ts tests/unit/opfs-byte-store.test.ts tests/unit/indexeddb-opfs-journal.test.ts - node scripts/run-vitest.ts run tests/recipes/browser-file-storage-contracts.test.ts - corepack pnpm test:browser-capabilities tests/browser-capabilities/opfs-runtime.spec.ts --project=chromium Refs: 1103/05-01
2170 lines
65 KiB
TypeScript
2170 lines
65 KiB
TypeScript
import type {
|
|
ByteCount,
|
|
BrowserFilePolicyProfile,
|
|
BrowserManagedDownloadCapabilityResolver,
|
|
BrowserManagedDownloadCapabilityReceipt,
|
|
DownloadDeliveryPort,
|
|
DownloadOutcome,
|
|
DurableObjectDescriptor,
|
|
DurableObjectMaintenancePort,
|
|
DurableObjectStorePort,
|
|
ExampleQuarantinedUpload,
|
|
ExampleQuarantinedUploadPort,
|
|
ExampleUploadPartReceipt,
|
|
ExampleUploadSession,
|
|
FileBytePattern,
|
|
FileCandidate,
|
|
FileByteSource,
|
|
FileContentPort,
|
|
FileInspection,
|
|
FileInspectionPolicy,
|
|
FilePolicyReference,
|
|
FilePickerPort,
|
|
FileSelectionOutcome,
|
|
FileSelectionLimitReduction,
|
|
FileSelectionPolicy,
|
|
FileVerificationReceipt,
|
|
LocalFileRef,
|
|
MigrationProgress,
|
|
OfflineCommitReceipt,
|
|
OfflinePage,
|
|
OfflineStoreLifecycleEvent,
|
|
OfflineStoreMaintenancePort,
|
|
OfflineStoreStatus,
|
|
DurableObjectId,
|
|
ObjectGeneration,
|
|
PublicAssetEntry,
|
|
PublicCacheInspection,
|
|
PublicCacheLookup,
|
|
PublicResponseCacheAdmin,
|
|
StorageDurabilityPort,
|
|
StorageEstimate,
|
|
StoredRecord,
|
|
StructuredOfflineMutation,
|
|
StructuredOfflineStore,
|
|
TransientPreviewPort,
|
|
RegisteredDownloadPolicy,
|
|
RegisteredPreviewPolicy,
|
|
} from "./browser-file-storage-contracts.ts";
|
|
import type {
|
|
BrowserDataFailureCode,
|
|
BrowserDataOperation,
|
|
BrowserDataRecovery,
|
|
BrowserDataResult,
|
|
BrowserStoragePolicy,
|
|
ByteSource,
|
|
OpfsPolicyMaintenanceReport,
|
|
OpfsReconciliationReport,
|
|
OpfsStorageScope,
|
|
} from "../../src/application/ports/browser-file-storage/index.ts";
|
|
import type { CapabilityResult } from "./contracts.ts";
|
|
import { failure, success } from "./fake-adapters.ts";
|
|
|
|
/**
|
|
* [0929] 05-03. The file, storage-durability and OPFS fakes implement the
|
|
* `src` ports, so they answer in that result shape: `error` with a closed
|
|
* failure code and the operation it belongs to. The recipe-only fakes below
|
|
* (upload example, structured offline store, public cache admin) keep the
|
|
* recipe `CapabilityResult`.
|
|
*/
|
|
function dataSuccess<T>(value: T): BrowserDataResult<T> {
|
|
return Object.freeze({ ok: true as const, value });
|
|
}
|
|
|
|
function dataFailure(
|
|
code: BrowserDataFailureCode,
|
|
operation: BrowserDataOperation,
|
|
retryable = false,
|
|
recovery: BrowserDataRecovery = retryable ? "RETRY" : "NONE",
|
|
): BrowserDataResult<never> {
|
|
return Object.freeze({
|
|
ok: false as const,
|
|
error: Object.freeze({ code, operation, retryable, recovery }),
|
|
});
|
|
}
|
|
|
|
function dataCancelled(
|
|
signal: AbortSignal | undefined,
|
|
operation: BrowserDataOperation,
|
|
): BrowserDataResult<never> | null {
|
|
return signal?.aborted ? dataFailure("ABORTED", operation) : null;
|
|
}
|
|
|
|
export function asByteCount(value: number): ByteCount {
|
|
if (!Number.isSafeInteger(value) || value < 0) {
|
|
throw new TypeError("Byte counts must be non-negative safe integers.");
|
|
}
|
|
return value as ByteCount;
|
|
}
|
|
|
|
export function asLocalFileRef(value: string): LocalFileRef {
|
|
if (value.length === 0) {
|
|
throw new TypeError("Local file references must not be empty.");
|
|
}
|
|
return value as LocalFileRef;
|
|
}
|
|
|
|
export function asFileVerificationReceipt(
|
|
value: string,
|
|
): FileVerificationReceipt {
|
|
if (!/^[a-z0-9][a-z0-9:_-]{0,127}$/i.test(value)) {
|
|
throw new TypeError("File verification receipts must be opaque tokens.");
|
|
}
|
|
return value as FileVerificationReceipt;
|
|
}
|
|
|
|
const issuedFilePolicyReferences = new WeakSet<object>();
|
|
|
|
export function browserFilePolicyReference(
|
|
policyKey: string,
|
|
intention: string,
|
|
): FilePolicyReference {
|
|
const token = /^[a-z0-9][a-z0-9._:-]{0,127}$/i;
|
|
if (!token.test(policyKey) || !token.test(intention)) {
|
|
throw new TypeError("File policy references must be opaque tokens.");
|
|
}
|
|
const reference = Object.freeze({
|
|
policyKey:
|
|
policyKey as FilePolicyReference["policyKey"],
|
|
intention:
|
|
intention as FilePolicyReference["intention"],
|
|
});
|
|
issuedFilePolicyReferences.add(reference);
|
|
return reference;
|
|
}
|
|
|
|
export function asBrowserManagedDownloadCapabilityReceipt(
|
|
value: string,
|
|
): BrowserManagedDownloadCapabilityReceipt {
|
|
if (!/^[a-z0-9][a-z0-9:_-]{0,127}$/i.test(value)) {
|
|
throw new TypeError(
|
|
"Browser-managed download receipts must be opaque tokens.",
|
|
);
|
|
}
|
|
return value as BrowserManagedDownloadCapabilityReceipt;
|
|
}
|
|
|
|
type MemoryPolicyProfile = Readonly<{
|
|
bindingId: string;
|
|
selection?: FileSelectionPolicy;
|
|
inspection?: FileInspectionPolicy;
|
|
preview?: RegisteredPreviewPolicy;
|
|
download?: RegisteredDownloadPolicy;
|
|
}>;
|
|
|
|
/**
|
|
* Composition-time dataset policy registry used by the deterministic fakes.
|
|
* It deep-snapshots profile data and resolves only the exact registered
|
|
* reference object. Equal key/intention strings are not authority.
|
|
*/
|
|
export class MemoryBrowserFilePolicyRegistry {
|
|
readonly #profiles =
|
|
new Map<FilePolicyReference, MemoryPolicyProfile>();
|
|
|
|
constructor(profiles: ReadonlyArray<BrowserFilePolicyProfile>) {
|
|
if (profiles.length === 0) {
|
|
throw new TypeError("At least one file policy profile is required.");
|
|
}
|
|
const semanticKeys = new Set<string>();
|
|
for (const profile of profiles) {
|
|
if (
|
|
!issuedFilePolicyReferences.has(profile.reference) ||
|
|
(!profile.selection &&
|
|
!profile.inspection &&
|
|
!profile.preview &&
|
|
!profile.download) ||
|
|
(profile.preview && !profile.inspection)
|
|
) {
|
|
throw new TypeError("The file policy profile is invalid.");
|
|
}
|
|
const bindingId = `${profile.reference.policyKey}\u0000${profile.reference.intention}`;
|
|
if (semanticKeys.has(bindingId)) {
|
|
throw new TypeError("The file policy profile is duplicated.");
|
|
}
|
|
semanticKeys.add(bindingId);
|
|
this.#profiles.set(
|
|
profile.reference,
|
|
Object.freeze({
|
|
bindingId,
|
|
...(profile.selection
|
|
? { selection: snapshotSelectionPolicy(profile.selection) }
|
|
: {}),
|
|
...(profile.inspection
|
|
? {
|
|
inspection: snapshotInspectionPolicy(
|
|
profile.inspection,
|
|
),
|
|
}
|
|
: {}),
|
|
...(profile.preview
|
|
? { preview: snapshotPreviewPolicy(profile.preview) }
|
|
: {}),
|
|
...(profile.download
|
|
? {
|
|
download: Object.freeze({
|
|
...profile.download,
|
|
}),
|
|
}
|
|
: {}),
|
|
}),
|
|
);
|
|
}
|
|
}
|
|
|
|
selection(
|
|
reference: FilePolicyReference,
|
|
reductions?: FileSelectionLimitReduction,
|
|
): BrowserDataResult<FileSelectionPolicy> {
|
|
const profile = this.#profiles.get(reference);
|
|
if (!profile?.selection) return rejectedPolicy("FILE_SELECT");
|
|
const maxCount = reduceLimit(
|
|
reductions?.maxCount,
|
|
profile.selection.maxCount,
|
|
);
|
|
const maxFileBytes = reduceLimit(
|
|
reductions?.maxFileBytes,
|
|
profile.selection.maxFileBytes,
|
|
);
|
|
const maxTotalBytes = reduceLimit(
|
|
reductions?.maxTotalBytes,
|
|
profile.selection.maxTotalBytes,
|
|
);
|
|
if (
|
|
maxCount === null ||
|
|
maxFileBytes === null ||
|
|
maxTotalBytes === null
|
|
) {
|
|
return dataFailure("LIMIT_EXCEEDED", "FILE_SELECT");
|
|
}
|
|
return dataSuccess(
|
|
Object.freeze({
|
|
...profile.selection,
|
|
maxCount,
|
|
maxFileBytes: asByteCount(maxFileBytes),
|
|
maxTotalBytes: asByteCount(maxTotalBytes),
|
|
}),
|
|
);
|
|
}
|
|
|
|
inspection(
|
|
reference: FilePolicyReference,
|
|
reduction?: number,
|
|
): BrowserDataResult<
|
|
Readonly<{
|
|
policy: FileInspectionPolicy;
|
|
bindingId: string;
|
|
}>
|
|
> {
|
|
const profile = this.#profiles.get(reference);
|
|
if (!profile?.inspection) return rejectedPolicy("FILE_INSPECT");
|
|
const maxInspectionBytes = reduceLimit(
|
|
reduction,
|
|
profile.inspection.maxInspectionBytes,
|
|
);
|
|
if (maxInspectionBytes === null) {
|
|
return dataFailure("LIMIT_EXCEEDED", "FILE_INSPECT");
|
|
}
|
|
return dataSuccess(
|
|
Object.freeze({
|
|
bindingId: profile.bindingId,
|
|
policy: Object.freeze({
|
|
...profile.inspection,
|
|
maxInspectionBytes: asByteCount(maxInspectionBytes),
|
|
}),
|
|
}),
|
|
);
|
|
}
|
|
|
|
preview(
|
|
reference: FilePolicyReference,
|
|
reduction?: number,
|
|
): BrowserDataResult<
|
|
Readonly<{
|
|
bindingId: string;
|
|
allowedMediaTypes: ReadonlySet<string>;
|
|
maxPreviewBytes: ByteCount;
|
|
}>
|
|
> {
|
|
const profile = this.#profiles.get(reference);
|
|
if (!profile?.preview || !profile.inspection) {
|
|
return rejectedPolicy("PREVIEW");
|
|
}
|
|
const maxPreviewBytes = reduceLimit(
|
|
reduction,
|
|
profile.preview.maxPreviewBytes,
|
|
);
|
|
if (maxPreviewBytes === null) {
|
|
return dataFailure("LIMIT_EXCEEDED", "PREVIEW");
|
|
}
|
|
return dataSuccess(
|
|
Object.freeze({
|
|
bindingId: profile.bindingId,
|
|
allowedMediaTypes: new Set(
|
|
profile.preview.allowedMediaTypes,
|
|
),
|
|
maxPreviewBytes: asByteCount(maxPreviewBytes),
|
|
}),
|
|
);
|
|
}
|
|
|
|
download(
|
|
reference: FilePolicyReference,
|
|
reductions: Readonly<{
|
|
maxTransferBytes?: number;
|
|
maxBufferedBytes?: number;
|
|
}>,
|
|
): BrowserDataResult<RegisteredDownloadPolicy> {
|
|
const profile = this.#profiles.get(reference);
|
|
if (!profile?.download) return rejectedPolicy("DOWNLOAD");
|
|
const maxTransferBytes = reduceLimit(
|
|
reductions.maxTransferBytes,
|
|
profile.download.maxTransferBytes,
|
|
);
|
|
const maxBufferedBytes = reduceLimit(
|
|
reductions.maxBufferedBytes,
|
|
Math.min(
|
|
profile.download.maxBufferedBytes,
|
|
maxTransferBytes ?? -1,
|
|
),
|
|
);
|
|
if (
|
|
maxTransferBytes === null ||
|
|
maxBufferedBytes === null
|
|
) {
|
|
return dataFailure("LIMIT_EXCEEDED", "DOWNLOAD");
|
|
}
|
|
return dataSuccess(
|
|
Object.freeze({
|
|
...profile.download,
|
|
maxTransferBytes: asByteCount(maxTransferBytes),
|
|
maxBufferedBytes: asByteCount(maxBufferedBytes),
|
|
}),
|
|
);
|
|
}
|
|
}
|
|
|
|
/** The composition-issued file policy is not available. */
|
|
function rejectedPolicy(
|
|
operation: BrowserDataOperation,
|
|
): BrowserDataResult<never> {
|
|
return dataFailure("POLICY_REJECTED", operation);
|
|
}
|
|
|
|
function reduceLimit(
|
|
reduction: number | undefined,
|
|
ceiling: number,
|
|
): number | null {
|
|
const value = reduction ?? ceiling;
|
|
return Number.isSafeInteger(value) &&
|
|
value > 0 &&
|
|
value <= ceiling
|
|
? value
|
|
: null;
|
|
}
|
|
|
|
function snapshotSelectionPolicy(
|
|
policy: FileSelectionPolicy,
|
|
): FileSelectionPolicy {
|
|
return Object.freeze({
|
|
...policy,
|
|
accept: Object.freeze(
|
|
policy.accept.map((rule) =>
|
|
Object.freeze({
|
|
mediaType: rule.mediaType,
|
|
extensions: Object.freeze([...rule.extensions]),
|
|
}),
|
|
),
|
|
),
|
|
});
|
|
}
|
|
|
|
function snapshotInspectionPolicy(
|
|
policy: FileInspectionPolicy,
|
|
): FileInspectionPolicy {
|
|
return Object.freeze({
|
|
...policy,
|
|
acceptedSignatures: Object.freeze(
|
|
policy.acceptedSignatures.map((rule) =>
|
|
Object.freeze({
|
|
mediaType: rule.mediaType,
|
|
extensions: Object.freeze([...rule.extensions]),
|
|
patterns: Object.freeze(
|
|
rule.patterns.map((pattern) =>
|
|
Object.freeze({
|
|
offset: pattern.offset,
|
|
bytes: Object.freeze([...pattern.bytes]),
|
|
...(pattern.mask
|
|
? { mask: Object.freeze([...pattern.mask]) }
|
|
: {}),
|
|
}),
|
|
),
|
|
),
|
|
}),
|
|
),
|
|
),
|
|
});
|
|
}
|
|
|
|
function snapshotPreviewPolicy(
|
|
policy: RegisteredPreviewPolicy,
|
|
): RegisteredPreviewPolicy {
|
|
return Object.freeze({
|
|
allowedMediaTypes: Object.freeze([
|
|
...policy.allowedMediaTypes,
|
|
]),
|
|
maxPreviewBytes: policy.maxPreviewBytes,
|
|
});
|
|
}
|
|
|
|
export function asDurableObjectId(value: string): DurableObjectId {
|
|
if (value.length === 0) {
|
|
throw new TypeError("Durable object IDs must not be empty.");
|
|
}
|
|
return value as DurableObjectId;
|
|
}
|
|
|
|
export function asObjectGeneration(value: number): ObjectGeneration {
|
|
if (!Number.isSafeInteger(value) || value < 1) {
|
|
throw new TypeError("Object generations must be positive safe integers.");
|
|
}
|
|
return value as ObjectGeneration;
|
|
}
|
|
|
|
function cancelled(signal?: AbortSignal): CapabilityResult<never> | null {
|
|
return signal?.aborted
|
|
? failure("ABORTED", false, "The operation was cancelled.")
|
|
: null;
|
|
}
|
|
|
|
function isReadableStatus(status: OfflineStoreStatus): boolean {
|
|
return status.kind === "READY" || status.kind === "READ_ONLY";
|
|
}
|
|
|
|
function isWritableStatus(status: OfflineStoreStatus): boolean {
|
|
return status.kind === "READY";
|
|
}
|
|
|
|
function cloneBytes(bytes: Uint8Array): Uint8Array {
|
|
return bytes.slice();
|
|
}
|
|
|
|
function extensionOf(fileName: string): string | null {
|
|
const normalized = fileName.normalize("NFC");
|
|
const index = normalized.lastIndexOf(".");
|
|
return index > 0 && index < normalized.length - 1
|
|
? normalized.slice(index).toLowerCase()
|
|
: null;
|
|
}
|
|
|
|
function acceptsCandidate(
|
|
policy: FileSelectionPolicy,
|
|
candidate: FileCandidate,
|
|
): boolean {
|
|
if (policy.accept.length === 0) return true;
|
|
const extension = extensionOf(candidate.displayName);
|
|
return policy.accept.some(
|
|
(rule) =>
|
|
(candidate.reportedMediaType !== null &&
|
|
candidate.reportedMediaType.toLowerCase() ===
|
|
rule.mediaType.toLowerCase()) ||
|
|
(extension !== null &&
|
|
rule.extensions.some(
|
|
(accepted) => accepted.toLowerCase() === extension,
|
|
)),
|
|
);
|
|
}
|
|
|
|
function matchesFileBytePattern(
|
|
bytes: Uint8Array,
|
|
pattern: FileBytePattern,
|
|
): boolean {
|
|
if (pattern.offset + pattern.bytes.length > bytes.byteLength) {
|
|
return false;
|
|
}
|
|
for (const [index, expected] of pattern.bytes.entries()) {
|
|
const actual = bytes[pattern.offset + index];
|
|
const mask = pattern.mask?.[index] ?? 0xff;
|
|
if (
|
|
actual === undefined ||
|
|
!Number.isInteger(expected) ||
|
|
expected < 0 ||
|
|
expected > 0xff ||
|
|
(actual & mask) !== (expected & mask)
|
|
) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
export type MemoryFileFixture = Readonly<{
|
|
ref: LocalFileRef;
|
|
displayName: string;
|
|
bytes: Uint8Array;
|
|
reportedMediaType: string | null;
|
|
detectedMediaType: string | null;
|
|
lastModifiedEpochMs?: number | null;
|
|
signature?: FileInspection["signature"];
|
|
source?: FileCandidate["source"];
|
|
}>;
|
|
|
|
/**
|
|
* Deterministic picker and transient file vault. Metadata matching is only a
|
|
* preflight policy simulation. Any separately selected backend transfer
|
|
* workflow must independently revalidate content.
|
|
*/
|
|
export class MemoryFileSelectionAdapter
|
|
implements FilePickerPort, FileContentPort
|
|
{
|
|
readonly support;
|
|
readonly #policies: MemoryBrowserFilePolicyRegistry;
|
|
readonly #files = new Map<LocalFileRef, MemoryFileFixture>();
|
|
readonly #verifications = new Map<
|
|
FileVerificationReceipt,
|
|
Readonly<{
|
|
ref: LocalFileRef;
|
|
policyBindingId: string;
|
|
mediaType: string;
|
|
}>
|
|
>();
|
|
#verificationSequence = 0;
|
|
#nextOutcome: "SELECTED" | "DISMISSED" | "PERMISSION_DENIED" = "SELECTED";
|
|
|
|
constructor(
|
|
files: ReadonlyArray<MemoryFileFixture>,
|
|
policies: MemoryBrowserFilePolicyRegistry,
|
|
support: FilePickerPort["support"] = {
|
|
nativeInput: true,
|
|
systemOpenPicker: false,
|
|
systemSavePicker: false,
|
|
},
|
|
) {
|
|
this.#policies = policies;
|
|
this.support = Object.freeze({ ...support });
|
|
for (const file of files) {
|
|
this.#files.set(file.ref, {
|
|
...file,
|
|
bytes: cloneBytes(file.bytes),
|
|
});
|
|
}
|
|
}
|
|
|
|
setNextOutcome(
|
|
outcome: "SELECTED" | "DISMISSED" | "PERMISSION_DENIED",
|
|
): void {
|
|
this.#nextOutcome = outcome;
|
|
}
|
|
|
|
async select(input: {
|
|
policy: FilePolicyReference;
|
|
limits?: FileSelectionLimitReduction;
|
|
signal?: AbortSignal;
|
|
}): Promise<BrowserDataResult<FileSelectionOutcome>> {
|
|
const aborted = dataCancelled(input.signal, "FILE_SELECT");
|
|
if (aborted) return aborted;
|
|
const outcome = this.#nextOutcome;
|
|
this.#nextOutcome = "SELECTED";
|
|
if (outcome === "DISMISSED") {
|
|
return dataSuccess({ kind: "DISMISSED" });
|
|
}
|
|
if (outcome === "PERMISSION_DENIED") {
|
|
return dataFailure("PERMISSION_DENIED", "FILE_SELECT");
|
|
}
|
|
const resolvedPolicy = this.#policies.selection(
|
|
input.policy,
|
|
input.limits,
|
|
);
|
|
if (!resolvedPolicy.ok) return resolvedPolicy;
|
|
const policy = resolvedPolicy.value;
|
|
|
|
const candidates = Array.from(this.#files.values(), (file) =>
|
|
Object.freeze({
|
|
ref: file.ref,
|
|
displayName: file.displayName,
|
|
sizeBytes: asByteCount(file.bytes.byteLength),
|
|
reportedMediaType: file.reportedMediaType,
|
|
lastModifiedEpochMs: file.lastModifiedEpochMs ?? null,
|
|
source: file.source ?? "NATIVE_INPUT",
|
|
}),
|
|
);
|
|
const total = candidates.reduce(
|
|
(sum, candidate) => sum + candidate.sizeBytes,
|
|
0,
|
|
);
|
|
if (
|
|
candidates.length > policy.maxCount ||
|
|
(!policy.multiple && candidates.length > 1) ||
|
|
candidates.some(
|
|
(candidate) =>
|
|
candidate.sizeBytes > policy.maxFileBytes ||
|
|
(!policy.allowEmpty && candidate.sizeBytes === 0),
|
|
) ||
|
|
total > policy.maxTotalBytes
|
|
) {
|
|
return dataFailure("LIMIT_EXCEEDED", "FILE_SELECT");
|
|
}
|
|
if (
|
|
candidates.some(
|
|
(candidate) => !acceptsCandidate(policy, candidate),
|
|
)
|
|
) {
|
|
return dataFailure("POLICY_REJECTED", "FILE_SELECT");
|
|
}
|
|
return dataSuccess({ kind: "SELECTED", files: candidates });
|
|
}
|
|
|
|
async inspect(input: {
|
|
ref: LocalFileRef;
|
|
policy: FilePolicyReference;
|
|
maxInspectionBytes?: number;
|
|
signal: AbortSignal;
|
|
}): Promise<BrowserDataResult<FileInspection>> {
|
|
const aborted = dataCancelled(input.signal, "FILE_INSPECT");
|
|
if (aborted) return aborted;
|
|
const resolvedPolicy = this.#policies.inspection(
|
|
input.policy,
|
|
input.maxInspectionBytes,
|
|
);
|
|
if (!resolvedPolicy.ok) return resolvedPolicy;
|
|
const { policy, bindingId } = resolvedPolicy.value;
|
|
const file = this.#files.get(input.ref);
|
|
if (!file) {
|
|
return dataFailure("NOT_FOUND", "FILE_INSPECT");
|
|
}
|
|
this.#invalidateVerifications(input.ref);
|
|
const inspectedBytes = file.bytes.slice(
|
|
0,
|
|
policy.maxInspectionBytes,
|
|
);
|
|
const matchedRule = policy.acceptedSignatures.find(
|
|
(rule) =>
|
|
rule.mediaType.toLowerCase() ===
|
|
file.detectedMediaType?.toLowerCase() &&
|
|
rule.patterns.some((pattern) =>
|
|
matchesFileBytePattern(inspectedBytes, pattern),
|
|
),
|
|
);
|
|
const detectedMediaType = matchedRule?.mediaType ?? null;
|
|
const signature =
|
|
file.signature === "MISMATCHED"
|
|
? "MISMATCHED"
|
|
: matchedRule
|
|
? "MATCHED"
|
|
: file.signature === "MATCHED"
|
|
? "MISMATCHED"
|
|
: "UNKNOWN";
|
|
const verificationReceipt =
|
|
signature === "MATCHED" && detectedMediaType !== null
|
|
? asFileVerificationReceipt(
|
|
`verification:${++this.#verificationSequence}`,
|
|
)
|
|
: null;
|
|
if (verificationReceipt) {
|
|
this.#verifications.set(
|
|
verificationReceipt,
|
|
Object.freeze({
|
|
ref: input.ref,
|
|
policyBindingId: bindingId,
|
|
mediaType: detectedMediaType!,
|
|
}),
|
|
);
|
|
}
|
|
return dataSuccess({
|
|
byteLength: asByteCount(file.bytes.byteLength),
|
|
reportedMediaType: file.reportedMediaType,
|
|
detectedMediaType,
|
|
normalizedExtension: extensionOf(file.displayName),
|
|
signature,
|
|
verificationReceipt,
|
|
});
|
|
}
|
|
|
|
async readRange(input: {
|
|
ref: LocalFileRef;
|
|
offset: number;
|
|
length: number;
|
|
signal: AbortSignal;
|
|
}): Promise<BrowserDataResult<Uint8Array>> {
|
|
const aborted = dataCancelled(input.signal, "FILE_READ");
|
|
if (aborted) return aborted;
|
|
const file = this.#files.get(input.ref);
|
|
if (!file) {
|
|
return dataFailure("NOT_FOUND", "FILE_READ");
|
|
}
|
|
const end = input.offset + input.length;
|
|
if (
|
|
!Number.isSafeInteger(end) ||
|
|
input.offset > file.bytes.byteLength ||
|
|
end > file.bytes.byteLength
|
|
) {
|
|
return dataFailure("INVALID_INPUT", "FILE_READ");
|
|
}
|
|
return dataSuccess(file.bytes.slice(input.offset, end));
|
|
}
|
|
|
|
async openSource(input: {
|
|
ref: LocalFileRef;
|
|
signal: AbortSignal;
|
|
}): Promise<BrowserDataResult<FileByteSource>> {
|
|
const aborted = dataCancelled(input.signal, "FILE_READ");
|
|
if (aborted) return aborted;
|
|
const file = this.#files.get(input.ref);
|
|
if (!file) {
|
|
return dataFailure("NOT_FOUND", "FILE_READ");
|
|
}
|
|
const bytes = cloneBytes(file.bytes);
|
|
return dataSuccess(
|
|
Object.freeze({
|
|
byteLength: asByteCount(bytes.byteLength),
|
|
async *stream(signal: AbortSignal) {
|
|
const streamAbort = dataCancelled(signal, "FILE_READ");
|
|
if (streamAbort) {
|
|
yield streamAbort;
|
|
return;
|
|
}
|
|
yield dataSuccess(cloneBytes(bytes));
|
|
},
|
|
}),
|
|
);
|
|
}
|
|
|
|
release(ref: LocalFileRef): void {
|
|
this.#invalidateVerifications(ref);
|
|
this.#files.delete(ref);
|
|
}
|
|
|
|
verification(
|
|
receipt: FileVerificationReceipt,
|
|
): Readonly<{
|
|
ref: LocalFileRef;
|
|
policyBindingId: string;
|
|
mediaType: string;
|
|
byteLength: ByteCount;
|
|
}> | null {
|
|
const verification = this.#verifications.get(receipt);
|
|
if (!verification) return null;
|
|
const file = this.#files.get(verification.ref);
|
|
return file
|
|
? Object.freeze({
|
|
...verification,
|
|
byteLength: asByteCount(file.bytes.byteLength),
|
|
})
|
|
: null;
|
|
}
|
|
|
|
#invalidateVerifications(ref: LocalFileRef): void {
|
|
for (const [receipt, verification] of this.#verifications) {
|
|
if (verification.ref === ref) this.#verifications.delete(receipt);
|
|
}
|
|
}
|
|
}
|
|
|
|
export class MemoryTransientPreviewAdapter implements TransientPreviewPort {
|
|
static readonly #ACTIVE_CONTENT_DENYLIST = new Set([
|
|
"application/pdf",
|
|
"application/xhtml+xml",
|
|
"application/xml",
|
|
"image/svg+xml",
|
|
"text/html",
|
|
"text/xml",
|
|
]);
|
|
|
|
readonly #files: MemoryFileSelectionAdapter;
|
|
readonly #policies: MemoryBrowserFilePolicyRegistry;
|
|
readonly #active = new Set<string>();
|
|
#sequence = 0;
|
|
#disposed = false;
|
|
|
|
constructor(
|
|
files: MemoryFileSelectionAdapter,
|
|
policies: MemoryBrowserFilePolicyRegistry,
|
|
) {
|
|
this.#files = files;
|
|
this.#policies = policies;
|
|
}
|
|
|
|
async create(
|
|
input: Parameters<TransientPreviewPort["create"]>[0],
|
|
): ReturnType<TransientPreviewPort["create"]> {
|
|
if (this.#disposed) {
|
|
return dataFailure("UNAVAILABLE", "PREVIEW");
|
|
}
|
|
const aborted = dataCancelled(input.signal, "PREVIEW");
|
|
if (aborted) return aborted;
|
|
const verification = this.#files.verification(
|
|
input.verificationReceipt,
|
|
);
|
|
const resolvedPolicy = this.#policies.preview(
|
|
input.policy,
|
|
input.maxPreviewBytes,
|
|
);
|
|
if (!resolvedPolicy.ok) return resolvedPolicy;
|
|
const policy = resolvedPolicy.value;
|
|
if (
|
|
!verification ||
|
|
verification.ref !== input.ref ||
|
|
verification.policyBindingId !== policy.bindingId
|
|
) {
|
|
return dataFailure("POLICY_REJECTED", "PREVIEW");
|
|
}
|
|
if (
|
|
verification.byteLength > policy.maxPreviewBytes
|
|
) {
|
|
return dataFailure("LIMIT_EXCEEDED", "PREVIEW");
|
|
}
|
|
if (
|
|
!policy.allowedMediaTypes.has(verification.mediaType) ||
|
|
MemoryTransientPreviewAdapter.#ACTIVE_CONTENT_DENYLIST.has(
|
|
verification.mediaType.toLowerCase(),
|
|
)
|
|
) {
|
|
return dataFailure("POLICY_REJECTED", "PREVIEW");
|
|
}
|
|
const url = `blob:memory-preview-${++this.#sequence}`;
|
|
this.#active.add(url);
|
|
let released = false;
|
|
return dataSuccess(
|
|
Object.freeze({
|
|
url,
|
|
mediaType: verification.mediaType,
|
|
release: () => {
|
|
if (released) return;
|
|
released = true;
|
|
this.#active.delete(url);
|
|
},
|
|
}),
|
|
);
|
|
}
|
|
|
|
get activeLeaseCount(): number {
|
|
return this.#active.size;
|
|
}
|
|
|
|
dispose(): void {
|
|
if (this.#disposed) return;
|
|
this.#disposed = true;
|
|
this.#active.clear();
|
|
}
|
|
}
|
|
|
|
type MemoryUploadState = {
|
|
expectedBytes: number;
|
|
parts: Map<
|
|
number,
|
|
Readonly<{ offset: number; receipt: ExampleUploadPartReceipt }>
|
|
>;
|
|
idempotency: Map<
|
|
string,
|
|
Readonly<{
|
|
fingerprint: string;
|
|
receipt: ExampleUploadPartReceipt;
|
|
}>
|
|
>;
|
|
};
|
|
|
|
/**
|
|
* Deterministic example for a separately selected, backend-authorized
|
|
* resumable upload workflow. It is not part of browser-file composition.
|
|
*/
|
|
export class MemoryExampleQuarantinedUploadAdapter
|
|
implements ExampleQuarantinedUploadPort
|
|
{
|
|
readonly #sessions = new Map<string, MemoryUploadState>();
|
|
#sequence = 0;
|
|
|
|
constructor(
|
|
private readonly maxUploadBytes: ByteCount,
|
|
private readonly partSizeBytes: ByteCount,
|
|
private readonly now: () => number = Date.now,
|
|
) {}
|
|
|
|
async create(input: {
|
|
purpose: string;
|
|
byteLength: ByteCount;
|
|
detectedMediaType: string;
|
|
signal: AbortSignal;
|
|
}): Promise<CapabilityResult<ExampleUploadSession>> {
|
|
const aborted = cancelled(input.signal);
|
|
if (aborted) return aborted;
|
|
if (
|
|
input.purpose.length === 0 ||
|
|
input.detectedMediaType.length === 0 ||
|
|
input.byteLength > this.maxUploadBytes
|
|
) {
|
|
return failure("LIMIT_EXCEEDED", false, "The upload policy rejected the file.");
|
|
}
|
|
const sessionId = `upload-${++this.#sequence}`;
|
|
this.#sessions.set(sessionId, {
|
|
expectedBytes: input.byteLength,
|
|
parts: new Map(),
|
|
idempotency: new Map(),
|
|
});
|
|
return success({
|
|
sessionId,
|
|
partSizeBytes: this.partSizeBytes,
|
|
maxConcurrency: 2,
|
|
expiresAt: new Date(this.now() + 15 * 60_000).toISOString(),
|
|
checksumAlgorithm: "SHA-256",
|
|
});
|
|
}
|
|
|
|
async uploadPart(input: {
|
|
sessionId: string;
|
|
partNumber: number;
|
|
offset: ByteCount;
|
|
bytes: Uint8Array;
|
|
checksumSha256: string;
|
|
idempotencyKey: string;
|
|
signal: AbortSignal;
|
|
}): Promise<CapabilityResult<ExampleUploadPartReceipt>> {
|
|
const aborted = cancelled(input.signal);
|
|
if (aborted) return aborted;
|
|
const session = this.#sessions.get(input.sessionId);
|
|
if (!session) {
|
|
return failure(
|
|
"EXPIRED_RESOURCE",
|
|
false,
|
|
"The upload session is no longer available.",
|
|
);
|
|
}
|
|
const fingerprint = [
|
|
input.partNumber,
|
|
input.offset,
|
|
input.bytes.byteLength,
|
|
input.checksumSha256,
|
|
].join(":");
|
|
const replay = session.idempotency.get(input.idempotencyKey);
|
|
if (replay) {
|
|
return replay.fingerprint === fingerprint
|
|
? success(replay.receipt)
|
|
: failure(
|
|
"CONFLICT",
|
|
false,
|
|
"The idempotency key was reused for a different upload part.",
|
|
);
|
|
}
|
|
if (
|
|
input.partNumber < 1 ||
|
|
input.bytes.byteLength === 0 ||
|
|
input.bytes.byteLength > this.partSizeBytes ||
|
|
input.offset + input.bytes.byteLength > session.expectedBytes ||
|
|
input.checksumSha256.length === 0
|
|
) {
|
|
return failure("INVALID_INPUT", false, "The upload part is invalid.");
|
|
}
|
|
if (session.parts.has(input.partNumber)) {
|
|
return failure("CONFLICT", false, "The upload part already exists.");
|
|
}
|
|
const receipt = Object.freeze({
|
|
partNumber: input.partNumber,
|
|
acceptedBytes: asByteCount(input.bytes.byteLength),
|
|
checksumSha256: input.checksumSha256,
|
|
});
|
|
session.parts.set(input.partNumber, {
|
|
offset: input.offset,
|
|
receipt,
|
|
});
|
|
session.idempotency.set(input.idempotencyKey, {
|
|
fingerprint,
|
|
receipt,
|
|
});
|
|
return success(receipt);
|
|
}
|
|
|
|
async complete(input: {
|
|
sessionId: string;
|
|
parts: ReadonlyArray<ExampleUploadPartReceipt>;
|
|
signal: AbortSignal;
|
|
}): Promise<CapabilityResult<ExampleQuarantinedUpload>> {
|
|
const aborted = cancelled(input.signal);
|
|
if (aborted) return aborted;
|
|
const session = this.#sessions.get(input.sessionId);
|
|
if (!session) {
|
|
return failure(
|
|
"EXPIRED_RESOURCE",
|
|
false,
|
|
"The upload session is no longer available.",
|
|
);
|
|
}
|
|
const partNumbers = new Set(input.parts.map((part) => part.partNumber));
|
|
const acceptedBytes = input.parts.reduce(
|
|
(sum, part) => sum + part.acceptedBytes,
|
|
0,
|
|
);
|
|
const matches = input.parts.every(
|
|
(part) =>
|
|
session.parts.get(part.partNumber)?.receipt.checksumSha256 ===
|
|
part.checksumSha256,
|
|
);
|
|
const storedParts = Array.from(session.parts.values()).sort(
|
|
(left, right) => left.offset - right.offset,
|
|
);
|
|
let nextOffset = 0;
|
|
const contiguous = storedParts.every((part) => {
|
|
if (part.offset !== nextOffset) return false;
|
|
nextOffset += part.receipt.acceptedBytes;
|
|
return true;
|
|
});
|
|
if (
|
|
!matches ||
|
|
partNumbers.size !== input.parts.length ||
|
|
input.parts.length !== session.parts.size ||
|
|
!contiguous ||
|
|
nextOffset !== session.expectedBytes ||
|
|
acceptedBytes !== session.expectedBytes
|
|
) {
|
|
return failure(
|
|
"INTEGRITY_FAILED",
|
|
false,
|
|
"The uploaded parts did not pass final verification.",
|
|
);
|
|
}
|
|
this.#sessions.delete(input.sessionId);
|
|
return success({
|
|
resourceId: `resource-${input.sessionId}`,
|
|
state: "QUARANTINED",
|
|
});
|
|
}
|
|
|
|
async abort(
|
|
sessionId: string,
|
|
signal?: AbortSignal,
|
|
): Promise<CapabilityResult<void>> {
|
|
const aborted = cancelled(signal);
|
|
if (aborted) return aborted;
|
|
this.#sessions.delete(sessionId);
|
|
return success(undefined);
|
|
}
|
|
}
|
|
|
|
const windowsDeviceNames = new Set([
|
|
"CON",
|
|
"PRN",
|
|
"AUX",
|
|
"NUL",
|
|
"COM1",
|
|
"COM2",
|
|
"COM3",
|
|
"COM4",
|
|
"COM5",
|
|
"COM6",
|
|
"COM7",
|
|
"COM8",
|
|
"COM9",
|
|
"LPT1",
|
|
"LPT2",
|
|
"LPT3",
|
|
"LPT4",
|
|
"LPT5",
|
|
"LPT6",
|
|
"LPT7",
|
|
"LPT8",
|
|
"LPT9",
|
|
]);
|
|
|
|
function sanitizeFileNameCharacter(character: string): string {
|
|
const codePoint = character.codePointAt(0) ?? 0;
|
|
const control = codePoint <= 31 || codePoint === 127;
|
|
const bidiControl =
|
|
(codePoint >= 0x202a && codePoint <= 0x202e) ||
|
|
(codePoint >= 0x2066 && codePoint <= 0x2069);
|
|
if (control || bidiControl) return "";
|
|
return character === ":" ? "_" : character;
|
|
}
|
|
|
|
export function sanitizeDownloadFileName(
|
|
candidate: string,
|
|
fallback = "download.bin",
|
|
): string {
|
|
const normalized = candidate.normalize("NFC");
|
|
const pathSegments = normalized.split(/[/\\]/);
|
|
const leafName = pathSegments.at(-1) ?? normalized;
|
|
const cleaned = Array.from(leafName)
|
|
.map(sanitizeFileNameCharacter)
|
|
.join("")
|
|
.trim()
|
|
.replace(/^[. ]+|[. ]+$/g, "")
|
|
.replace(/_+/g, "_");
|
|
const bounded = Array.from(cleaned).slice(0, 180).join("");
|
|
const stem = bounded.split(".")[0]?.toUpperCase() ?? "";
|
|
if (
|
|
bounded.length === 0 ||
|
|
bounded === "." ||
|
|
bounded === ".." ||
|
|
windowsDeviceNames.has(stem)
|
|
) {
|
|
return fallback;
|
|
}
|
|
return bounded;
|
|
}
|
|
|
|
export class RecordingDownloadDeliveryAdapter
|
|
implements DownloadDeliveryPort
|
|
{
|
|
readonly receipts: Array<
|
|
Readonly<{ fileName: string; strategy: string; bytesWritten: number }>
|
|
> = [];
|
|
readonly #policies: MemoryBrowserFilePolicyRegistry;
|
|
readonly #resolveBrowserManaged:
|
|
BrowserManagedDownloadCapabilityResolver["resolve"];
|
|
readonly #now: () => number;
|
|
#sequence = 0;
|
|
|
|
constructor(
|
|
policies: MemoryBrowserFilePolicyRegistry,
|
|
browserManagedCapabilities: BrowserManagedDownloadCapabilityResolver,
|
|
now: () => number = Date.now,
|
|
) {
|
|
this.#policies = policies;
|
|
this.#resolveBrowserManaged =
|
|
browserManagedCapabilities.resolve.bind(
|
|
browserManagedCapabilities,
|
|
);
|
|
this.#now = now;
|
|
}
|
|
|
|
async deliver(
|
|
input: Parameters<DownloadDeliveryPort["deliver"]>[0],
|
|
): Promise<BrowserDataResult<DownloadOutcome>> {
|
|
const aborted = dataCancelled(input.signal, "DOWNLOAD");
|
|
if (aborted) return aborted;
|
|
const resolvedPolicy = this.#policies.download(input.policy, {
|
|
maxTransferBytes: input.maxTransferBytes,
|
|
maxBufferedBytes: input.maxBufferedBytes,
|
|
});
|
|
if (!resolvedPolicy.ok) return resolvedPolicy;
|
|
const policy = resolvedPolicy.value;
|
|
const sanitized = sanitizeDownloadFileName(input.suggestedFileName);
|
|
const safeExtension = policy.safeExtension.toLowerCase();
|
|
const fileName = sanitized.toLowerCase().endsWith(safeExtension)
|
|
? sanitized
|
|
: `${sanitized.replace(/\.[^.]+$/, "")}${safeExtension}`;
|
|
const transferId = `download-${++this.#sequence}`;
|
|
if (
|
|
(policy.strategy === "BROWSER_MANAGED" &&
|
|
input.source.kind !== "BROWSER_MANAGED_RESOURCE") ||
|
|
(policy.strategy !== "BROWSER_MANAGED" &&
|
|
input.source.kind === "BROWSER_MANAGED_RESOURCE")
|
|
) {
|
|
return dataFailure("POLICY_REJECTED", "DOWNLOAD");
|
|
}
|
|
if (
|
|
policy.strategy === "BROWSER_MANAGED" &&
|
|
input.source.kind === "BROWSER_MANAGED_RESOURCE"
|
|
) {
|
|
const capability = this.#resolveBrowserManaged({
|
|
resourceId: input.source.resourceId,
|
|
capabilityReceipt: input.source.capabilityReceipt,
|
|
});
|
|
if (!capability.ok) return capability;
|
|
if (
|
|
capability.value.capabilityReceipt !==
|
|
input.source.capabilityReceipt ||
|
|
capability.value.resourceId !== input.source.resourceId ||
|
|
capability.value.mediaType !== policy.mediaType ||
|
|
capability.value.safeExtension !== policy.safeExtension ||
|
|
capability.value.maxBytes > policy.maxTransferBytes ||
|
|
capability.value.expiresAtEpochMs <= this.#now() ||
|
|
(policy.integrity === "REQUIRED" &&
|
|
!capability.value.expectedSha256)
|
|
) {
|
|
return dataFailure(
|
|
capability.value.expiresAtEpochMs <= this.#now()
|
|
? "EXPIRED_RESOURCE"
|
|
: "POLICY_REJECTED",
|
|
"DOWNLOAD",
|
|
);
|
|
}
|
|
this.receipts.push({
|
|
fileName,
|
|
strategy: policy.strategy,
|
|
bytesWritten: 0,
|
|
});
|
|
return dataSuccess({ kind: "BROWSER_HANDOFF", transferId });
|
|
}
|
|
if (input.source.kind === "AUTHORIZED_STREAM_RESOURCE") {
|
|
return dataFailure("UNSUPPORTED", "DOWNLOAD");
|
|
}
|
|
if (input.source.kind !== "GENERATED") {
|
|
return dataFailure("POLICY_REJECTED", "DOWNLOAD");
|
|
}
|
|
const expectedSha256 = input.source.expectedSha256;
|
|
if (policy.integrity === "REQUIRED" && !expectedSha256) {
|
|
return dataFailure("POLICY_REJECTED", "DOWNLOAD");
|
|
}
|
|
if (
|
|
policy.strategy === "BOUNDED_OBJECT_URL" &&
|
|
input.source.bytes.byteLength !== null &&
|
|
input.source.bytes.byteLength > policy.maxBufferedBytes
|
|
) {
|
|
return dataFailure("LIMIT_EXCEEDED", "DOWNLOAD");
|
|
}
|
|
let bytesWritten = 0;
|
|
const integrityChunks: Uint8Array[] = [];
|
|
for await (const chunkResult of input.source.bytes.stream(
|
|
input.signal,
|
|
)) {
|
|
if (!chunkResult.ok) return chunkResult;
|
|
const chunk = chunkResult.value;
|
|
const duringTransfer = dataCancelled(input.signal, "DOWNLOAD");
|
|
if (duringTransfer) return duringTransfer;
|
|
bytesWritten += chunk.byteLength;
|
|
if (bytesWritten > policy.maxTransferBytes) {
|
|
return dataFailure("LIMIT_EXCEEDED", "DOWNLOAD");
|
|
}
|
|
if (
|
|
input.source.bytes.byteLength !== null &&
|
|
bytesWritten > input.source.bytes.byteLength
|
|
) {
|
|
return dataFailure("INTEGRITY_FAILED", "DOWNLOAD");
|
|
}
|
|
if (expectedSha256) integrityChunks.push(cloneBytes(chunk));
|
|
input.onProgress({
|
|
phase: "TRANSFERRING",
|
|
transferredBytes: bytesWritten,
|
|
totalBytes: input.source.bytes.byteLength,
|
|
});
|
|
}
|
|
if (
|
|
input.source.bytes.byteLength !== null &&
|
|
bytesWritten !== input.source.bytes.byteLength
|
|
) {
|
|
return dataFailure("INTEGRITY_FAILED", "DOWNLOAD");
|
|
}
|
|
if (expectedSha256) {
|
|
const beforeVerification = dataCancelled(input.signal, "DOWNLOAD");
|
|
if (beforeVerification) return beforeVerification;
|
|
input.onProgress({
|
|
phase: "VERIFYING",
|
|
transferredBytes: bytesWritten,
|
|
totalBytes: input.source.bytes.byteLength,
|
|
});
|
|
const actualSha256 = await sha256Hex(concatenateBytes(integrityChunks));
|
|
if (actualSha256 !== expectedSha256.toLowerCase()) {
|
|
return dataFailure("INTEGRITY_FAILED", "DOWNLOAD");
|
|
}
|
|
}
|
|
this.receipts.push({
|
|
fileName,
|
|
strategy: policy.strategy,
|
|
bytesWritten,
|
|
});
|
|
return dataSuccess({
|
|
kind: "SAVED",
|
|
transferId,
|
|
bytesWritten: asByteCount(bytesWritten),
|
|
integrity: expectedSha256 ? "VERIFIED" : "NOT_PROVIDED",
|
|
});
|
|
}
|
|
}
|
|
|
|
function concatenateBytes(chunks: ReadonlyArray<Uint8Array>): Uint8Array {
|
|
const totalBytes = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
|
|
const combined = new Uint8Array(totalBytes);
|
|
let offset = 0;
|
|
for (const chunk of chunks) {
|
|
combined.set(chunk, offset);
|
|
offset += chunk.byteLength;
|
|
}
|
|
return combined;
|
|
}
|
|
|
|
type MemoryStructuredOfflineStoreOptions = Readonly<{
|
|
maxBytes: number;
|
|
now?: () => number;
|
|
initialStatus?: OfflineStoreStatus;
|
|
}>;
|
|
|
|
export class MemoryStructuredOfflineStore<T>
|
|
implements StructuredOfflineStore<T>, OfflineStoreMaintenancePort
|
|
{
|
|
readonly #records = new Map<string, StoredRecord<T>>();
|
|
readonly #receipts = new Map<
|
|
string,
|
|
Readonly<{ fingerprint: string; receipt: OfflineCommitReceipt }>
|
|
>();
|
|
readonly #now: () => number;
|
|
readonly #maxBytes: number;
|
|
#status: OfflineStoreStatus;
|
|
#onLifecycle: ((event: OfflineStoreLifecycleEvent) => void) | null = null;
|
|
#commitSequence = 0;
|
|
|
|
constructor(options: MemoryStructuredOfflineStoreOptions) {
|
|
this.#maxBytes = options.maxBytes;
|
|
this.#now = options.now ?? Date.now;
|
|
this.#status =
|
|
options.initialStatus ??
|
|
Object.freeze({
|
|
kind: "CLOSED",
|
|
reason: "DISPOSED",
|
|
});
|
|
}
|
|
|
|
async open(input: {
|
|
partitionKey: string;
|
|
signal?: AbortSignal;
|
|
onLifecycle(event: OfflineStoreLifecycleEvent): void;
|
|
}): Promise<CapabilityResult<OfflineStoreStatus>> {
|
|
const aborted = cancelled(input.signal);
|
|
if (aborted) return aborted;
|
|
if (input.partitionKey.length === 0) {
|
|
return failure("INVALID_INPUT", false, "The storage partition is invalid.");
|
|
}
|
|
this.#onLifecycle = input.onLifecycle;
|
|
if (this.#status.kind === "UPGRADE_BLOCKED") {
|
|
input.onLifecycle({ kind: "STATUS_CHANGED", status: this.#status });
|
|
return success(this.#status);
|
|
}
|
|
this.#status = Object.freeze({
|
|
kind: "READY",
|
|
persistence: "BEST_EFFORT",
|
|
});
|
|
input.onLifecycle({ kind: "STATUS_CHANGED", status: this.#status });
|
|
return success(this.#status);
|
|
}
|
|
|
|
async read(
|
|
id: string,
|
|
signal?: AbortSignal,
|
|
): Promise<CapabilityResult<StoredRecord<T> | null>> {
|
|
const aborted = cancelled(signal);
|
|
if (aborted) return aborted;
|
|
if (!isReadableStatus(this.#status)) {
|
|
return failure("PROVIDER_UNAVAILABLE", false, "The offline store is not open.");
|
|
}
|
|
const record = this.#records.get(id);
|
|
if (
|
|
record?.expiresAtEpochMs !== null &&
|
|
record?.expiresAtEpochMs !== undefined &&
|
|
record.expiresAtEpochMs <= this.#now()
|
|
) {
|
|
return success(null);
|
|
}
|
|
return success(record ? structuredClone(record) : null);
|
|
}
|
|
|
|
async page(input: {
|
|
cursor?: string;
|
|
limit: number;
|
|
includeExpired?: boolean;
|
|
signal?: AbortSignal;
|
|
}): Promise<CapabilityResult<OfflinePage<T>>> {
|
|
const aborted = cancelled(input.signal);
|
|
if (aborted) return aborted;
|
|
if (!isReadableStatus(this.#status)) {
|
|
return failure("PROVIDER_UNAVAILABLE", false, "The offline store is not open.");
|
|
}
|
|
if (!Number.isInteger(input.limit) || input.limit < 1 || input.limit > 500) {
|
|
return failure("LIMIT_EXCEEDED", false, "The offline page limit is invalid.");
|
|
}
|
|
const offset = input.cursor === undefined ? 0 : Number(input.cursor);
|
|
if (!Number.isSafeInteger(offset) || offset < 0) {
|
|
return failure("INVALID_INPUT", false, "The offline cursor is invalid.");
|
|
}
|
|
const now = this.#now();
|
|
const records = Array.from(this.#records.values())
|
|
.filter(
|
|
(record) =>
|
|
input.includeExpired === true ||
|
|
record.expiresAtEpochMs === null ||
|
|
record.expiresAtEpochMs > now,
|
|
)
|
|
.sort((left, right) => left.id.localeCompare(right.id));
|
|
const selected = records
|
|
.slice(offset, offset + input.limit)
|
|
.map((record) => structuredClone(record));
|
|
const nextOffset = offset + selected.length;
|
|
return success({
|
|
records: selected,
|
|
nextCursor: nextOffset < records.length ? String(nextOffset) : null,
|
|
});
|
|
}
|
|
|
|
async commit(input: {
|
|
idempotencyKey: string;
|
|
mutations: ReadonlyArray<StructuredOfflineMutation<T>>;
|
|
signal?: AbortSignal;
|
|
}): Promise<CapabilityResult<OfflineCommitReceipt>> {
|
|
const aborted = cancelled(input.signal);
|
|
if (aborted) return aborted;
|
|
if (!isWritableStatus(this.#status)) {
|
|
return failure("PROVIDER_UNAVAILABLE", false, "The offline store is read-only.");
|
|
}
|
|
if (input.idempotencyKey.length === 0 || input.mutations.length === 0) {
|
|
return failure("INVALID_INPUT", false, "The offline commit is empty.");
|
|
}
|
|
let fingerprint: string;
|
|
try {
|
|
fingerprint = JSON.stringify(input.mutations);
|
|
} catch {
|
|
return failure(
|
|
"CORRUPT_DATA",
|
|
false,
|
|
"The offline mutation cannot be encoded safely.",
|
|
);
|
|
}
|
|
const replay = this.#receipts.get(input.idempotencyKey);
|
|
if (replay) {
|
|
return replay.fingerprint === fingerprint
|
|
? success({ ...replay.receipt, replayed: true })
|
|
: failure(
|
|
"CONFLICT",
|
|
false,
|
|
"The idempotency key was reused for a different offline commit.",
|
|
);
|
|
}
|
|
|
|
const draft = new Map(
|
|
Array.from(this.#records, ([id, record]) => [
|
|
id,
|
|
structuredClone(record),
|
|
]),
|
|
);
|
|
const revisions: Record<string, number | null> = {};
|
|
const now = this.#now();
|
|
try {
|
|
for (const mutation of input.mutations) {
|
|
const current = draft.get(mutation.id);
|
|
if (!revisionAllows(mutation.revision, current?.revision)) {
|
|
return failure(
|
|
"CONFLICT",
|
|
false,
|
|
"The offline record changed before the commit.",
|
|
);
|
|
}
|
|
if (mutation.kind === "DELETE") {
|
|
draft.delete(mutation.id);
|
|
revisions[mutation.id] = null;
|
|
continue;
|
|
}
|
|
const revision = (current?.revision ?? 0) + 1;
|
|
draft.set(
|
|
mutation.id,
|
|
structuredClone({
|
|
id: mutation.id,
|
|
revision,
|
|
payloadVersion: mutation.payloadVersion,
|
|
createdAtEpochMs: current?.createdAtEpochMs ?? now,
|
|
updatedAtEpochMs: now,
|
|
expiresAtEpochMs: mutation.expiresAtEpochMs,
|
|
value: mutation.value,
|
|
}),
|
|
);
|
|
revisions[mutation.id] = revision;
|
|
}
|
|
} catch {
|
|
return failure(
|
|
"CORRUPT_DATA",
|
|
false,
|
|
"The offline value cannot be persisted safely.",
|
|
);
|
|
}
|
|
|
|
if (estimateRecordBytes(draft) > this.#maxBytes) {
|
|
return failure(
|
|
"QUOTA_EXCEEDED",
|
|
true,
|
|
"The offline storage budget was exceeded.",
|
|
);
|
|
}
|
|
const lastAbortCheck = cancelled(input.signal);
|
|
if (lastAbortCheck) return lastAbortCheck;
|
|
this.#records.clear();
|
|
for (const [id, record] of draft) this.#records.set(id, record);
|
|
const receipt = Object.freeze({
|
|
commitId: `commit-${++this.#commitSequence}`,
|
|
revisions: Object.freeze(revisions),
|
|
replayed: false,
|
|
});
|
|
this.#receipts.set(input.idempotencyKey, { fingerprint, receipt });
|
|
return success(receipt);
|
|
}
|
|
|
|
async clearPartition(input: {
|
|
reason: "LOGOUT" | "ACCOUNT_DELETION" | "USER_REQUEST";
|
|
signal?: AbortSignal;
|
|
}): Promise<CapabilityResult<void>> {
|
|
const aborted = cancelled(input.signal);
|
|
if (aborted) return aborted;
|
|
this.#records.clear();
|
|
this.#receipts.clear();
|
|
return success(undefined);
|
|
}
|
|
|
|
status(): OfflineStoreStatus {
|
|
return this.#status;
|
|
}
|
|
|
|
close(): void {
|
|
this.#onLifecycle = null;
|
|
this.#status = Object.freeze({ kind: "CLOSED", reason: "DISPOSED" });
|
|
}
|
|
|
|
async resumeDataMigration(input: {
|
|
migrationId: string;
|
|
maxRecords: number;
|
|
timeBudgetMs: number;
|
|
signal?: AbortSignal;
|
|
}): Promise<CapabilityResult<MigrationProgress>> {
|
|
const aborted = cancelled(input.signal);
|
|
if (aborted) return aborted;
|
|
if (
|
|
input.migrationId.length === 0 ||
|
|
input.maxRecords < 1 ||
|
|
input.timeBudgetMs < 1
|
|
) {
|
|
return failure("INVALID_INPUT", false, "The migration budget is invalid.");
|
|
}
|
|
const progress = Object.freeze({
|
|
migrationId: input.migrationId,
|
|
state: "COMPLETED" as const,
|
|
processedCount: Math.min(this.#records.size, input.maxRecords),
|
|
remainingEstimate: 0,
|
|
});
|
|
this.#onLifecycle?.({ kind: "MIGRATION_PROGRESS", ...progress });
|
|
return success(progress);
|
|
}
|
|
|
|
async purgeExpired(input: {
|
|
maxRecords: number;
|
|
nowEpochMs: number;
|
|
signal?: AbortSignal;
|
|
}): Promise<CapabilityResult<Readonly<{ purgedCount: number }>>> {
|
|
const aborted = cancelled(input.signal);
|
|
if (aborted) return aborted;
|
|
if (input.maxRecords < 1) {
|
|
return failure("INVALID_INPUT", false, "The purge budget is invalid.");
|
|
}
|
|
let purgedCount = 0;
|
|
for (const [id, record] of this.#records) {
|
|
if (purgedCount >= input.maxRecords) break;
|
|
if (
|
|
record.expiresAtEpochMs !== null &&
|
|
record.expiresAtEpochMs <= input.nowEpochMs
|
|
) {
|
|
this.#records.delete(id);
|
|
purgedCount += 1;
|
|
}
|
|
}
|
|
return success({ purgedCount });
|
|
}
|
|
}
|
|
|
|
function revisionAllows(
|
|
guard: StructuredOfflineMutation<unknown>["revision"],
|
|
currentRevision: number | undefined,
|
|
): boolean {
|
|
if (guard.kind === "ANY") return true;
|
|
if (guard.kind === "MUST_NOT_EXIST") return currentRevision === undefined;
|
|
return currentRevision === guard.revision;
|
|
}
|
|
|
|
function estimateRecordBytes<T>(
|
|
records: ReadonlyMap<string, StoredRecord<T>>,
|
|
): number {
|
|
try {
|
|
return new TextEncoder().encode(JSON.stringify(Array.from(records.values())))
|
|
.byteLength;
|
|
} catch {
|
|
return Number.POSITIVE_INFINITY;
|
|
}
|
|
}
|
|
|
|
export class MemoryStorageDurabilityAdapter implements StorageDurabilityPort {
|
|
#persisted: boolean;
|
|
|
|
constructor(
|
|
private readonly usageBytes: number | null,
|
|
private readonly quotaBytes: number | null,
|
|
private readonly persistenceDecision: "GRANTED" | "DENIED",
|
|
persisted = false,
|
|
) {
|
|
this.#persisted = persisted;
|
|
}
|
|
|
|
async inspect(
|
|
signal?: AbortSignal,
|
|
): Promise<BrowserDataResult<StorageEstimate>> {
|
|
return (
|
|
dataCancelled(signal, "STORAGE_ESTIMATE") ??
|
|
dataSuccess({
|
|
usageBytes: this.usageBytes,
|
|
quotaBytes: this.quotaBytes,
|
|
persisted: this.#persisted,
|
|
pressure: storagePressure(
|
|
this.usageBytes,
|
|
this.quotaBytes,
|
|
),
|
|
})
|
|
);
|
|
}
|
|
|
|
async requestPersistence(input: {
|
|
reason: "PROTECT_UNSYNCED_USER_DATA";
|
|
userInitiated: true;
|
|
signal?: AbortSignal;
|
|
}): Promise<BrowserDataResult<"GRANTED" | "DENIED">> {
|
|
const aborted = dataCancelled(input.signal, "STORAGE_PERSIST");
|
|
if (aborted) return aborted;
|
|
this.#persisted = this.persistenceDecision === "GRANTED";
|
|
return dataSuccess(this.persistenceDecision);
|
|
}
|
|
}
|
|
|
|
function storagePressure(
|
|
usageBytes: number | null,
|
|
quotaBytes: number | null,
|
|
): StorageEstimate["pressure"] {
|
|
if (
|
|
usageBytes === null ||
|
|
quotaBytes === null ||
|
|
!Number.isFinite(usageBytes) ||
|
|
!Number.isFinite(quotaBytes) ||
|
|
usageBytes < 0 ||
|
|
quotaBytes <= 0
|
|
) {
|
|
return "UNKNOWN";
|
|
}
|
|
const ratio = usageBytes / quotaBytes;
|
|
if (ratio >= 0.85) return "CRITICAL";
|
|
if (ratio >= 0.7) return "PRESSURE";
|
|
return "NORMAL";
|
|
}
|
|
|
|
type MemoryObject = Readonly<{
|
|
descriptor: DurableObjectDescriptor;
|
|
chunks: ReadonlyArray<Uint8Array>;
|
|
}>;
|
|
|
|
type MemoryDurableObjectStoreOptions = Readonly<{
|
|
scope: OpfsStorageScope;
|
|
storagePolicy: BrowserStoragePolicy;
|
|
maxObjectBytes: number;
|
|
now?: () => number;
|
|
}>;
|
|
|
|
/**
|
|
* [0929] 05-03. Deterministic stand-in for the OPFS reference runtime
|
|
* (`src/adapters/storage/opfs`). It implements the same ports, so a feature
|
|
* test written against it compiles against the runtime too. It keeps the
|
|
* runtime's visible rules: a put is invisible until its logical commit, a
|
|
* stale `expectedGeneration` is `CONFLICT`, a put that stopped mid-way leaves
|
|
* a journal row, and a LOGOUT or ACCOUNT_DELETION the policy allows leaves the
|
|
* partition empty. `reconcile` rolls a row that stopped while PREPARING back
|
|
* and commits one that stopped after FILES_READY, like the runtime's
|
|
* roll-forward; such a purge also drops every stopped row. Every purge
|
|
* reports `partitionDeleted`, never a chunk sweep (2026-11-03 05-01, 05-04,
|
|
* 1103/05-01 rest).
|
|
*
|
|
* It does not model the worker, Web Locks, the composition authority, chunk
|
|
* dedup, orphan GC or the other maintenance reasons (`UNSUPPORTED`). Its
|
|
* integrity digest is not the runtime's tree digest; compare digests only
|
|
* within one store.
|
|
*/
|
|
export class MemoryDurableObjectStore
|
|
implements DurableObjectStorePort, DurableObjectMaintenancePort
|
|
{
|
|
readonly #objects = new Map<string, MemoryObject>();
|
|
/**
|
|
* Journal rows of puts that stopped before they committed or rolled back.
|
|
* A row that reached FILES_READY keeps the object its commit would publish.
|
|
*/
|
|
readonly #pending = new Map<
|
|
number,
|
|
Readonly<{ expectedGeneration: number | null; ready: MemoryObject | null }>
|
|
>();
|
|
readonly #scope: OpfsStorageScope;
|
|
readonly #storagePolicy: BrowserStoragePolicy;
|
|
readonly #maxObjectBytes: number;
|
|
readonly #now: () => number;
|
|
#sequence = 0;
|
|
#failurePhase: "PREPARING" | "FILES_READY" | null = null;
|
|
|
|
constructor(options: MemoryDurableObjectStoreOptions) {
|
|
this.#scope = Object.freeze({ ...options.scope });
|
|
this.#storagePolicy = options.storagePolicy;
|
|
this.#maxObjectBytes = options.maxObjectBytes;
|
|
this.#now = options.now ?? Date.now;
|
|
}
|
|
|
|
/** The next put stops after this phase, the way a closed tab would. */
|
|
failNextPutAfter(phase: "PREPARING" | "FILES_READY"): void {
|
|
this.#failurePhase = phase;
|
|
}
|
|
|
|
async capabilities() {
|
|
return dataSuccess(
|
|
Object.freeze({
|
|
available: true,
|
|
dedicatedWorkerRequired: true as const,
|
|
crossContextMutationLockAvailable: true,
|
|
synchronousAccessHandleAvailable: false,
|
|
}),
|
|
);
|
|
}
|
|
|
|
async put(
|
|
request: Parameters<DurableObjectStorePort["put"]>[0],
|
|
): Promise<BrowserDataResult<DurableObjectDescriptor>> {
|
|
const aborted = dataCancelled(request.signal, "OBJECT_WRITE");
|
|
if (aborted) return aborted;
|
|
const declared = request.source.byteLength;
|
|
if (declared !== null && declared > this.#maxObjectBytes) {
|
|
return dataFailure("LIMIT_EXCEEDED", "OBJECT_WRITE");
|
|
}
|
|
const current = this.#objects.get(request.objectId);
|
|
if (
|
|
(request.expectedGeneration === null && current !== undefined) ||
|
|
(request.expectedGeneration !== null &&
|
|
current?.descriptor.generation !== request.expectedGeneration)
|
|
) {
|
|
return dataFailure("CONFLICT", "OBJECT_WRITE", false, "REOPEN");
|
|
}
|
|
const row = ++this.#sequence;
|
|
this.#pending.set(
|
|
row,
|
|
Object.freeze({ expectedGeneration: request.expectedGeneration, ready: null }),
|
|
);
|
|
const stopped = (phase: "PREPARING" | "FILES_READY") => {
|
|
if (this.#failurePhase !== phase) return null;
|
|
this.#failurePhase = null;
|
|
// The row stays: only reconcile can settle it.
|
|
return dataFailure("UNAVAILABLE", "OBJECT_WRITE", true, "RECONCILE");
|
|
};
|
|
const afterPreparing = stopped("PREPARING");
|
|
if (afterPreparing) return afterPreparing;
|
|
|
|
const chunks: Uint8Array[] = [];
|
|
let totalBytes = 0;
|
|
const settle = (result: BrowserDataResult<never>) => {
|
|
// A put that fails on its own compensates: its row is rolled back.
|
|
this.#pending.delete(row);
|
|
return result;
|
|
};
|
|
for await (const chunk of request.source.stream(
|
|
request.signal ?? new AbortController().signal,
|
|
)) {
|
|
if (!chunk.ok) {
|
|
return settle(
|
|
dataFailure(chunk.error.code, "OBJECT_WRITE", chunk.error.retryable),
|
|
);
|
|
}
|
|
const duringWrite = dataCancelled(request.signal, "OBJECT_WRITE");
|
|
if (duringWrite) return settle(duringWrite);
|
|
totalBytes += chunk.value.byteLength;
|
|
if (totalBytes > this.#maxObjectBytes) {
|
|
return settle(dataFailure("LIMIT_EXCEEDED", "OBJECT_WRITE"));
|
|
}
|
|
if (declared !== null && totalBytes > declared) {
|
|
return settle(dataFailure("INTEGRITY_FAILED", "OBJECT_WRITE"));
|
|
}
|
|
chunks.push(cloneBytes(chunk.value));
|
|
request.onProgress?.({
|
|
phase: "TRANSFERRING",
|
|
transferredBytes: totalBytes,
|
|
totalBytes: declared,
|
|
});
|
|
}
|
|
if (declared !== null && totalBytes !== declared) {
|
|
return settle(dataFailure("INTEGRITY_FAILED", "OBJECT_WRITE"));
|
|
}
|
|
|
|
const chunkDigests = await Promise.all(chunks.map(sha256Hex));
|
|
const chunkSizeBytes = Math.max(
|
|
0,
|
|
...chunks.map((chunk) => chunk.byteLength),
|
|
);
|
|
const canonicalTree = new TextEncoder().encode(
|
|
[
|
|
totalBytes,
|
|
chunkSizeBytes,
|
|
...chunks.map(
|
|
(chunk, index) =>
|
|
`${chunk.byteLength}:${chunkDigests[index] ?? "missing"}`,
|
|
),
|
|
].join(":"),
|
|
);
|
|
const descriptor: DurableObjectDescriptor = Object.freeze({
|
|
objectId: request.objectId,
|
|
scope: this.#scope,
|
|
generation: (current?.descriptor.generation ?? 0) + 1,
|
|
byteLength: totalBytes,
|
|
mediaType: request.mediaType,
|
|
createdAtEpochMs: this.#now(),
|
|
integrity: Object.freeze({
|
|
algorithm: "SHA-256-TREE-V1" as const,
|
|
rootDigestHex: await sha256Hex(canonicalTree),
|
|
chunkSizeBytes,
|
|
}),
|
|
storagePolicy: this.#storagePolicy,
|
|
});
|
|
const ready: MemoryObject = { descriptor, chunks };
|
|
this.#pending.set(
|
|
row,
|
|
Object.freeze({ expectedGeneration: request.expectedGeneration, ready }),
|
|
);
|
|
const afterFilesReady = stopped("FILES_READY");
|
|
if (afterFilesReady) return afterFilesReady;
|
|
this.#objects.set(request.objectId, ready);
|
|
this.#pending.delete(row);
|
|
return dataSuccess(descriptor);
|
|
}
|
|
|
|
async open(
|
|
request: Parameters<DurableObjectStorePort["open"]>[0],
|
|
): ReturnType<DurableObjectStorePort["open"]> {
|
|
const aborted = dataCancelled(request.signal, "OBJECT_READ");
|
|
if (aborted) return aborted;
|
|
const object = this.#objects.get(request.objectId);
|
|
if (
|
|
!object ||
|
|
(request.generation !== undefined &&
|
|
request.generation !== object.descriptor.generation)
|
|
) {
|
|
return dataFailure("NOT_FOUND", "OBJECT_READ", false, "REHYDRATE");
|
|
}
|
|
const chunks = object.chunks.map(cloneBytes);
|
|
const source: ByteSource = Object.freeze({
|
|
byteLength: object.descriptor.byteLength,
|
|
async *stream(signal: AbortSignal) {
|
|
for (const chunk of chunks) {
|
|
const stopped = dataCancelled(signal, "OBJECT_READ");
|
|
if (stopped) {
|
|
yield stopped;
|
|
return;
|
|
}
|
|
yield dataSuccess(cloneBytes(chunk));
|
|
}
|
|
},
|
|
});
|
|
return dataSuccess(
|
|
Object.freeze({ descriptor: object.descriptor, source }),
|
|
);
|
|
}
|
|
|
|
async remove(
|
|
request: Parameters<DurableObjectStorePort["remove"]>[0],
|
|
): Promise<BrowserDataResult<void>> {
|
|
const aborted = dataCancelled(request.signal, "OBJECT_DELETE");
|
|
if (aborted) return aborted;
|
|
const current = this.#objects.get(request.objectId);
|
|
if (!current) return dataFailure("NOT_FOUND", "OBJECT_DELETE");
|
|
if (current.descriptor.generation !== request.expectedGeneration) {
|
|
return dataFailure("CONFLICT", "OBJECT_DELETE", false, "REOPEN");
|
|
}
|
|
this.#objects.delete(request.objectId);
|
|
return dataSuccess(undefined);
|
|
}
|
|
|
|
async reconcile(
|
|
request: Parameters<DurableObjectMaintenancePort["reconcile"]>[0] = {},
|
|
): Promise<BrowserDataResult<OpfsReconciliationReport>> {
|
|
const aborted = dataCancelled(request.signal, "OBJECT_RECONCILE");
|
|
if (aborted) return aborted;
|
|
const maxTransactions = request.maxTransactions ?? 100;
|
|
if (
|
|
!Number.isSafeInteger(maxTransactions) ||
|
|
maxTransactions < 1 ||
|
|
(request.budgetMs !== undefined &&
|
|
(!Number.isSafeInteger(request.budgetMs) || request.budgetMs < 1))
|
|
) {
|
|
return dataFailure("INVALID_INPUT", "OBJECT_RECONCILE");
|
|
}
|
|
const rows = [...this.#pending].slice(0, maxTransactions);
|
|
let committed = 0;
|
|
for (const [row, { expectedGeneration, ready }] of rows) {
|
|
this.#pending.delete(row);
|
|
// The runtime re-verifies a FILES_READY row and commits it under the
|
|
// same generation check a live put has; anything else is rolled back.
|
|
const current = ready && this.#objects.get(ready.descriptor.objectId);
|
|
if (
|
|
ready &&
|
|
(current?.descriptor.generation ?? null) === expectedGeneration
|
|
) {
|
|
this.#objects.set(ready.descriptor.objectId, ready);
|
|
committed += 1;
|
|
}
|
|
}
|
|
return dataSuccess(
|
|
Object.freeze({
|
|
inspectedTransactions: rows.length,
|
|
committedTransactions: committed,
|
|
rolledBackTransactions: rows.length - committed,
|
|
cleanedTransactions: committed,
|
|
inspectedOrphanChunks: 0,
|
|
deletedOrphanChunks: 0,
|
|
orphanGcStatus: "COMPLETED" as const,
|
|
moreTransactionsAvailable: this.#pending.size > 0,
|
|
deadlineReached: false,
|
|
skippedLiveTransactions: 0,
|
|
failedTransactions: 0,
|
|
corruptTransactions: 0,
|
|
}),
|
|
);
|
|
}
|
|
|
|
async enforcePolicies(
|
|
request: Parameters<DurableObjectMaintenancePort["enforcePolicies"]>[0],
|
|
): Promise<BrowserDataResult<OpfsPolicyMaintenanceReport>> {
|
|
const aborted = dataCancelled(request.signal, "OBJECT_RECONCILE");
|
|
if (aborted) return aborted;
|
|
if (request.reason !== "LOGOUT" && request.reason !== "ACCOUNT_DELETION") {
|
|
return dataFailure("UNSUPPORTED", "OBJECT_RECONCILE");
|
|
}
|
|
const policy = this.#storagePolicy;
|
|
if (
|
|
policy.accountScope !== "OPAQUE_PARTITION" ||
|
|
(request.reason === "LOGOUT"
|
|
? policy.logoutAction === "KEEP_ORIGIN_SHARED"
|
|
: policy.accountDeletionAction !== "PURGE_PARTITION")
|
|
) {
|
|
return dataFailure("POLICY_REJECTED", "OBJECT_RECONCILE", false, "READ_ONLY");
|
|
}
|
|
let releasedBytes = 0;
|
|
for (const object of this.#objects.values()) {
|
|
releasedBytes += object.descriptor.byteLength;
|
|
}
|
|
const removedObjects = this.#objects.size;
|
|
this.#objects.clear();
|
|
// 2026-11-03 05-01. A stopped put goes with the partition, as the
|
|
// runtime's partition delete takes its row and its files. 1103/05-01
|
|
// rest: the runtime ends every purge that walked all objects in that
|
|
// delete, so this one always reports it.
|
|
this.#pending.clear();
|
|
return dataSuccess(
|
|
Object.freeze({
|
|
inspectedObjects: removedObjects,
|
|
removedObjects,
|
|
releasedBytes,
|
|
moreObjectsAvailable: false,
|
|
deadlineReached: false,
|
|
partitionDeleted: true as const,
|
|
}),
|
|
);
|
|
}
|
|
}
|
|
|
|
async function sha256Hex(bytes: Uint8Array): Promise<string> {
|
|
const buffer = new ArrayBuffer(bytes.byteLength);
|
|
new Uint8Array(buffer).set(bytes);
|
|
const digest = await crypto.subtle.digest("SHA-256", buffer);
|
|
return Array.from(new Uint8Array(digest), (byte) =>
|
|
byte.toString(16).padStart(2, "0"),
|
|
).join("");
|
|
}
|
|
|
|
type MemoryCacheRelease = Readonly<{
|
|
manifestDigest: string;
|
|
entries: ReadonlyMap<string, PublicAssetEntry>;
|
|
}>;
|
|
|
|
type MemoryPublicResponseCacheOptions = Readonly<{
|
|
origin: string;
|
|
maxEntryBytes: number;
|
|
allowedMediaTypes: ReadonlySet<string>;
|
|
forbiddenPaths?: ReadonlyArray<string>;
|
|
}>;
|
|
|
|
export class MemoryPublicResponseCache
|
|
implements PublicResponseCacheAdmin
|
|
{
|
|
readonly #releases = new Map<string, MemoryCacheRelease>();
|
|
readonly #origin: string;
|
|
readonly #maxEntryBytes: number;
|
|
readonly #allowedMediaTypes: ReadonlySet<string>;
|
|
readonly #forbiddenPaths: ReadonlyArray<string>;
|
|
#activeReleaseId: string | null = null;
|
|
#previousReleaseId: string | null = null;
|
|
|
|
constructor(options: MemoryPublicResponseCacheOptions) {
|
|
this.#origin = new URL(options.origin).origin;
|
|
this.#maxEntryBytes = options.maxEntryBytes;
|
|
this.#allowedMediaTypes = options.allowedMediaTypes;
|
|
this.#forbiddenPaths = options.forbiddenPaths ?? [
|
|
"/config.json",
|
|
"/release-manifest.json",
|
|
"/api/",
|
|
"/auth/",
|
|
"/user/",
|
|
"/tenant/",
|
|
];
|
|
}
|
|
|
|
async stageRelease(
|
|
input: Parameters<PublicResponseCacheAdmin["stageRelease"]>[0],
|
|
): Promise<CapabilityResult<void>> {
|
|
const aborted = cancelled(input.signal);
|
|
if (aborted) return aborted;
|
|
if (
|
|
input.releaseId.length === 0 ||
|
|
input.manifestDigest.length === 0 ||
|
|
input.entries.length === 0
|
|
) {
|
|
return failure("INVALID_INPUT", false, "The cache release is invalid.");
|
|
}
|
|
const staged = new Map<string, PublicAssetEntry>();
|
|
for (const entry of input.entries) {
|
|
const key = this.#cacheKey(entry.url);
|
|
if (
|
|
key === null ||
|
|
entry.byteLength > this.#maxEntryBytes ||
|
|
entry.integritySha256.length === 0 ||
|
|
entry.requestCredentials !== "OMIT" ||
|
|
entry.dataClass !== "PUBLIC" ||
|
|
!this.#allowedMediaTypes.has(entry.mediaType) ||
|
|
staged.has(key)
|
|
) {
|
|
return failure(
|
|
"POLICY_REJECTED",
|
|
false,
|
|
"A public cache entry violates the cache policy.",
|
|
);
|
|
}
|
|
staged.set(key, Object.freeze({ ...entry, url: key }));
|
|
}
|
|
this.#releases.set(input.releaseId, {
|
|
manifestDigest: input.manifestDigest,
|
|
entries: staged,
|
|
});
|
|
return success(undefined);
|
|
}
|
|
|
|
async activateRelease(
|
|
input: Parameters<PublicResponseCacheAdmin["activateRelease"]>[0],
|
|
): Promise<CapabilityResult<void>> {
|
|
const aborted = cancelled(input.signal);
|
|
if (aborted) return aborted;
|
|
const candidate = this.#releases.get(input.releaseId);
|
|
if (
|
|
!candidate ||
|
|
candidate.manifestDigest !== input.manifestDigest ||
|
|
this.#activeReleaseId !== input.expectedPreviousReleaseId
|
|
) {
|
|
return failure(
|
|
"CONFLICT",
|
|
false,
|
|
"The cache candidate is incomplete or stale.",
|
|
);
|
|
}
|
|
this.#previousReleaseId = this.#activeReleaseId;
|
|
this.#activeReleaseId = input.releaseId;
|
|
return success(undefined);
|
|
}
|
|
|
|
async lookup(
|
|
input: Parameters<PublicResponseCacheAdmin["lookup"]>[0],
|
|
): Promise<CapabilityResult<PublicCacheLookup>> {
|
|
const aborted = cancelled(input.signal);
|
|
if (aborted) return aborted;
|
|
if (
|
|
input.requestCredentials !== "OMIT" ||
|
|
input.hasAuthorization !== false
|
|
) {
|
|
return success({ kind: "MISS", reason: "POLICY_REJECTED" });
|
|
}
|
|
if (!this.#activeReleaseId) {
|
|
return success({ kind: "MISS", reason: "NO_ACTIVE_RELEASE" });
|
|
}
|
|
const key = this.#cacheKey(input.url);
|
|
if (!key) return success({ kind: "MISS", reason: "POLICY_REJECTED" });
|
|
const entry = this.#releases
|
|
.get(this.#activeReleaseId)
|
|
?.entries.get(key);
|
|
return entry
|
|
? success({
|
|
kind: "HIT",
|
|
releaseId: this.#activeReleaseId,
|
|
entry,
|
|
})
|
|
: success({ kind: "MISS", reason: "NOT_FOUND" });
|
|
}
|
|
|
|
async inspect(
|
|
signal?: AbortSignal,
|
|
): Promise<CapabilityResult<PublicCacheInspection>> {
|
|
const aborted = cancelled(signal);
|
|
if (aborted) return aborted;
|
|
// Every release here was staged after its entries passed policy, so each
|
|
// owned cache is readable and each candidate is verified.
|
|
return success({
|
|
activePointer: this.#activeReleaseId === null ? "NONE" : "READABLE",
|
|
activeReleaseRegistryId: this.#activeReleaseId,
|
|
ownedCacheCount: this.#releases.size,
|
|
unreadableOwnedCacheCount: 0,
|
|
releaseCandidates: Array.from(this.#releases)
|
|
.filter(
|
|
([releaseId]) =>
|
|
releaseId !== this.#activeReleaseId &&
|
|
releaseId !== this.#previousReleaseId,
|
|
)
|
|
.map(([releaseRegistryId, release]) => ({
|
|
releaseRegistryId,
|
|
verified: true,
|
|
entryCount: release.entries.size,
|
|
})),
|
|
});
|
|
}
|
|
|
|
async rollback(
|
|
signal?: AbortSignal,
|
|
): Promise<CapabilityResult<void>> {
|
|
const aborted = cancelled(signal);
|
|
if (aborted) return aborted;
|
|
if (!this.#previousReleaseId) {
|
|
return failure("NOT_FOUND", false, "No previous cache release is available.");
|
|
}
|
|
const active = this.#activeReleaseId;
|
|
this.#activeReleaseId = this.#previousReleaseId;
|
|
this.#previousReleaseId = active;
|
|
return success(undefined);
|
|
}
|
|
|
|
async deleteOwned(
|
|
input: Parameters<PublicResponseCacheAdmin["deleteOwned"]>[0],
|
|
): Promise<CapabilityResult<Readonly<{ deletedCount: number }>>> {
|
|
const aborted = cancelled(input.signal);
|
|
if (aborted) return aborted;
|
|
let deletedCount = 0;
|
|
if (input.roles.includes("CANDIDATE")) {
|
|
for (const releaseId of Array.from(this.#releases.keys())) {
|
|
if (
|
|
releaseId !== this.#activeReleaseId &&
|
|
releaseId !== this.#previousReleaseId
|
|
) {
|
|
this.#releases.delete(releaseId);
|
|
deletedCount += 1;
|
|
}
|
|
}
|
|
}
|
|
if (
|
|
input.roles.includes("PREVIOUS") &&
|
|
this.#previousReleaseId !== null
|
|
) {
|
|
this.#releases.delete(this.#previousReleaseId);
|
|
this.#previousReleaseId = null;
|
|
deletedCount += 1;
|
|
}
|
|
return success({ deletedCount });
|
|
}
|
|
|
|
#cacheKey(value: string): string | null {
|
|
try {
|
|
const url = new URL(value, this.#origin);
|
|
if (
|
|
url.origin !== this.#origin ||
|
|
this.#forbiddenPaths.some(
|
|
(path) =>
|
|
url.pathname === path ||
|
|
(path.endsWith("/") && url.pathname.startsWith(path)),
|
|
)
|
|
) {
|
|
return null;
|
|
}
|
|
url.hash = "";
|
|
return url.href;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
}
|