Files
clean-architecture-frontend…/src/application/ports/browser-file-storage/shared.ts
T
DongHyeonkaandClaude Opus 5.5 d76653bfcd fix(browser-files): observe dismissals as DISMISSED instead of SUCCEEDED (02-06)
A cancelled save dialog and a browser handoff were both recorded as
DOWNLOAD SUCCEEDED, so the cancel rate hid inside the handoff success rate.
BrowserDataObservation.outcome gains DISMISSED (additive).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 00:20:17 +09:00

295 lines
8.6 KiB
TypeScript

import type { Result } from "../../result.ts";
/**
* STO-RR-03. The runtime membership set behind the closed failure taxonomy. A
* boundary decoder needs to test a value against it, and a type alone cannot
* stop an arbitrary string from reaching application code.
*/
export const BROWSER_DATA_FAILURE_CODES = Object.freeze([
"ABORTED",
"BLOCKED",
"CONFLICT",
"CORRUPT_DATA",
"EXPIRED_RESOURCE",
"INTEGRITY_FAILED",
"INVALID_INPUT",
"LIMIT_EXCEEDED",
"MIGRATION_FAILED",
"NOT_FOUND",
"NOT_READABLE",
"PERMISSION_DENIED",
"POLICY_REJECTED",
"QUOTA_EXCEEDED",
"STALE_RESULT",
"STORAGE_EVICTED",
"UNAVAILABLE",
"UNSUPPORTED",
] as const);
export function isBrowserDataFailureCode(
value: unknown,
): value is BrowserDataFailureCode {
return (
typeof value === "string" &&
(BROWSER_DATA_FAILURE_CODES as readonly string[]).includes(value)
);
}
export type BrowserDataFailureCode =
(typeof BROWSER_DATA_FAILURE_CODES)[number];
export type BrowserDataOperation =
| "CACHE_ACTIVATE"
| "CACHE_DELETE"
| "CACHE_LOOKUP"
| "CACHE_STAGE"
| "DOWNLOAD"
| "FILE_INSPECT"
| "FILE_READ"
| "FILE_SELECT"
| "IMAGE_RESOLVE"
| "INDEXEDDB_MIGRATE"
| "INDEXEDDB_OPEN"
| "INDEXEDDB_READ"
| "INDEXEDDB_WRITE"
| "OBJECT_DELETE"
| "OBJECT_READ"
| "OBJECT_RECONCILE"
| "OBJECT_WRITE"
| "PRESIGNED_TRANSFER"
| "PREVIEW"
| "STORAGE_ESTIMATE"
| "STORAGE_PERSIST"
| "UPLOAD_ABORT"
| "UPLOAD_COMPLETE"
| "UPLOAD_PART"
| "UPLOAD_RECONCILE"
| "UPLOAD_SESSION";
export type BrowserDataRecovery =
| "NONE"
| "RETRY"
| "REOPEN"
| "RESELECT"
| "RELOAD_OTHER_CONTEXTS"
| "READ_ONLY"
| "ONLINE_ONLY"
| "REHYDRATE"
| "EXPORT_REQUIRED"
| "REISSUE_CAPABILITY"
| "RESUME"
| "RESTART"
| "RECONCILE";
/**
* Closed, telemetry-safe failure. Native exception messages, paths, record
* keys, URLs, file names and data values must not cross the adapter boundary.
*/
export type BrowserDataFailure = Readonly<{
code: BrowserDataFailureCode;
operation: BrowserDataOperation;
retryable: boolean;
recovery: BrowserDataRecovery;
}>;
export type BrowserDataResult<Value> = Result<Value, BrowserDataFailure>;
export type BrowserDataObservation = Readonly<{
operation: BrowserDataOperation;
/** `DISMISSED`: the user closed a picker or save dialog; not a failure. */
outcome: "SUCCEEDED" | "FAILED" | "DEGRADED" | "DISMISSED";
failureCode?: BrowserDataFailureCode;
durationBucket?: "LT100MS" | "100_TO_499MS" | "500_TO_1999MS" | "GTE2000MS";
byteBucket?: "ZERO" | "LT1MIB" | "1_TO_9MIB" | "10_TO_99MIB" | "GTE100MIB";
countBucket?: "ZERO" | "ONE" | "TWO_TO_TEN" | "ELEVEN_TO_HUNDRED" | "GT_HUNDRED";
}>;
export interface BrowserDataObserver {
record(observation: BrowserDataObservation): void;
}
export type TransferProgress = Readonly<{
phase:
| "VALIDATING"
| "PREPARING"
| "TRANSFERRING"
| "VERIFYING"
| "FINALIZING";
transferredBytes: number;
totalBytes: number | null;
}>;
/**
* Technology-neutral byte stream. Implementations must validate every emitted
* chunk, honor AbortSignal between chunks and close native/runtime failures
* into BrowserDataResult. A consumer must stop after the first failed chunk.
*/
export interface ByteSource {
readonly byteLength: number | null;
stream(
signal: AbortSignal,
): AsyncIterable<BrowserDataResult<Uint8Array>>;
}
export type PersistableDataClass =
| "PUBLIC"
| "INTERNAL"
| "PERSONAL"
| "CONFIDENTIAL";
export type BrowserDataAuthority =
| "SERVER"
| "LOCAL_FIRST"
| "RECONSTRUCTABLE";
export type BrowserAccountScope =
| "ORIGIN_SHARED"
| "OPAQUE_PARTITION";
export type BrowserLogoutAction =
| "KEEP_ORIGIN_SHARED"
| "PURGE_PARTITION"
| "EXPORT_THEN_PURGE";
export type BrowserAccountDeletionAction =
| "KEEP_ORIGIN_SHARED"
| "PURGE_PARTITION";
export type BrowserPressureAction =
| "EVICT_RECONSTRUCTABLE"
| "RETAIN";
export type BrowserStoragePolicy = Readonly<{
/** Governance owner/team identifier, never an account or user ID. */
owner: string;
namespace: string;
classification: PersistableDataClass;
authority: BrowserDataAuthority;
accountScope: BrowserAccountScope;
retention:
| Readonly<{ kind: "SESSION" }>
| Readonly<{ kind: "TTL"; maxAgeMs: number }>
| Readonly<{ kind: "UNTIL_SYNCED" }>
| Readonly<{ kind: "EXPLICIT_DELETE" }>;
softBudgetBytes: number;
hardBudgetBytes: number;
evictionPriority: "RECONSTRUCTABLE" | "SYNCED_COPY" | "USER_AUTHORED";
logoutAction: BrowserLogoutAction;
accountDeletionAction: BrowserAccountDeletionAction;
pressureAction: BrowserPressureAction;
unavailableFallback: "ONLINE_ONLY" | "READ_ONLY" | "EXPORT_REQUIRED";
}>;
export function isValidByteLength(value: number): boolean {
return Number.isSafeInteger(value) && value >= 0;
}
export function isNonNegativeSafeInteger(value: unknown): value is number {
return Number.isSafeInteger(value) && (value as number) >= 0;
}
/** True when `value` carries a C0 control character or DEL. */
export function hasControlCharacter(value: string): boolean {
return [...value].some((character) => {
const codePoint = character.codePointAt(0) ?? 0;
return codePoint < 0x20 || codePoint === 0x7f;
});
}
export function isPositiveSafeInteger(value: unknown): value is number {
return Number.isSafeInteger(value) && (value as number) > 0;
}
/**
* The observation bucket for a byte length. An absent, fractional, negative or
* unsafe length has no bucket, so an observation never reports a guessed size.
*/
export function browserDataByteBucket(
byteLength: number | null | undefined,
): BrowserDataObservation["byteBucket"] {
if (
byteLength === null ||
byteLength === undefined ||
!isValidByteLength(byteLength)
) {
return undefined;
}
if (byteLength === 0) return "ZERO";
if (byteLength < 1_048_576) return "LT1MIB";
if (byteLength < 10_485_760) return "1_TO_9MIB";
if (byteLength < 104_857_600) return "10_TO_99MIB";
return "GTE100MIB";
}
export function assertValidStoragePolicy(
policy: BrowserStoragePolicy,
): void {
const safeRegistryIdentifier =
/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
if (
!policy ||
typeof policy !== "object" ||
typeof policy.owner !== "string" ||
!safeRegistryIdentifier.test(policy.owner) ||
typeof policy.namespace !== "string" ||
!safeRegistryIdentifier.test(policy.namespace) ||
!["PUBLIC", "INTERNAL", "PERSONAL", "CONFIDENTIAL"].includes(
policy.classification,
) ||
!["SERVER", "LOCAL_FIRST", "RECONSTRUCTABLE"].includes(
policy.authority,
) ||
!["ORIGIN_SHARED", "OPAQUE_PARTITION"].includes(
policy.accountScope,
) ||
!policy.retention ||
typeof policy.retention !== "object" ||
!["SESSION", "TTL", "UNTIL_SYNCED", "EXPLICIT_DELETE"].includes(
policy.retention.kind,
) ||
!isValidByteLength(policy.softBudgetBytes) ||
!isValidByteLength(policy.hardBudgetBytes) ||
policy.hardBudgetBytes === 0 ||
policy.softBudgetBytes > policy.hardBudgetBytes ||
!["RECONSTRUCTABLE", "SYNCED_COPY", "USER_AUTHORED"].includes(
policy.evictionPriority,
) ||
![
"KEEP_ORIGIN_SHARED",
"PURGE_PARTITION",
"EXPORT_THEN_PURGE",
].includes(policy.logoutAction) ||
!["KEEP_ORIGIN_SHARED", "PURGE_PARTITION"].includes(
policy.accountDeletionAction,
) ||
!["EVICT_RECONSTRUCTABLE", "RETAIN"].includes(
policy.pressureAction,
) ||
!["ONLINE_ONLY", "READ_ONLY", "EXPORT_REQUIRED"].includes(
policy.unavailableFallback,
) ||
(policy.retention.kind === "TTL" &&
(!Number.isSafeInteger(policy.retention.maxAgeMs) ||
policy.retention.maxAgeMs < 1)) ||
(policy.accountScope === "ORIGIN_SHARED" &&
(policy.logoutAction !== "KEEP_ORIGIN_SHARED" ||
policy.accountDeletionAction !== "KEEP_ORIGIN_SHARED")) ||
(policy.accountScope === "OPAQUE_PARTITION" &&
(policy.logoutAction === "KEEP_ORIGIN_SHARED" ||
policy.accountDeletionAction !== "PURGE_PARTITION")) ||
(["PERSONAL", "CONFIDENTIAL"].includes(policy.classification) &&
policy.accountScope !== "OPAQUE_PARTITION") ||
(policy.accountScope === "OPAQUE_PARTITION" &&
(policy.retention.kind === "UNTIL_SYNCED" ||
(policy.authority === "LOCAL_FIRST" &&
policy.unavailableFallback === "EXPORT_REQUIRED")) &&
policy.logoutAction !== "EXPORT_THEN_PURGE") ||
(policy.pressureAction === "EVICT_RECONSTRUCTABLE" &&
(policy.authority !== "RECONSTRUCTABLE" ||
policy.evictionPriority !== "RECONSTRUCTABLE" ||
policy.retention.kind === "EXPLICIT_DELETE"))
) {
throw new TypeError("Browser storage policy is invalid.");
}
}