fix(browser-transfer): upload 실패 번역이 code도 보고 행동을 고른다 (0929/01-01)

문제: 포트는 upload() 실패의 recovery가 호출자 행동 하나를 가리킨다고
적는다. 번역은 toUploadAction 한 곳이 하는데 recovery 단어만 본다. 표
밖 값이면 REISSUE_CAPABILITY·RETRY만 RESUME, 나머지는 NONE으로 바꾸고
retryable은 그대로 둔다. 그래서 지난 리뷰 실험 X1의 경로들이 표와 다른
행동을 가리킨다.
- ① 고른 파일이 바뀜(NOT_READABLE/REOPEN): NONE에 retryable:true.
  표대로면 RESELECT다.
- ② IndexedDB 일시 오류(UNAVAILABLE/REOPEN, retryable:true): NONE.
  다시 부르면 성공한다.
- ③ part 발급 404(서버가 session을 모름): NONE. 다시 부르면 새
  session으로 성공한다.
- ⑤ 닫힌 runtime: RESUME. 같은 runtime은 늘 같은 답이다.
- ⑥ session보다 긴 capability(POLICY_REJECTED/REISSUE_CAPABILITY):
  RESUME. 서버가 같은 값을 다시 준다.

고른 방법(지난 리뷰 3절 D1의 (a), 번역 기준 보강): 번역은 계속 한 곳에
둔다. 몇 가지 code가 먼저 정한다. POLICY_REJECTED → NONE, file store의
NOT_READABLE/REOPEN → RESELECT, UPLOAD_PART의 NOT_FOUND → RECONCILE.
나머지는 지금처럼 표 안 값은 그대로 두고, 표 밖이면 retryable:true나
REISSUE_CAPABILITY·RETRY일 때 RESUME, 아니면 NONE이다. NONE과 RESELECT는
번역 끝에서 retryable:false로 맞춘다. 닫힌 runtime은 NONE을 돌려준다.
포트 표 주석과 설계 문서 표에 이 규칙을 적었다.

버린 대안:
- 리뷰 예시의 STALE_RESULT → RESELECT. 기존 STALE_RESULT/RECONCILE
  경로(resumable-upload-runtime.ts의 재조정)를 깨뜨린다. 지금
  STALE_RESULT는 모두 표 안 값을 갖고 있어 규칙이 필요 없다.
- 리뷰 예시의 NOT_READABLE → RESELECT(조건 없이). PUT 중 네트워크 읽기
  실패도 NOT_READABLE(REISSUE_CAPABILITY)이라 파일 재선택으로 잘못
  보낸다. 그래서 REOPEN(file store가 붙이는 값)일 때만 RESELECT다.
- 출처마다 포트 어휘를 만들게 하는 안(b), action 필드 추가(c). 지난
  리뷰가 다른 포트를 틀어지게 하거나 공유 타입을 바꾼다고 기각했다.

위험·한계:
- ④ part 발급(BFF) 401/403은 고치지 않았다. 지금도 RESUME이다. object
  store PUT 403(재발급으로 풀리고, 기존 01-05 표 테스트가 RESUME으로
  고정)과 code·단계·recovery가 모두 같아 번역 한 곳에서 가를 수 없다.
  리뷰 예시("PERMISSION_DENIED는 단계와 무관하게 NONE")와 보존 조건
  ("기존 7경로 기대값 유지")이 이 경로에서 서로 어긋난다. runtime
  호출 지점에서 발급 거절만 따로 표시할지는 소유자 판단이 필요하다.
  그래서 이 발견은 부분 충족이다.
- 몇 경로의 recovery 값이 바뀐다(위 ①②③⑤⑥). 기존 테스트 하나
  (resumable-upload-runtime-contract.test.ts "rejects a part capability
  that outlives its session")의 기대값을 RESUME → NONE으로 바꿨다.
  다운스트림 화면이 이 값으로 분기하므로 CHANGELOG [계약] 한 줄이
  필요하다. 이번 수정 묶음은 CHANGELOG를 한 번에 쓰므로 여기서는 쓰지
  않았다.
- 실제 브라우저 오류 발생은 재현하지 않았다. 단위 harness에서 오류
  값을 주입했다.
- file-transfer 레시피 번들이 55,937 → 56,031 gzip bytes가 되어 예산
  56,000을 넘었다. 다음 백 단위 규칙대로 56,100으로 올렸다.

검증:
- RED(수정 전): resumable-upload-runtime-recovery.test.ts 새 5건 실패.
  ① recovery NONE·retryable true(기대 RESELECT·false), ② NONE(기대
  RESUME), ③ NONE(기대 RECONCILE), ⑤ RESUME(기대 NONE), ⑥ RESUME(기대
  NONE). 수정 전 번역 규칙으로 되돌리면 같은 5건이 실패한다.
- GREEN: 같은 파일 통과. 기존 7경로 표 테스트에 "NONE이면
  retryable:false" 단언을 더했고 통과한다.
- 회귀: resumable-upload·presigned·upload-cancellation·browser-file·
  image-cdn 단위 20파일 326건 통과. tsc app·test·recipes 통과. 바꾼
  파일 eslint 통과. verify-documentation-readiness PASS_SCOPED.
  check-architecture(exec 전용 shim) 통과. check-optional-recipes
  (source) file-transfer 56031/56100.

Refs: docs/reviews/2026-09-29-maturity-review/01-adapters-browser-transfer.md
This commit is contained in:
DongHyeonka
2026-11-01 23:14:48 +09:00
parent aedd32841f
commit 9142390422
6 changed files with 139 additions and 18 deletions
@@ -195,7 +195,7 @@
"lifecycleMethods": ["release-file-ref", "release-or-dispose-preview-leases", "cancel-via-AbortSignal", "reconcile-or-explicitly-abort-upload", "close-checkpoint-store", "dispose-capability-and-image-runtime", "dispose-browser-file-runtime-on-logout-or-account-switch"],
"owner": "project-owner-required",
"securityPrivacy": ["Treat file name, extension, MIME and lastModified as untrusted metadata.", "Resolve only exact composition-issued file and image policy object identities; callers cannot raise byte, candidate, pixel, quality, format, lifetime or origin ceilings.", "Use opaque file references and verification receipts bound to an inspected immutable file snapshot and the exact registered profile; reject replay through another profile even when an inspection rule ID matches.", "Treat presigned URLs as bearer capabilities; bind exact method, resource or upload part, offset, length, media type, checksum, origin, path, query, headers and expiry in an in-memory identity vault.", "Use credentials omit, redirect error, no-referrer and no-store for direct data-plane fetch; never persist or observe URL, query, signed header, capability, file name or raw backend message, and never emit digest, raw ETag or receipt values to diagnostics or telemetry.", "A strict account-partitioned upload checkpoint may persist only the protocol-defined SHA-256 file fingerprint, per-part checksum and bounded opaque non-authorizing part receipt token required for server reconciliation; no bearer token or raw signed capability is allowed.", "Persist only strict non-authorizing upload checkpoints and reconcile them with server-authoritative status and re-hashed local parts before completion.", "Require a synchronous server-issued browser-managed download capability whose receipt exactly equals the caller's branded capability receipt and whose resource, media type, safe extension, maximum bytes, optional digest and expiry all match before handoff.", "Expose File, OPFS, Cache and transfer byte streams only as chunk-level closed Results; stop after the first failure, cancel native readers and never throw a raw native exception across the port.", "Accept Image CDN assets only through immutable allowlisted or signature-verified descriptors and registered preset identities; reject active formats, arbitrary transforms, pixel/decode-budget overflow and unsafe cache policy.", "Upload completion remains QUARANTINED until backend scan and promotion; client capability checks are not an authorization boundary.", "Active content preview requires isolation or download-only treatment."],
"bundleBudgetGzipBytes": 56000,
"bundleBudgetGzipBytes": 56100,
"fallback": "Accessible native file input, same-origin authorized server upload/download and a single bounded server-selected image rendition; generated artifacts above the buffer budget move to server-side generation.",
"removal": ["Stop new capability and upload-session issuance, then cancel active reads and transfers.", "Reconcile or explicitly abort active multipart sessions and let backend TTL cleanup remove ambiguous orphans.", "Remove non-secret checkpoints according to account and retention policy.", "Release file references, revoke preview object-URL leases and dispose file, capability and image runtimes.", "Remove transfer/image feature facades and composition, then prove browser-transfer sources are absent from the production module inventory."],
"serverStatePolicy": "query-cache-metadata-only"
@@ -729,10 +729,16 @@ analytics는 제품 presentation이 소유한다.
| recovery | 호출자 행동 |
| --- | --- |
| `RESUME` | 같은 파일·key로 `upload()`를 다시 부른다. `retryable:true`면 자동 재시도해도 된다. capability 재발급이 필요한 실패도 여기로 온다 |
| `RECONCILE` | `upload()`를 다시 부른다. 서버 상태를 먼저 읽는다(예: 다른 문맥이 checkpoint를 먼저 씀) |
| `RECONCILE` | `upload()`를 다시 부른다. 서버 상태를 먼저 읽는다(예: 다른 문맥이 checkpoint를 먼저 씀, part 발급에 서버가 session을 모른다고 404) |
| `RESTART` | `abort()` 뒤 `upload()`로 새 session을 연다. abort가 남아 있음(operation `UPLOAD_ABORT`), 읽을 수 없는 checkpoint 행, 서버 part가 파일과 다름 |
| `RESELECT` | 파일을 다시 고르거나, 다른 파일이면 새 key를 쓴다 |
| `NONE` | 이 요청으로 할 행동이 없다. 잘못된 입력, 상한·정책·권한 거절, 호출자 자신의 abort, 다시 불러도 같은 답이 오는 서버 응답(정책보다 긴 session 등) |
| `RESELECT` | 파일을 다시 고르거나, 다른 파일이면 새 key를 쓴다(고른 파일이 바뀌었거나 읽을 수 없음 포함). `retryable`은 늘 `false`다 |
| `NONE` | 이 요청으로 할 행동이 없다. 잘못된 입력, 상한·정책·권한 거절, 호출자 자신의 abort, 닫힌 runtime, 다시 불러도 같은 답이 오는 서버 응답(정책보다 긴 session·capability 등). `retryable`은 늘 `false`다 |
번역은 recovery 값만이 아니라 code도 본다(0929/01-01). `POLICY_REJECTED`는
`NONE`, file store의 `NOT_READABLE`/`REOPEN`은 `RESELECT`, `UPLOAD_PART`의
`NOT_FOUND`는 `RECONCILE`이다. 표 밖 값 중 `retryable:true`인 일시 오류는
`RESUME`이다. part 발급(BFF)의 401/403은 아직 `RESUME`으로 나온다. object store
PUT 403(재발급으로 풀리는 경우)과 같은 code·단계라 번역 한 곳에서 가를 수 없다.
관측성에는 operation, safe outcome, byte/candidate bucket, retry bucket과
failure code만 기록한다. capability ID, URL, query, asset/resource/session ID,
@@ -13,6 +13,7 @@ import type {
} from "../../../application/ports/browser-transfer/resumable-upload.ts";
import { RESUMABLE_UPLOAD_PROTOCOL } from "../../../application/ports/browser-transfer/resumable-upload.ts";
import type {
BrowserDataFailure,
BrowserDataFailureCode,
BrowserDataOperation,
BrowserDataRecovery,
@@ -170,9 +171,9 @@ export function createResumableUploadRuntime<Capability>(
input: ResumableUploadRequest,
): Promise<BrowserDataResult<QuarantinedUpload>> {
if (closed) {
return browserDataFailure("UNAVAILABLE", "UPLOAD_SESSION", {
recovery: "RESUME",
});
// 0929/01-01. This runtime answers the same way every time; the
// caller needs a new runtime, which is no action on this request.
return browserDataFailure("UNAVAILABLE", "UPLOAD_SESSION");
}
let request: UploadRequestSnapshot;
try {
@@ -1710,21 +1711,51 @@ function reportProgress(
* caller actions. Provider vocabulary the caller cannot act on itself (a
* capability to reissue, a request to retry) means "call `upload()` again";
* anything else outside the table has no caller action.
*
* 0929/01-01. The recovery word alone pointed some paths at the wrong action,
* so a few codes decide first (see `uploadActionFor`). `NONE` and `RESELECT`
* are never retryable: calling again with the same file only repeats them.
*/
function toUploadAction<Value>(
result: BrowserDataResult<Value>,
): BrowserDataResult<Value> {
if (result.ok || UPLOAD_ACTIONS.has(result.error.recovery)) return result;
if (result.ok) return result;
const recovery = uploadActionFor(result.error);
const retryable =
recovery !== "NONE" && recovery !== "RESELECT" && result.error.retryable;
if (
recovery === result.error.recovery &&
retryable === result.error.retryable
) {
return result;
}
return browserDataFailure(result.error.code, result.error.operation, {
retryable: result.error.retryable,
recovery:
result.error.recovery === "REISSUE_CAPABILITY" ||
result.error.recovery === "RETRY"
? "RESUME"
: "NONE",
retryable,
recovery,
});
}
function uploadActionFor(failure: BrowserDataFailure): BrowserDataRecovery {
// A refusal that a new call would replay, such as a capability that
// outlives its session.
if (failure.code === "POLICY_REJECTED") return "NONE";
// The file store reports a changed or vanished file as NOT_READABLE/REOPEN.
// A network read failure is NOT_READABLE/REISSUE_CAPABILITY and stays below.
if (failure.code === "NOT_READABLE" && failure.recovery === "REOPEN") {
return "RESELECT";
}
// The server no longer knows the part's session; a new call reads status.
if (failure.code === "NOT_FOUND" && failure.operation === "UPLOAD_PART") {
return "RECONCILE";
}
if (UPLOAD_ACTIONS.has(failure.recovery)) return failure.recovery;
return failure.retryable ||
failure.recovery === "REISSUE_CAPABILITY" ||
failure.recovery === "RETRY"
? "RESUME"
: "NONE";
}
function mapLockFailure(
error: unknown,
operation: BrowserDataOperation,
@@ -115,10 +115,12 @@ export interface ResumableUploadPort {
* | | file. |
* | `RESELECT` | Select the file again, or use a new key for another file. |
* | `NONE` | No action on this request: invalid input, a limit, a |
* | | policy or permission refusal, the caller's own abort, or |
* | | a server answer that a new call would only replay. |
* | | policy or permission refusal, the caller's own abort, a |
* | | closed runtime, or a server answer that a new call would |
* | | only replay. |
*
* No other recovery value is returned from `upload()`.
* No other recovery value is returned from `upload()`. `NONE` and
* `RESELECT` always come with `retryable: false` (0929/01-01).
*/
upload(
request: ResumableUploadRequest,
@@ -308,10 +308,13 @@ describe("resumable upload runtime server response validation", () => {
});
await expect(upload(dependencies(harness))).resolves.toMatchObject({
ok: false,
// 0929/01-01. The server would issue the same capability again, so a
// new upload() only replays this refusal.
error: {
code: "POLICY_REJECTED",
operation: "UPLOAD_PART",
recovery: "RESUME",
retryable: false,
recovery: "NONE",
},
});
});
@@ -962,7 +962,86 @@ describe("upload() failure recovery maps to one caller action (01-05)", () => {
error: { code, operation, recovery },
});
if (!result.ok) expect(UPLOAD_ACTIONS.has(result.error.recovery)).toBe(true);
if (!result.ok && recovery === "NONE") {
expect(result.error.retryable).toBe(false);
}
});
/**
* 0929/01-01. Paths whose recovery vocabulary alone pointed at the wrong
* action. `retryable` is part of the answer: `NONE` and `RESELECT` are never
* retried automatically.
*/
const vocabularyScenarios = {
"the selected file can no longer be read": async () =>
await runtimeFor(createControlHarness()).upload({
...request("upload_key_unreadable_file"),
source: {
kind: "RANGE_READER",
reader: {
byteLength: 4,
async readRange() {
return browserDataFailure("NOT_READABLE", "FILE_READ", {
retryable: true,
recovery: "REOPEN",
});
},
},
},
}),
"the checkpoint store fails transiently": async () => {
const checkpoints = new MemoryCheckpointStore();
checkpoints.read = async () =>
browserDataFailure("UNAVAILABLE", "UPLOAD_RECONCILE", {
retryable: true,
recovery: "REOPEN",
});
return await runtimeFor(createControlHarness(), { checkpoints }).upload(
request("upload_key_store_busy"),
);
},
"the BFF no longer knows the session's part": async () =>
await runtimeFor(
createControlHarness({
issueCapability: () =>
browserDataFailure("NOT_FOUND", "PRESIGNED_TRANSFER"),
}),
).upload(request("upload_key_forgotten_session")),
"the runtime is closed": async () => {
const runtime = runtimeFor(createControlHarness());
runtime.close();
return await runtime.upload(request("upload_key_closed"));
},
"a capability outlives its session": async () =>
await runtimeFor(
createControlHarness({
issueCapability: (input, callIndex) =>
browserDataSuccess({
capability: Object.freeze({ id: `cap-${callIndex}` }),
uploadBindingSha256: input.uploadBindingSha256,
expiresAtEpochMs: 1_000 + 6_000,
}),
}),
).upload(request("upload_key_long_capability")),
} as const;
it.each([
["the selected file can no longer be read", "NOT_READABLE", "RESELECT", false],
["the checkpoint store fails transiently", "UNAVAILABLE", "RESUME", true],
["the BFF no longer knows the session's part", "NOT_FOUND", "RECONCILE", false],
["the runtime is closed", "UNAVAILABLE", "NONE", false],
["a capability outlives its session", "POLICY_REJECTED", "NONE", false],
] as const)(
"%s → %s/%s (retryable %s) (0929/01-01)",
async (scenario, code, recovery, retryable) => {
const result = await vocabularyScenarios[scenario]();
expect(result).toMatchObject({
ok: false,
error: { code, recovery, retryable },
});
},
);
});
describe("device clock skew on server lifetimes (01-06)", () => {