문제: `recipes/frontend-capabilities/`가 `src/application/ports/`와
같은 이름의 타입 34개를 따로 정의한다(`DurableObjectStorePort`,
`FilePickerPort`, `StorageDurabilityPort`, `TransferProgress`,
`PublicCacheInspection` 등). 7월 이후 runtime port가 바뀌어도(0929
05-01~05-14) recipe 복사본은 한 번도 따라오지 않았다. catalog는 이
복사본을 구현한 fake를 runtime의 fake로 안내해서, 그 fake로 쓴 테스트는
runtime에 없는 resume·quarantine을 전제했다.
고른 방법 (리뷰의 (c)):
- runtime이 있는 port와 그 표면의 타입은 recipe 정의를 지우고
`src/application/ports`의 것을 같은 이름으로 다시 내보낸다. 옛 recipe
port에만 쓰이던 `DurableObjectDataClass`, `DurableObjectIntegrity`,
`DurableObjectRead`, `ObjectStoreRecoverySummary`도 지운다. src에 없는
`DurableObjectId`·`ObjectGeneration` 브랜드와 `as*` 헬퍼는 남긴다(src
port가 그대로 받는다).
- fake는 src port를 `implements`한다.
- 파일 picker·content·preview·download fake와 storage durability fake:
결과를 `BrowserDataResult`(`error`, 닫힌 코드, operation)로 바꿨다.
`PROVIDER_UNAVAILABLE`은 src 코드 `UNAVAILABLE`이 된다.
- `MemoryDurableObjectStore`: src OPFS port에 맞춰 다시 썼다. 생성자는
scope·storagePolicy·maxObjectBytes를 받는다. 멈춘 put의 행은
reconcile이 rollback만 한다(resume·quarantine 없음, runtime과 같다).
LOGOUT·ACCOUNT_DELETION만 지원하고 나머지 reason은 `UNSUPPORTED`다.
- 고칠 수 없는 fake: `MemoryStructuredOfflineStore`는
`IndexedDbRepositoryPort`와 설계가 달라(배치 commit·idempotency 대
CAS·lifecycle batch) catalog offline-indexeddb 행의 fake 칸에서 뺐다.
recipe 전용 `StructuredOfflineStore`의 fake로는 남는다.
- recipe 전용 port 두 곳:
- `PublicResponseCacheAdmin.inspect`는 runtime의 `PublicCacheInspection`
모양으로 보고한다. `MemoryPublicResponseCache`가 그 모양을 만든다.
- `FileTransferPort`(runtime 없음)의 progress는 `FileTransferProgress`로
나눴다. `TransferProgress`라는 이름은 recipe barrel에서 src 타입으로
계속 나간다. 일반 recipe인 `contracts.ts`가 선택형 runtime port를
import하지 않게 하려는 것이다.
- 다시 갈라지지 않게 `optional-capability-contracts.test.ts`에 검사를
더했다. recipes/가 src/application/ports/에 있는 이름으로 타입을
정의하면 실패한다(다시 내보내기는 허용).
- runtime 제거 fixture(`test-browser-file-storage-runtime-removal.ts`)는
이 runtime의 port를 다시 내보내는 recipe 두 파일과 그 테스트를 함께
지우고, recipe barrel에서 두 export 줄을 먼저 뺀다.
버린 대안: 현상 유지(변경 누락 계속), 이름만 바꿔 `*Sketch`로 표시(중복
유지비가 남음), 두 벌을 비교하는 타입 테스트(두 벌을 계속 유지).
위험·한계:
- recipe에서 위 타입·fake를 쓰던 다운스트림은 컴파일 오류로 드러난다
(조용히 깨지지 않는다). 같은 이름 타입의 모양, `MemoryDurableObjectStore`
생성자·메서드, 파일 fake의 실패 결과(`failure` → `error`), 지운 타입
4개가 바뀌었다. 두 제품 repo의 사용 여부는 확인하지 않았다.
- `MemoryDurableObjectStore`의 integrity digest는 runtime의 tree digest가
아니다(주석에 적음). worker·Web Lock·authority·GC는 흉내내지 않는다.
- `test:browser-file-storage-removal`은 pnpm이 필요해 돌리지 못했다.
barrel 줄 제거와 경로 추가는 코드로만 확인했다.
검증:
- RED: 새 검사를 수정 전 recipe 소스로 돌리면 실패한다.
`expected [ 'LocalFileRef', …(33) ] to deeply equal []` (34개).
- GREEN: `node scripts/run-vitest.ts run tests/unit tests/recipes
tests/contract` 180 files 2,548건 통과. `tsc` app·recipes·test·node
통과, 바꾼 파일 eslint 통과, `check-registries` PASS(재승인 불필요),
`verify-documentation-readiness` PASS_SCOPED.
`check-optional-recipes`(source)는 0929/05-01의 offline-indexeddb 예산
초과(37,327 > 36,900)만 실패하고 catalog·source 검사는 통과했다.
이 커밋은 그 번들 크기를 바꾸지 않는다(recipes/는 sourceRoots 밖).
BREAKING CHANGE: recipes/frontend-capabilities의 browser-file·OPFS·
storage durability·public cache 타입 중 src/application/ports와 이름이
같은 것은 이제 그 src 타입이다. file·durability·OPFS fake는 src port를
구현하고 BrowserDataResult를 돌려준다(`result.failure.code` →
`result.error.code`). `MemoryDurableObjectStore`는 `{ scope, storagePolicy,
maxObjectBytes }`로 만든다. `FileTransferPort`의 progress 타입은
`FileTransferProgress`다. `DurableObjectDataClass`·`DurableObjectIntegrity`
·`DurableObjectRead`·`ObjectStoreRecoverySummary`는 없어졌다.
Refs: docs/reviews/2026-09-29-maturity-review/05-adapters-storage-kernel.md 05-03
744 lines
22 KiB
TypeScript
744 lines
22 KiB
TypeScript
import { describe, expect, expectTypeOf, it } from "vitest";
|
|
|
|
import {
|
|
MemoryDurableObjectStore,
|
|
MemoryBrowserFilePolicyRegistry,
|
|
MemoryExampleQuarantinedUploadAdapter,
|
|
MemoryFileSelectionAdapter,
|
|
MemoryPublicResponseCache,
|
|
MemoryStorageDurabilityAdapter,
|
|
MemoryStructuredOfflineStore,
|
|
MemoryTransientPreviewAdapter,
|
|
RecordingDownloadDeliveryAdapter,
|
|
asByteCount,
|
|
asBrowserManagedDownloadCapabilityReceipt,
|
|
asDurableObjectId,
|
|
asLocalFileRef,
|
|
asObjectGeneration,
|
|
browserFilePolicyReference,
|
|
sanitizeDownloadFileName,
|
|
} from "../../recipes/frontend-capabilities/index.ts";
|
|
import type {
|
|
BrowserFileComposition,
|
|
BrowserPersistencePolicy,
|
|
DurableObjectStorageComposition,
|
|
ExampleBackendUploadComposition,
|
|
PublicResponseCacheComposition,
|
|
StorageDurabilityComposition,
|
|
StructuredOfflineStorageComposition,
|
|
} from "../../recipes/frontend-capabilities/index.ts";
|
|
import type {
|
|
BrowserStoragePolicy,
|
|
DownloadDeliveryPort,
|
|
DurableObjectMaintenancePort,
|
|
DurableObjectStorePort,
|
|
FileContentPort,
|
|
FilePickerPort,
|
|
StorageDurabilityPort,
|
|
TransientPreviewPort,
|
|
} from "../../src/application/ports/browser-file-storage/index.ts";
|
|
|
|
async function* byteChunks(
|
|
...values: ReadonlyArray<string>
|
|
): AsyncIterable<Readonly<{ ok: true; value: Uint8Array }>> {
|
|
for (const value of values) {
|
|
yield {
|
|
ok: true,
|
|
value: new TextEncoder().encode(value),
|
|
};
|
|
}
|
|
}
|
|
|
|
async function* failedByteChunks() {
|
|
yield {
|
|
ok: false,
|
|
error: {
|
|
code: "NOT_READABLE",
|
|
operation: "OBJECT_WRITE",
|
|
retryable: true,
|
|
recovery: "RETRY",
|
|
},
|
|
} as const;
|
|
}
|
|
|
|
describe("production browser file and storage recipe contracts", () => {
|
|
it("separates picker dismissal, metadata policy and bounded content reads", async () => {
|
|
const ref = asLocalFileRef("opaque-local-1");
|
|
const selectionPolicy = {
|
|
policyId: "support-attachment-v1",
|
|
purpose: "support-attachment",
|
|
classification: "PERSONAL" as const,
|
|
multiple: false,
|
|
maxCount: 1,
|
|
maxFileBytes: asByteCount(10),
|
|
maxTotalBytes: asByteCount(10),
|
|
allowEmpty: false,
|
|
accept: [{ mediaType: "text/plain", extensions: [".txt"] }],
|
|
};
|
|
const filePolicy = browserFilePolicyReference(
|
|
"support-attachment",
|
|
"select-inspect-preview-text",
|
|
);
|
|
const policies = new MemoryBrowserFilePolicyRegistry([
|
|
{
|
|
reference: filePolicy,
|
|
selection: selectionPolicy,
|
|
inspection: {
|
|
policyId: selectionPolicy.policyId,
|
|
maxInspectionBytes: asByteCount(1_445),
|
|
acceptedSignatures: [
|
|
{
|
|
mediaType: "text/plain",
|
|
extensions: [".txt"],
|
|
patterns: [
|
|
{
|
|
offset: asByteCount(0),
|
|
bytes: [104],
|
|
},
|
|
],
|
|
},
|
|
],
|
|
},
|
|
preview: {
|
|
allowedMediaTypes: ["text/plain"],
|
|
maxPreviewBytes: asByteCount(10),
|
|
},
|
|
},
|
|
]);
|
|
const adapter = new MemoryFileSelectionAdapter(
|
|
[
|
|
{
|
|
ref,
|
|
displayName: "notes.txt",
|
|
bytes: new TextEncoder().encode("hello"),
|
|
reportedMediaType: "text/plain",
|
|
detectedMediaType: "text/plain",
|
|
signature: "MATCHED",
|
|
},
|
|
],
|
|
policies,
|
|
);
|
|
|
|
adapter.setNextOutcome("DISMISSED");
|
|
expect(await adapter.select({ policy: filePolicy })).toEqual({
|
|
ok: true,
|
|
value: { kind: "DISMISSED" },
|
|
});
|
|
|
|
const selected = await adapter.select({ policy: filePolicy });
|
|
expect(selected.ok && selected.value.kind).toBe("SELECTED");
|
|
expect(
|
|
await adapter.select({
|
|
policy: browserFilePolicyReference(
|
|
"support-attachment",
|
|
"select-inspect-preview-text",
|
|
),
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "POLICY_REJECTED", operation: "FILE_SELECT" },
|
|
});
|
|
const inspected = await adapter.inspect({
|
|
ref,
|
|
policy: filePolicy,
|
|
signal: new AbortController().signal,
|
|
});
|
|
expect(inspected).toMatchObject({
|
|
ok: true,
|
|
value: {
|
|
detectedMediaType: "text/plain",
|
|
signature: "MATCHED",
|
|
},
|
|
});
|
|
if (!inspected.ok || !inspected.value.verificationReceipt) return;
|
|
expect(
|
|
await adapter.readRange({
|
|
ref,
|
|
offset: asByteCount(1),
|
|
length: asByteCount(3),
|
|
signal: new AbortController().signal,
|
|
}),
|
|
).toEqual({
|
|
ok: true,
|
|
value: new TextEncoder().encode("ell"),
|
|
});
|
|
const previews = new MemoryTransientPreviewAdapter(
|
|
adapter,
|
|
policies,
|
|
);
|
|
const preview = await previews.create({
|
|
ref,
|
|
verificationReceipt: inspected.value.verificationReceipt,
|
|
policy: filePolicy,
|
|
maxPreviewBytes: asByteCount(10),
|
|
signal: new AbortController().signal,
|
|
});
|
|
expect(preview.ok).toBe(true);
|
|
expect(previews.activeLeaseCount).toBe(1);
|
|
if (preview.ok) {
|
|
preview.value.release();
|
|
preview.value.release();
|
|
}
|
|
expect(previews.activeLeaseCount).toBe(0);
|
|
previews.dispose();
|
|
expect(
|
|
await previews.create({
|
|
ref,
|
|
verificationReceipt: inspected.value.verificationReceipt,
|
|
policy: filePolicy,
|
|
maxPreviewBytes: asByteCount(10),
|
|
signal: new AbortController().signal,
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "UNAVAILABLE", operation: "PREVIEW" },
|
|
});
|
|
adapter.release(ref);
|
|
expect(
|
|
(
|
|
await adapter.readRange({
|
|
ref,
|
|
offset: asByteCount(0),
|
|
length: asByteCount(1),
|
|
signal: new AbortController().signal,
|
|
})
|
|
).ok,
|
|
).toBe(false);
|
|
});
|
|
|
|
it("keeps the optional backend upload example resumable and quarantined", async () => {
|
|
const adapter = new MemoryExampleQuarantinedUploadAdapter(
|
|
asByteCount(16),
|
|
asByteCount(4),
|
|
() => Date.parse("2026-07-27T00:00:00.000Z"),
|
|
);
|
|
const signal = new AbortController().signal;
|
|
const created = await adapter.create({
|
|
purpose: "avatar",
|
|
byteLength: asByteCount(4),
|
|
detectedMediaType: "image/png",
|
|
signal,
|
|
});
|
|
expect(created.ok).toBe(true);
|
|
if (!created.ok) return;
|
|
|
|
const part = await adapter.uploadPart({
|
|
sessionId: created.value.sessionId,
|
|
partNumber: 1,
|
|
offset: asByteCount(0),
|
|
bytes: new Uint8Array([1, 2, 3, 4]),
|
|
checksumSha256: "part-checksum",
|
|
idempotencyKey: "part-one-attempt",
|
|
signal,
|
|
});
|
|
expect(part.ok).toBe(true);
|
|
const replay = await adapter.uploadPart({
|
|
sessionId: created.value.sessionId,
|
|
partNumber: 1,
|
|
offset: asByteCount(0),
|
|
bytes: new Uint8Array([1, 2, 3, 4]),
|
|
checksumSha256: "part-checksum",
|
|
idempotencyKey: "part-one-attempt",
|
|
signal,
|
|
});
|
|
expect(replay).toEqual(part);
|
|
expect(
|
|
await adapter.uploadPart({
|
|
sessionId: created.value.sessionId,
|
|
partNumber: 1,
|
|
offset: asByteCount(0),
|
|
bytes: new Uint8Array([9, 9, 9, 9]),
|
|
checksumSha256: "different-request-body",
|
|
idempotencyKey: "part-one-attempt",
|
|
signal,
|
|
}),
|
|
).toMatchObject({ ok: false, failure: { code: "CONFLICT" } });
|
|
if (!part.ok) return;
|
|
expect(
|
|
await adapter.complete({
|
|
sessionId: created.value.sessionId,
|
|
parts: [part.value],
|
|
signal,
|
|
}),
|
|
).toMatchObject({
|
|
ok: true,
|
|
value: { state: "QUARANTINED" },
|
|
});
|
|
});
|
|
|
|
// [0929] 05-03. The fakes the catalog names for a runtime port implement
|
|
// that `src` port, not a recipe copy of it.
|
|
it("fakes the src runtime ports themselves", () => {
|
|
expectTypeOf<MemoryFileSelectionAdapter>().toMatchTypeOf<
|
|
FilePickerPort & FileContentPort
|
|
>();
|
|
expectTypeOf<MemoryTransientPreviewAdapter>().toMatchTypeOf<TransientPreviewPort>();
|
|
expectTypeOf<RecordingDownloadDeliveryAdapter>().toMatchTypeOf<DownloadDeliveryPort>();
|
|
expectTypeOf<MemoryStorageDurabilityAdapter>().toMatchTypeOf<StorageDurabilityPort>();
|
|
expectTypeOf<MemoryDurableObjectStore>().toMatchTypeOf<
|
|
DurableObjectStorePort & DurableObjectMaintenancePort
|
|
>();
|
|
});
|
|
|
|
it("keeps each browser technology independently composable", () => {
|
|
expectTypeOf<keyof BrowserFileComposition>().toEqualTypeOf<
|
|
"picker" | "content" | "previews" | "downloads"
|
|
>();
|
|
expectTypeOf<
|
|
keyof StructuredOfflineStorageComposition<unknown>
|
|
>().toEqualTypeOf<"store" | "maintenance">();
|
|
expectTypeOf<
|
|
keyof StorageDurabilityComposition
|
|
>().toEqualTypeOf<"durability">();
|
|
expectTypeOf<
|
|
keyof DurableObjectStorageComposition
|
|
>().toEqualTypeOf<"store" | "maintenance">();
|
|
expectTypeOf<
|
|
keyof PublicResponseCacheComposition
|
|
>().toEqualTypeOf<"cache">();
|
|
expectTypeOf<
|
|
keyof ExampleBackendUploadComposition
|
|
>().toEqualTypeOf<"upload">();
|
|
expectTypeOf<
|
|
BrowserPersistencePolicy["logoutAction"]
|
|
>().toEqualTypeOf<
|
|
"KEEP_ORIGIN_SHARED" | "PURGE_PARTITION" | "EXPORT_THEN_PURGE"
|
|
>();
|
|
expectTypeOf<
|
|
BrowserPersistencePolicy["accountDeletionAction"]
|
|
>().toEqualTypeOf<"KEEP_ORIGIN_SHARED" | "PURGE_PARTITION">();
|
|
expectTypeOf<
|
|
BrowserPersistencePolicy["pressureAction"]
|
|
>().toEqualTypeOf<"EVICT_RECONSTRUCTABLE" | "RETAIN">();
|
|
});
|
|
|
|
it("distinguishes browser handoff from a verified streamed save", async () => {
|
|
const browserPolicy = browserFilePolicyReference(
|
|
"reports",
|
|
"browser-managed-pdf",
|
|
);
|
|
const streamPolicy = browserFilePolicyReference(
|
|
"exports",
|
|
"stream-text",
|
|
);
|
|
const policies = new MemoryBrowserFilePolicyRegistry([
|
|
{
|
|
reference: browserPolicy,
|
|
download: {
|
|
strategy: "BROWSER_MANAGED",
|
|
mediaType: "application/pdf",
|
|
safeExtension: ".pdf",
|
|
maxTransferBytes: asByteCount(10),
|
|
maxBufferedBytes: asByteCount(10),
|
|
integrity: "OPTIONAL",
|
|
},
|
|
},
|
|
{
|
|
reference: streamPolicy,
|
|
download: {
|
|
strategy: "PROMPT_AND_STREAM",
|
|
mediaType: "text/plain",
|
|
safeExtension: ".txt",
|
|
maxTransferBytes: asByteCount(10),
|
|
maxBufferedBytes: asByteCount(10),
|
|
integrity: "REQUIRED",
|
|
},
|
|
},
|
|
]);
|
|
const capabilityReceipt =
|
|
asBrowserManagedDownloadCapabilityReceipt(
|
|
"capability:report",
|
|
);
|
|
const adapter = new RecordingDownloadDeliveryAdapter(
|
|
policies,
|
|
{
|
|
resolve(input) {
|
|
return {
|
|
ok: true,
|
|
value: {
|
|
capabilityReceipt,
|
|
href: "/downloads/report",
|
|
resourceId: input.resourceId,
|
|
mediaType: "application/pdf",
|
|
safeExtension: ".pdf",
|
|
maxBytes: asByteCount(10),
|
|
expiresAtEpochMs: 2_000,
|
|
},
|
|
};
|
|
},
|
|
},
|
|
() => 1_000,
|
|
);
|
|
const progress: number[] = [];
|
|
expect(sanitizeDownloadFileName("../CON\u202e.exe")).toBe("download.bin");
|
|
|
|
const handedOff = await adapter.deliver({
|
|
policy: browserPolicy,
|
|
source: {
|
|
kind: "BROWSER_MANAGED_RESOURCE",
|
|
resourceId: "opaque-resource",
|
|
capabilityReceipt,
|
|
},
|
|
suggestedFileName: "report.pdf",
|
|
maxTransferBytes: asByteCount(10),
|
|
maxBufferedBytes: asByteCount(10),
|
|
signal: new AbortController().signal,
|
|
onProgress() {},
|
|
});
|
|
expect(handedOff).toMatchObject({
|
|
ok: true,
|
|
value: { kind: "BROWSER_HANDOFF" },
|
|
});
|
|
expect(
|
|
await adapter.deliver({
|
|
policy: browserPolicy,
|
|
source: {
|
|
kind: "BROWSER_MANAGED_RESOURCE",
|
|
resourceId: "opaque-resource",
|
|
capabilityReceipt:
|
|
asBrowserManagedDownloadCapabilityReceipt(
|
|
"capability:forged",
|
|
),
|
|
},
|
|
suggestedFileName: "report.pdf",
|
|
signal: new AbortController().signal,
|
|
onProgress() {},
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "POLICY_REJECTED", operation: "DOWNLOAD" },
|
|
});
|
|
|
|
const saved = await adapter.deliver({
|
|
policy: streamPolicy,
|
|
source: {
|
|
kind: "GENERATED",
|
|
bytes: {
|
|
byteLength: asByteCount(4),
|
|
stream: () => byteChunks("ab", "cd"),
|
|
},
|
|
expectedSha256:
|
|
"88d4266fd4e6338d13b845fcf289579d209c897823b9217da3e161936f031589",
|
|
},
|
|
suggestedFileName: "safe.txt",
|
|
maxTransferBytes: asByteCount(10),
|
|
maxBufferedBytes: asByteCount(10),
|
|
signal: new AbortController().signal,
|
|
onProgress(value) {
|
|
progress.push(value.transferredBytes);
|
|
},
|
|
});
|
|
expect(saved).toMatchObject({
|
|
ok: true,
|
|
value: {
|
|
kind: "SAVED",
|
|
bytesWritten: 4,
|
|
integrity: "VERIFIED",
|
|
},
|
|
});
|
|
expect(progress).toEqual([2, 4, 4]);
|
|
});
|
|
|
|
it("commits IndexedDB-like mutations atomically with CAS and idempotency", async () => {
|
|
const store = new MemoryStructuredOfflineStore<{ title: string }>({
|
|
maxBytes: 10_000,
|
|
now: () => 1_000,
|
|
});
|
|
expect(
|
|
(
|
|
await store.open({
|
|
partitionKey: "opaque-account-partition",
|
|
onLifecycle() {},
|
|
})
|
|
).ok,
|
|
).toBe(true);
|
|
const createMutation = {
|
|
kind: "PUT",
|
|
id: "one",
|
|
value: { title: "first" },
|
|
payloadVersion: 1,
|
|
expiresAtEpochMs: null,
|
|
revision: { kind: "MUST_NOT_EXIST" },
|
|
} as const;
|
|
const committed = await store.commit({
|
|
idempotencyKey: "create-one",
|
|
mutations: [createMutation],
|
|
});
|
|
expect(committed).toMatchObject({
|
|
ok: true,
|
|
value: { replayed: false, revisions: { one: 1 } },
|
|
});
|
|
expect(await store.commit({
|
|
idempotencyKey: "create-one",
|
|
mutations: [createMutation],
|
|
})).toMatchObject({ ok: true, value: { replayed: true } });
|
|
expect(
|
|
await store.commit({
|
|
idempotencyKey: "create-one",
|
|
mutations: [
|
|
{
|
|
kind: "DELETE",
|
|
id: "one",
|
|
revision: { kind: "ANY" },
|
|
},
|
|
],
|
|
}),
|
|
).toMatchObject({ ok: false, failure: { code: "CONFLICT" } });
|
|
|
|
const rejectedBatch = await store.commit({
|
|
idempotencyKey: "atomic-conflict",
|
|
mutations: [
|
|
{
|
|
kind: "PUT",
|
|
id: "two",
|
|
value: { title: "must-not-commit" },
|
|
payloadVersion: 1,
|
|
expiresAtEpochMs: null,
|
|
revision: { kind: "MUST_NOT_EXIST" },
|
|
},
|
|
{
|
|
kind: "PUT",
|
|
id: "one",
|
|
value: { title: "stale" },
|
|
payloadVersion: 1,
|
|
expiresAtEpochMs: null,
|
|
revision: { kind: "MATCH", revision: 999 },
|
|
},
|
|
],
|
|
});
|
|
expect(rejectedBatch).toMatchObject({
|
|
ok: false,
|
|
failure: { code: "CONFLICT" },
|
|
});
|
|
expect(await store.read("two")).toEqual({ ok: true, value: null });
|
|
});
|
|
|
|
it("makes quota and persistence downgrade explicit", async () => {
|
|
const store = new MemoryStructuredOfflineStore<{ value: string }>({
|
|
maxBytes: 16,
|
|
});
|
|
await store.open({ partitionKey: "partition", onLifecycle() {} });
|
|
expect(
|
|
await store.commit({
|
|
idempotencyKey: "too-large",
|
|
mutations: [
|
|
{
|
|
kind: "PUT",
|
|
id: "one",
|
|
value: { value: "far larger than the approved storage budget" },
|
|
payloadVersion: 1,
|
|
expiresAtEpochMs: null,
|
|
revision: { kind: "MUST_NOT_EXIST" },
|
|
},
|
|
],
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
failure: { code: "QUOTA_EXCEEDED" },
|
|
});
|
|
|
|
const durability = new MemoryStorageDurabilityAdapter(
|
|
70,
|
|
100,
|
|
"DENIED",
|
|
);
|
|
expect(await durability.inspect()).toMatchObject({
|
|
ok: true,
|
|
value: { pressure: "PRESSURE" },
|
|
});
|
|
expect(
|
|
await durability.requestPersistence({
|
|
reason: "PROTECT_UNSYNCED_USER_DATA",
|
|
userInitiated: true,
|
|
}),
|
|
).toEqual({ ok: true, value: "DENIED" });
|
|
});
|
|
|
|
it("keeps partially written OPFS objects invisible until logical commit", async () => {
|
|
const storagePolicy: BrowserStoragePolicy = {
|
|
owner: "recipe-test",
|
|
namespace: "durable-objects",
|
|
classification: "PERSONAL",
|
|
authority: "LOCAL_FIRST",
|
|
accountScope: "OPAQUE_PARTITION",
|
|
retention: { kind: "EXPLICIT_DELETE" },
|
|
softBudgetBytes: 32,
|
|
hardBudgetBytes: 64,
|
|
evictionPriority: "USER_AUTHORED",
|
|
logoutAction: "EXPORT_THEN_PURGE",
|
|
accountDeletionAction: "PURGE_PARTITION",
|
|
pressureAction: "RETAIN",
|
|
unavailableFallback: "EXPORT_REQUIRED",
|
|
};
|
|
const store = new MemoryDurableObjectStore({
|
|
scope: {
|
|
namespace: "durable-objects",
|
|
authorityToken: "authority_12345678",
|
|
namespaceToken: "namespace_12345678",
|
|
partitionToken: "partition_12345678",
|
|
},
|
|
storagePolicy,
|
|
maxObjectBytes: 32,
|
|
});
|
|
// The recipe brands are still accepted by the runtime port.
|
|
const objectId = asDurableObjectId("object_opaque_0001");
|
|
const source = (...values: ReadonlyArray<string>) => ({
|
|
byteLength: values.join("").length,
|
|
stream: () => byteChunks(...values),
|
|
});
|
|
|
|
store.failNextPutAfter("FILES_READY");
|
|
expect(
|
|
await store.put({
|
|
objectId,
|
|
expectedGeneration: null,
|
|
mediaType: "application/octet-stream",
|
|
source: source("ab", "cd"),
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "UNAVAILABLE", recovery: "RECONCILE" },
|
|
});
|
|
expect(await store.open({ objectId })).toMatchObject({
|
|
ok: false,
|
|
error: { code: "NOT_FOUND" },
|
|
});
|
|
// Like the runtime, reconcile rolls a stopped put back; it never resumes.
|
|
expect(await store.reconcile()).toMatchObject({
|
|
ok: true,
|
|
value: { rolledBackTransactions: 1, moreTransactionsAvailable: false },
|
|
});
|
|
|
|
expect(
|
|
await store.put({
|
|
objectId,
|
|
expectedGeneration: null,
|
|
mediaType: "application/octet-stream",
|
|
source: { byteLength: 4, stream: failedByteChunks },
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "NOT_READABLE", operation: "OBJECT_WRITE" },
|
|
});
|
|
// A put that fails on its own compensates, so nothing is left behind.
|
|
expect(await store.reconcile()).toMatchObject({
|
|
ok: true,
|
|
value: { rolledBackTransactions: 0 },
|
|
});
|
|
|
|
expect(
|
|
await store.put({
|
|
objectId,
|
|
expectedGeneration: null,
|
|
mediaType: "application/octet-stream",
|
|
source: source("abcd"),
|
|
}),
|
|
).toMatchObject({
|
|
ok: true,
|
|
value: {
|
|
objectId,
|
|
generation: 1,
|
|
byteLength: 4,
|
|
integrity: { algorithm: "SHA-256-TREE-V1" },
|
|
},
|
|
});
|
|
const opened = await store.open({ objectId });
|
|
expect(opened.ok).toBe(true);
|
|
if (opened.ok) {
|
|
const bytes: number[] = [];
|
|
for await (const chunk of opened.value.source.stream(
|
|
new AbortController().signal,
|
|
)) {
|
|
expect(chunk.ok).toBe(true);
|
|
if (chunk.ok) bytes.push(...chunk.value);
|
|
}
|
|
expect(new TextDecoder().decode(new Uint8Array(bytes))).toBe("abcd");
|
|
}
|
|
expect(
|
|
await store.remove({
|
|
objectId,
|
|
expectedGeneration: asObjectGeneration(2),
|
|
}),
|
|
).toMatchObject({ ok: false, error: { code: "CONFLICT" } });
|
|
expect(
|
|
await store.enforcePolicies({ reason: "ACCOUNT_DELETION" }),
|
|
).toMatchObject({
|
|
ok: true,
|
|
value: { removedObjects: 1, chunkSweep: "COMPLETED" },
|
|
});
|
|
expect(await store.open({ objectId })).toMatchObject({
|
|
ok: false,
|
|
error: { code: "NOT_FOUND" },
|
|
});
|
|
});
|
|
|
|
it("stages and activates only exact public Cache Storage representations", async () => {
|
|
const cache = new MemoryPublicResponseCache({
|
|
origin: "https://app.example.test",
|
|
maxEntryBytes: 1_000,
|
|
allowedMediaTypes: new Set(["text/javascript"]),
|
|
});
|
|
const entry = {
|
|
url: "https://app.example.test/assets/app.js?v=1#ignored",
|
|
byteLength: asByteCount(100),
|
|
mediaType: "text/javascript",
|
|
integritySha256: "sha256-entry",
|
|
requestCredentials: "OMIT" as const,
|
|
dataClass: "PUBLIC" as const,
|
|
};
|
|
expect(
|
|
await cache.stageRelease({
|
|
releaseId: "release-1",
|
|
manifestDigest: "manifest-1",
|
|
entries: [entry],
|
|
signal: new AbortController().signal,
|
|
}),
|
|
).toEqual({ ok: true, value: undefined });
|
|
expect(
|
|
await cache.activateRelease({
|
|
releaseId: "release-1",
|
|
manifestDigest: "manifest-1",
|
|
expectedPreviousReleaseId: null,
|
|
}),
|
|
).toEqual({ ok: true, value: undefined });
|
|
expect(
|
|
await cache.lookup({
|
|
url: "https://app.example.test/assets/app.js?v=1",
|
|
requestCredentials: "OMIT",
|
|
hasAuthorization: false,
|
|
}),
|
|
).toMatchObject({ ok: true, value: { kind: "HIT" } });
|
|
expect(
|
|
await cache.lookup({
|
|
url: "https://app.example.test/assets/app.js?v=2",
|
|
requestCredentials: "OMIT",
|
|
hasAuthorization: false,
|
|
}),
|
|
).toEqual({
|
|
ok: true,
|
|
value: { kind: "MISS", reason: "NOT_FOUND" },
|
|
});
|
|
expect(
|
|
await cache.stageRelease({
|
|
releaseId: "poisoned",
|
|
manifestDigest: "bad",
|
|
entries: [{ ...entry, url: "https://app.example.test/config.json" }],
|
|
signal: new AbortController().signal,
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
failure: { code: "POLICY_REJECTED" },
|
|
});
|
|
// [0929] 05-03. Reported in the runtime's `PublicCacheInspection` shape.
|
|
expect(await cache.inspect()).toEqual({
|
|
ok: true,
|
|
value: {
|
|
activeReleaseRegistryId: "release-1",
|
|
ownedCacheCount: 1,
|
|
unreadableOwnedCacheCount: 0,
|
|
releaseCandidates: [],
|
|
},
|
|
});
|
|
});
|
|
});
|