문제: `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
459 lines
12 KiB
TypeScript
459 lines
12 KiB
TypeScript
import type { CapabilityResult } from "./contracts.ts";
|
|
import type {
|
|
DownloadDeliveryPort,
|
|
DownloadStrategy,
|
|
DurableObjectMaintenancePort,
|
|
DurableObjectStorePort,
|
|
FileContentPort,
|
|
FilePickerPort,
|
|
FilePolicyReference,
|
|
PersistableDataClass,
|
|
PublicCacheInspection,
|
|
StorageDurabilityPort,
|
|
TransientPreviewPort,
|
|
} from "../../src/application/ports/browser-file-storage/index.ts";
|
|
|
|
/**
|
|
* Deep opt-in contracts for browser file and origin-storage capabilities.
|
|
*
|
|
* These contracts intentionally expose no File, Blob, FileSystemHandle,
|
|
* IDBDatabase, IDBTransaction, Cache, Request or Response. A selected project
|
|
* copies and narrows only the ports that its product actually owns.
|
|
*/
|
|
|
|
/**
|
|
* [0929] 05-03. A port that has a reference runtime under `src/` is not
|
|
* copied here. The copies kept their July shape while the runtime ports moved
|
|
* on, so a fake written against a recipe copy promised behaviour the runtime
|
|
* does not have. These names are the `src/application/ports` types themselves.
|
|
* Removing that runtime removes this file and its fakes with it
|
|
* (`scripts/test-browser-file-storage-runtime-removal.ts`).
|
|
*/
|
|
export type {
|
|
BrowserManagedDownloadCapability,
|
|
BrowserManagedDownloadCapabilityReceipt,
|
|
BrowserManagedDownloadCapabilityResolver,
|
|
DownloadDeliveryPort,
|
|
DownloadOutcome,
|
|
DownloadSource,
|
|
DownloadStrategy,
|
|
DurableObjectDescriptor,
|
|
DurableObjectMaintenancePort,
|
|
DurableObjectStorePort,
|
|
FileByteSource,
|
|
FileCandidate,
|
|
FileContentPort,
|
|
FileInspection,
|
|
FilePickerPort,
|
|
FilePickerSupport,
|
|
FilePolicyIntention,
|
|
FilePolicyKey,
|
|
FilePolicyReference,
|
|
FileSelectionLimitReduction,
|
|
FileSelectionOutcome,
|
|
FileSelectionSource,
|
|
FileSignatureResult,
|
|
FileVerificationReceipt,
|
|
LocalFileRef,
|
|
PersistableDataClass,
|
|
PreviewLease,
|
|
PublicCacheInspection,
|
|
StorageDurabilityPort,
|
|
StorageEstimate,
|
|
TransferProgress,
|
|
TransientPreviewPort,
|
|
} from "../../src/application/ports/browser-file-storage/index.ts";
|
|
export type {
|
|
AuthorizedDownloadCapability,
|
|
AuthorizedDownloadCapabilityReceipt,
|
|
} from "../../src/application/ports/browser-transfer/index.ts";
|
|
|
|
declare const byteCountBrand: unique symbol;
|
|
declare const objectIdBrand: unique symbol;
|
|
declare const objectGenerationBrand: unique symbol;
|
|
|
|
export type ByteCount = number & {
|
|
readonly [byteCountBrand]: "ByteCount";
|
|
};
|
|
|
|
/**
|
|
* Recipe-only brands for a durable object's id and generation. The runtime
|
|
* port takes plain values; a branded one is still accepted there.
|
|
*/
|
|
export type DurableObjectId = string & {
|
|
readonly [objectIdBrand]: "DurableObjectId";
|
|
};
|
|
|
|
export type ObjectGeneration = number & {
|
|
readonly [objectGenerationBrand]: "ObjectGeneration";
|
|
};
|
|
|
|
export type FileAcceptRule = Readonly<{
|
|
mediaType: string;
|
|
extensions: ReadonlyArray<string>;
|
|
}>;
|
|
|
|
export type FileSelectionPolicy = Readonly<{
|
|
policyId: string;
|
|
purpose: string;
|
|
classification: PersistableDataClass;
|
|
multiple: boolean;
|
|
maxCount: number;
|
|
maxFileBytes: ByteCount;
|
|
maxTotalBytes: ByteCount;
|
|
allowEmpty: boolean;
|
|
accept: ReadonlyArray<FileAcceptRule>;
|
|
}>;
|
|
|
|
export type FileBytePattern = Readonly<{
|
|
offset: ByteCount;
|
|
bytes: ReadonlyArray<number>;
|
|
mask?: ReadonlyArray<number>;
|
|
}>;
|
|
|
|
export type FileSignatureRule = Readonly<{
|
|
mediaType: string;
|
|
extensions: ReadonlyArray<string>;
|
|
patterns: ReadonlyArray<FileBytePattern>;
|
|
}>;
|
|
|
|
export type FileInspectionPolicy = Readonly<{
|
|
policyId: string;
|
|
maxInspectionBytes: ByteCount;
|
|
acceptedSignatures: ReadonlyArray<FileSignatureRule>;
|
|
}>;
|
|
|
|
/**
|
|
* Feature/backend workflow example, not a browser capability dependency.
|
|
* Copy it only when the backend owns authorization, resumable-session expiry,
|
|
* integrity verification, content inspection and quarantine promotion.
|
|
*/
|
|
export type ExampleUploadSession = Readonly<{
|
|
sessionId: string;
|
|
partSizeBytes: ByteCount;
|
|
maxConcurrency: number;
|
|
expiresAt: string;
|
|
checksumAlgorithm: "SHA-256";
|
|
}>;
|
|
|
|
export type ExampleUploadPartReceipt = Readonly<{
|
|
partNumber: number;
|
|
acceptedBytes: ByteCount;
|
|
checksumSha256: string;
|
|
}>;
|
|
|
|
export type ExampleQuarantinedUpload = Readonly<{
|
|
resourceId: string;
|
|
state: "QUARANTINED";
|
|
}>;
|
|
|
|
export interface ExampleQuarantinedUploadPort {
|
|
create(input: {
|
|
purpose: string;
|
|
byteLength: ByteCount;
|
|
detectedMediaType: string;
|
|
signal: AbortSignal;
|
|
}): Promise<CapabilityResult<ExampleUploadSession>>;
|
|
|
|
uploadPart(input: {
|
|
sessionId: string;
|
|
partNumber: number;
|
|
offset: ByteCount;
|
|
bytes: Uint8Array;
|
|
checksumSha256: string;
|
|
idempotencyKey: string;
|
|
signal: AbortSignal;
|
|
}): Promise<CapabilityResult<ExampleUploadPartReceipt>>;
|
|
|
|
complete(input: {
|
|
sessionId: string;
|
|
parts: ReadonlyArray<ExampleUploadPartReceipt>;
|
|
signal: AbortSignal;
|
|
}): Promise<CapabilityResult<ExampleQuarantinedUpload>>;
|
|
|
|
abort(
|
|
sessionId: string,
|
|
signal?: AbortSignal,
|
|
): Promise<CapabilityResult<void>>;
|
|
}
|
|
|
|
export type RegisteredPreviewPolicy = Readonly<{
|
|
allowedMediaTypes: ReadonlyArray<string>;
|
|
maxPreviewBytes: ByteCount;
|
|
}>;
|
|
|
|
export type RegisteredDownloadPolicy = Readonly<{
|
|
strategy: DownloadStrategy;
|
|
mediaType: string;
|
|
safeExtension: string;
|
|
maxTransferBytes: ByteCount;
|
|
maxBufferedBytes: ByteCount;
|
|
integrity: "OPTIONAL" | "REQUIRED";
|
|
}>;
|
|
|
|
/**
|
|
* Dataset policy belongs at composition. Feature and presentation callers
|
|
* receive only the reference plus optional reductions.
|
|
*/
|
|
export type BrowserFilePolicyProfile = Readonly<{
|
|
reference: FilePolicyReference;
|
|
selection?: FileSelectionPolicy;
|
|
inspection?: FileInspectionPolicy;
|
|
preview?: RegisteredPreviewPolicy;
|
|
download?: RegisteredDownloadPolicy;
|
|
}>;
|
|
|
|
export type BrowserPersistencePolicy = Readonly<{
|
|
owner: string;
|
|
namespace: string;
|
|
classification: PersistableDataClass;
|
|
authority: "SERVER" | "LOCAL_FIRST" | "RECONSTRUCTABLE";
|
|
accountScope: "ORIGIN_SHARED" | "OPAQUE_PARTITION";
|
|
retention:
|
|
| Readonly<{ kind: "SESSION" }>
|
|
| Readonly<{ kind: "TTL"; maxAgeMs: number }>
|
|
| Readonly<{ kind: "UNTIL_SYNCED" }>
|
|
| Readonly<{ kind: "EXPLICIT_DELETE" }>;
|
|
softBudgetBytes: ByteCount;
|
|
hardBudgetBytes: ByteCount;
|
|
evictionPriority: "RECONSTRUCTABLE" | "SYNCED_COPY" | "USER_AUTHORED";
|
|
logoutAction:
|
|
| "KEEP_ORIGIN_SHARED"
|
|
| "PURGE_PARTITION"
|
|
| "EXPORT_THEN_PURGE";
|
|
accountDeletionAction: "KEEP_ORIGIN_SHARED" | "PURGE_PARTITION";
|
|
pressureAction: "EVICT_RECONSTRUCTABLE" | "RETAIN";
|
|
unavailableFallback: "ONLINE_ONLY" | "READ_ONLY" | "EXPORT_REQUIRED";
|
|
}>;
|
|
|
|
export type OfflineStoreStatus =
|
|
| Readonly<{
|
|
kind: "READY";
|
|
persistence: "BEST_EFFORT" | "PERSISTENT";
|
|
}>
|
|
| Readonly<{
|
|
kind: "READ_ONLY";
|
|
reason: "FUTURE_SCHEMA" | "QUOTA" | "RECOVERY";
|
|
}>
|
|
| Readonly<{
|
|
kind: "ONLINE_ONLY";
|
|
reason: "UNAVAILABLE" | "MIGRATION_FAILED";
|
|
}>
|
|
| Readonly<{
|
|
kind: "UPGRADE_BLOCKED";
|
|
targetVersion: number;
|
|
}>
|
|
| Readonly<{
|
|
kind: "CLOSED";
|
|
reason: "VERSION_CHANGE" | "FORCED" | "DISPOSED";
|
|
}>;
|
|
|
|
export type OfflineStoreLifecycleEvent =
|
|
| Readonly<{ kind: "STATUS_CHANGED"; status: OfflineStoreStatus }>
|
|
| Readonly<{
|
|
kind: "MIGRATION_PROGRESS";
|
|
migrationId: string;
|
|
processedCount: number;
|
|
remainingEstimate: number | null;
|
|
}>;
|
|
|
|
export type StoredRecord<T> = Readonly<{
|
|
id: string;
|
|
revision: number;
|
|
payloadVersion: number;
|
|
createdAtEpochMs: number;
|
|
updatedAtEpochMs: number;
|
|
expiresAtEpochMs: number | null;
|
|
value: T;
|
|
}>;
|
|
|
|
export type RevisionGuard =
|
|
| Readonly<{ kind: "ANY" }>
|
|
| Readonly<{ kind: "MUST_NOT_EXIST" }>
|
|
| Readonly<{ kind: "MATCH"; revision: number }>;
|
|
|
|
export type StructuredOfflineMutation<T> =
|
|
| Readonly<{
|
|
kind: "PUT";
|
|
id: string;
|
|
value: T;
|
|
payloadVersion: number;
|
|
expiresAtEpochMs: number | null;
|
|
revision: RevisionGuard;
|
|
}>
|
|
| Readonly<{
|
|
kind: "DELETE";
|
|
id: string;
|
|
revision: RevisionGuard;
|
|
}>;
|
|
|
|
export type OfflineCommitReceipt = Readonly<{
|
|
commitId: string;
|
|
revisions: Readonly<Record<string, number | null>>;
|
|
replayed: boolean;
|
|
}>;
|
|
|
|
export type OfflinePage<T> = Readonly<{
|
|
records: ReadonlyArray<StoredRecord<T>>;
|
|
nextCursor: string | null;
|
|
}>;
|
|
|
|
/**
|
|
* Copy this as a feature-specific repository. Do not expose a generic
|
|
* transaction callback, object-store name, index name or schema version.
|
|
*/
|
|
export interface StructuredOfflineStore<T> {
|
|
open(input: {
|
|
partitionKey: string;
|
|
signal?: AbortSignal;
|
|
onLifecycle(event: OfflineStoreLifecycleEvent): void;
|
|
}): Promise<CapabilityResult<OfflineStoreStatus>>;
|
|
|
|
read(
|
|
id: string,
|
|
signal?: AbortSignal,
|
|
): Promise<CapabilityResult<StoredRecord<T> | null>>;
|
|
|
|
page(input: {
|
|
cursor?: string;
|
|
limit: number;
|
|
includeExpired?: boolean;
|
|
signal?: AbortSignal;
|
|
}): Promise<CapabilityResult<OfflinePage<T>>>;
|
|
|
|
commit(input: {
|
|
idempotencyKey: string;
|
|
mutations: ReadonlyArray<StructuredOfflineMutation<T>>;
|
|
signal?: AbortSignal;
|
|
}): Promise<CapabilityResult<OfflineCommitReceipt>>;
|
|
|
|
clearPartition(input: {
|
|
reason: "LOGOUT" | "ACCOUNT_DELETION" | "USER_REQUEST";
|
|
signal?: AbortSignal;
|
|
}): Promise<CapabilityResult<void>>;
|
|
|
|
status(): OfflineStoreStatus;
|
|
close(): void;
|
|
}
|
|
|
|
export type MigrationProgress = Readonly<{
|
|
migrationId: string;
|
|
state: "PENDING" | "RUNNING" | "COMPLETED" | "FAILED";
|
|
processedCount: number;
|
|
remainingEstimate: number | null;
|
|
}>;
|
|
|
|
export interface OfflineStoreMaintenancePort {
|
|
resumeDataMigration(input: {
|
|
migrationId: string;
|
|
maxRecords: number;
|
|
timeBudgetMs: number;
|
|
signal?: AbortSignal;
|
|
}): Promise<CapabilityResult<MigrationProgress>>;
|
|
|
|
purgeExpired(input: {
|
|
maxRecords: number;
|
|
nowEpochMs: number;
|
|
signal?: AbortSignal;
|
|
}): Promise<CapabilityResult<Readonly<{ purgedCount: number }>>>;
|
|
}
|
|
|
|
export type PublicAssetEntry = Readonly<{
|
|
url: string;
|
|
byteLength: ByteCount;
|
|
mediaType: string;
|
|
integritySha256: string;
|
|
requestCredentials: "OMIT";
|
|
dataClass: "PUBLIC";
|
|
}>;
|
|
|
|
export type PublicCacheLookup =
|
|
| Readonly<{
|
|
kind: "HIT";
|
|
releaseId: string;
|
|
entry: PublicAssetEntry;
|
|
}>
|
|
| Readonly<{
|
|
kind: "MISS";
|
|
reason:
|
|
| "NOT_FOUND"
|
|
| "EXPIRED"
|
|
| "NO_ACTIVE_RELEASE"
|
|
| "POLICY_REJECTED";
|
|
}>;
|
|
|
|
/**
|
|
* Platform-local Cache Storage policy facade. Raw Request/Response/Cache
|
|
* objects remain inside the adapter, and no application repository imports it.
|
|
*/
|
|
export interface PublicResponseCacheAdmin {
|
|
stageRelease(input: {
|
|
releaseId: string;
|
|
manifestDigest: string;
|
|
entries: ReadonlyArray<PublicAssetEntry>;
|
|
signal: AbortSignal;
|
|
}): Promise<CapabilityResult<void>>;
|
|
|
|
activateRelease(input: {
|
|
releaseId: string;
|
|
manifestDigest: string;
|
|
expectedPreviousReleaseId: string | null;
|
|
signal?: AbortSignal;
|
|
}): Promise<CapabilityResult<void>>;
|
|
|
|
lookup(input: {
|
|
url: string;
|
|
requestCredentials: "OMIT";
|
|
hasAuthorization: false;
|
|
signal?: AbortSignal;
|
|
}): Promise<CapabilityResult<PublicCacheLookup>>;
|
|
|
|
/**
|
|
* [0929] 05-03. Reports in the runtime's `PublicCacheInspection` shape;
|
|
* the recipe kept a same-named copy with other fields.
|
|
*/
|
|
inspect(signal?: AbortSignal): Promise<
|
|
CapabilityResult<PublicCacheInspection>
|
|
>;
|
|
|
|
rollback(signal?: AbortSignal): Promise<CapabilityResult<void>>;
|
|
|
|
deleteOwned(input: {
|
|
roles: ReadonlyArray<"CANDIDATE" | "PREVIOUS" | "RUNTIME_PUBLIC">;
|
|
signal?: AbortSignal;
|
|
}): Promise<CapabilityResult<Readonly<{ deletedCount: number }>>>;
|
|
}
|
|
|
|
export type BrowserFileComposition = Readonly<{
|
|
picker: FilePickerPort;
|
|
content: FileContentPort;
|
|
previews: TransientPreviewPort;
|
|
downloads: DownloadDeliveryPort;
|
|
}>;
|
|
|
|
export type StructuredOfflineStorageComposition<T> = Readonly<{
|
|
store: StructuredOfflineStore<T>;
|
|
maintenance: OfflineStoreMaintenancePort;
|
|
}>;
|
|
|
|
export type StorageDurabilityComposition = Readonly<{
|
|
durability: StorageDurabilityPort;
|
|
}>;
|
|
|
|
export type DurableObjectStorageComposition = Readonly<{
|
|
store: DurableObjectStorePort;
|
|
maintenance: DurableObjectMaintenancePort;
|
|
}>;
|
|
|
|
export type PublicResponseCacheComposition = Readonly<{
|
|
cache: PublicResponseCacheAdmin;
|
|
}>;
|
|
|
|
/**
|
|
* Explicitly separate from BrowserFileComposition: installing file selection,
|
|
* preview or download must never imply a resumable backend upload protocol.
|
|
*/
|
|
export type ExampleBackendUploadComposition = Readonly<{
|
|
upload: ExampleQuarantinedUploadPort;
|
|
}>;
|