문제
1103/14-04 조치는 참조 기능을 지운 사본에서 문서 검사가 통과하도록 참조
기능·참조 context 경로와 그 전용 파일·script를 백틱 없이 다시 적었다.
검사기는 백틱 안·명령 안·링크의 경로만 보므로(verify-documentation-
readiness.ts) 그 26줄은 참조 기능이 설치된 템플릿에서도 검사 밖이다. 참조
기능 파일 이름이 바뀌면 매뉴얼이 없는 경로를 가리켜도 어느 게이트도
실패하지 않는다. docs/manual/README.md의 "이 폴더 문서의 경로는 검사된다"가
예제 경로에서 거짓이다.
고른 방법
- 앞 커밋(1105/14-01)으로 검사기가 지운 템플릿 기능의 경로를 받으므로,
README, starter-experience, static-delivery, compatibility,
backend-api-and-server-state-contract, manual-checklist,
adapter-remediation-ledger, performance-evidence, 매뉴얼 01·02·patterns의
참조 기능 경로와 test:reference-feature를 다시 백틱(또는 명령 한 줄)으로
적는다. 두 줄로 끊겨 검사되지 않던 measure 명령도 한 줄로 적었다.
1105/15-02·16-01 조치가 starter-experience.md 표와 매뉴얼 03(A 표, "기능을
지울 때")에 백틱 없이 더한 config/scale/feature-shape-ceilings.json과
measure 명령 세 줄도 같은 규칙으로 고쳤다.
- patterns.md 첫머리 규칙("백틱 없이 적는다")과 README의 SAMPLE_EXTRAS
안내를 새 규칙(설치된 동안 검사, 지운 사본에서는 받음)과 목록 모듈
위치로 고쳤다.
- 테스트: template-feature-removal-documents.test.ts에 "names their paths
and scripts only where verify:documentation checks them"을 더했다. 검사기가
읽은 1절 문서 목록(documentation-review.json)을 받아, 지울 수 있는 템플릿
기능의 경로·script가 백틱 span·링크 대상·셸 블록 밖에 나오면 실패한다.
같은 우회가 다시 들어오는 것을 막는다. 지운 사본에서 통과하는 성질은 앞
커밋의 "passes in a copy without reference-feature"가 본다.
- 버린 대안: 경로 존재만 보는 단위 테스트를 따로 두기(리뷰의 차선책).
검사기와 같은 규칙을 두 곳에 두게 된다.
위험·한계
- 다음에 참조 기능 경로를 백틱 없이 적는 문서 변경은 새 테스트가 막는다.
백틱으로 적으면 참조 기능을 지운 사본에서도 통과한다.
- 언어 없는 펜스 블록은 검사기처럼 셸 블록으로 보고 넘긴다. 그 안의 명령이
아닌 줄(트리 그림 등)에 적은 경로는 검사기도 새 테스트도 보지 않는다.
검증
- desktop batch에서 확인: node scripts/run-vitest.ts run
tests/unit/template-feature-removal-documents.test.ts
tests/unit/documentation-readiness.test.ts, corepack pnpm
verify:documentation, corepack pnpm test:sample-removal
Refs: 1105/14-03
843 lines
48 KiB
Markdown
843 lines
48 KiB
Markdown
# Backend API와 Server State handoff contract
|
|
|
|
> **정본 안내 (non-authoritative for runtime capability decisions)**
|
|
>
|
|
> Runtime Config/boot, Fetch HTTP client, Router, Query/Mutation, realtime 공통 경계, Web Worker,
|
|
> Service Worker, offline command와 Background Sync의 구현 결정은
|
|
> [프론트엔드 런타임 Capability 저장소 정합형 구현 결정 폐쇄 상세 설계](./2026-07-30-frontend-runtime-capability-repository-aligned-implementation-closed-deep-design.md)가 정본이다.
|
|
> 본 문서의 해당 서술이 정본과 충돌하면 정본을 따른다.
|
|
|
|
|
|
- 상태: frontend handoff design accepted, backend implementation/evidence pending. 단 4.1·6·6.1절(Envelope 읽기, effect 판정, 쓰기 전 거절 표)은 지금 실행 규칙이다(`COMPOSED`, `src/adapters/http/backend-envelope.ts`)
|
|
- 기준일: 2026-07-28
|
|
- 대상: Web API/BFF, application service, persistence, identity, GraphQL router,
|
|
Connect/gRPC-Web gateway, Protobuf REST Gateway와 운영 owner
|
|
- frontend 기준:
|
|
[API contract, Schema, Mapper와 Server State](./api-contract-schema-mapper-and-server-state.md)
|
|
- browser Protobuf/gateway 기준:
|
|
[Protobuf browser transport와 REST Gateway](./protobuf-browser-transport-and-rest-gateway.md)
|
|
- 파일 전송 backend 기준:
|
|
[Server file capability infrastructure](./server-file-capability-infrastructure.md)
|
|
- 복구 절차:
|
|
[API contract와 server-state recovery](../operations/api-contract-and-server-state-recovery.md)
|
|
|
|
## 1. 문서의 경계
|
|
|
|
이 문서는 이 frontend template이 실제 제품 backend와 연결될 때 backend가
|
|
제공해야 하는 구조, wire contract, 상태 의미와 운영 증거를 정의한다. 특정
|
|
언어·framework·cloud 제품을 강제하지 않는다. Spring, Nest/Fastify, Go,
|
|
.NET 또는 다른 stack을 사용해도 아래 불변조건은 동일하다.
|
|
|
|
이 repository에는 backend source, database migration, identity provider,
|
|
GraphQL schema/router, protobuf descriptor, Connect/gRPC-Web runtime/proxy,
|
|
REST transcoder와 실제 provider evidence가 없다. 따라서 이 문서는 backend 구현
|
|
완료 증거가 아니다.
|
|
|
|
파일 업로드·다운로드, object storage, presigned URL, multipart와 Image CDN은
|
|
별도 server file 문서가 소유한다. 이 문서는 ordinary REST/GraphQL/Connect/
|
|
gRPC-Web application API, Protobuf REST Gateway와 frontend Server State 계약만
|
|
소유한다.
|
|
|
|
## 2. 권장 논리 구조
|
|
|
|
```text
|
|
Browser
|
|
-> CDN / reverse proxy / WAF
|
|
-> Browser-facing Web API or BFF
|
|
-> authentication + authorization
|
|
-> exact operation registry
|
|
-> request schema / byte / rate limit
|
|
-> REST controller
|
|
-> optional persisted GraphQL router
|
|
-> optional Connect browser RPC gateway
|
|
-> optional gRPC-Web gateway
|
|
-> optional Protobuf REST transcoder
|
|
-> application service
|
|
-> command transaction
|
|
-> query/read-model service
|
|
-> idempotency coordinator
|
|
-> revision/validator owner
|
|
-> outbox/event owner
|
|
-> primary database
|
|
-> idempotency store
|
|
-> read replica/read model
|
|
-> event broker when selected
|
|
```
|
|
|
|
Browser-facing contract owner와 내부 service contract owner를 분리한다.
|
|
|
|
- Browser API/BFF는 CORS, cookie/CSRF 또는 bearer, public DTO, envelope,
|
|
body ceiling, status/media와 redaction을 소유한다.
|
|
- Application service는 authorization 재검사, transaction, idempotency,
|
|
conflict, revision과 domain invariant를 소유한다.
|
|
- Persistence adapter는 SQL/NoSQL/Redis vendor type, row version과 cursor
|
|
implementation을 외부 DTO에 노출하지 않는다.
|
|
- GraphQL router, Connect/gRPC-Web gateway와 REST transcoder는 선택 adapter다.
|
|
다른 protocol로 임의 fallback하거나 frontend에 내부 service address를
|
|
노출하지 않는다.
|
|
|
|
작은 제품은 이 논리 모듈을 하나의 deployable로 구현할 수 있다. deployable을
|
|
나누는 것보다 transaction/idempotency/authorization owner가 하나로 명확한지가
|
|
우선이다.
|
|
|
|
## 3. 공통 contract artifact
|
|
|
|
Backend와 frontend release는 다음 bounded contract set을 공유한다.
|
|
|
|
```text
|
|
ApiContractSetV1
|
|
globalApiContractVersion
|
|
restArtifactId + digest
|
|
runtimeSchemaManifestId + digest
|
|
mapperSemanticManifestId + digest
|
|
errorVocabularyVersion
|
|
minimumFrontendVersion
|
|
minimumBackendVersion
|
|
effectiveAt
|
|
retirementEpoch | null
|
|
|
|
optional:
|
|
graphqlSchemaId + digest
|
|
persistedGraphqlManifestId + digest
|
|
protobufDescriptorId + digest
|
|
protobufSourceOrModuleId + digest
|
|
protobufCodegenProfileId
|
|
connectProviderProfileId
|
|
grpcWebProviderProfileId
|
|
protobufRestGatewayProfileId
|
|
httpRuleArtifactId + digest
|
|
protoJsonProfileId
|
|
gatewayOpenApiArtifactId + digest
|
|
```
|
|
|
|
최소 산출물:
|
|
|
|
- authenticated OpenAPI 또는 동등한 REST schema source
|
|
- exact status/media/envelope fixture
|
|
- stable error code vocabulary
|
|
- request/response byte와 collection ceiling
|
|
- scalar/date/null/enum 의미
|
|
- N/N-1 compatibility 결과
|
|
- backend build와 frontend release가 참조하는 immutable digest
|
|
|
|
runtime config의 version 문자열 일치만 compatibility 증거로 사용하지 않는다.
|
|
artifact digest가 없는 동안에는 실제 staging conformance fixture와 수동 승인
|
|
evidence가 필요하다.
|
|
|
|
## 4. 현재 reference REST 계약
|
|
|
|
현재 frontend에 실제 조립된 operation은 다음 세 개다.
|
|
|
|
| operation | request | success |
|
|
| --- | --- | --- |
|
|
| `LIST_REFERENCE_RESOURCES` | `GET /api/reference-resources?cursor&limit&tags` | `200 application/json` |
|
|
| `GET_REFERENCE_RESOURCE` | `GET /api/reference-resources/{resourceId}` | `200 application/json` |
|
|
| `CREATE_REFERENCE_RESOURCE` | `POST /api/reference-resources` | `200` 또는 `201 application/json` |
|
|
|
|
현재 list payload는 `ReferenceResource[]`다. `cursor` 입력이 존재하더라도
|
|
`CursorPage` 출력 계약은 아직 아니다. backend가 같은 operation에서 배열을
|
|
page object로 조용히 바꾸면 schema mismatch로 실패한다.
|
|
|
|
resource DTO:
|
|
|
|
```text
|
|
ReferenceResourceDtoV1
|
|
id: non-empty string, maximum 120 characters
|
|
name: non-empty string, maximum 240 characters
|
|
createdAt?: RFC 3339 date-time
|
|
```
|
|
|
|
create command:
|
|
|
|
```text
|
|
CreateReferenceResourceCommandV1
|
|
name: trimmed string, 1..120
|
|
note?: trimmed string, 0..500
|
|
```
|
|
|
|
Backend는 frontend validation을 신뢰하지 않고 동일하거나 더 좁은 validation과
|
|
authorization을 다시 수행한다.
|
|
|
|
### 4.1 JSON envelope
|
|
|
|
Envelope의 모양과 키 존재 규칙은 짝 백엔드 템플릿 문서가 정본이다. 이
|
|
문서에 표를 다시 적지 않는다.
|
|
|
|
- 정본: [`clean-architecture-backend-template/docs/web/http-contract.md`](../../../clean-architecture-backend-template/docs/web/http-contract.md)
|
|
1절 "Envelope 키 존재 규칙"
|
|
- 기준 커밋: 백엔드 `45d2a478`. 기계가 읽는 정본은
|
|
`config/contracts/backend-contract-pin.json`(repo, 전체 SHA, 대조한 절 §1·§2·§4,
|
|
담당)이다. 백엔드 §2 표와 §4의 503 셋(`REQUEST_TIMEOUT`, `RATE_LIMIT_UNAVAILABLE`,
|
|
`RATE_LIMIT_INCOMPATIBLE`)은
|
|
`config/contracts/backend-idempotency-answers.json`에 code·status·쓰기 전 거절·같은 키
|
|
재전송 열로 옮겨 두었다. `tests/unit/backend-contract-pin.test.ts`가 그 표와
|
|
`backend-envelope.ts`의 판정을 양방향으로 대조한다. 값이 null인 필드는 키째
|
|
생략한다. 백엔드 기준 커밋을 올리면 pin, 답 표 JSON, 6.1절 표를 같은 변경에서
|
|
다시 확인한다.
|
|
- 백엔드 §2·§4 표의 행은 pin 커밋 그대로
|
|
`config/contracts/backend-http-contract-excerpt.json`에 옮겨 두었다. 같은 테스트가
|
|
답 표의 code·status를 이 사본과 대조한다. 사본에만 있는 행은 답 표에 옮기거나 pin의
|
|
`notCopied`에 이유와 함께 적는다(지금은 없다). pin의
|
|
`sectionsCompared`의 §4에서 답 표가 옮긴 행은 503 셋(`REQUEST_TIMEOUT`,
|
|
`RATE_LIMIT_UNAVAILABLE`, `RATE_LIMIT_INCOMPATIBLE`)이다.
|
|
`IDEMPOTENCY_KEY_INVALID`는 §2 행으로 옮겼다.
|
|
- 사본이 백엔드 문서와 같은지는 `corepack pnpm check:backend-contract-drift --backend <백엔드 checkout>`이
|
|
본다(게이트 밖. CI는 이 repo만 checkout한다). pin 커밋의 표와 사본·답 표를
|
|
비교하고, pin 뒤 백엔드 HEAD에서 바뀐 표 행을 알린다. 1은 어긋남, 2는 비교하지
|
|
못함(통과가 아니다)이다. 짝 백엔드를 새로 받을 때마다 돌린다. pin을 올릴 때는
|
|
`--write-excerpt`가 사본을 pin 커밋에서 다시 옮긴다.
|
|
- `create:feature --with-create`는 백엔드 생성기 템플릿의 사실 넷(경로 복수형,
|
|
이름 상한 100, 오류 code, 검사 순서)을 생성기 문자열로 옮겼다. 그 파일들은
|
|
pin의 `backend.scaffoldSources`에 있고, 각 항목이 옮긴 곳(프론트 파일과
|
|
이름)을 적는다. drift 검사는 pin 뒤 HEAD에서 이 파일들이 바뀌었는지도 보고,
|
|
바뀐 파일마다 다시 볼 프론트 위치를 말하며 1로 끝난다(1105/16-02).
|
|
- 프론트에서 Envelope를 읽는 곳: `src/adapters/http/backend-envelope.ts`(스키마와
|
|
해석). V3 실행기는 descriptor가 `responseEnvelope: "ENVELOPE_V1"`일 때 쓴다.
|
|
`create:feature`가 만든 기능은 이 값을 선언한다. 참조 기능은 `"NONE"`을
|
|
선언하고 DTO와 problem details를 검증한다. 이 칸은 descriptor 타입의 필수
|
|
칸이라 빠뜨리면 `check:types`가 실패한다(1103/16-01).
|
|
- 실패 Envelope의 `error.code`가 "적용 안 됨"인지는 6.1절이 정한다.
|
|
- 페이지 목록의 `meta.page`(`number`·`size`·`total`·`sort`)는 기능의
|
|
`mapSuccess(value, { page })` 두 번째 인자로 간다(`FeatureHttpSuccessContext`).
|
|
`outputValidator`는 지금처럼 `data`만 본다. 백엔드 범위(정수, `size` 1~100) 밖의
|
|
`page`는 버리고 응답은 그대로 읽는다. 목록 화면의 전체 수는 `page.total`이다.
|
|
배열 길이는 첫 페이지 크기(기본 20)일 뿐이다.
|
|
- bulk 응답(`results`, `BATCH_PARTIAL_FAILURE`)은 지원하지 않는다. 성공 status의
|
|
`results` Envelope는 `ENVELOPE_MISMATCH`다. bulk 엔드포인트를 붙이려면
|
|
`responseEnvelope`를 빼고 기능 스키마가 본문 전체를 읽는다.
|
|
|
|
### 4.2 Status와 error
|
|
|
|
| HTTP status | 의미 |
|
|
| --- | --- |
|
|
| `400` | malformed request 또는 closed request contract 위반. 짝 백엔드의 필드 검증 실패는 400 `VALIDATION_FAILED`(필드 목록 `details`)다. 적용 여부는 6.1절 |
|
|
| `401` | 인증 없음/만료. 이미 적용된 command를 401로 반환하지 않음 |
|
|
| `403` | authenticated principal에게 권한 없음 |
|
|
| `404` | authorization 정책상 공개 가능한 not-found |
|
|
| `409` | domain revision 또는 semantic conflict. 멱등성 응답(409·422·400)은 6절 |
|
|
| `412` | selected conditional write의 `If-Match` precondition 실패 |
|
|
| `422` | 짝 백엔드에서는 field validation이 아니다. 기본 배포는 `IDEMPOTENT_REQUEST_MISMATCH`(6절)만, fileserver 모듈은 쓰기 뒤에도 나오는 code를 422로 보낸다. 프론트는 `IDEMPOTENT_REQUEST_MISMATCH`만 적용 안 됨으로 보고, 폼 필드 오류는 `details.issues[]`가 있으면 읽는다. 필드 목록이 없는 422는 입력 오류가 아니라 `UNKNOWN_CLIENT_FAILURE`다(폼은 지원 참조가 있는 실패 상태를 보인다). 적용 여부는 6.1절 |
|
|
| `429` | rate limit. 유효한 `Retry-After`와 operation 정책 제공 |
|
|
| `500/502/503/504` | server/provider failure. command effect certainty 별도 |
|
|
|
|
현재 frontend의 ordinary status mapper는 `412` 전용 처리를 아직 연결하지
|
|
않았다. conditional mutation을 선택할 때 frontend failure vocabulary와
|
|
transaction을 함께 승격해야 한다.
|
|
|
|
Backend `error.code`는 machine-readable stable code다. stack, SQL/vendor error,
|
|
raw validation value, authorization reason과 내부 service address를 반환하지
|
|
않는다.
|
|
|
|
## 5. 인증, CSRF와 CORS
|
|
|
|
현재 reference operation은 다음 profile로 조립돼 있다.
|
|
|
|
```text
|
|
auth = external bearer
|
|
Authorization: Bearer <credential>
|
|
fetch credentials = omit
|
|
CSRF profile = none
|
|
redirect = error
|
|
referrer policy = no-referrer
|
|
```
|
|
|
|
Backend/BFF는 bearer의 issuer, audience, signature algorithm, time claims와
|
|
revocation/session policy를 검증하고 operation별 authorization을 적용한다.
|
|
401과 403을 구분하며 frontend cache를 authorization authority로 사용하지 않는다.
|
|
|
|
쿠키 session으로 전환할 경우 같은 profile로 간주하지 않는다. 별도
|
|
`SAME_ORIGIN_COOKIE` profile에 다음을 함께 승인한다.
|
|
|
|
- `Secure`, `HttpOnly`, 명시적 `SameSite`와 host/path scope
|
|
- unsafe method의 CSRF token/header와 Origin/Sec-Fetch-Site 검증
|
|
- credentialed CORS에서 wildcard origin 금지
|
|
- login/logout/session rotation과 cache generation 전환
|
|
- session fixation, token rotation과 concurrent tab 동작
|
|
|
|
Cross-origin bearer provider 최소 CORS:
|
|
|
|
- exact allow-origin 목록과 bounded preflight cache
|
|
- `Authorization`, `Content-Type`, `Idempotency-Key`,
|
|
`X-Correlation-ID`, 향후 `If-None-Match`, `If-Match` 허용
|
|
- 필요한 경우 `ETag`, `Retry-After`, request/trace header만 expose.
|
|
`X-Correlation-ID`를 expose하면 V3 실패의 `AppFailure.requestId`가 된다
|
|
(`src/adapters/http/feature-http-binding.ts`). expose하지 않거나 응답이 없으면
|
|
클라이언트가 보낸 값이 된다. Envelope operation의 실패 본문 `meta.traceId`는
|
|
`AppFailure.traceId`가 된다(헤더가 아니라 본문이라 CORS expose와 상관없다)
|
|
- redirect login page, HTML error body와 wildcard credential 금지
|
|
|
|
## 6. Command와 idempotency
|
|
|
|
`CREATE_REFERENCE_RESOURCE`는 keyed command다. frontend memory single-flight는
|
|
backend idempotency를 대체하지 않는다.
|
|
|
|
멱등성 응답의 status·`error.code`·`retryable`·`Retry-After`와 키 문법은 짝
|
|
백엔드 템플릿 문서가 정본이다. 이 문서에 표를 다시 적지 않는다.
|
|
|
|
- 정본: [`clean-architecture-backend-template/docs/web/http-contract.md`](../../../clean-architecture-backend-template/docs/web/http-contract.md)
|
|
2절 "멱등성 응답", 4절 "web 전용 오류 코드"
|
|
- 기준 커밋: 4.1절과 같다(백엔드 `45d2a478`, `config/contracts/backend-contract-pin.json`).
|
|
- 프론트가 그 응답을 읽는 곳:
|
|
- 키 생성·검사: `src/contracts/mutation-intent.ts` `isValidIdempotencyKey`
|
|
- 결과 불명 재전송이 같은 키를 쓰고 `Retry-After`까지 기다리는 곳:
|
|
`src/presentation/adapters/query/application-query.ts`
|
|
- Envelope operation의 거절 판정: `src/adapters/http/backend-envelope.ts`
|
|
`REFUSED_BEFORE_WRITE`(6.1절 표)
|
|
- 참조 기능(Envelope 없음) 판정: `src/features/reference-feature/contracts/reference-feature-contract-contribution.ts`
|
|
(effect), `src/features/reference-feature/adapters/reference-http-gateway.ts`
|
|
(code)
|
|
|
|
### 6.1 거절 code와 적용 여부
|
|
|
|
mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐는지 정해야 한다.
|
|
|
|
- `NOT_APPLIED`: 쓰기 전에 거절됐다. 다음 저장은 새 `Idempotency-Key`를 쓴다.
|
|
- `MAYBE_APPLIED`: 쓰기 뒤에도 나올 수 있다. mutation 코디네이터가 키를 붙들고
|
|
결과 불명으로 보인다. effect가 없는 실패도 이 값이다.
|
|
|
|
백엔드 `http-contract.md`는 code가 어느 단계에서 나오는지 적지 않는다. 아래 표는
|
|
프론트가 백엔드 코드를 읽고 정한 판정이다. `5786126c`에서 읽었고, `bbe944bd`에서
|
|
바뀐 파일(`GlobalExceptionHandler`, `IdempotencyExecutor`, `PersistenceExceptionTranslator`,
|
|
`FailureCategory`, `DomainExceptionHandler`)을 다시 읽었다. 판정은 바뀌지 않았고 줄
|
|
번호만 옮겼다. `c508b1ba`에서는 바뀐 `IdempotencyExecutor`(늦게 끝난 실행 기록)를 다시
|
|
읽었다. 처리 중·불일치 판정은 그대로 action 전이고 줄 번호만 옮겼다. `45d2a478`에서는
|
|
바뀐 `GlobalExceptionHandler`(로그 줄 정리)와 `IdempotencyExecutor`를 다시 읽었다. 인용한
|
|
블록의 내용은 그대로이고 줄 번호만 옮겼다. §2는 처리 중(PostgreSQL 저장소는 409 대신
|
|
기다림)과 `IDEMPOTENCY_UNAVAILABLE`(lease 만료로 시작 거절) 설명만 늘었고 code·status·재시도는 같다. 같은 code가 쓰기 전과
|
|
뒤에서 모두 나오면 "쓰기 뒤 가능"으로 둔다. 프론트는 code만 보고 둘을 가를 수
|
|
없다.
|
|
|
|
| code (status) | 나오는 곳 | 단계 | 프론트 결과 | 백엔드 파일:줄 |
|
|
| --- | --- | --- | --- | --- |
|
|
| `VALIDATION_FAILED` (400), details = 필드 목록 | 요청 본문 `@Valid` 실패, 컨트롤러 파라미터 제약 실패. 컨트롤러 메서드가 불리기 전 | 쓰기 전 | `NOT_APPLIED` | `GlobalExceptionHandler.java:205-218`, `:333-355` |
|
|
| `VALIDATION_FAILED` (400), details = 필드 목록 | `ConstraintViolationException`. 어느 층에서 던져도 이 handler가 받는다. 요청 경로에서 던지는 코드는 없다(application bean에 `@Validated` 없음, JPA entity에 Bean Validation 제약 없음, 직접 throw 없음) | 쓰기 전(현재 출처 없음) | `NOT_APPLIED` | `GlobalExceptionHandler.java:101-106` |
|
|
| `VALIDATION_FAILED` (400), details = `{cause}` 또는 없음 | 본문을 읽지 못함(`HttpMessageNotReadableException`) | 쓰기 전 | `NOT_APPLIED` | `GlobalExceptionHandler.java:220-238` |
|
|
| `VALIDATION_FAILED` (400), details = `{field, code}` | 페이지·정렬 파라미터. 목록 GET 컨트롤러가 use case 전에 검사한다 | 쓰기 전 | `NOT_APPLIED` | `GlobalExceptionHandler.java:149-153`, `PageParams.java:27-33`, `SortParam.java:16-43` |
|
|
| `IDEMPOTENCY_KEY_INVALID` (400) | KEYED 컨트롤러 첫 줄의 키 파싱 | 쓰기 전 | `NOT_APPLIED` | `IdempotencyKeyHeader.java:32-38`, `PosterImagePublicationController.java:64` |
|
|
| `IDEMPOTENT_REQUEST_MISMATCH` (422) | 멱등성 executor가 action 전에 판정 | 쓰기 전 | `NOT_APPLIED` | `IdempotencyExecutor.java:127-128`, `:166-167` |
|
|
| `IDEMPOTENT_IN_FLIGHT` (409) | 멱등성 executor가 action 전에 판정. 같은 키의 앞선 요청이 실행 중이다 | 이번 요청은 쓰기 전. 앞선 요청은 적용될 수 있다 | `MAYBE_APPLIED` | `IdempotencyExecutor.java:129-130`, `:168-169` |
|
|
| `BAD_PARAMETER` (400) | 타입 변환 실패, 필수 파라미터·헤더 없음(쓰기 전). **어느 층이든 `IllegalArgumentException`**(use case·domain 포함) | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `GlobalExceptionHandler.java:92-99`, `:108-116`, `:384-404`, `HttpStatusErrorCodes.java:33-34` |
|
|
| `MAPPING_FAILED` (400) | web 매퍼(쓰기 전), outbound ACL 매퍼(use case 안), 멱등성 응답 직렬화(action이 끝난 뒤) | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `WorkLogWebMapper.java:36`, `RepoStatsAclMapper.java:14`, `JsonIdempotentResponseCodec.java:32`, `IdempotencyExecutor.java:276` |
|
|
| `DB_SERIALIZATION_FAILURE`, `DB_DEADLOCK`, `DB_LOCK_TIMEOUT`, `DB_NULL_VIOLATION`, `DB_FK_VIOLATION`, `DB_UNIQUE_VIOLATION`, `DB_CHECK_VIOLATION`, `DB_OPTIMISTIC_CONFLICT` (409) | persistence 어댑터가 SQL·JPA 실패를 바꾼 것. 트랜잭션 안이나 commit에서 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `FailureCategory.java:86-102`, `StandardSqlStateErrorMapping.java:46-52`, `PersistenceExceptionTranslator.java:133` |
|
|
| `LOCK_ACQUISITION_TIMEOUT` (409) | 분산 락 대기 초과. use case 안 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `LockRegistryDistributedLock.java:50`, `:53` |
|
|
| 참조 도메인 `WORKLOG_INVALID`, `POSTER_INVALID_STATE`, `POSTER_IMAGE_REQUIRED` (400), `WORKLOG_CONFLICT`, `POSTER_ALREADY_EXISTS`, `POSTER_IMAGE_ALREADY_PUBLISHED` (409) | application·domain 예외 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `DomainExceptionHandler.java:52-90` |
|
|
| 선택 모듈 web-advanced `PATCH_REJECTED` (400), `PATCH_TEST_FAILED` (409) | patch 라이브러리. 부르는 코드가 단계를 정한다 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `clean-architecture-backend-template/src/adapter/inbound/web-advanced/README.md` 「오류 응답」 |
|
|
| 선택 모듈 fileserver `BAD_REQUEST` (400), `FILE_ALREADY_EXISTS`, `FILE_NOT_READY`, `UPLOAD_OFFSET_MISMATCH`, `CONCURRENT_MODIFICATION` (409), `INTEGRITY_MISMATCH`, `MALWARE_DETECTED`, `INVALID_PATH`, `PATH_OUTSIDE_NAMESPACE` (422) | application·outbound 층. `INTEGRITY_MISMATCH`·`MALWARE_DETECTED`는 레코드를 `REJECTED`로 쓴 뒤 던진다 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `FileserverErrorCode.java:26-44`, `FinalizeUploadApplicationUseCase.java:211-224`, `:336-341` |
|
|
|
|
- application-notification의 `VALIDATION_FAILED`(`NotificationFailureCode`)는
|
|
`ApiErrorCarrier`가 아니다. HTTP로는 500 `INTERNAL_ERROR`로 나가므로 표에 없다.
|
|
- 표에 없는 400·409·422 code는 `MAYBE_APPLIED`로 본다.
|
|
- 400·409·422 밖에서 백엔드 계약이 직접 정한 답 넷도 status와 code가 함께
|
|
맞으면 기능 분류기와 상관없이 `MAYBE_APPLIED`다(`backend-envelope.ts`
|
|
`MAYBE_APPLIED_ANSWERS`). `http-contract.md` §2의 503 `IDEMPOTENCY_UNAVAILABLE`,
|
|
503 `IDEMPOTENCY_COMPLETION_UNKNOWN`(백엔드 `bbe944bd`부터), 500
|
|
`IDEMPOTENCY_RECOVERY_REQUIRED`, §4의 503 `REQUEST_TIMEOUT`이다. 실행기가
|
|
자동으로 다시 보내는 것은 KEYED 명령의 503 `IDEMPOTENCY_UNAVAILABLE`뿐이다.
|
|
나머지는 결과 불명 화면에서 사용자가 같은 키로 다시 보낸다.
|
|
- §4의 503 `RATE_LIMIT_UNAVAILABLE`(rate-limit 저장소 응답 없음, `Retry-After` 있음)과
|
|
503 `RATE_LIMIT_INCOMPATIBLE`(rate-limit 제공자가 계약과 맞지 않음)은 status와 code가
|
|
함께 맞으면 기능 분류기와 상관없이 `NOT_APPLIED`다(1105/03-02, `backend-envelope.ts`
|
|
`REFUSED_BEFORE_WRITE`). 백엔드 `RateLimitInterceptor.java`의 `preHandle`이 컨트롤러 전에
|
|
`false`를 돌려주며 낸다. `45d2a478`의 main 소스에서 이 두 code를 내는 곳은 그 두
|
|
줄뿐이다. 자동 재전송은 없다(KEYED도 같다). 남은 위험(추론, 실행 확인 안 함): Spring MVC는
|
|
비동기 처리(`Callable`·`DeferredResult`)가 끝난 뒤의 ASYNC 재디스패치에서도 interceptor의
|
|
`preHandle`을 다시 부른다. 그 interceptor는 dispatcher 종류를 보지 않으므로 비동기 쓰기
|
|
컨트롤러라면 이 503(그리고 429)이 쓰기 뒤에도 나올 수 있다. `45d2a478`에는 Envelope을
|
|
돌려주는 비동기 쓰기 컨트롤러가 없다(web-advanced 스트리밍과 fileserver 전송뿐).
|
|
- 파일 위치(백엔드 repo `clean-architecture-backend-template` 기준):
|
|
- `GlobalExceptionHandler.java`, `HttpStatusErrorCodes.java`: `clean-architecture-backend-template/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/`
|
|
- `PageParams.java`, `SortParam.java`: 같은 모듈 `.../web/pagination/`
|
|
- `IdempotencyKeyHeader.java`: 같은 모듈 `.../web/http/`
|
|
- `IdempotencyExecutor.java`: `clean-architecture-backend-template/src/application-core/src/main/java/dev/caskeleton/application/idempotency/`
|
|
- `JsonIdempotentResponseCodec.java`: `clean-architecture-backend-template/src/adapter/inbound/web-advanced/.../advanced/idempotency/`
|
|
- `FailureCategory.java`, `StandardSqlStateErrorMapping.java`,
|
|
`PersistenceExceptionTranslator.java`, `LockRegistryDistributedLock.java`:
|
|
`clean-architecture-backend-template/src/adapter/outbound/persistence-jpa/`
|
|
- `PosterImagePublicationController.java`, `WorkLogWebMapper.java`,
|
|
`RepoStatsAclMapper.java`, `DomainExceptionHandler.java`: `clean-architecture-backend-template/src/sample-portfolio/`
|
|
- `FileserverErrorCode.java`, `FinalizeUploadApplicationUseCase.java`:
|
|
`clean-architecture-backend-template/src/application-fileserver/`
|
|
- Fileserver 한 번 업로드(`POST /v1/files`)는 V3 실행기가 아니라
|
|
`src/adapters/http/fileserver-upload.ts`의 client가 부른다(1105/01-02). 이 client는
|
|
위 표의 fileserver 행과 달리 4xx를 `NOT_APPLIED`로 본다. 업로드 use case
|
|
(`UploadFileApplicationUseCase.java`)가 모호하지 않은 실패에서 업로드를 취소하므로
|
|
`READY` 파일이 남지 않는다. `MALWARE_DETECTED`처럼 레코드를 `REJECTED`로 쓴 뒤
|
|
던지는 code도 그 레코드는 공개되지 않는다. 위 행은 fileserver 응답을 V3 실행기로
|
|
읽을 때의 판정이다.
|
|
- 멱등성 code와 V3 표(`REFUSED_BEFORE_WRITE`, `MAYBE_APPLIED_ANSWERS`)에 있는 답은
|
|
client도 V3 표로 판정한다. 그래서 503 `IDEMPOTENCY_UNAVAILABLE`은 `MAYBE_APPLIED`다.
|
|
`tests/integration/fileserver-upload.test.ts`가 복사한 답 표의 행마다 둘이 같은지 본다.
|
|
- 5xx는 작업 스레드가 게시 전에 내는 code 넷(`PARTIAL_WRITE`,
|
|
`ATOMIC_PUBLISH_UNSUPPORTED`, `STORAGE_UNAVAILABLE`, `STORAGE_FULL`)만
|
|
`NOT_APPLIED`다. 504 `TRANSFER_TIMEOUT`은 `MAYBE_APPLIED`다. 대기 스레드가
|
|
작업 단계와 상관없이 내고, 게시 rename과 `READY` 커밋은 interrupt로 멈추지 않는다
|
|
(`BlockingTransferExecutor.java`, `FinalizeUploadApplicationUseCase.java`). 백엔드는
|
|
이 code를 `retryable: true`, `ambiguous` 없이 보낸다. 이 차이는 백엔드 결정으로 남는다.
|
|
|
|
**operation이 선언하는 쓰기 전 거절**(1103/03-01): 업무 code는 엔드포인트마다
|
|
단계가 달라 위 표에 "쓰기 뒤 가능"으로 둔다. 쓰기 전에만 그 code를 내는 엔드포인트를
|
|
아는 사람은 기능 작성자다. 그 사람이 descriptor의
|
|
`commandEffect.refusedBeforeWrite`에 code를 적는다.
|
|
|
|
- 그 code로 온 400·409·422는 `NOT_APPLIED`다. 적지 않은 code는 그대로 `MAYBE_APPLIED`다.
|
|
- 짝 백엔드 생성 기능의 create는 이름 규칙을 `build(command)`에서 트랜잭션 전에
|
|
검사하고 400 `<FEATURE>_INVALID`를 준다(`Create__Feature__UseCase.java.tmpl`,
|
|
`__Feature__ErrorCode.java.tmpl`). 이 code는 적는다.
|
|
- 위 표의 code(`VALIDATION_FAILED` 등)는 적어도 표의 status 규칙을 따른다.
|
|
`IDEMPOTENT_*`·`IDEMPOTENCY_*`는 적을 수 없다. 계약 조립이 거절하고, 실행기도
|
|
무시한다. 409 `IDEMPOTENT_IN_FLIGHT`의 앞선 요청은 적용될 수 있기 때문이다.
|
|
- 위 표에서 "쓰기 뒤 가능"인 플랫폼 code(`BAD_PARAMETER`, `MAPPING_FAILED`, `DB_*` 8개,
|
|
`LOCK_ACQUISITION_TIMEOUT`, fileserver code)도 적을 수 없다(1105/03-01). 계약 조립이
|
|
거절하고 실행기도 무시한다. 목록은 `src/contracts/external-contract-runtime.ts`의
|
|
`PLATFORM_CODES_POSSIBLY_AFTER_WRITE`이고, `tests/unit/backend-contract-pin.test.ts`가
|
|
이 표의 "쓰기 뒤 가능" 행과 대조한다. 참조 도메인 code와 web-advanced patch code는
|
|
엔드포인트가 단계를 정하므로 그 엔드포인트를 확인한 기능 작성자가 적을 수 있다. 이 표에
|
|
"쓰기 뒤 가능" 플랫폼 code를 더하면 그 목록도 같은 변경에서 고친다.
|
|
- `responseEnvelope: "ENVELOPE_V1"`가 아닌 operation에는 적을 수 없다. 실행기가
|
|
백엔드 code를 읽지 않는다.
|
|
- 판정은 `src/adapters/http/backend-envelope.ts` `envelopeFailureEffect`, 조립 검사는
|
|
`src/contracts/external-contract-runtime.ts` `assertRefusedBeforeWrite`다.
|
|
|
|
프론트 판정과 표가 다른 곳(고치면 이 줄을 지운다):
|
|
|
|
- 참조 기능 분류기(`classifyProblem`)는 참조 fixture(problem+json)용이라
|
|
400·422를 모두 `NOT_APPLIED`로 본다. 참조 기능은 Envelope operation이 아니라
|
|
이 표의 대상이 아니다. 짝 백엔드에 붙이는 Envelope operation은
|
|
`src/adapters/http/backend-envelope.ts`의 표가 400·409·422를 정한다(`3261208`).
|
|
|
|
남은 위험: "쓰기 전"은 현재 코드에서 그 handler에 닿는 출처를 센 결과다. 백엔드가
|
|
application bean에 `@Validated`를 달거나 JPA entity에 Bean Validation 제약을
|
|
넣으면, 필드 목록이 있는 400 `VALIDATION_FAILED`가 use case 안에서도 나온다.
|
|
백엔드에는 이것을 막는 검사가 없다.
|
|
|
|
## 7. Cursor pagination과 snapshot
|
|
|
|
짝 백엔드 템플릿의 페이지 목록은 이 절의 cursor가 아니라 offset이다(`PageParams`,
|
|
`meta.page`, 4.1절). 프론트는 그 `meta.page`를 읽어 기능에 넘길 뿐이고, 아래
|
|
`CursorPage` 계약은 cursor를 고른 백엔드를 위한 것이다. 백엔드가 cursor로 바꾸면
|
|
이 절로 합친다.
|
|
|
|
Backend가 pagination을 선택할 때 새 response schema/operation version으로 다음
|
|
contract를 제공한다.
|
|
|
|
```text
|
|
CursorPage<T>
|
|
items: T[]
|
|
nextCursor: opaque string | null
|
|
hasMore: boolean
|
|
snapshotToken: opaque string | null
|
|
```
|
|
|
|
필수 불변조건:
|
|
|
|
- `hasMore === (nextCursor !== null)`
|
|
- 동일 chain의 `snapshotToken`은 모든 page에서 동일
|
|
- cursor는 principal/tenant, filter, sort, contract version과 snapshot에 binding
|
|
- cursor는 opaque, 무결성 보호, 만료와 key rotation 정책 보유
|
|
- offset이 아니라 stable keyset ordering 사용
|
|
- total order의 마지막 tie-breaker는 immutable unique ID
|
|
- deleted/inserted row가 duplicate/gap을 만드는 의미를 snapshot 정책으로 결정
|
|
- empty page인데 `hasMore=true`인 sparse page 허용 여부를 operation profile에 고정
|
|
- cursor 최대 encoded byte, page size와 total scan/cost ceiling을 server도 강제
|
|
- invalid, expired, wrong-principal, wrong-filter cursor의 safe error code를 고정
|
|
|
|
권장 query ordering 예:
|
|
|
|
```text
|
|
ORDER BY created_at DESC, resource_id DESC
|
|
cursor payload = version + snapshot watermark + last(created_at, resource_id)
|
|
+ filter digest + principal/tenant binding + expiry
|
|
```
|
|
|
|
Cursor 원문은 log, trace, analytics와 frontend persistent storage에 넣지 않는다.
|
|
|
|
### 7.1 배열에서 page로의 migration
|
|
|
|
1. `ReferenceResourceListPagePayloadV2` schema와 새 operation/version을 추가한다.
|
|
2. backend가 N/N-1 동안 기존 배열과 page contract를 동시에 제공한다.
|
|
3. frontend가 cursor runtime을 새 bound query/infinite query에 연결한다.
|
|
4. loop/snapshot/ceiling/abort conformance를 staging에서 검증한다.
|
|
5. 새 operation을 canary한 뒤 기존 배열 operation을 retirement한다.
|
|
|
|
동일 media/status에서 payload shape만 바꾸는 in-place migration은 금지한다.
|
|
|
|
## 8. Conditional read와 revision/CAS
|
|
|
|
### 8.1 Read validator
|
|
|
|
Backend가 application-managed revalidation을 선택하면 exact mapped
|
|
representation마다 ETag를 제공한다.
|
|
|
|
```text
|
|
GET without validator
|
|
-> 200 + JSON envelope + ETag
|
|
|
|
GET with If-None-Match
|
|
-> representation unchanged: 304 + empty body
|
|
-> changed: 200 + JSON envelope + new ETag
|
|
```
|
|
|
|
불변조건:
|
|
|
|
- validator는 principal/tenant, authorization-visible representation,
|
|
response schema/mapper semantics와 encoding variant에 binding
|
|
- weak/strong 선택을 operation profile에 고정
|
|
- user-private response를 shared CDN/public cache에 저장하지 않음
|
|
- cross-origin이면 `ETag`를 expose하고 `If-None-Match`를 preflight 허용
|
|
- 304에는 JSON success envelope를 넣지 않음
|
|
- validator 원문을 log/metric/diagnostics에 넣지 않음
|
|
- `Vary`와 `Cache-Control` owner를 명확히 하고 browser HTTP cache와
|
|
TanStack/application revalidation이 서로 다른 value owner가 되지 않게 함
|
|
|
|
Frontend는 validator와 mapped cache value의 scope, query identity,
|
|
representation version과 cache revision이 모두 일치할 때만 304를 success로
|
|
받는다. cache value가 없으면 unconditional refetch 또는 safe failure로 닫는다.
|
|
|
|
### 8.2 Conditional command
|
|
|
|
수정/삭제 command가 선택되면 DTO에 opaque domain `revision`을 추가하고:
|
|
|
|
```text
|
|
If-Match: "<revision validator>"
|
|
```
|
|
|
|
를 요구한다. 일치하지 않으면 `412` 또는 승인된 `409` contract 하나만
|
|
사용한다. frontend optimistic layer의 commit/rollback은 backend revision
|
|
authority를 대체하지 않는다.
|
|
|
|
## 9. Optimistic mutation을 위한 backend 의미
|
|
|
|
Frontend ordered optimistic layer runtime은 구현돼 있지만 제품 operation에
|
|
연결하려면 backend가 다음을 결정해야 한다.
|
|
|
|
- resource/list membership을 결정하는 canonical filter와 sort
|
|
- command가 생성/수정/삭제하는 stable identity
|
|
- server-assigned ID와 client correlation의 reconcile 방법
|
|
- authoritative resource/list revision
|
|
- conflict status와 stable error code
|
|
- commit response가 complete resource인지 receipt인지
|
|
- effect certainty와 idempotency status/reconcile endpoint
|
|
- event/outbox가 있을 때 sequence/gap/snapshot reset 의미
|
|
|
|
Create가 server-assigned ID를 사용하는 경우 temporary UI ID를 backend ID로
|
|
원자적으로 교체하고 관련 detail/list key를 reconcile하는 정책이 필요하다.
|
|
이 의미 없이 generic optimistic append를 기본 활성화하지 않는다.
|
|
|
|
## 10. Database와 application service baseline
|
|
|
|
구현 예시는 다음 논리 table/constraint를 만족해야 한다.
|
|
|
|
```text
|
|
reference_resource
|
|
tenant_id
|
|
resource_id
|
|
display_name
|
|
note
|
|
revision
|
|
created_at
|
|
updated_at
|
|
deleted_at | null
|
|
unique(tenant_id, resource_id)
|
|
|
|
idempotency_record
|
|
principal/tenant fingerprint
|
|
operation + contract version
|
|
key hash
|
|
request fingerprint
|
|
state + receipt
|
|
lease/retention timestamps
|
|
unique(principal/tenant, operation, contract version, key hash)
|
|
|
|
outbox_event when selected
|
|
aggregate identity + revision
|
|
event type/version
|
|
sequence
|
|
payload reference or bounded safe projection
|
|
publication state
|
|
```
|
|
|
|
Application service transaction은 authorization scope와 tenant predicate를
|
|
모든 read/write에 적용하고, resource mutation과 revision/outbox 기록을 같은
|
|
transaction boundary에 둔다. cache/replica lag를 고려해 command 직후 read
|
|
consistency와 invalidation owner를 선언한다.
|
|
|
|
## 11. GraphQL 선택 시 추가 구조
|
|
|
|
GraphQL은 제품 operation이 REST보다 aggregation 이점을 실제로 가질 때만
|
|
선택한다.
|
|
|
|
```text
|
|
Browser
|
|
-> persisted-operation endpoint
|
|
-> manifest allowlist
|
|
-> auth/CSRF/rate/cost/depth/alias enforcement
|
|
-> GraphQL router
|
|
-> application services/loaders
|
|
```
|
|
|
|
Backend handoff:
|
|
|
|
- authenticated immutable schema artifact와 digest
|
|
- named operation source와 persisted ID/hash manifest
|
|
- variables/result runtime fixtures
|
|
- selected GraphQL-over-HTTP revision과 exact media/status profile
|
|
- partial data policy와 safe error extension vocabulary
|
|
- field/row authorization, cost/depth/alias/list ceiling
|
|
- N/N-1 router/frontend manifest rollout과 retirement
|
|
|
|
Production endpoint는 arbitrary document와 persisted miss 후 full-document
|
|
fallback을 받지 않는다. normalized frontend entity cache는 별도 제품 선택이다.
|
|
|
|
## 12. gRPC-Web 선택 시 추가 구조
|
|
|
|
gRPC-Web은 browser-facing gateway/proxy가 실제 선택된 unary 또는 bounded
|
|
server-stream operation에만 사용한다.
|
|
|
|
```text
|
|
Browser
|
|
-> same-origin BFF/Envoy/gRPC-Web gateway
|
|
-> exact service/method allowlist
|
|
-> frame/message/deadline/status/trailer enforcement
|
|
-> internal gRPC application service
|
|
```
|
|
|
|
Backend handoff:
|
|
|
|
- authenticated proto source와 immutable descriptor digest
|
|
- Buf/protoc lint/breaking 및 deterministic generation evidence
|
|
- exact service/method/rpc-kind allowlist
|
|
- selected gRPC-Web runtime kind, client API와 binary/JSON/text/wire revision;
|
|
official XHR와 Connect-Web Fetch profile을 분리
|
|
- proxy CORS, content-type, terminal status/trailer behavior
|
|
- Envoy를 선택하면 exact version/config digest, filter order, upstream HTTP/2,
|
|
route/idle/max-stream timeout, timeout offset와 buffering/flush
|
|
- message/frame/count/queue/idle/total budget
|
|
- server-stream sequence, gap, resume와 snapshot reset protocol
|
|
- actual browser/proxy conformance
|
|
|
|
client streaming과 bidirectional streaming은 common gRPC-Web browser contract로
|
|
간주하지 않는다. upload는 REST transfer, duplex는 별도 protocol을 선택한다.
|
|
|
|
## 13. Connect-Web/Connect 선택 시 추가 구조
|
|
|
|
Connect는 Protobuf-first backend의 selected unary 또는 bounded server-stream
|
|
operation에만 사용한다. Connect protocol과 Connect-Web의 gRPC-Web transport는
|
|
서로 다른 provider row다.
|
|
|
|
```text
|
|
Browser Connect-Web adapter
|
|
-> same-origin BFF 또는 exact cross-origin Connect endpoint
|
|
-> auth/CSRF/CORS + service/method allowlist
|
|
-> Connect protocol handler
|
|
-> application service
|
|
```
|
|
|
|
Backend handoff:
|
|
|
|
- authenticated proto/Buf source, descriptor와 generated-service digest
|
|
- exact Connect-Web/client runtime과 server/gateway version
|
|
- protocol revision, JSON/binary encoding, POST 또는 approved GET
|
|
- unary HTTP/error profile 또는 stream EndStream terminal profile
|
|
- request/response/envelope/message/count/queue byte ceiling
|
|
- unary/stream compression capability; stock browser stream은 identity-only
|
|
- total/idle timeout, browser abort→server context→downstream cancellation 전파
|
|
- exact CORS allow/expose/preflight와 auth/CSRF profile
|
|
- actual Chromium/Firefox/WebKit와 selected proxy/server conformance
|
|
|
|
GET은 descriptor `NO_SIDE_EFFECTS`, non-sensitive bounded input, URL/cache key,
|
|
`Vary`와 credential policy가 모두 승인된 unary에만 허용한다. browser
|
|
client-streaming/bidi는 Connect protocol 자체 기능과 별개로 `PLATFORM_LIMITED`다.
|
|
|
|
## 14. Protobuf REST Gateway 선택 시 추가 구조
|
|
|
|
한 route는 `CURATED_BFF | GRPC_GATEWAY | ENVOY_TRANSCODER` 중 하나만 소유한다.
|
|
현재 reference REST의 envelope와 `200|201`, 향후 `204/304/412` 의미를 유지하는
|
|
기본 선택은 curated BFF다.
|
|
|
|
Direct gateway는 ProtoJSON/HttpRule/status/error 자체를 새 public contract로
|
|
승인한 unary operation에서만 선택한다. Backend handoff:
|
|
|
|
- `.proto` annotation 또는 precedence가 고정된 service config의 immutable source
|
|
- descriptor/Buf image, canonical HttpRule route manifest와 digest
|
|
- pinned gateway/runtime/generator/plugin과 generated OpenAPI artifact
|
|
- ProtoJSON name/default/enum/int64/bytes/null/presence/unknown-field profile
|
|
- exact method/path/query/body/response-body/additional-binding와 path escaping
|
|
- safe status/error/header mapping과 raw `google.rpc.Status` detail redaction
|
|
- CORS/auth/CSRF, body/header/query ceiling와 rate limit
|
|
- browser abort/deadline의 upstream gRPC/application work 전파
|
|
- N/N-1 route/OpenAPI/runtime conformance와 coherent rollback
|
|
|
|
Gateway는 durable idempotency, pagination snapshot, ETag/HTTP conditional,
|
|
product envelope, authorization와 file transfer semantics를 자동 구현하지 않는다.
|
|
필요한 operation은 application service와 BFF가 계속 소유한다. generated
|
|
REST streaming은 별도 framing/terminal/cache ADR 없이는 `NOT_SELECTED`다.
|
|
|
|
## 15. Invalidation과 realtime
|
|
|
|
현재 frontend cross-tab invalidation은 같은 browser origin 안의 opaque
|
|
invalidate-only hint다. backend event delivery를 의미하지 않는다.
|
|
|
|
Backend-driven invalidation/realtime을 선택하면:
|
|
|
|
- transactional outbox 또는 동등한 durable publication
|
|
- principal/tenant authorization을 통과한 event projection
|
|
- event type/version, aggregate revision, sequence와 dedupe identity
|
|
- reconnect cursor, gap detection과 snapshot reset
|
|
- retention, replay ceiling과 slow-consumer policy
|
|
|
|
를 제공해야 한다. event payload를 authoritative resource snapshot으로 쓸지
|
|
query invalidate hint로만 쓸지 operation별 reducer contract가 필요하다.
|
|
|
|
## 16. Rate limit, deadline와 retry
|
|
|
|
- backend deadline은 frontend total deadline보다 짧거나 cancellation을 전파할 수
|
|
있어야 한다.
|
|
- disconnect/cancel 뒤 불필요한 query 작업은 중단한다.
|
|
- keyed command는 disconnect가 transaction rollback을 보장하지 않으므로
|
|
idempotency receipt로 effect를 판정한다.
|
|
- `Retry-After`는 selected status에서만 bounded delta/date 형식으로 제공한다.
|
|
- retry-safe read와 keyed command를 구분한다.
|
|
- proxy, BFF와 service retry가 겹쳐 retry amplification을 만들지 않게 한 owner만
|
|
재시도한다.
|
|
- rate limit key는 principal/tenant/operation과 abuse policy에 binding하며 raw
|
|
credential/IP를 metric label에 넣지 않는다.
|
|
|
|
### 16.1 전송별 재시도·타임아웃 규칙 (2026-09-25 코드 기준)
|
|
|
|
같은 이름의 정책이라도 전송마다 동작이 다르다. operation을 다른 전송으로 옮기면
|
|
이 표로 동작 변화를 확인한다.
|
|
|
|
| 규칙 | V3 contract executor | Browser RPC |
|
|
|---|---|---|
|
|
| KEYED 명령 자동 재시도 | 전송 전 실패만 재시도한다. 전송 뒤 실패는 재시도하지 않고 `MAYBE_APPLIED`다. 응답으로는 재시도하지 않는다. 예외: Envelope operation이 503 `IDEMPOTENCY_UNAVAILABLE`(실행 전 거절, 백엔드 §2가 같은 키 재전송을 요구)을 받으면 `retryBudget` 안에서 같은 키로 다시 보낸다 (`src/adapters/http/http-retry-lifecycle.ts` `canRetryTransport`, `isRetryableSemantics`, `backend-envelope.ts` `invitesKeyedResend`) | `KEYED_COMMAND`는 유효한 키가 있고 profile `retryOwner`가 `FRONTEND_ADAPTER`면 `retryableFailures`에서 같은 키로 다시 보낸다 (`src/adapters/browser-rpc/browser-rpc-runtime.ts` `shouldRetry`) |
|
|
| 재시도 횟수 상한 | min(계약 `retryBudget`, `MAX_RETRY_ATTEMPTS`, 2) (`http-execution-v3.ts` `retryCeiling`) | profile `maxAttempts`(시도 횟수), 하드 상한 4 (`src/contracts/browser-rpc.ts` `BROWSER_RPC_HARD_LIMITS`) |
|
|
| `Retry-After` | 5초를 넘으면 재시도하지 않는다. 이하면 hint에 jitter를 더해 기다린다 (`http-retry-lifecycle.ts` `retryDelayFor`) | profile `maxRetryAfterMs`로 잘라 max(backoff, hint)만큼 기다린다. 하드 상한 60초 (`browser-rpc-runtime.ts` `retryDelay`) |
|
|
| `REQUEST_TIMEOUT_MS` | 상한이다. 계약 `totalDeadlineMs`를 줄이기만 한다 (`runtime-adapters.ts` `requestDeadlineCeilingMs`) | 쓰지 않는다. operation `totalDeadlineMs`만 쓴다. 하드 상한 30분 |
|
|
|
|
결과 불명 뒤 사용자 재전송은 전송과 무관하게 같은 intent·같은 키를 쓴다
|
|
(`src/presentation/adapters/query/application-query.ts` `resendUnknownEffect`).
|
|
|
|
## 17. Observability와 privacy
|
|
|
|
허용되는 공통 dimension:
|
|
|
|
```text
|
|
operation ID
|
|
contract/profile version
|
|
status group / safe error code
|
|
attempt bucket
|
|
duration bucket
|
|
provider/runtime health
|
|
traffic admission stage
|
|
```
|
|
|
|
금지:
|
|
|
|
- Authorization, cookie, CSRF와 idempotency key
|
|
- request/response body와 validation value
|
|
- URL query, cursor, snapshot, ETag/revision
|
|
- GraphQL variables/path/raw error/extensions
|
|
- protobuf bytes, metadata와 trailer 원문
|
|
- user ID/email/file name을 metric label이나 trace attribute로 사용
|
|
|
|
Request ID와 trace ID는 browser에 반환할 수 있지만 credential 역할을 하지 않으며
|
|
추측 가능한 database primary key를 포함하지 않는다.
|
|
|
|
필수 SLO/alert 후보:
|
|
|
|
- operation availability와 latency
|
|
- 401/403/409/412/422/429 및 5xx rate
|
|
- schema/mapper/contract mismatch
|
|
- idempotency in-progress age, collision과 unknown effect
|
|
- cursor invalid/expired/loop-equivalent server detection
|
|
- conditional hit/miss와 invalid 304
|
|
- GraphQL persisted miss/cost reject
|
|
- Connect missing/duplicate EndStream, whole-body/queue overflow와 compression mismatch
|
|
- gRPC-Web missing terminal status, frame/idle/queue overflow
|
|
- REST Gateway route/OpenAPI/runtime rewrite drift와 cancel propagation loss
|
|
|
|
## 18. 배포, compatibility와 rollback
|
|
|
|
권장 순서:
|
|
|
|
1. contract artifact와 compatibility diff를 생성한다.
|
|
2. backend가 N/N-1 fixture를 통과한 상태로 먼저 배포한다.
|
|
3. frontend operation은 traffic disabled 상태에서 staging conformance를 실행한다.
|
|
4. read-only shadow/canary 뒤 query traffic을 올린다.
|
|
5. keyed command는 idempotency/reconcile fault injection 뒤 별도 canary한다.
|
|
6. pagination, conditional, optimistic, GraphQL, Connect, gRPC-Web과 REST
|
|
Gateway는 각각 독립 gate로 승격한다.
|
|
7. provider/browser/operations evidence가 완료된 operation만 enabled한다.
|
|
|
|
Rollback은 frontend/backend/contract artifact를 coherent set으로 되돌린다.
|
|
unknown-effect command를 다른 protocol이나 새 idempotency key로 replay하지 않는다.
|
|
Backend가 old contract를 제거하는 시점은 실제 frontend support window와 cache/CDN
|
|
retention 뒤다.
|
|
|
|
## 19. Conformance와 fault-injection matrix
|
|
|
|
Backend 완료 판정에는 unit test 외에 actual staging provider evidence가 필요하다.
|
|
|
|
| 범위 | 필수 증거 |
|
|
| --- | --- |
|
|
| REST | exact path/query/body, media/status/envelope, max body, malformed/truncated JSON |
|
|
| Auth | missing/expired credential, 401/403, rotation, cross-origin preflight |
|
|
| Command | concurrent same-key replay, fingerprint mismatch, commit 뒤 response loss |
|
|
| Cursor | filter/sort binding, expiry, snapshot stability, loop/gap/duplicate 방지 |
|
|
| Conditional | 200→304, cache-missing 304 방지, representation change, 412 |
|
|
| Schema | additive/breaking/null/enum/time/number fixtures와 N/N-1 |
|
|
| GraphQL | persisted hit/miss/hash mismatch, partial, cost/depth, router rollout |
|
|
| Connect | JSON/binary unary, GET restriction, EndStream, body/message cap, compression, cancel/deadline와 CORS |
|
|
| gRPC-Web | proxy media/status/trailer, oversized frame, cancel, idle, gap/resume |
|
|
| REST Gateway | HttpRule path/query/body, ProtoJSON, OpenAPI/status/error rewrite, abort propagation과 N/N-1 |
|
|
| Operations | deadline/retry amplification, rate limit, kill switch, coherent rollback |
|
|
|
|
## 20. Backend handoff checklist
|
|
|
|
- [ ] Browser-facing API/BFF owner와 on-call이 정해졌다.
|
|
- [ ] reference REST exact endpoint/envelope/status/media fixture가 있다.
|
|
- [ ] bearer 또는 cookie+CSRF 중 하나의 실제 profile과 CORS evidence가 있다.
|
|
- [ ] stable error vocabulary와 redaction contract가 있다.
|
|
- [ ] keyed command idempotency store, TTL, receipt와 reconcile이 있다.
|
|
- [ ] CursorPage를 선택했다면 opaque cursor/snapshot contract가 있다.
|
|
- [ ] conditional을 선택했다면 ETag/304/412와 cache owner가 있다.
|
|
- [ ] optimistic을 선택했다면 identity/membership/revision/conflict 의미가 있다.
|
|
- [ ] OpenAPI/runtime schema/mapper semantic artifact와 digest가 release에 binding됐다.
|
|
- [ ] GraphQL을 선택했다면 schema/persisted manifest/router evidence가 있다.
|
|
- [ ] Connect를 선택했다면 descriptor/runtime/server/browser evidence가 있다.
|
|
- [ ] gRPC-Web을 선택했다면 descriptor/proxy/browser evidence가 있다.
|
|
- [ ] REST Gateway를 선택했다면 kind/HttpRule/ProtoJSON/OpenAPI와 runtime
|
|
conformance evidence가 있다.
|
|
- [ ] staging conformance, fault injection, canary, kill switch와 rollback drill이
|
|
통과했다.
|
|
|
|
## 21. Frontend 완료 경계
|
|
|
|
Backend 구현과 별개로 현재 frontend 상태를 다음처럼 해석한다.
|
|
|
|
| 범위 | 현재 상태 | 남은 owner |
|
|
| --- | --- | --- |
|
|
| REST path/provider/auth/deadline/bounded JSON | `COMPOSED` | actual provider conformance는 backend/operations |
|
|
| runtime schema와 mapper registry | `COMPOSED` | artifact digest/source provenance는 backend contract source + frontend/platform |
|
|
| session generation과 query identity | `COMPOSED` | account identity projection은 identity integration + frontend |
|
|
| Cursor runtime | `AVAILABLE_NOT_COMPOSED` | CursorPage backend 계약 후 frontend query binding |
|
|
| conditional validator store | `AVAILABLE_NOT_COMPOSED` | ETag/304/412 backend 계약 후 frontend HTTP/cache transaction |
|
|
| ordered optimistic layer | `AVAILABLE_NOT_COMPOSED` | product membership/revision 승인 후 frontend mutation definition |
|
|
| GraphQL adapter | `DESIGNED_NOT_IMPLEMENTED` | product/backend 선택 뒤 frontend adapter/codegen |
|
|
| Browser RPC V3 공통 계약/coordinator | `AVAILABLE_NOT_COMPOSED` | selected descriptor/generated client와 protocol transport 확정 뒤 frontend provider adapter |
|
|
| Protobuf schema/codegen | `DESIGNED_NOT_IMPLEMENTED` | authenticated backend contract source 선택 뒤 pinned frontend generation |
|
|
| Connect-Web adapter | `DESIGNED_NOT_IMPLEMENTED` | product/backend/server 선택 뒤 frontend adapter/codegen |
|
|
| gRPC-Web adapter | `DESIGNED_NOT_IMPLEMENTED` | product/backend/proxy 선택 뒤 frontend adapter/codegen |
|
|
| Protobuf REST Gateway | `NOT_SELECTED` | gateway kind와 public HTTP contract 승인 뒤 REST adapter binding |
|
|
| persisted query/offline command | `NOT_SELECTED` | 별도 product ADR와 backend durability 계약 |
|
|
|
|
따라서 “backend만 구현하면 frontend가 아무 변경 없이 모든 capability를 자동
|
|
사용한다”는 의미는 아니다. 현재 선택된 REST reference vertical의 공통 frontend
|
|
기반은 완료됐지만, backend contract가 확정되면 Cursor/conditional/optimistic의
|
|
마지막 composition과 schema/mapper 변경이 frontend에 남는다. GraphQL,
|
|
Connect/gRPC-Web과 Protobuf REST Gateway는 제품이 선택되지 않았다. 공통 Browser
|
|
RPC operation/profile registry, application port와 lifecycle coordinator는
|
|
구현했지만, wire별 generated client/decoder/provider binding은 아직 구현하지
|
|
않았다. 따라서 backend contract가 정해져도 frontend provider adapter와
|
|
composition 작업은 명시적으로 남는다.
|