diff --git a/docs/architecture/backend-api-and-server-state-contract.md b/docs/architecture/backend-api-and-server-state-contract.md index 77a1fe7b..86dd5aeb 100644 --- a/docs/architecture/backend-api-and-server-state-contract.md +++ b/docs/architecture/backend-api-and-server-state-contract.md @@ -8,9 +8,9 @@ > 본 문서의 해당 서술이 정본과 충돌하면 정본을 따른다. -- 상태: frontend handoff design accepted, backend implementation/evidence pending. 단 4.1·6·6.1절(Envelope 읽기, effect 판정, 쓰기 전 거절 표)은 지금 실행 규칙이다(`COMPOSED`, `src/adapters/http/backend-envelope.ts`) +- 상태: frontend handoff 설계는 승인됨, backend 구현·증거는 대기 중. 단 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, +- 대상: Web API/BFF, 애플리케이션 서비스, 영속 계층(persistence), 신원(identity), GraphQL router, Connect/gRPC-Web gateway, Protobuf REST Gateway와 운영 owner - frontend 기준: [API contract, Schema, Mapper와 Server State](../design/2026-07-28-api-contract-schema-mapper-and-server-state-design.md) @@ -28,14 +28,14 @@ 언어·framework·cloud 제품을 강제하지 않는다. Spring, Nest/Fastify, Go, .NET 또는 다른 stack을 사용해도 아래 불변조건은 동일하다. -이 repository에는 backend source, database migration, identity provider, +이 repository에는 backend 소스 코드, 데이터베이스 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 계약만 +gRPC-Web 애플리케이션 API, Protobuf REST Gateway와 frontend Server State 계약만 소유한다. ## 2. 권장 논리 구조 @@ -70,8 +70,8 @@ Browser-facing contract owner와 내부 service contract owner를 분리한다. 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에 노출하지 않는다. +- 영속 계층(persistence) adapter는 SQL/NoSQL/Redis vendor 타입, row version과 cursor + 구현을 외부 DTO에 노출하지 않는다. - GraphQL router, Connect/gRPC-Web gateway와 REST transcoder는 선택 adapter다. 다른 protocol로 임의 fallback하거나 frontend에 내부 service address를 노출하지 않는다. @@ -193,8 +193,8 @@ Envelope의 모양과 키 존재 규칙은 짝 백엔드 템플릿 문서가 정 `results` Envelope는 `ENVELOPE_MISMATCH`다. bulk 엔드포인트를 붙이려면 그 operation을 `responseEnvelope: "NONE" as const`로 적고 별도 계약 기여에 둔다(한 기여의 operation은 같은 값을 적는다. 기능 하나가 기여 둘을 낼 수 있다, - `tests/unit/external-contract-runtime.test.ts` "lets one feature read two backends - through two contributions"). 기능 스키마가 본문 전체를 읽고 `classifyProblem`이 + `tests/unit/external-contract-runtime.test.ts` + "lets one feature read two backends through two contributions"). 기능 스키마가 본문 전체를 읽고 `classifyProblem`이 적용 여부를 정한다. ### 4.2 Status와 error @@ -215,7 +215,7 @@ Envelope의 모양과 키 존재 규칙은 짝 백엔드 템플릿 문서가 정 않았다. conditional mutation을 선택할 때 frontend failure vocabulary와 transaction을 함께 승격해야 한다. -Backend `error.code`는 machine-readable stable code다. stack, SQL/vendor error, +Backend `error.code`는 기계가 읽을 수 있는 안정된 code다. stack, SQL/vendor 오류, raw validation value, authorization reason과 내부 service address를 반환하지 않는다. @@ -243,7 +243,7 @@ revocation/session policy를 검증하고 operation별 authorization을 적용 - 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 동작 +- session 고정 공격(session fixation), token 교체(rotation)와 여러 탭을 동시에 쓸 때의 동작 Cross-origin bearer provider 최소 CORS: @@ -255,7 +255,7 @@ Cross-origin bearer provider 최소 CORS: (`src/adapters/http/feature-http-binding.ts`). expose하지 않거나 응답이 없으면 클라이언트가 보낸 값이 된다. Envelope operation의 실패 본문 `meta.traceId`는 `AppFailure.traceId`가 된다(헤더가 아니라 본문이라 CORS expose와 상관없다) -- redirect login page, HTML error body와 wildcard credential 금지 +- login 페이지로 redirect, HTML 오류 본문과 wildcard credential 금지 ## 6. Command와 idempotency @@ -436,7 +436,7 @@ CursorPage - 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를 고정 +- 잘못된 cursor, 만료된 cursor, 다른 principal의 cursor, 다른 filter의 cursor에 줄 안전한 오류 code를 고정 권장 query ordering 예: @@ -486,7 +486,7 @@ GET with If-None-Match - `Vary`와 `Cache-Control` owner를 명확히 하고 browser HTTP cache와 TanStack/application revalidation이 서로 다른 value owner가 되지 않게 함 -Frontend는 validator와 mapped cache value의 scope, query identity, +Frontend는 validator와 mapping된 cache 값의 scope, query identity, representation version과 cache revision이 모두 일치할 때만 304를 success로 받는다. cache value가 없으면 unconditional refetch 또는 safe failure로 닫는다. @@ -578,7 +578,7 @@ Backend handoff: - 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 +- 부분 데이터(partial data) 정책과 안전한 error extension 어휘 - field/row authorization, cost/depth/alias/list ceiling - N/N-1 router/frontend manifest rollout과 retirement @@ -600,16 +600,16 @@ Browser Backend handoff: -- authenticated proto source와 immutable descriptor digest +- 인증된 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, +- Envoy를 선택하면 정확한 version/config digest, filter 순서, 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 +- server-stream의 순번(sequence), 빈틈(gap), 재개(resume)와 snapshot 초기화 protocol - actual browser/proxy conformance client streaming과 bidirectional streaming은 common gRPC-Web browser contract로 @@ -636,7 +636,7 @@ Backend handoff: - 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 +- unary/stream 압축 capability. 기본(stock) 브라우저 stream은 identity 인코딩만 쓴다 - 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 @@ -664,7 +664,7 @@ Direct gateway는 ProtoJSON/HttpRule/status/error 자체를 새 public contract - browser abort/deadline의 upstream gRPC/application work 전파 - N/N-1 route/OpenAPI/runtime conformance와 coherent rollback -Gateway는 durable idempotency, pagination snapshot, ETag/HTTP conditional, +Gateway는 지속되는(durable) 멱등성, pagination snapshot, ETag/HTTP 조건부 요청, product envelope, authorization와 file transfer semantics를 자동 구현하지 않는다. 필요한 operation은 application service와 BFF가 계속 소유한다. generated REST streaming은 별도 framing/terminal/cache ADR 없이는 `NOT_SELECTED`다. @@ -678,8 +678,8 @@ 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 +- event type/version, aggregate revision, 순번(sequence)과 중복 제거(dedupe) identity +- 재연결 cursor, 빈틈 감지(gap detection)와 snapshot 초기화 - retention, replay ceiling과 slow-consumer policy 를 제공해야 한다. event payload를 authoritative resource snapshot으로 쓸지 @@ -745,13 +745,13 @@ Request ID와 trace ID는 browser에 반환할 수 있지만 credential 역할 - operation availability와 latency - 401/403/409/412/422/429 및 5xx rate - schema/mapper/contract mismatch -- idempotency in-progress age, collision과 unknown effect +- 멱등 요청이 처리 중(in-progress)으로 머문 시간, 키 충돌(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 +- REST Gateway route/OpenAPI/runtime rewrite의 어긋남(drift)과 취소 전파 유실 ## 18. 배포, compatibility와 rollback @@ -779,7 +779,7 @@ 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 | +| Command | 같은 키 동시 replay, fingerprint 불일치, commit 뒤 응답 유실 | | 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 | @@ -787,7 +787,7 @@ Backend 완료 판정에는 unit test 외에 actual staging provider evidence가 | 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 | +| Operations | deadline/retry 증폭, 요청 한도(rate limit), 긴급 차단 스위치(kill switch), 일관된 rollback | ## 20. Backend handoff checklist @@ -805,7 +805,7 @@ Backend 완료 판정에는 unit test 외에 actual staging provider 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이 +- [ ] staging 적합성 검사(conformance), 장애 주입(fault injection), canary, kill switch와 rollback drill이 통과했다. ## 21. Frontend 완료 경계 @@ -815,17 +815,17 @@ 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 | +| runtime schema와 mapper registry | `COMPOSED` | artifact digest/source provenance는 backend 계약 원천(contract source)과 frontend/platform | +| session generation과 query identity | `COMPOSED` | 계정 identity projection은 identity 연동 담당과 frontend | +| Cursor runtime | `AVAILABLE_NOT_COMPOSED` | CursorPage backend 계약 뒤 frontend query 연결(binding) | +| conditional validator store | `AVAILABLE_NOT_COMPOSED` | ETag/304/412 backend 계약 뒤 frontend HTTP/cache 트랜잭션 | +| ordered optimistic layer | `AVAILABLE_NOT_COMPOSED` | 제품의 membership/revision 승인 뒤 frontend mutation 정의 | | 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 | +| Protobuf schema/codegen | `DESIGNED_NOT_IMPLEMENTED` | 인증된 backend contract source 선택 뒤, 버전을 고정한 frontend 코드 생성 | | 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 | +| Protobuf REST Gateway | `NOT_SELECTED` | gateway 종류와 공개 HTTP contract 승인 뒤 REST adapter 연결(binding) | | persisted query/offline command | `NOT_SELECTED` | 별도 product ADR와 backend durability 계약 | 따라서 “backend만 구현하면 frontend가 아무 변경 없이 모든 capability를 자동 diff --git a/docs/architecture/capability-consumer-experience.md b/docs/architecture/capability-consumer-experience.md index 422fbc66..8711e45e 100644 --- a/docs/architecture/capability-consumer-experience.md +++ b/docs/architecture/capability-consumer-experience.md @@ -1,157 +1,146 @@ -# Capability consumer experience baseline +# capability 소비자 경험 기준선 -Correctness inside a reusable capability is not sufficient. The platform is -also evaluated by how much of that correctness a normal feature developer must -understand. +재사용 capability 안이 올바르다는 것만으로는 부족하다. +플랫폼은 그 올바름을 쓰려고 보통의 feature 개발자가 얼마나 많이 알아야 하는지로도 평가받는다. -These measurements are baselines, not score targets. A lower line count is not -automatically better if it hides business semantics or creates a universal -repository abstraction. +이 측정값은 기준선이지 점수 목표가 아니다. +줄 수가 적어도 업무 의미를 숨기거나 만능 repository 추상화를 만든다면, 저절로 더 좋은 것이 아니다. -## Scenario A — a REST feature +## 시나리오 A — REST feature -The REST consumer is the feature `corepack pnpm create:feature --with-create` -writes (the template's reference sample had this role until 2026-11-07). +REST 소비자는 `corepack pnpm create:feature --with-create`가 +쓰는 feature다(2026-11-07까지는 템플릿의 참조 샘플이 이 역할을 했다). -It covers list/detail/create behavior, mapping, typed operation inputs and -application ports. +목록·상세·생성 동작, 매핑, 타입이 있는 operation 입력, application port를 다룬다. -The feature-owned boundary and application source is these four files: +feature가 소유한 경계 코드와 application 코드는 다음 네 파일이다. - `application/-feature-api.ts` - `contracts/-mapper.ts` - `adapters/-http-gateway.ts` - `adapters/create--feature-input.ts` -This document does not keep their line counts; a hand-typed count drifted -from the code (review 14-07). Measure them in a generated feature with -`wc -l` on those four files. +이 문서는 이 파일들의 줄 수를 적어 두지 않는다. 손으로 적은 줄 수가 코드와 어긋난 적이 있다(리뷰 14-07). +생성한 feature에서 이 네 파일에 `wc -l`을 돌려 잰다. -The important boundary metric is not the raw total. It is what those files need -to know about the platform. +중요한 경계 지표는 단순 합계가 아니다. 이 파일들이 플랫폼에 대해 무엇을 알아야 하는지다. -Current result: +지금 결과: -- HTTP platform imports in the feature adapter layer: 2 files, -- canonical import path used by both: - `src/adapters/http/index.ts`, -- direct imports of `http-execution-v3.ts`, retry scheduler, response reader, - auth admission or effect-certainty internals: 0, -- feature gateway owns transport failure projection: 0, -- feature gateway chooses operation ID, route ID, exact input/value type and - mapper: yes, -- central installed files own feature-specific adapter/runtime wiring: no; - feature-owned contributions are aggregated centrally. +- feature adapter 계층에서 HTTP 플랫폼을 import하는 파일: 2개 +- 두 파일이 쓰는 정식 import 경로: + `src/adapters/http/index.ts` +- `http-execution-v3.ts`, retry scheduler, 응답 reader, 인증 승인(auth admission), + effect-certainty 내부 모듈을 직접 import하는 곳: 0 +- 전송 실패를 변환(projection)하는 일을 feature gateway가 맡는 곳: 0 +- feature gateway가 operation ID, route ID, 정확한 입력·값 타입, mapper를 고르는가: 예 +- 중앙 설치 파일이 feature 전용 adapter·runtime 연결을 소유하는가: 아니오. + feature가 소유한 contribution을 중앙에서 모을 뿐이다. -The reusable HTTP capability now owns execution-outcome normalization through -`createFeatureHttpBinding`. A feature may still implement a custom outbound -adapter behind its application port when the reusable contract does not match -its business requirement. +실행 결과를 정규화하는 일은 이제 재사용 HTTP capability가 +`createFeatureHttpBinding`으로 맡는다. +재사용 계약이 업무 요구에 맞지 않으면, feature는 여전히 자기 application port 뒤에 직접 만든 outbound adapter를 둘 수 있다. -## Scenario B — IndexedDB local draft +## 시나리오 B — IndexedDB 로컬 초안 -The executable consumer probe is: +실행되는 소비자 탐침(probe)은 다음이다. `tests/contract/consumer-experience/indexeddb-local-draft.test.ts` -It runs and reads the one Local Draft implementation, the test fixture -`tests/fixtures/indexeddb-consumer` (the template's former local-draft sample -under `src/features/`, moved there because it is no product feature). An -earlier isolated copy had drifted from it and was removed (09-12). +이 테스트는 Local Draft 구현 하나를 실행하고 읽는다. 그 구현은 테스트 fixture +`tests/fixtures/indexeddb-consumer`다. 예전에 `src/features/` 아래 있던 템플릿의 local-draft 샘플인데, +제품 feature가 아니라서 이리로 옮겼다. +예전에 따로 떼어 둔 복사본은 이 구현과 어긋나서 지웠다(09-12). -The consumer owns the Local Draft domain/application API and declares the slice -of the repository it calls (`LocalDraftRepository` in -`tests/fixtures/indexeddb-consumer/adapters/local-draft-indexeddb-store.ts`). The -host hands in an `IndexedDbRepositoryPort` through the -`indexedDb` capability; the port satisfies that slice structurally. The -cross-capability composition contract lives at: +소비자는 Local Draft의 domain·application API를 소유한다. +그리고 repository에서 자기가 부르는 부분(slice)을 선언한다 +(`tests/fixtures/indexeddb-consumer/adapters/local-draft-indexeddb-store.ts`의 `LocalDraftRepository`). +host는 `indexedDb` capability로 `IndexedDbRepositoryPort`를 넘겨준다. +이 port는 구조적 타입으로 그 slice를 만족한다. +capability를 가로지르는 조립 계약은 다음에 있다. `tests/contract/reusable-capability/feature-adapter-composition.test.ts` -That test composes one HTTP-only contribution and the IndexedDB-only Local Draft -contribution through the same generic catalog path. +이 테스트는 HTTP만 쓰는 contribution 하나와 IndexedDB만 쓰는 Local Draft contribution을 +같은 범용 카탈로그 경로로 조립한다. -The browser-level composition proof lives at: +브라우저 수준의 조립 증명은 다음에 있다. `tests/browser-capabilities/local-draft-composition.spec.ts` -It runs against native browser IndexedDB. The test creates the platform -`createIndexedDbRuntime`, exposes that runtime through the typed -`createIndexedDbRepositoryProvider`, composes -`LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION`, then executes Local Draft -save/find/remove through the feature API. The Local Draft feature still does -not import the IndexedDB runtime or native browser API. +이 테스트는 브라우저의 실제 IndexedDB에서 돈다. 먼저 플랫폼의 +`createIndexedDbRuntime`을 만들고, 타입이 있는 +`createIndexedDbRepositoryProvider`로 그 runtime을 내놓는다. 그다음 +`LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION`을 조립하고, feature API로 Local Draft의 +저장·조회·삭제를 실행한다. 그래도 Local Draft feature는 IndexedDB runtime이나 브라우저 기본 API를 import하지 않는다. -Measured on the Local Draft consumer, then under `src/features/` (09-12): +Local Draft 소비자가 아직 `src/features/` 아래 있을 때 잰 값(09-12): -| Metric | Result | +| 지표 | 결과 | | --- | ---: | -| feature LOC (all `.ts` files) | 295 | -| import statements leaving the feature (`contracts/errors`, `contracts/result`, `application-api`, `feature-adapter-contribution`) | 7 | -| native IndexedDB API references | 0 | -| `src/adapters/storage/indexeddb/**` imports | 0 | -| `src/application/ports/browser-file-storage/**` imports | 0 | +| feature LOC (모든 `.ts` 파일) | 295 | +| feature 밖으로 나가는 import 문(`contracts/errors`, `contracts/result`, `application-api`, `feature-adapter-contribution`) | 7 | +| 브라우저 기본 IndexedDB API 참조 | 0 | +| `src/adapters/storage/indexeddb/**` import | 0 | +| `src/application/ports/browser-file-storage/**` import | 0 | -The feature does not import the storage runtime or its port, so removing the -browser file/storage runtime (`test:browser-file-storage-removal`) leaves it -compiling. +이 feature는 storage runtime도 그 port도 import하지 않는다. +그래서 브라우저 file/storage runtime을 지워도(`test:browser-file-storage-removal`) 계속 컴파일된다. -The contract test rejects feature source that reaches for +계약 테스트는 다음에 손대는 feature 코드를 거부한다. `globalThis.indexedDB`, `IDBFactory`, `IDBDatabase`, `IDBTransaction`, -`IDBObjectStore`, the concrete IndexedDB adapter directory or the -browser-file-storage port. +`IDBObjectStore`, 구체 IndexedDB adapter 디렉터리, browser-file-storage port다. -## What this does and does not prove +## 이것이 증명하는 것과 증명하지 않는 것 -The contract probe confirms that **feature business code does not need native -IndexedDB knowledge** once an `IndexedDbRepositoryPort` has been composed. -The browser-capability proof additionally confirms that the same feature -contribution works when that port is backed by the repository's real -`createIndexedDbRuntime` and native IndexedDB implementation. +계약 탐침은 `IndexedDbRepositoryPort`가 조립되고 나면 +**feature 업무 코드에 브라우저 기본 IndexedDB 지식이 필요 없다**는 것을 확인한다. +브라우저 capability 증명은 하나를 더 확인한다. +그 port 뒤에 이 repo의 실제 `createIndexedDbRuntime`과 브라우저 기본 IndexedDB 구현이 있어도, +같은 feature contribution이 동작한다는 것이다. -It does not prove that composition of `createIndexedDbRuntime` is cheap. -That constructor still owns substantial infrastructure policy: +`createIndexedDbRuntime`을 조립하는 비용이 싸다는 것은 증명하지 않는다. +이 생성 함수는 여전히 상당한 인프라 정책을 갖고 있다. -- dataset scope and storage policy, -- physical store governance, -- retention/idempotency stores, -- schema migrations, -- codec and query policy, -- lifecycle authority, -- durability, scheduling and observation. +- dataset 범위와 저장 정책 +- 물리 store 관리 +- 보존·멱등성(idempotency) store +- schema 마이그레이션 +- codec과 조회 정책 +- 수명 주기 권한(lifecycle authority) +- 내구성, 스케줄링, 관측 -That complexity belongs at the composition/platform boundary, not in the -feature. The Local Draft vertical slice is now the second concrete consumer, and -it confirms that the stable seam is the typed repository provider plus a -feature-owned repository identity. It does **not** show that dataset scope, -retention, migration, codec or lifecycle-authority configuration can be safely -collapsed into one universal `create...Repository` factory. +이 복잡함은 feature가 아니라 조립·플랫폼 경계에 둔다. +Local Draft 세로 slice는 이제 두 번째 구체 소비자다. +이 소비자는 안정된 연결 지점(seam)이 타입이 있는 repository provider와, +feature가 소유한 repository 식별자라는 것을 확인한다. +dataset 범위, 보존, 마이그레이션, codec, 수명 주기 권한 설정을 만능 +`create...Repository` factory 하나로 안전하게 합칠 수 있다는 것은 보여 주지 **않는다**. -A convenience profile should therefore be introduced only after another -IndexedDB-backed product feature repeats the same infrastructure policy, not -merely because two features consume the same repository port. +그래서 편의 프로필은 IndexedDB를 쓰는 다른 제품 feature가 같은 인프라 정책을 되풀이한 뒤에만 들인다. +두 feature가 같은 repository port를 쓴다는 이유만으로 들이지 않는다. -## Consumer-quality review checklist +## 소비자 품질 검토 체크리스트 -For each new product feature, record: +새 제품 feature마다 다음을 기록한다. -- feature-owned adapter LOC, -- platform glue LOC, -- files changed, -- central catalog edits, -- direct imports from capability-internal modules, -- native browser/network API references, -- duplicated failure/retry/lifecycle policy. +- feature가 소유한 adapter LOC +- 플랫폼 연결 코드(glue) LOC +- 바뀐 파일 +- 중앙 카탈로그 수정 +- capability 내부 모듈 직접 import +- 브라우저·네트워크 기본 API 참조 +- 중복된 실패·retry·수명 주기 정책 -A healthy feature path should look like: +건강한 feature 경로는 다음 모양이다. -1. domain type and invariant, -2. use case, -3. business port, -4. feature-owned mapper/codec and policy, -5. capability-specific binding, -6. presentation controller/page. +1. domain 타입과 불변식 +2. use case +3. 업무 port +4. feature가 소유한 mapper·codec과 정책 +5. capability 전용 binding +6. presentation controller·페이지 -The feature should not need the retry scheduler, abort ownership, -effect-certainty machinery, IndexedDB transaction lifecycle, OPFS journal, -reconnect coordinator or provider process model. +feature는 다음을 알 필요가 없어야 한다. +retry scheduler, abort 소유, effect-certainty 장치, IndexedDB transaction 수명 주기, +OPFS journal, 재연결 coordinator, provider 프로세스 모델이다. diff --git a/docs/architecture/contract-ownership.md b/docs/architecture/contract-ownership.md index a2838c9b..c36b2a09 100644 --- a/docs/architecture/contract-ownership.md +++ b/docs/architecture/contract-ownership.md @@ -1,124 +1,115 @@ -# Contract ownership +# 계약 소유 -`src/contracts` is not a default destination for every shared-looking type. -A contract belongs there only when the change authority is genuinely shared -across layers, capabilities, build tooling, or runtime composition. +`src/contracts`는 공유되는 것처럼 보이는 타입을 모두 넣는 기본 자리가 아니다. +계약을 바꿀 권한이 계층, capability, 빌드 도구, runtime 조립 사이에 정말로 나뉘어 있을 때만 계약이 거기 들어간다. -## Decision rule +## 판단 규칙 -For every proposed contract, ask: +제안된 계약마다 묻는다. -1. Which requirement can cause this type or policy to change? -2. Is there one clear capability or feature owner? -3. Does another runtime/tooling boundary consume the same semantic contract? -4. Is the contract a wire/artifact authority shared by browser runtime and - build/release tooling? +1. 어떤 요구 사항이 이 타입이나 정책을 바꾸게 할 수 있나? +2. 분명한 capability owner나 feature owner가 하나 있나? +3. 다른 runtime 경계나 도구 경계가 같은 의미의 계약을 쓰나? +4. 이 계약이 브라우저 runtime과 빌드·release 도구가 함께 따르는 + wire 형식이나 산출물(artifact)의 기준인가? -The placement rule is: +두는 자리는 다음 규칙으로 정한다. -- one feature owner -> keep it under that feature, -- one reusable capability owner -> keep it under that adapter/capability and - export it through the capability public entry point, -- a product-neutral primitive any layer may call, with no product vocabulary - in it (a budget, deadline, retry, execution context, telemetry pipeline step - or error envelope) -> `src/platform`, -- multiple independent capability/layer owners -> `src/contracts`, -- browser/build/release wire or artifact authority -> `src/contracts` even - when the browser source graph alone looks small. +- feature owner가 하나 -> 그 feature 아래에 둔다. +- 재사용 capability owner가 하나 -> 그 adapter·capability 아래에 둔다. + 그리고 capability의 공개 진입점으로 export한다. +- 어느 계층이든 부를 수 있고 제품 어휘가 들어 있지 않은 제품 중립 primitive + (budget, deadline, retry, 실행 context, telemetry pipeline 단계, 오류 envelope) -> `src/platform` +- 서로 독립된 capability·계층 owner가 여럿 -> `src/contracts` +- 브라우저·빌드·release가 함께 따르는 wire 형식이나 산출물의 기준 -> `src/contracts`. + 브라우저 소스 그래프만 보면 작아 보여도 그렇다. -Consumer count alone is not sufficient. Scripts, generated artifacts and -release gates are semantic consumers too. +소비자 수만으로는 판단할 수 없다. script, 생성된 산출물, release gate도 의미상의 소비자다. -`src/platform` and `src/contracts` differ in what they hold. `src/contracts` -holds the product's shared vocabulary: registries, schemas and wire formats -such as routes, API operations, storage keys and release artifacts. -`src/platform` holds mechanisms that work without that vocabulary, plus the -few error kinds no feature owns (network, deadline, cancellation, response -bounds). Today `src/contracts` imports `src/platform` and not the other way -round. `platform-kernel-is-product-neutral` stops `src/platform` from importing -any feature, context, app, adapter, bootstrap, presentation or application -module. A primitive that needs a route, an API operation or a feature's -vocabulary is not product-neutral: put it in `src/contracts` or with its owner. +`src/platform`과 `src/contracts`는 담는 것이 다르다. +`src/contracts`는 제품의 공유 어휘를 담는다. +라우트, API operation, storage key, release 산출물 같은 registry, schema, wire 형식이다. +`src/platform`은 그 어휘 없이 동작하는 장치를 담는다. +그리고 어느 feature도 소유하지 않는 몇 가지 오류 종류(network, deadline, 취소, 응답 한도)도 담는다. +지금은 `src/contracts`가 `src/platform`을 import하고, 반대 방향은 없다. +`platform-kernel-is-product-neutral`은 `src/platform`이 feature, context, app, adapter, +bootstrap, presentation, application 모듈을 import하지 못하게 막는다. +라우트, API operation, feature 어휘가 필요한 primitive는 제품 중립이 아니다. +그런 것은 `src/contracts`에 두거나 그 owner 곁에 둔다. -## Audit result +## 감사 결과 -The September 2026 architecture review triggered an import-graph audit of all -39 contract files. +2026년 9월 아키텍처 리뷰를 계기로 계약 파일 39개 전체의 import 그래프를 감사했다. -### Capability-owned contract moved +### capability 소유 계약을 옮김 -`cursor-pagination.ts` had one production owner: -`src/adapters/query-cache/cursor-pagination-runtime.ts`. +`cursor-pagination.ts`를 운영 코드에서 소유한 곳은 하나였다. +`src/adapters/query-cache/cursor-pagination-runtime.ts`다. -It moved to: +이 파일은 다음으로 옮겼다. `src/adapters/query-cache/cursor-pagination-contract.ts` -and is exported through: +그리고 다음을 거쳐 export된다. `src/adapters/query-cache/index.ts` -Tests use that public capability entry point. Pagination vocabulary no longer -occupies the global contract bucket merely because it is reusable inside one -adapter. +테스트도 그 capability 공개 진입점을 쓴다. +pagination 어휘는 이제 adapter 하나 안에서 재사용된다는 이유만으로 전역 계약 자리를 차지하지 않는다. -### Contracts intentionally kept global +### 일부러 전역에 둔 계약 -The following examples have multiple semantic owners and remain global: +다음 예는 의미상의 owner가 여럿이라 전역에 남는다. -- `errors.ts` — application, presentation and several adapters, -- `result.ts` — common success/failure carrier below application, -- `boundary-mapper.ts` — HTTP, browser RPC, realtime and feature registries, -- `mutation-intent.ts` — application, presentation, HTTP, platform and - bootstrap, -- `exact-snapshot.ts` — HTTP, query-cache and browser-transfer, -- `rest-profiles.ts` — auth, HTTP, bootstrap and feature contract validation, +- `errors.ts` — application, presentation, 여러 adapter +- `result.ts` — application 아래에서 쓰는 공통 성공·실패 운반 타입 +- `boundary-mapper.ts` — HTTP, 브라우저 RPC, realtime, feature registry +- `mutation-intent.ts` — application, presentation, HTTP, platform, + bootstrap +- `exact-snapshot.ts` — HTTP, query-cache, browser-transfer +- `rest-profiles.ts` — auth, HTTP, bootstrap, feature 계약 검증 - `query-invalidation.ts` / `query-keys.ts` — query-cache, presentation, - bootstrap and features, -- `cache-invalidation.ts` — cross-context wire protocol plus query - invalidation policy, -- `storage-keys.ts` — browser storage and cross-context invalidation, -- `telemetry.ts` / `diagnostics.ts` — runtime adapters, application and - bootstrap. + bootstrap, feature +- `cache-invalidation.ts` — cross-context wire 프로토콜과 query + 무효화 정책 +- `storage-keys.ts` — 브라우저 storage와 cross-context 무효화 +- `telemetry.ts` / `diagnostics.ts` — runtime adapter, application, + bootstrap -Some contracts appear to have few browser-source consumers but are still shared -authorities: +어떤 계약은 브라우저 소스에서 쓰는 곳이 적어 보이지만, 여전히 여러 곳이 함께 따르는 기준이다. -- `env.ts` is consumed by bootstrap, runtime-schema/security tests and - registry governance, -- `deployment-admission.ts` is shared by runtime-config generation and release - admission, -- `release-tokens.ts` is shared by runtime coherence tooling and tests, -- `service-worker-static-manifest.ts` is a runtime-neutral canonical format - shared by build generation, validation and service-worker evidence. +- `env.ts`는 bootstrap, runtime-schema·보안 테스트, + registry governance가 쓴다. +- `deployment-admission.ts`는 runtime-config 생성과 release + 승인(admission)이 함께 쓴다. +- `release-tokens.ts`는 runtime 정합성 도구와 테스트가 함께 쓴다. +- `service-worker-static-manifest.ts`는 runtime에 묶이지 않는 정식 형식이다. + 빌드 생성, 검증, Service Worker 증거가 함께 쓴다. -Moving those based only on `src/**` import counts would split one semantic -authority across processes. +`src/**`의 import 수만 보고 이것들을 옮기면, 의미상 하나인 기준이 여러 프로세스로 쪼개진다. -## Feature contracts +## feature 계약 -Feature-specific contracts stay inside the vertical slice: +feature 전용 계약은 세로 slice 안에 둔다. `features//contracts` -A feature owns its routes, schemas, mapper definitions, message catalogs and -contribution identities (`create:feature` writes them under its `contracts/`). Central installed files aggregate those -contributions; they do not own their semantics. +feature는 자기 라우트, schema, mapper 정의, message 카탈로그, +contribution 식별자를 소유한다(`create:feature`가 이것들을 그 feature의 `contracts/` 아래에 쓴다). +중앙 설치 파일은 이 contribution을 모을 뿐, 그 의미를 소유하지 않는다. -The message catalog is a deliberate special case: the compiled catalog remains -total even when a feature is build-time disabled so the typed message lookup -does not become partial. The central message file therefore aggregates compiled -message keys rather than treating runtime installation as message ownership. +message 카탈로그는 일부러 둔 예외다. +빌드 때 feature를 꺼도 컴파일된 카탈로그는 모든 키를 그대로 갖는다. +그래야 타입이 있는 message 조회가 일부 키에서 비지 않는다(partial이 되지 않는다). +그래서 중앙 message 파일은 컴파일된 message 키를 모은다. +runtime에 설치됐다는 사실을 message 소유로 보지 않는다. -## Review rule for future additions +## 앞으로 더할 때의 리뷰 규칙 -A new file under `src/contracts` should be rejected during review when all of -the following are true: +`src/contracts` 아래 새 파일은 다음이 모두 참이면 리뷰에서 거부한다. -- one feature or one capability is the only semantic owner, -- no build/release/runtime wire authority needs the same definition, -- moving the definition to that owner does not create an inward dependency - violation. +- 의미상의 owner가 feature 하나나 capability 하나뿐이다. +- 같은 정의가 필요한 빌드·release·runtime wire 기준이 없다. +- 정의를 그 owner로 옮겨도 안쪽 방향 의존성 규칙을 어기지 않는다. -Do not move a contract merely to reduce the number 39. The goal is explicit -ownership, not a smaller directory. +39라는 숫자를 줄이려고 계약을 옮기지 않는다. 목표는 디렉터리를 작게 하는 것이 아니라 소유를 분명히 하는 것이다. diff --git a/docs/architecture/optional-adapter-recipes.md b/docs/architecture/optional-adapter-recipes.md index f10d445f..da5355de 100644 --- a/docs/architecture/optional-adapter-recipes.md +++ b/docs/architecture/optional-adapter-recipes.md @@ -1,4 +1,4 @@ -# Optional frontend adapter recipes +# 선택형 frontend adapter recipe 이 문서는 도메인과 무관한 선택형 frontend capability를 실제 프로젝트에 도입하는 실행 가이드다. 기본 스켈레톤에는 vendor runtime을 설치하지 않는다. @@ -43,7 +43,7 @@ production readiness를 뜻하지 않는다. | 완전 제거 gate | `scripts/test-optional-recipe-removal.ts` | 아니오 | | native reference runtime 제거 gate | `scripts/test-browser-file-storage-runtime-removal.ts` | 아니오 | -현재 `productionRuntimeDependencies`는 빈 배열이며 12개 recipe 모두 선택되지 +현재 `productionRuntimeDependencies`는 빈 배열이며 카탈로그의 recipe 모두 선택되지 않았다. `recipes/`의 TypeScript example은 선택 시 복사하고 좁힐 출발점이고, `src/adapters`의 browser-native reference runtime은 공통 lifecycle·failure mechanism을 재사용할 수 있는 실제 구현이다. 제품 feature는 이 runtime에 @@ -95,7 +95,7 @@ source가 예산을 넘으면 gate를 우회하지 않는다. output artifact와 | --- | --- | --- | --- | | application이 외부 결과를 요청 | application | outbound | `src/adapters/` | | URL/browser event가 의도를 전달 | application input | inbound | `src/presentation/adapters` | -| React rendering behavior만 교체 | presentation | local facade | `src/presentation/` | +| React 렌더링 동작만 교체 | presentation | local facade | `src/presentation/` | | feature 전용 protocol | feature application | in/out 분리 | `src/features//adapters` | WebSocket 연결 생성, reconnect와 credential attachment는 outbound다. 수신 JSON @@ -103,14 +103,14 @@ WebSocket 연결 생성, reconnect와 credential attachment는 outbound다. 수 BroadcastChannel event도 같은 원칙을 적용한다. generated DTO와 vendor SDK type은 facade 밖으로 노출하지 않는다. -## 3. 12개 recipe 선택표 +## 3. recipe 선택표 | recipe | 설치하는 경우 | 설치하면 안 되는 경우 | 핵심 fallback | | --- | --- | --- | --- | | realtime | foreground ordered event 또는 duplex protocol이 확정됨 | focus refetch/manual refresh가 충분하거나 ordering·replay owner 없음 | bounded polling 또는 stale UI | | offline/IndexedDB/OPFS | structured offline data/queue 또는 large local binary가 제품 요구 | credential, partition/retention/recovery 미정, HTTP cache로 충분 | read-only/online-only 또는 승인된 bounded Blob | | Service Worker/Cache Storage | 설치형(installability) 또는 public HTTP representation cache owner 승인. 오프라인 셸은 지원하지 않는다(이 절 끝) | auth/private/opaque cache, update/rollback UX 없음 | hosting cache 기반 network app | -| file/picker/download | selection/preview/upload/download와 bounded memory/integrity 요구 | backend 재검증 없음, whole-buffer large file, long-lived credential URL | native input + authorized direct download | +| file/picker/download | selection/preview/upload/download와 크기 제한이 있는 memory/integrity 요구 | backend 재검증 없음, 큰 파일을 통째로 buffer에 올림, 오래 사는 credential URL | native input + 인가된 직접 download | | generated API | versioned source와 drift CI가 있음 | DTO가 domain/UI로 노출됨 | typed request builder + schema | | feature flag | rollout/kill switch owner와 default 있음 | authorization에 사용 | typed local default | | Web Worker | profiler가 main-thread 병목을 증명 | 단순 network I/O | chunked/deferred execution | @@ -179,8 +179,8 @@ release" 성질은 제품이 다시 증명한다. 넘겨받은 뒤에는 템플 Web Push target은 현재 13번째 설치 recipe가 아니다. 기존 `realtime`, `service-worker-pwa`, `browser-permission`의 인접 경계를 조합해야 하는 별도 `NOT_SELECTED` capability다. 실제 선택 전 VD-10 amendment와 machine-readable -catalog에 permission, subscription/backend provider, worker handler, notification -policy와 removal source를 명시하며, foreground realtime이 선택됐다는 이유로 +catalog에 권한(permission), subscription/backend provider, worker handler, 알림(notification) +정책과 제거 source를 명시하며, foreground realtime이 선택됐다는 이유로 Web Push를 함께 설치하지 않는다. ## 4. 공통 구현 순서 @@ -196,9 +196,9 @@ Web Push를 함께 설치하지 않는다. import한다. 7. composition root가 concrete adapter를 주입한다. page/use case가 constructor를 직접 호출하지 않는다. -8. fake, unavailable, timeout/cancel, cleanup, malformed input, redaction과 +8. fake, 사용 불가(unavailable), timeout/cancel, cleanup, 형식이 틀린 입력, redaction과 integration test를 작성한다. -9. runtime config schema, dependency inventory/approval, SBOM, bundle budget, +9. runtime config schema, 의존성 inventory/승인, SBOM, bundle budget, browser support와 runbook을 갱신한다. 운영 CSP(`config/hosting/security-headers.json`)도 여기서 넓힌다. 기본 CSP는 아래 기능을 막는다(리뷰 13-08). @@ -266,14 +266,14 @@ Web Push를 함께 설치하지 않는다. 자동 reload와 database 삭제를 금지한다. - OPFS는 immutable bytes만 소유하고 IndexedDB journal이 `PREPARING -> FILES_READY -> COMMITTED -> CLEANED` commit authority를 가진다. -- quota, corrupt row/manifest, migration checkpoint, worker crash, storage eviction, +- quota, 깨진 row/manifest, migration checkpoint, worker 비정상 종료, storage 축출(eviction), N-1 rollback을 fixture와 실제 browser에서 검증한다. ### Cache Storage/Service Worker - Cache Storage는 public HTTP representation 전용이며 application repository나 query cache가 아니다. -- auth, cookie-dependent, private, personal, no-store, opaque, redirect, 206을 +- 인증 필요, cookie 의존, private, 개인 정보, no-store, opaque, redirect, 206 응답을 거절하고 query/Vary exact match를 보존한다. - candidate 전체의 type/size/integrity가 검증된 뒤에만 release를 활성화하고 verified previous release를 rollback용으로 유지한다. @@ -324,7 +324,7 @@ Web Push를 함께 설치하지 않는다. - virtualization은 profiler와 production-like row count로 정당화하며 keyboard, focus restoration, screen reader와 stale row identity를 검증한다. - analytics는 essential diagnostics와 consent-required event를 분리하고 closed - event/attribute registry, pre-queue redaction, sampling, bounded queue와 + event/attribute registry, queue에 넣기 전 redaction, sampling, 크기 제한 queue와 retention을 적용한다. ## 6. 검증 명령 @@ -340,7 +340,7 @@ corepack pnpm test:optional-recipe-removal corepack pnpm test:browser-file-storage-removal ``` -negative gate는 cleanup 누락, unselected dependency, local adapter 밖 vendor +negative gate는 cleanup 누락, 선택하지 않은 의존성, local adapter 밖 vendor import, credential localStorage/URL/telemetry 경로, workflow store의 server-state 복제, production source의 recipe import와 선택 전 reference runtime composition을 거절한다. removal gate는 recipe와 recipe test를 삭제한 임시 사본에서 base @@ -352,7 +352,7 @@ build와 optional catalog 검사를 다시 실행한다. ## 7. 제거 체크리스트 1. 신규 호출과 background 작업을 중지한다. -2. subscription, worker, channel, media track, observer를 cleanup한다. +2. subscription, worker, channel, media track, observer를 정리(cleanup)한다. 3. persisted store/cache/event queue의 migrate 또는 purge 정책을 실행한다. 4. composition registration과 runtime config를 제거한다. 5. concrete adapter, facade/port와 vendor dependency를 제거한다. diff --git a/docs/architecture/review-evidence.md b/docs/architecture/review-evidence.md index b1ec6182..fbf399ac 100644 --- a/docs/architecture/review-evidence.md +++ b/docs/architecture/review-evidence.md @@ -1,22 +1,21 @@ -# Imported scoped diagram review evidence +# 가져온 범위 한정 도식 리뷰 증거 -This ledger entry consumes the canonical evidence already recorded by the -`ca-skeleton-frontend-operational-contract` project note. It does not claim -review of the repository-local Mermaid projections or of the complete -production deployment topology. +이 ledger 항목은 `ca-skeleton-frontend-operational-contract` 프로젝트 노트에 +이미 기록된 정본 증거를 가져다 쓴다. 이 repo 안의 Mermaid 투영 그림을 +리뷰했다고 주장하지 않는다. 운영 배포 토폴로지 전체를 리뷰했다고 주장하지도 +않는다. -- Reviewer: `wiki-diagram-reviewer` -- Standard: `rules/diagram-standards.md` v2 -- Canonical report: +- 리뷰어: `wiki-diagram-reviewer` +- 기준: `rules/diagram-standards.md` v2 +- 정본 보고서: `docs/superpowers/specs/2026-07-18-ca-skeleton-frontend-operational-contract-review/diagram-review.md` -- Canonical report SHA-256: +- 정본 보고서 SHA-256: `b4d2a35e4f07e176717786408f98dab5cee1047f77f6ff61f5faeddfccd78a29` -| Canonical diagram | SHA-256 | Score | Verdict | Reviewed scope | +| 정본 도식 | SHA-256 | 점수 | 판정 | 리뷰 범위 | | --- | --- | ---: | --- | --- | -| `raw/diagrams/ca-skeleton-frontend/architecture-overview-2026-07-18.drawio` | `c0ae56c9c964c5c6e698ab7dcc91736b9b811b2b834381817905db81c4230ba0` | 100 | PASS | Clean Architecture compile-time dependency ownership | -| `raw/diagrams/ca-skeleton-frontend/architecture-deployment-2026-07-18.drawio` | `9a654326fb840ddf24b832221ff7eec4b8fadd9f87ad84174fccfa3bfcd1a25b` | 100 | PASS | immutable static assets and mutable `/config.json` delivery | +| `raw/diagrams/ca-skeleton-frontend/architecture-overview-2026-07-18.drawio` | `c0ae56c9c964c5c6e698ab7dcc91736b9b811b2b834381817905db81c4230ba0` | 100 | PASS | Clean Architecture 컴파일 시점 의존성 소유 | +| `raw/diagrams/ca-skeleton-frontend/architecture-deployment-2026-07-18.drawio` | `9a654326fb840ddf24b832221ff7eec4b8fadd9f87ad84174fccfa3bfcd1a25b` | 100 | PASS | 불변 정적 asset과 변경 가능한 `/config.json` 전달 | -The canonical report explicitly limits this `PASS_SCOPED`: it does not verify -the complete release/rollback topology, the implementation topology, or live -hosting state. +정본 보고서는 이 `PASS_SCOPED`의 범위를 분명히 제한한다. release·rollback +토폴로지 전체, 구현 토폴로지, 실제 hosting 상태는 검증하지 않는다. diff --git a/docs/architecture/scale-architecture.md b/docs/architecture/scale-architecture.md index 7c554a9b..67ec89d0 100644 --- a/docs/architecture/scale-architecture.md +++ b/docs/architecture/scale-architecture.md @@ -1,10 +1,10 @@ -# Scale Architecture +# 규모 아키텍처 > **상태 머리말 (2026-11-03)** > > - **현재 계약인 범위.** 아래 표에서 상태가 "현재 계약"인 절만 지금 코드가 지키는 규칙이다. "기록만"인 절은 2026-09-23 설계 당시의 계획·목록이고, 구현되지 않았거나 바뀌었다. 문서와 코드가 다르면 코드가 맞다. > - **출처.** 2026-09-23 설계서 "Extreme-Scale Frontend Architecture Design"을 커밋 `6f6c48e`(2026-09-24)에서 옮겼다. 원래 파일은 작업 이력 묶음 안에 있어 복사한 프로젝트가 지울 수 있다. 원문은 `git show 6f6c48e:docs/reviews/2026-09-23-extreme-scale-frontend-plan-bundle/docs/design/2026-09-23-extreme-scale-frontend-architecture-design.md`로 볼 수 있다. -> - **본문.** §1~§55는 영어 원문 그대로다. 절 번호는 바꾸지 않았다. 원문 머리의 날짜·대상·상태·예정 경로 줄만 이 머리말로 바꿨다. +> - **본문.** §1~§55는 영어 원문을 2026-11-08에 한국어로 옮긴 것이다. 뜻은 바꾸지 않았고 절 번호도 그대로다. 원문 머리의 날짜·대상·상태·예정 경로 줄만 이 머리말로 바꿨다. > - **코드가 이 문서를 가리키는 방법.** 코드 주석은 `scale-architecture.md §N` 형식으로 쓴다. 문서 이름이 없는 "Spec" + 절 번호 참조는 `tests/unit/deletable-history-documents.test.ts`가 거부한다. 절 번호를 바꾸면 `git grep "scale-architecture.md §"`로 찾은 주석을 모두 함께 고친다. > - **코드와 달라진 곳을 적는 규칙.** 원문 문장은 고치지 않는다. 확인한 차이는 그 절 끝에 `> YYYY-MM-DD 현재:` 한두 줄로 적는다. 절의 상태가 바뀌면 아래 표도 고친다. @@ -19,105 +19,105 @@ | § | 제목 | 상태 | 차이 메모 | |---|---|---|---| -| 1 | Purpose | 현재 계약 | | -| 2 | Core Principle | 현재 계약 | | -| 3 | Scale Model | 현재 계약 (코드 참조) | | -| 4 | Target Source Structure | 현재 계약 (코드 참조) | 있음 | -| 5 | Module Ownership | 현재 계약 | 있음 | -| 6 | Dependency Rules | 현재 계약 | | -| 7 | Cardinality Budgets | 현재 계약 | 있음 | -| 8 | Registry Composition | 현재 계약 | | -| 9 | Router Architecture | 현재 계약 | | -| 10 | Execution Model | 현재 계약 (코드 참조) | 있음 | -| 11 | Traffic Budget | 현재 계약 (코드 참조) | 있음 | -| 12 | Request Fan-Out | 현재 계약 (코드 참조) | | -| 13 | Retry Model | 현재 계약 (코드 참조) | | -| 14 | Concurrency Budget | 현재 계약 (코드 참조) | | -| 15 | Deadline Propagation | 현재 계약 (코드 참조) | | -| 16 | Request Deduplication and Coalescing | 현재 계약 (코드 참조) | | -| 17 | Error Model | 현재 계약 (코드 참조) | | -| 18 | Error Envelope | 현재 계약 (코드 참조) | | -| 19 | Presentation Error Mapping | 현재 계약 (코드 참조) | | -| 20 | Validation Boundaries | 현재 계약 (코드 참조) | | -| 21 | Validate Once at Trust Boundaries | 현재 계약 (코드 참조) | | -| 22 | Validation Budget | 현재 계약 (코드 참조) | | -| 23 | Telemetry Model | 현재 계약 (코드 참조) | | -| 24 | Telemetry Ownership | 현재 계약 (코드 참조) | 있음 | -| 25 | Telemetry Pipeline | 현재 계약 (코드 참조) | 있음 | -| 26 | Telemetry Must Fail Open for Business Behavior | 현재 계약 (코드 참조) | | -| 27 | Telemetry Storm Protection | 현재 계약 (코드 참조) | | -| 28 | Telemetry Privacy and Redaction | 현재 계약 (코드 참조) | | -| 29 | Trace and Correlation | 현재 계약 (코드 참조) | 있음 | -| 30 | Failure Boundaries | 현재 계약 (코드 참조) | | -| 31 | Async Failure Model | 현재 계약 | 있음 | -| 32 | Spike Traffic Design | 현재 계약 (코드 참조) | 있음 | -| 33 | Sustained Traffic Design | 현재 계약 (코드 참조) | | -| 34 | Amplification Metrics | 현재 계약 (코드 참조) | | -| 35 | Scale Profiles | 현재 계약 (코드 참조) | | -| 36 | Local Scale Verification | 현재 계약 (코드 참조) | 있음 | -| 37 | Global Topology Verification | 현재 계약 (코드 참조) | 있음 | -| 38 | TypeScript Scale Gate | 현재 계약 (코드 참조) | | -| 39 | Runtime Composition Scale Gate | 현재 계약 (코드 참조) | | -| 40 | Browser Boot Gate | 기록만 | 있음 | -| 41 | Request Fan-Out Gate | 현재 계약 (코드 참조) | | -| 42 | Failure and Chaos Scenarios | 현재 계약 (코드 참조) | | -| 43 | Telemetry Storm Test | 현재 계약 (코드 참조) | | -| 44 | Soak Testing | 현재 계약 (코드 참조) | 있음 | -| 45 | Horizontal Scaling and Release Coherence | 현재 계약 (코드 참조) | 있음 | -| 46 | Multi-Replica Release Matrix | 현재 계약 (코드 참조) | | -| 47 | CI Execution Tiers | 현재 계약 (코드 참조) | 있음 | -| 48 | Benchmark Result Format | 현재 계약 (코드 참조) | 있음 | -| 49 | Regression Policy | 현재 계약 (코드 참조) | | -| 50 | Required Architecture Gates | 현재 계약 (코드 참조) | 있음 | -| 51 | Compatibility With Current Template Strengths | 기록만 | | -| 52 | Explicit Non-Goals | 현재 계약 | | -| 53 | Implementation Sequence Constraints | 기록만 | | -| 54 | Acceptance Criteria | 기록만 | | -| 55 | Design Summary | 현재 계약 | | +| 1 | 목적 | 현재 계약 | | +| 2 | 핵심 원칙 | 현재 계약 | | +| 3 | 규모 모델 | 현재 계약 (코드 참조) | | +| 4 | 목표 소스 구조 | 현재 계약 (코드 참조) | 있음 | +| 5 | 모듈 소유 | 현재 계약 | 있음 | +| 6 | 의존성 규칙 | 현재 계약 | | +| 7 | 개수 예산 | 현재 계약 | 있음 | +| 8 | registry 조립 | 현재 계약 | | +| 9 | 라우터 구조 | 현재 계약 | | +| 10 | 실행 모델 | 현재 계약 (코드 참조) | 있음 | +| 11 | 트래픽 예산 | 현재 계약 (코드 참조) | 있음 | +| 12 | 요청 fan-out | 현재 계약 (코드 참조) | | +| 13 | 재시도 모델 | 현재 계약 (코드 참조) | | +| 14 | 동시 실행 예산 | 현재 계약 (코드 참조) | | +| 15 | 마감 시간 전파 | 현재 계약 (코드 참조) | | +| 16 | 요청 중복 제거와 합치기 | 현재 계약 (코드 참조) | | +| 17 | 오류 모델 | 현재 계약 (코드 참조) | | +| 18 | 오류 봉투 | 현재 계약 (코드 참조) | | +| 19 | presentation 오류 매핑 | 현재 계약 (코드 참조) | | +| 20 | 검증 경계 | 현재 계약 (코드 참조) | | +| 21 | 신뢰 경계에서 한 번만 검증 | 현재 계약 (코드 참조) | | +| 22 | 검증 예산 | 현재 계약 (코드 참조) | | +| 23 | telemetry 모델 | 현재 계약 (코드 참조) | | +| 24 | telemetry 소유 | 현재 계약 (코드 참조) | 있음 | +| 25 | telemetry 파이프라인 | 현재 계약 (코드 참조) | 있음 | +| 26 | 업무 동작에는 telemetry가 fail-open이어야 한다 | 현재 계약 (코드 참조) | | +| 27 | telemetry 폭주 방어 | 현재 계약 (코드 참조) | | +| 28 | telemetry 개인정보 보호와 redaction | 현재 계약 (코드 참조) | | +| 29 | trace와 correlation | 현재 계약 (코드 참조) | 있음 | +| 30 | 실패 경계 | 현재 계약 (코드 참조) | | +| 31 | 비동기 실패 모델 | 현재 계약 | 있음 | +| 32 | 급증 트래픽 설계 | 현재 계약 (코드 참조) | 있음 | +| 33 | 지속 트래픽 설계 | 현재 계약 (코드 참조) | | +| 34 | 증폭 지표 | 현재 계약 (코드 참조) | | +| 35 | 규모 프로필 | 현재 계약 (코드 참조) | | +| 36 | 로컬 규모 검증 | 현재 계약 (코드 참조) | 있음 | +| 37 | 전역 토폴로지 검증 | 현재 계약 (코드 참조) | 있음 | +| 38 | TypeScript 규모 게이트 | 현재 계약 (코드 참조) | | +| 39 | runtime 조립 규모 게이트 | 현재 계약 (코드 참조) | | +| 40 | 브라우저 부팅 게이트 | 기록만 | 있음 | +| 41 | 요청 fan-out 게이트 | 현재 계약 (코드 참조) | | +| 42 | 실패·카오스 시나리오 | 현재 계약 (코드 참조) | | +| 43 | telemetry 폭주 테스트 | 현재 계약 (코드 참조) | | +| 44 | soak 테스트 | 현재 계약 (코드 참조) | 있음 | +| 45 | 수평 확장과 릴리스 일관성 | 현재 계약 (코드 참조) | 있음 | +| 46 | 다중 replica 릴리스 행렬 | 현재 계약 (코드 참조) | | +| 47 | CI 실행 단계 | 현재 계약 (코드 참조) | 있음 | +| 48 | 벤치마크 결과 형식 | 현재 계약 (코드 참조) | 있음 | +| 49 | 회귀 정책 | 현재 계약 (코드 참조) | | +| 50 | 필요한 아키텍처 게이트 | 현재 계약 (코드 참조) | 있음 | +| 51 | 현재 템플릿 강점과의 호환 | 기록만 | | +| 52 | 명시적으로 하지 않는 것 | 현재 계약 | | +| 53 | 구현 순서 제약 | 기록만 | | +| 54 | 완료 기준 | 기록만 | | +| 55 | 설계 요약 | 현재 계약 | | -## 1. Purpose +## 1. 목적 -This design evolves the frontend template from a single-application Clean Architecture skeleton into a frontend application platform that remains maintainable when logical domain count, traffic, failure rate, and operating duration become extreme. +이 설계는 프론트엔드 템플릿을 앱 하나짜리 Clean Architecture 뼈대에서 프론트엔드 애플리케이션 플랫폼으로 키운다. 이 플랫폼은 논리 도메인 수, 트래픽, 실패율, 운영 기간이 극단으로 커져도 유지보수할 수 있어야 한다. -The design must remain valid under worst-case growth assumptions: +이 설계는 아래 최악의 성장 가정에서도 성립해야 한다. -- 100, 1,000, 10,000, 100,000, or 1,000,000 logical features/domains across the product ecosystem. -- Short, severe spike traffic. -- Sustained high traffic over long periods. -- Partial and total backend failures. -- Retry storms, telemetry storms, cache-miss storms, and slow upstreams. -- Long-lived browser sessions. -- Multi-replica frontend deployments during rolling releases. +- 제품 생태계 전체에 논리 기능·도메인이 100, 1,000, 10,000, 100,000, 1,000,000개 있다. +- 짧고 심한 급증 트래픽이 온다. +- 높은 트래픽이 오래 이어진다. +- 백엔드가 일부 또는 전부 실패한다. +- 재시도 폭주, telemetry 폭주, cache-miss 폭주, 느린 upstream이 생긴다. +- 브라우저 세션이 오래 열려 있다. +- rolling 릴리스 중에 프론트엔드가 여러 replica로 배포되어 있다. -The goal is **not** to make one SPA compile and boot one million features. The goal is to make global growth independent from local runtime and build cost by enforcing bounded architecture boundaries. +목표는 SPA 하나가 기능 백만 개를 컴파일하고 부팅하게 만드는 것이 **아니다**. 목표는 한도가 있는 아키텍처 경계를 강제해서, 전역 규모가 커져도 로컬 runtime 비용과 빌드 비용이 따라 늘지 않게 하는 것이다. -## 2. Core Principle +## 2. 핵심 원칙 -> No cardinality may become implicitly unbounded. +> 어떤 개수(cardinality)도 암묵적으로 무제한이 되어서는 안 된다. -The same rule applies to: +이 규칙은 아래 모두에 똑같이 적용된다. -- compile graphs, -- route graphs, -- feature registries, -- cross-feature dependencies, -- HTTP request fan-out, -- retries, -- concurrency, -- payload size, -- validation cost, -- telemetry buffering, -- timers/listeners, -- browser storage, -- failure propagation. +- 컴파일 그래프 +- route 그래프 +- 기능 registry +- 기능 간 의존성 +- HTTP 요청 fan-out(요청 하나가 여러 요청으로 퍼지는 것) +- 재시도 +- 동시 실행 수 +- payload 크기 +- 검증 비용 +- telemetry 버퍼링 +- timer·listener +- 브라우저 저장소 +- 실패 전파 -The platform must expose these costs explicitly in code and CI instead of allowing them to hide behind arrays, `map`, `Promise.all`, global registries, retries, timers, or framework abstractions. +플랫폼은 이 비용을 코드와 CI에서 드러내야 한다. 배열, `map`, `Promise.all`, 전역 registry, 재시도, timer, 프레임워크 추상화 뒤에 숨게 두면 안 된다. -## 3. Scale Model +## 3. 규모 모델 -### 3.1 Separate global and local cardinality +### 3.1 전역 개수와 로컬 개수를 나눈다 -Two different concepts must never be conflated: +서로 다른 두 개념을 절대 섞지 않는다. ```text GlobalFeatureCount @@ -127,9 +127,9 @@ LocalFeatureCount = feature count compiled and booted by one deployable frontend application ``` -A system may contain 1,000,000 logical features while an individual deployable app sees only 100-300 features. +시스템 전체에는 논리 기능이 1,000,000개 있어도, 배포 단위 app 하나는 기능을 100~300개만 볼 수 있다. -### 3.2 Architectural hierarchy +### 3.2 아키텍처 계층 구조 ```text Product @@ -140,9 +140,9 @@ Product -> Route / Adapter ``` -A parent boundary knows only its direct children. It does not flatten every descendant into a global registry. +부모 경계는 바로 아래 자식만 안다. 모든 자손을 전역 registry 하나로 펼치지 않는다. -Example: +예: ```text Product @@ -154,11 +154,11 @@ Product -> Identity Context ``` -`Product` must not import `OrderCreatePage`, `PaymentRefundUseCase`, or other deep descendants. +`Product`는 `OrderCreatePage`, `PaymentRefundUseCase` 같은 깊은 자손을 import하면 안 된다. -### 3.3 Scale escape rule +### 3.3 규모 탈출 규칙 -When a boundary reaches its measured cardinality ceiling, the response is architectural split, not increasing the ceiling indefinitely. +경계가 측정한 개수 한도에 닿으면 아키텍처를 나눈다. 한도를 끝없이 올리지 않는다. ```text Feature too large @@ -171,9 +171,9 @@ App too large -> split deployable app ``` -This is equivalent to refusing an implicit unbounded one-to-many relation in server-side architecture. +서버 아키텍처에서 한도 없는 암묵적 일대다 관계를 거부하는 것과 같다. -## 4. Target Source Structure +## 4. 목표 소스 구조 ```text src/ @@ -208,18 +208,18 @@ src/ └─ compose-product.ts ``` -The exact path layout may adapt to current repository conventions, but ownership boundaries are mandatory. +정확한 경로 배치는 repo의 현재 관례에 맞춰 바꿔도 된다. 소유 경계는 반드시 지킨다. > 2026-11-03 현재: 위 그림의 최상위 `domain/` 폴더는 없다. domain 계층은 기능 안(`src/features//domain`)에만 있다. `src/platform`에는 `execution`·`release`·`routing`도 있다. > 색인은 생성기가 git이 무시하는 `src/.generated/`에 쓴다. 조립 코드는 `src/bootstrap/`에 있고 `compose-product.ts`라는 파일은 없다. 실제 폴더 목록의 정본은 [`layers.md`](layers.md)다. -## 5. Module Ownership +## 5. 모듈 소유 -### 5.1 Feature module +### 5.1 기능 모듈 -Each feature owns one descriptor containing its own contributions. +기능마다 자기 기여(contribution)를 담은 descriptor 하나를 소유한다. -Conceptual API: +개념 API: ```ts export const ORDER_FEATURE = defineFeatureModule({ @@ -234,25 +234,25 @@ export const ORDER_FEATURE = defineFeatureModule({ }); ``` -A new feature must not require hand editing multiple central installation files. +새 기능을 넣으려고 중앙 설치 파일 여러 개를 손으로 고치게 하면 안 된다. -Target change surface: +목표 변경 범위: ```text src/features/new-feature/** .generated/** ``` -Central handwritten production files changed for a normal feature addition: +보통의 기능 추가에서 고치는, 손으로 쓴 중앙 production 파일 수: ```text 0 preferred 1 maximum when a deliberate bounded-context registration is required ``` -### 5.2 Bounded context module +### 5.2 bounded context 모듈 -A context composes only its direct feature modules. +context는 바로 아래 기능 모듈만 조립한다. ```ts export const COMMERCE_CONTEXT = defineBoundedContextModule({ @@ -262,11 +262,11 @@ export const COMMERCE_CONTEXT = defineBoundedContextModule({ }); ``` -It does not expose concrete internal feature implementations to unrelated contexts. +관계없는 context에 기능의 구체적인 내부 구현을 드러내지 않는다. -### 5.3 Deployable app module +### 5.3 배포 단위 app 모듈 -A deployable app owns only direct bounded contexts. +배포 단위 app은 바로 아래 bounded context만 소유한다. ```ts export const CUSTOMER_APP = defineDeployableApp({ @@ -275,38 +275,38 @@ export const CUSTOMER_APP = defineDeployableApp({ }); ``` -Each app becomes an independent compilation and deployment unit once scale requires it. +규모가 그만큼 커지면 app마다 따로 컴파일하고 배포하는 단위가 된다. -### 5.4 Generated indexes +### 5.4 생성 색인 -Indexes are generated at build time from approved static source declarations. +색인은 빌드 때 승인된 정적 소스 선언에서 생성한다. -Required properties: +지켜야 할 성질: -- static TypeScript imports, -- deterministic output, -- no arbitrary runtime import path, -- no runtime plugin discovery from untrusted configuration, -- generated files are not handwritten registries. +- 정적 TypeScript import +- 결정적 출력(같은 입력이면 같은 결과) +- runtime에 임의 경로를 import하지 않음 +- 믿을 수 없는 설정을 보고 runtime에 plugin을 찾지 않음 +- 생성 파일은 손으로 쓰는 registry가 아님 -This preserves tree-shaking, supply-chain reviewability, and compile-time visibility while eliminating central merge hotspots. +이렇게 하면 tree-shaking, 공급망 검토 가능성, 컴파일 시점 가시성을 지킨다. 동시에 중앙 파일에서 merge 충돌이 몰리는 지점을 없앤다. > 2026-11-03 현재: 실제 API는 `defineFeatureModule`(`src/features/feature-module.ts`), `defineBoundedContextModule`(`src/contexts/bounded-context-module.ts`), `defineDeployableAppModule`(`src/apps/deployable-app-module.ts`)이다. 기능 모듈의 필드는 `id`·`contracts`·`routes`·`messages`·`loadRuntime`이다. > context와 app은 `context-module.ts`·`app-module.ts`의 상수로 소유와 한도를 선언한다. 생성기 `scripts/generate-product-feature-index.ts`가 이 선언을 읽어 색인을 만든다. -## 6. Dependency Rules +## 6. 의존성 규칙 -### 6.1 Cross-feature concrete imports are forbidden +### 6.1 기능 간 구체 import 금지 -For different features A and B: +서로 다른 기능 A와 B 사이의 아래 의존은 ```text src/features/A/** -> src/features/B/** ``` -is an architecture violation unless the dependency is through an explicitly approved public contract boundary. +아키텍처 위반이다. 명시적으로 승인한 공개 계약 경계를 거치는 의존만 예외다. -Preferred interaction boundaries: +권장하는 상호작용 경계: ```text feature @@ -315,26 +315,26 @@ feature -> explicit orchestration/workflow feature ``` -### 6.2 Cross-context imports are stricter +### 6.2 context 간 import는 더 엄격하다 -A context must not import another context's concrete feature internals. +context는 다른 context에 있는 기능의 구체적인 내부를 import하면 안 된다. -Allowed communication is through: +허용하는 통신 경로: -- public contracts, -- application ports, -- explicitly named integration contracts, -- server-backed integration where appropriate. +- 공개 계약 +- application port +- 이름을 붙여 명시한 통합 계약 +- 맞는 경우, 서버를 거친 통합 -### 6.3 Cycles are always forbidden +### 6.3 순환은 언제나 금지다 -No cycle is permitted across feature, context, or app boundaries. +기능, context, app 경계를 넘는 순환은 하나도 허용하지 않는다. -## 7. Cardinality Budgets +## 7. 개수 예산 -The platform defines explicit architectural budgets. +플랫폼은 아키텍처 예산을 명시적으로 정한다. -Conceptual shape: +개념상의 모양: ```ts interface ArchitectureCardinalityBudget { @@ -346,13 +346,13 @@ interface ArchitectureCardinalityBudget { } ``` -Initial numeric values are not hardcoded by this design. They must be established through repository benchmarks. +초기 숫자는 이 설계가 정하지 않는다. repo 벤치마크로 정해야 한다. -Budget files must be visible in review and version controlled. +예산 파일은 리뷰에서 보여야 하고 버전 관리해야 한다. -Budget increases must produce a detectable architecture-review signal. +예산을 올리면 아키텍처 리뷰가 알아챌 수 있는 신호가 나와야 한다. -Example failure: +실패 예: ```text ARCHITECTURE_CARDINALITY_EXCEEDED @@ -365,11 +365,11 @@ Action: split the context or create another deployable boundary. > 2026-11-03 현재: 한도를 하나로 묶은 `ArchitectureCardinalityBudget` 타입은 없다. 선언마다 자기 한도를 가진다(`APP_MAX_CONTEXTS = 20`, `CONTEXT_MAX_FEATURES = 200`). > 한도를 넘으면 `src/platform/cardinality/cardinality-budget.ts`의 `assertWithinCardinalityBudget`이 `CardinalityBudgetExceededError`를 던진다. -## 8. Registry Composition +## 8. registry 조립 -### 8.1 No repeated object spread in accumulation loops +### 8.1 누적 루프에서 객체 spread를 반복하지 않는다 -This pattern is forbidden in scale-sensitive composition paths: +규모에 민감한 조립 경로에서는 아래 패턴을 금지한다. ```ts features.reduce( @@ -378,11 +378,11 @@ features.reduce( ); ``` -It repeatedly copies accumulated state and becomes quadratic-like as the registry grows. +누적한 상태를 매번 복사하므로 registry가 커질수록 제곱에 가깝게 느려진다. -### 8.2 Required composition strategy +### 8.2 정해진 조립 방법 -Use one mutable local accumulator, explicit duplicate detection, then freeze once. +바꿀 수 있는 로컬 누적 객체 하나를 쓴다. 중복은 명시적으로 검사한다. 마지막에 한 번만 freeze한다. ```ts const result = Object.create(null); @@ -399,25 +399,25 @@ for (const feature of features) { return Object.freeze(result); ``` -The same strategy applies to operation, schema, mapper, invalidation, adapter, runtime, and message contribution composition when a registry is necessary. +registry가 필요하면 연산, schema, mapper, invalidation, adapter, runtime, message 기여를 조립할 때도 같은 방법을 쓴다. -### 8.3 Membership checks +### 8.3 포함 여부 검사 -Repeated linear membership tests such as: +아래처럼 선형 포함 검사를 반복하는 코드는 ```ts installedIds.includes(featureId) ``` -must not be used in scale-sensitive loops. +규모에 민감한 루프에서 쓰면 안 된다. -Build a `Set` once and use `has`. +`Set`을 한 번 만들고 `has`를 쓴다. -## 9. Router Architecture +## 9. 라우터 구조 -A flat product-wide route table is not an acceptable extreme-scale model. +제품 전체를 담은 평평한 route 표는 극단 규모에서 받아들일 수 없는 모델이다. -Target hierarchy: +목표 계층: ```text Product Router @@ -427,9 +427,9 @@ Product Router -> Page Route ``` -Only the next boundary is loaded eagerly. +바로 다음 경계만 미리 불러온다. -Example at global scale: +전역 규모의 예: ```text Global logical features: 1,000,000 @@ -438,22 +438,22 @@ Commerce app selected: commerce context routes loaded Order context selected: order feature routes loaded ``` -Global feature count must not linearly increase initial route object count, initial bundle size, or boot heap. +전역 기능 수가 늘어도 초기 route 객체 수, 초기 번들 크기, 부팅 heap이 선형으로 늘면 안 된다. -## 10. Execution Model +## 10. 실행 모델 -### 10.1 Interaction is the root execution scope +### 10.1 interaction이 가장 바깥 실행 범위다 -HTTP requests are not the highest-level unit. A user or application interaction is. +가장 높은 단위는 HTTP 요청이 아니다. 사용자나 애플리케이션의 동작 하나(interaction)다. -Examples: +예: -- open an order page, -- submit a payment, -- change workspace, -- load search results. +- 주문 페이지 열기 +- 결제 제출 +- workspace 바꾸기 +- 검색 결과 불러오기 -Conceptual context: +개념상의 context: ```ts interface ExecutionContext { @@ -464,9 +464,9 @@ interface ExecutionContext { } ``` -Operations run under the same interaction scope. +연산은 같은 interaction 범위 안에서 돈다. -### 10.2 Interaction context +### 10.2 interaction context ```ts interface InteractionContext { @@ -476,15 +476,15 @@ interface InteractionContext { } ``` -All child operations inherit correlation and deadline information. +모든 자식 연산은 correlation 정보와 마감 시간 정보를 물려받는다. > 2026-11-03 현재: `src/platform/execution/execution-context.ts`의 `ExecutionContext` 필드는 `interaction`(`id`·`startedAt`·`deadlineAt`), `cancellation`, `traffic`, 선택 필드 `trace`, `clock`이다. `telemetry` 필드는 없다. -## 11. Traffic Budget +## 11. 트래픽 예산 -Traffic cost must be explicit and bounded. +트래픽 비용은 드러나 있어야 하고 한도가 있어야 한다. -Conceptual model: +개념 모델: ```ts interface TrafficBudget { @@ -495,7 +495,7 @@ interface TrafficBudget { } ``` -A feature owns the policy declaration; the platform owns enforcement. +정책 선언은 기능이 소유한다. 강제는 플랫폼이 소유한다. ```ts defineQueryOperation({ @@ -509,16 +509,16 @@ defineQueryOperation({ }); ``` -The platform must not maintain one global per-feature traffic registry. +플랫폼은 기능별 트래픽 설정을 모은 전역 registry를 하나 두면 안 된다. > 2026-11-03 현재: `TrafficBudget`의 필드는 `maxPhysicalRequests`·`maxRetries`·`maxConcurrentRequests`·`maxQueuedRequests`다. 마감 시간은 따로 받는다(`createExecutionContext`의 `deadlineMs`, HTTP 계약의 `totalDeadlineMs`). > 연산의 정책은 HTTP 계약의 선택 필드 `traffic`(`src/contracts/external-contract-runtime.ts`)이다. 없으면 `src/adapters/http/http-execution-v3.ts`의 `DEFAULT_OPERATION_TRAFFIC_BUDGET`을 쓴다. `defineQueryOperation`은 없다. -## 12. Request Fan-Out +## 12. 요청 fan-out -Frontend N+1 is treated as an architecture defect. +프론트엔드 N+1은 아키텍처 결함으로 본다. -Forbidden behavior: +금지하는 동작: ```text load 1 collection @@ -526,24 +526,24 @@ load 1 collection -> N detail requests ``` -Preferred behavior: +권장하는 동작: -- pagination/cursor APIs, -- bounded page sizes, -- backend bulk endpoints, -- backend read models, -- request coalescing, -- shared query/cache ownership. +- 페이지·cursor API +- 한도가 있는 페이지 크기 +- 백엔드 bulk 엔드포인트 +- 백엔드 read model +- 요청 합치기(coalescing) +- query·cache 소유 공유 -A representative user interaction must have a physical-request budget. +대표 사용자 interaction마다 물리 요청 예산이 있어야 한다. -Synthetic integration tests increase data cardinality while asserting that network request count remains bounded rather than O(N). +합성 통합 테스트는 데이터 개수를 늘리면서 네트워크 요청 수가 O(N)이 아니라 한도 안에 머무는지 확인한다. -## 13. Retry Model +## 13. 재시도 모델 -### 13.1 Retry budget is interaction-scoped +### 13.1 재시도 예산은 interaction 단위다 -Retry count is not independently reset for every request. +재시도 횟수는 요청마다 따로 초기화하지 않는다. ```text Interaction retry budget = 2 @@ -552,51 +552,51 @@ B consumes retry C cannot retry after budget exhaustion ``` -This prevents multiple child requests from multiplying recovery traffic. +그래서 자식 요청 여러 개가 복구 트래픽을 몇 배로 늘리지 못한다. -### 13.2 Retry prerequisites +### 13.2 재시도 전제 조건 -Retries are allowed only when operation semantics permit them. +재시도는 연산의 의미가 허락할 때만 한다. -The existing idempotency/replay semantics remain authoritative. +기존 idempotency·replay 의미가 계속 기준이다. -### 13.3 Retry-After and jitter +### 13.3 Retry-After와 jitter -A `Retry-After` response must not synchronize all clients into a second spike. +`Retry-After` 응답 때문에 모든 클라이언트가 같은 시각에 맞춰져 두 번째 급증을 만들면 안 된다. -Effective scheduling combines server guidance with bounded jitter. +실제 재시도 시각은 서버가 알려 준 값에 한도가 있는 jitter(무작위 지연)를 합쳐 정한다. -## 14. Concurrency Budget +## 14. 동시 실행 예산 -Each interaction has bounded concurrent physical requests. +interaction마다 동시에 보내는 물리 요청 수에 한도가 있다. -Waiting work must be cancelable. +기다리는 작업은 취소할 수 있어야 한다. -Cancellation of an interaction must cancel or release: +interaction을 취소하면 아래를 취소하거나 놓아 줘야 한다. -- queued requests, -- in-flight requests where possible, -- retry timers, -- concurrency leases, -- delayed telemetry associated only with that discarded interaction when safe. +- 대기열의 요청 +- 가능하면, 진행 중인 요청 +- 재시도 timer +- 동시 실행 lease +- 안전하면, 버려진 그 interaction에만 묶인 지연 telemetry -## 15. Deadline Propagation +## 15. 마감 시간 전파 -Timeouts do not reset after each retry or downstream call. +timeout은 재시도나 하위 호출마다 다시 시작하지 않는다. -A root deadline is established at interaction start. +interaction이 시작할 때 루트 마감 시간을 정한다. -Each child computes remaining time: +자식은 남은 시간을 계산한다. ```ts remainingMs = deadlineAt - now(); ``` -A chain of retries therefore cannot turn a 5-second user operation into an unbounded 20- or 30-second operation. +그래서 재시도가 이어져도 5초짜리 사용자 동작이 한도 없이 20초, 30초짜리 동작으로 늘어나지 않는다. -## 16. Request Deduplication and Coalescing +## 16. 요청 중복 제거와 합치기 -Multiple consumers requesting the same logical resource concurrently should share compatible in-flight work. +여러 소비자가 같은 논리 자원을 동시에 요청하면, 호환되는 진행 중 작업을 함께 쓰는 것이 맞다. ```text 10 consumers @@ -604,13 +604,13 @@ Multiple consumers requesting the same logical resource concurrently should shar -> 10 subscribers ``` -The existing TanStack Query infrastructure is a natural implementation foundation where its semantics match the operation. +의미가 연산과 맞는 곳에서는 기존 TanStack Query 기반이 자연스러운 구현 바탕이다. -Deduplication must never merge requests across incompatible authentication, tenant, scope, locale, or cache identity boundaries. +중복 제거는 인증, tenant, scope, locale, cache 신원 경계가 서로 맞지 않는 요청을 절대 합치면 안 된다. -## 17. Error Model +## 17. 오류 모델 -Errors are owned at the correct boundary. +오류는 알맞은 경계가 소유한다. ```text Platform Error @@ -619,33 +619,33 @@ Application / Domain Error Presentation Mapping ``` -### 17.1 Platform errors +### 17.1 플랫폼 오류 -Examples: +예: -- network unavailable, -- request timeout, -- cancellation, -- response too large, -- unsupported content type, -- malformed transport response, -- traffic budget exceeded. +- 네트워크 없음 +- 요청 timeout +- 취소 +- 너무 큰 응답 +- 지원하지 않는 content type +- 형식이 깨진 전송 응답 +- 트래픽 예산 초과 -### 17.2 Contract errors +### 17.2 계약 오류 -Contract failures identify violations at an external boundary: +계약 실패는 외부 경계에서 생긴 위반을 가리킨다. -- schema mismatch, -- protocol mismatch, -- unsupported media type, -- missing required field, -- malformed payload. +- schema 불일치 +- protocol 불일치 +- 지원하지 않는 media type +- 필수 필드 누락 +- 형식이 깨진 payload -### 17.3 Domain/application errors +### 17.3 domain·application 오류 -Concrete business errors remain feature-owned. +구체적인 업무 오류는 계속 기능이 소유한다. -Example: +예: ```ts type PaymentError = @@ -654,9 +654,9 @@ type PaymentError = | PaymentLimitExceeded; ``` -### 17.4 No global error union +### 17.4 전역 오류 union 금지 -This is forbidden: +아래는 금지다. ```ts type GlobalApplicationError = @@ -665,19 +665,19 @@ type GlobalApplicationError = | ...; ``` -Use local generic boundaries instead: +대신 로컬 generic 경계를 쓴다. ```ts Result ``` -The platform understands only the common envelope. +플랫폼은 공통 봉투(envelope)만 안다. -## 18. Error Envelope +## 18. 오류 봉투 -Unstructured `throw new Error("...")` is not the primary cross-layer error contract. +구조 없는 `throw new Error("...")`는 계층을 넘는 주된 오류 계약이 아니다. -Conceptual common metadata: +개념상의 공통 메타데이터: ```ts interface AppError { @@ -688,19 +688,19 @@ interface AppError { } ``` -Concrete domain error semantics remain local. +구체적인 domain 오류의 의미는 로컬에 남는다. -## 19. Presentation Error Mapping +## 19. presentation 오류 매핑 -HTTP status codes and transport details must not leak into presentation logic. +HTTP 상태 코드와 전송 세부가 presentation 로직으로 새면 안 된다. -Bad: +나쁜 예: ```ts if (status === 409) { ... } ``` -Preferred flow: +권장 흐름: ```text HTTP 409 @@ -709,20 +709,20 @@ HTTP 409 -> localized presentation message ``` -## 20. Validation Boundaries +## 20. 검증 경계 -Validation has distinct purposes: +검증은 목적이 서로 다르다. -1. user-input validation, -2. transport validation, -3. domain invariant validation, -4. runtime configuration validation. +1. 사용자 입력 검증 +2. 전송 검증 +3. domain 불변식 검증 +4. runtime 설정 검증 -Frontend validation improves UX but is never an authoritative security boundary. Backend validation remains authoritative. +프론트엔드 검증은 UX를 좋게 한다. 하지만 기준이 되는 보안 경계는 절대 아니다. 기준은 계속 백엔드 검증이다. -## 21. Validate Once at Trust Boundaries +## 21. 신뢰 경계에서 한 번만 검증 -External data enters as unknown/untrusted data. +외부 데이터는 모르는(unknown), 믿을 수 없는 데이터로 들어온다. ```text unknown HTTP body @@ -734,37 +734,37 @@ unknown HTTP body -> domain/application types ``` -The same payload should not be repeatedly schema-validated at every internal layer without a specific trust-boundary reason. +신뢰 경계라는 구체적인 이유 없이 같은 payload를 내부 계층마다 schema로 다시 검증하지 않는다. -## 22. Validation Budget +## 22. 검증 예산 -Validation itself has bounded cost. +검증 자체에도 비용 한도가 있다. -Before expensive parsing and validation, enforce structural constraints where possible: +비싼 파싱과 검증 전에, 가능한 곳에서 구조 제약을 먼저 건다. -- maximum response bytes, -- maximum collection items, -- maximum string lengths, -- maximum allowed nesting/depth where relevant, -- bounded mapper output size. +- 응답 최대 바이트 +- collection 최대 항목 수 +- 문자열 최대 길이 +- 해당하면, 허용하는 최대 중첩 깊이 +- 한도가 있는 mapper 출력 크기 -Oversized responses must be rejected before allocating or validating an arbitrarily large object graph. +너무 큰 응답은 크기 제한 없는 객체 그래프를 메모리에 만들거나 검증하기 전에 거절해야 한다. -## 23. Telemetry Model +## 23. telemetry 모델 -Production frontend observability is required, but raw logging is not the architecture. +production 프론트엔드에는 관측성(observability)이 필요하다. 하지만 날 로그를 찍는 것이 아키텍처는 아니다. -The platform supports: +플랫폼이 지원하는 것: -- error reporting, -- real user monitoring, -- trace/correlation propagation, -- structured operational events, -- performance metrics. +- 오류 보고 +- 실사용자 모니터링(RUM) +- trace·correlation 전파 +- 구조화한 운영 이벤트 +- 성능 지표 -Feature code must not depend directly on a vendor SDK such as Sentry or Datadog. +기능 코드는 Sentry, Datadog 같은 vendor SDK에 직접 의존하면 안 된다. -Conceptual port: +개념상의 port: ```ts interface TelemetryPort { @@ -772,33 +772,33 @@ interface TelemetryPort { } ``` -Provider adapters live behind the platform boundary. +provider adapter는 플랫폼 경계 뒤에 둔다. -## 24. Telemetry Ownership +## 24. telemetry 소유 -The platform owns a common envelope, not every feature event definition. +플랫폼은 공통 봉투를 소유한다. 기능마다의 이벤트 정의는 소유하지 않는다. -Common metadata may include: +공통 메타데이터에 들어갈 수 있는 것: -- event name, -- severity, -- release, -- app/context/feature identifiers, -- interaction ID, -- trace/correlation identifiers, -- timestamp, -- safe attributes. +- 이벤트 이름 +- 심각도 +- 릴리스 +- app·context·기능 식별자 +- interaction ID +- trace·correlation 식별자 +- 시각 +- 안전한 속성 -Concrete event payload schemas remain feature-owned. +구체적인 이벤트 payload schema는 계속 기능이 소유한다. -No global telemetry event union containing every feature is allowed. +모든 기능을 담는 전역 telemetry 이벤트 union은 허용하지 않는다. > 2026-11-03 현재: 봉투(`src/platform/telemetry/telemetry-event.ts`)의 필드는 `kind`·`severity`·`contextId`·`featureId`·`interactionId`·`traceId`·`payload`다. > 릴리스 식별자(`build_id`·`release_id`)는 수집기 adapter(`src/adapters/telemetry/telemetry-collector.ts`)가 붙인다. 시각과 app 식별자는 봉투에 없다. -## 25. Telemetry Pipeline +## 25. telemetry 파이프라인 -Required conceptual pipeline: +필요한 개념 파이프라인: ```text Feature event @@ -813,57 +813,59 @@ Feature event -> transport ``` -All in-browser queues and maps are bounded. +브라우저 안의 모든 queue와 map에는 한도가 있다. > 2026-11-03 현재: 코드의 순서는 봉투 검사 → redact → fingerprint → deduplicate → sample → buffer → rate limit → batch → transport다(`src/platform/telemetry/telemetry-pipeline.ts`). normalize 자리에 봉투 검사가 있고, rate limit이 batch보다 앞이다. -## 26. Telemetry Must Fail Open for Business Behavior +## 26. 업무 동작에는 telemetry가 fail-open이어야 한다 -Telemetry failure must not fail application behavior. +telemetry가 실패해도 애플리케이션 동작은 실패하면 안 된다. + +아래 두 경로는 ```text business path telemetry path ``` -are separated. +서로 분리되어 있다. -When telemetry capacity is exhausted, low-priority observability data is dropped rather than growing browser memory or blocking user operations. +telemetry 용량이 다 차면 우선순위가 낮은 관측 데이터를 버린다. 브라우저 메모리를 늘리거나 사용자 동작을 막지 않는다. -## 27. Telemetry Storm Protection +## 27. telemetry 폭주 방어 -A production incident may cause millions of browsers to report the same error simultaneously. +production 장애 하나 때문에 브라우저 수백만 개가 같은 오류를 동시에 보고할 수 있다. -The telemetry subsystem therefore requires: +그래서 telemetry 하위 시스템에는 아래가 필요하다. -- deterministic or policy-driven sampling, -- repeated-error fingerprinting, -- bounded deduplication state, -- bounded batch size, -- bounded queue bytes/events, -- rate limiting, -- priority-based dropping. +- 결정적이거나 정책을 따르는 sampling +- 반복 오류 fingerprint +- 한도가 있는 중복 제거 상태 +- 한도가 있는 batch 크기 +- queue의 바이트·이벤트 수 한도 +- rate limit +- 우선순위에 따른 버리기 -Observability must never amplify an incident into another outage. +관측이 장애를 키워 또 다른 장애를 만들면 절대 안 된다. -## 28. Telemetry Privacy and Redaction +## 28. telemetry 개인정보 보호와 redaction -Feature authors must not be able to casually emit secrets. +기능 작성자가 무심코 비밀 값을 내보낼 수 없어야 한다. -Runtime sanitization must reject/redact sensitive classes such as: +runtime 정제는 아래 같은 민감한 값을 거절하거나 가려야(redact) 한다. -- Authorization values, -- cookies, -- access tokens, -- refresh tokens, -- passwords, -- known secret fields. +- Authorization 값 +- cookie +- access token +- refresh token +- 비밀번호 +- 알려진 비밀 필드 -Typed safe payloads may be added where they improve correctness, but runtime defense remains required because compile-time types are not a security boundary. +정확성을 높인다면 타입이 있는 안전한 payload를 더해도 된다. 그래도 runtime 방어는 계속 필요하다. 컴파일 시점 타입은 보안 경계가 아니기 때문이다. -## 29. Trace and Correlation +## 29. trace와 correlation -User interactions should connect browser events with backend traces where supported. +지원되는 곳에서는 사용자 interaction이 브라우저 이벤트를 백엔드 trace와 잇는 것이 맞다. ```text user interaction @@ -873,13 +875,13 @@ user interaction -> downstream dependency ``` -Trace propagation must follow the chosen backend/OTel contract and must not invent incompatible identifiers independently per feature. +trace 전파는 선택한 백엔드·OTel 계약을 따라야 한다. 기능마다 호환되지 않는 식별자를 따로 만들면 안 된다. > 2026-11-03 현재: 전파는 interaction이 켰을 때만 한다(`ExecutionContext`의 `trace`는 선택 필드). 헤더는 `traceparent`와 `x-correlation-id`다(`src/platform/telemetry/trace-context.ts`). -## 30. Failure Boundaries +## 30. 실패 경계 -Failure containment mirrors architecture ownership. +실패를 가두는 범위는 아키텍처 소유 구조를 그대로 따른다. ```text App Boundary @@ -888,30 +890,30 @@ App Boundary -> Page Boundary where useful ``` -Not every component gets an ErrorBoundary. Boundaries correspond to meaningful recovery/fallback domains. +모든 컴포넌트에 ErrorBoundary를 두지 않는다. 경계는 의미 있는 복구·대체 화면 단위에 맞춘다. -A payment UI failure should not necessarily destroy order, catalog, or account UI. +결제 UI가 실패했다고 주문, 카탈로그, 계정 UI까지 무너질 필요는 없다. -## 31. Async Failure Model +## 31. 비동기 실패 모델 -React render failures are only one class of failure. +React 렌더링 실패는 실패의 한 종류일 뿐이다. -The architecture also models: +아키텍처는 아래도 모델로 다룬다. -- query failure, -- mutation failure, -- validation failure, -- timeout, -- cancellation, -- traffic-budget exhaustion. +- query 실패 +- mutation 실패 +- 검증 실패 +- timeout +- 취소 +- 트래픽 예산 소진 -Presentation state should distinguish recoverable, terminal, and cancelled outcomes where useful. +쓸모가 있는 곳에서는 화면 상태가 복구할 수 있는 결과, 끝난(terminal) 결과, 취소된 결과를 구분하는 것이 맞다. > 2026-11-03 현재: 화면 상태는 `src/application/view-models/async-state.ts`가 정한다. 기본 상태 `terminal-error`와 덧씌움 `stale-degraded`·`mutation-effect-unknown`·`mutation-conflict`가 있다. 취소만 따로 보여 주는 상태는 이 목록에 없다. -## 32. Spike Traffic Design +## 32. 급증 트래픽 설계 -Spike scenarios include rapid jumps such as: +급증 시나리오에는 아래 같은 급격한 증가가 있다. ```text 100 clients @@ -919,62 +921,62 @@ Spike scenarios include rapid jumps such as: -> 100,000+ ``` -The frontend platform cannot control the number of users, but it must control client-side amplification. +프론트엔드 플랫폼은 사용자 수를 통제할 수 없다. 하지만 클라이언트 쪽 증폭은 통제해야 한다. -Critical risks: +핵심 위험: -- retry storm, -- authentication refresh storm, -- cache-miss storm, -- telemetry storm, -- synchronized `Retry-After`, -- uncontrolled concurrency, -- duplicate requests. +- 재시도 폭주 +- 인증 갱신 폭주 +- cache-miss 폭주 +- telemetry 폭주 +- 모든 클라이언트가 같은 시각에 맞춰지는 `Retry-After` +- 통제되지 않는 동시 실행 +- 중복 요청 > 2026-11-03 현재: 이 절을 가리키는 테스트(`tests/platform/traffic/traffic-amplification.test.ts`)는 실패와 병렬 연산에서 요청·재시도 증폭만 본다. 인증 갱신 폭주와 cache-miss 폭주를 따로 재는 규모 테스트는 찾지 못했다. -## 33. Sustained Traffic Design +## 33. 지속 트래픽 설계 -Long-running high traffic and long-lived SPA sessions expose different risks: +오래 이어지는 높은 트래픽과 오래 열린 SPA 세션은 다른 위험을 드러낸다. -- heap growth, -- timer/listener leaks, -- query cache churn, -- browser storage growth, -- stale auth/session state, -- repeated background polling, -- telemetry backlog, -- orphaned AbortControllers or tasks. +- heap 증가 +- timer·listener 누수 +- query cache 교체 반복(churn) +- 브라우저 저장소 증가 +- 낡은 인증·세션 상태 +- 반복되는 백그라운드 polling +- 밀린 telemetry +- 주인 잃은 AbortController나 작업 -Scale verification therefore includes soak-style tests and memory slope, not only peak request count. +그래서 규모 검증은 최대 요청 수만 보지 않는다. soak 방식 테스트(오래 돌려 누수를 보는 테스트)와 메모리 기울기도 본다. -## 34. Amplification Metrics +## 34. 증폭 지표 -The platform test harness defines operational amplification metrics. +플랫폼 테스트 harness가 운영 증폭 지표를 정한다. -### 34.1 Request amplification +### 34.1 요청 증폭 ```text physical HTTP requests / logical interactions ``` -### 34.2 Retry amplification +### 34.2 재시도 증폭 ```text total physical attempts / initial physical requests ``` -### 34.3 Telemetry amplification +### 34.3 telemetry 증폭 ```text telemetry sends / logical failures or events ``` -These are measured under healthy, slow, partial-failure, and total-failure conditions. +이 지표는 정상, 느림, 부분 실패, 전체 실패 조건에서 잰다. -## 35. Scale Profiles +## 35. 규모 프로필 -Synthetic scale profiles: +합성 규모 프로필: ```text S0 100 @@ -984,42 +986,42 @@ S3 100,000 S4 1,000,000 ``` -These do not all mean “generate that many TypeScript source files”. +모든 프로필이 「TypeScript 소스 파일을 그만큼 만든다」는 뜻은 아니다. ### S0-S1 -Can exercise concrete module composition and type-check fixtures. +실제 모듈 조립과 타입 검사 fixture를 돌려 볼 수 있다. ### S2 -Exercises larger generated indexes and composition structures when affordable. +감당할 수 있으면 더 큰 생성 색인과 조립 구조를 돌려 본다. ### S3-S4 -Primarily verify global topology and local-boundary independence. They model one hundred thousand or one million logical features while asserting that any one app/context remains within local budgets. +주로 전역 토폴로지와 로컬 경계의 독립성을 검증한다. 논리 기능 10만 개나 100만 개를 모델로 만들고, 어느 app·context 하나도 로컬 예산 안에 머무는지 확인한다. -## 36. Local Scale Verification +## 36. 로컬 규모 검증 -Within one allowed boundary, measure: +허용된 경계 하나 안에서 아래를 잰다. -- registry composition, -- route composition, -- generated index cost, -- TypeScript diagnostics, -- bundle/build cost, -- browser boot cost. +- registry 조립 +- route 조립 +- 생성 색인 비용 +- TypeScript 진단 +- 번들·빌드 비용 +- 브라우저 부팅 비용 -Scale-sensitive composition should exhibit linear-or-better growth where linear work is unavoidable. +선형 작업을 피할 수 없는 곳에서, 규모에 민감한 조립은 선형이거나 그보다 나은 증가를 보여야 한다. -Quadratic-like growth is a failure. +제곱에 가까운 증가는 실패다. > 2026-11-03 현재: 규모 측정(`scripts/scale/run-composition-scale.ts`, `scripts/scale/collect-tsc-diagnostics.ts`)은 registry·route 조립, 생성 색인, TypeScript 진단을 잰다. 번들·빌드 비용과 브라우저 부팅 비용은 이 측정에 없다(§40). -## 37. Global Topology Verification +## 37. 전역 토폴로지 검증 -Increase global logical cardinality while holding one app unchanged. +app 하나를 그대로 두고 전역 논리 개수를 늘린다. -Assertions: +확인할 것: ```text Global feature count increases @@ -1032,62 +1034,62 @@ but unchanged App A should not materially increase: - boot CPU ``` -This is the critical proof that the architecture can extend toward 100K/1M logical domains. +이것이 아키텍처가 논리 도메인 10만·100만 개까지 늘 수 있다는 핵심 증거다. > 2026-11-03 현재: `tests/scale/global-local-independence.test.ts`는 생성 색인, 소스 그래프, 부팅 때 읽는 context 루트를 본다. 번들은 `check:app-build-input:bundle`이 "소유하지 않은 기능의 모듈이 없다"만 본다. 부팅 heap·CPU는 재지 않는다. -## 38. TypeScript Scale Gate +## 38. TypeScript 규모 게이트 -Use compiler diagnostics where supported, including `--extendedDiagnostics`. +지원되면 `--extendedDiagnostics`를 포함한 컴파일러 진단을 쓴다. -Track at least: +최소한 아래를 기록한다. -- source file count, -- type count, -- symbol count, -- instantiations, -- memory, -- total type-check time. +- 소스 파일 수 +- 타입 수 +- symbol 수 +- instantiation 수 +- 메모리 +- 전체 타입 검사 시간 -A global module augmentation or giant union that causes unrelated app compile cost to rise with global domain count is a design regression. +전역 module augmentation이나 거대한 union 때문에, 전역 도메인 수가 늘 때 관계없는 app의 컴파일 비용이 오르면 설계 회귀다. -## 39. Runtime Composition Scale Gate +## 39. runtime 조립 규모 게이트 -Benchmark relevant registries: +해당하는 registry를 벤치마크한다. -- route, -- API operation, -- schema, -- mapper, -- invalidation, -- adapter contribution, -- runtime contribution, -- locale/message contribution. +- route +- API 연산 +- schema +- mapper +- invalidation +- adapter 기여 +- runtime 기여 +- locale·message 기여 -Test multiple N values to detect nonlinear regression. +N 값을 여러 개로 시험해 비선형 회귀를 찾는다. -Absolute timing alone is insufficient; growth behavior matters. +절대 시간만으로는 부족하다. 늘어나는 모양이 중요하다. -## 40. Browser Boot Gate +## 40. 브라우저 부팅 게이트 -Measure: +잴 것: -- initial JS transferred, -- parsed/executed JS, -- initial route count, -- initial heap, -- bootstrap CPU, -- runtime config fetch, -- release manifest verification, -- first meaningful application render. +- 처음 전송하는 JS +- 파싱·실행한 JS +- 초기 route 수 +- 초기 heap +- bootstrap CPU +- runtime 설정 가져오기 +- 릴리스 manifest 검증 +- 의미 있는 첫 애플리케이션 렌더링 -Global topology growth must not cause proportional growth in these metrics for an unchanged app. +전역 토폴로지가 커져도, 바뀌지 않은 app의 이 지표가 비례해서 늘면 안 된다. > 2026-11-03 현재: 이 목록을 재는 부팅 게이트는 없다. 초기 JS gzip 크기만 `check:bundle`이 `config/performance/budgets.json`의 `initialJsGzipBytes`로 막는다. 초기 heap, 부팅 CPU, 첫 렌더, 초기 route 수는 재지 않는다. -## 41. Request Fan-Out Gate +## 41. 요청 fan-out 게이트 -Use representative collection pages with increasing server-returned cardinality: +서버가 돌려주는 개수를 늘려 가며 대표 collection 페이지를 쓴다. ```text N = 10 @@ -1095,33 +1097,33 @@ N = 100 N = 1,000 ``` -A page that requires two bounded bulk requests should remain around that request count instead of issuing O(N) row-detail calls. +한도 있는 bulk 요청 두 개가 필요한 페이지는 요청 수가 그 근처에 머물러야 한다. 행마다 상세 호출을 보내 O(N)번이 되면 안 된다. -> **Implementation note (2026-09-23).** The template's representative collection contract is a paginated bulk read with a hard page ceiling of 100 rows (`limit` ≤ 100, response schema `max(100)`). `N` above is the server-side collection cardinality, not the size of one response. Acceptance is therefore two-layered: +> **구현 메모 (2026-09-23).** 템플릿의 대표 collection 계약은 페이지로 나눈 bulk 읽기다. 페이지 한도는 100행으로 고정이다(`limit` ≤ 100, 응답 schema `max(100)`). 위의 `N`은 서버 쪽 collection 개수이지 응답 하나의 크기가 아니다. 그래서 합격 기준은 두 층이다. > -> - supported cardinality — collections of N = 10 / 50 / 100 / 1,000 rows load a page with **1** physical request, and a full 1,000-row walk costs ≤ ceil(N / 100) + 1 page requests, never one request per row; -> - oversized response — a single response carrying more than the page ceiling (e.g. 1,000 rows at once) is rejected within **1** request as a contract violation, with no per-row downstream fan-out. +> - 지원하는 개수 — N = 10 / 50 / 100 / 1,000행 collection은 물리 요청 **1**번으로 한 페이지를 불러온다. 1,000행 전체를 훑는 데는 페이지 요청이 ceil(N / 100) + 1번 이하로 든다. 행마다 요청을 하나씩 보내는 일은 없다. +> - 너무 큰 응답 — 페이지 한도보다 많이 담은 응답 하나(예: 한 번에 1,000행)는 계약 위반으로 보고 요청 **1**번 안에 거절한다. 행마다 하위 fan-out이 생기지 않는다. > -> The ceiling is not raised to make an oversized fixture pass. A source gate (`pnpm check:request-fanout`) rejects any request dispatch inside a loop or array-iteration callback in feature/application code. +> 너무 큰 fixture를 통과시키려고 한도를 올리지 않는다. 소스 게이트(`pnpm check:request-fanout`)가 기능·application 코드에서 루프나 배열 순회 callback 안에서 요청을 보내는 코드를 거절한다. -## 42. Failure and Chaos Scenarios +## 42. 실패·카오스 시나리오 -Required scenarios include: +필요한 시나리오는 아래와 같다. -### Total API failure +### 전체 API 실패 -Verify: +확인할 것: -- retry bound, -- concurrency bound, -- telemetry bound, -- bounded memory, -- no infinite loop, -- no reload loop. +- 재시도 한도 +- 동시 실행 한도 +- telemetry 한도 +- 한도가 있는 메모리 +- 무한 루프 없음 +- reload 반복 없음 -### Partial failure +### 부분 실패 -Example: +예: ```text Payment 100% failure @@ -1129,25 +1131,25 @@ Order healthy Catalog healthy ``` -Payment should degrade without collapsing unrelated contexts. +결제는 기능을 줄인 채 버티고, 관계없는 context를 무너뜨리지 않는 것이 맞다. -### Slow API +### 느린 API -Test long-tail latency. Verify deadlines, cancellation, concurrency queues, and queue limits. +긴 꼬리 지연(long-tail latency)을 시험한다. 마감 시간, 취소, 동시 실행 대기열, 대기열 한도를 확인한다. -### Network flap +### 네트워크 끊김 반복 -Repeated online/offline transitions must not produce duplicate unsafe mutations or retry bursts. +online·offline이 반복해서 바뀌어도 안전하지 않은 mutation이 중복되거나 재시도가 한꺼번에 몰리면 안 된다. -### Telemetry endpoint failure +### telemetry 엔드포인트 실패 -Business behavior remains functional and telemetry storage remains bounded. +업무 동작은 계속 돌고, telemetry 저장량은 한도 안에 머문다. -## 43. Telemetry Storm Test +## 43. telemetry 폭주 테스트 -Generate a large number of identical errors/events. +똑같은 오류·이벤트를 아주 많이 만든다. -Expected behavior: +기대 동작: ```text many logical errors @@ -1155,112 +1157,112 @@ many logical errors -> bounded number of buffered/sent telemetry events ``` -The test records emitted, deduplicated, sampled, dropped, and transmitted counts. +테스트는 내보낸 수, 중복 제거한 수, sampling에서 빠진 수, 버린 수, 전송한 수를 기록한다. -## 44. Soak Testing +## 44. soak 테스트 -Long-session profiles may include 30 minutes, 2 hours, 8 hours, or 24 hours depending on environment cost. +긴 세션 프로필은 환경 비용에 따라 30분, 2시간, 8시간, 24시간일 수 있다. -Observe: +볼 것: -- heap size and slope, -- active timers, -- event listeners, -- DOM nodes, -- query cache size, -- telemetry buffer, -- IndexedDB/browser storage, -- stale auth/session leakage. +- heap 크기와 기울기 +- 살아 있는 timer +- event listener +- DOM 노드 +- query cache 크기 +- telemetry buffer +- IndexedDB·브라우저 저장소 +- 낡은 인증·세션 상태가 새는 누수 -The primary leak signal is sustained positive growth after expected warm-up stabilization, not only an arbitrary maximum heap value. +누수의 주된 신호는 예상한 warm-up 안정화 뒤에도 계속 늘어나는 것이다. 임의로 정한 최대 heap 값만 보지 않는다. > 2026-11-03 현재: 브라우저 soak(`scripts/scale/browser-soak.ts`)은 nightly 단계에서 2분 돈다. heap, DOM 노드, listener, timer, 진행 중 fetch, Web Storage를 잰다. > query cache와 telemetry buffer는 논리 테스트(`tests/scale/session/long-session.test.ts`)가 본다. IndexedDB는 재지 않고, 30분 이상 돌리는 실행은 없다. -## 45. Horizontal Scaling and Release Coherence +## 45. 수평 확장과 릴리스 일관성 -Frontend application instances are intended to remain stateless with respect to server-hosted browser user state. +프론트엔드 애플리케이션 인스턴스는 stateless로 둔다. 브라우저 사용자 상태를 서버 인스턴스에 두지 않는다는 뜻이다. -Horizontal scaling is safe only when release coherence is maintained. +수평 확장은 릴리스 일관성을 지킬 때만 안전하다. -Deployment contract: +배포 계약: -- content-hashed assets are immutable, -- HTML is revalidated/no-cache according to current release strategy, -- runtime config and release manifest are no-store, -- old hashed assets remain available during rolling release windows, -- a deployment switches an active release tuple atomically, -- mixed incompatible HTML/config/manifest combinations fail closed rather than executing ambiguously. +- 내용 hash가 붙은 asset은 바꾸지 않는다(immutable). +- HTML은 현재 릴리스 전략에 따라 revalidate하거나 no-cache로 둔다. +- runtime 설정과 릴리스 manifest는 no-store다. +- rolling 릴리스 동안 예전 hash asset을 계속 받을 수 있다. +- 배포는 활성 릴리스 묶음(tuple)을 한 번에(atomic) 바꾼다. +- 호환되지 않는 HTML·설정·manifest가 섞이면 애매하게 실행하지 않고 닫힌 쪽으로 실패한다(fail closed). > 2026-11-03 현재: 불일치를 만나면 세션마다 한 번만 자동으로 다시 불러오고, 그 뒤의 불일치는 실패 화면으로 끝낸다(`src/platform/release/release-mismatch-recovery.ts`). 이 재시도는 원문에 없다. -## 46. Multi-Replica Release Matrix +## 46. 다중 replica 릴리스 행렬 -At minimum verify: +최소한 아래를 확인한다. -| HTML | Config | Manifest | Asset | Expected | +| HTML | 설정 | manifest | asset | 기대 결과 | | --- | --- | --- | --- | --- | | R10 | R10 | R10 | R10 | PASS | | R10 | R11 | R10 | R10 | FAIL CLOSED | | R10 | R10 | R11 | R10 | FAIL CLOSED | -| R10 | R10 | R10 | missing/incompatible | FAIL | +| R10 | R10 | R10 | 없음/호환 안 됨 | FAIL | | R11 | R11 | R11 | R11 | PASS | -Rolling deployments must also preserve reachability of previous immutable hashed assets for clients that loaded earlier HTML. +rolling 배포는 예전 HTML을 불러온 클라이언트가 이전의 immutable hash asset에 계속 닿을 수 있게 해야 한다. -## 47. CI Execution Tiers +## 47. CI 실행 단계 -Heavy scale tests must not make every pull request unusably expensive. +무거운 규모 테스트 때문에 모든 pull request가 쓸 수 없을 만큼 비싸지면 안 된다. -### Pull request +### pull request 단계 -Fast deterministic gates: +빠르고 결정적인 게이트: -- dependency architecture, -- cardinality budgets, -- unit tests, -- app/test type-check, -- small composition fixtures, -- duplicate collision tests, -- cross-feature dependency fixture, -- small request fan-out fixture. +- 의존성 아키텍처 +- 개수 예산 +- 단위 테스트 +- app·테스트 타입 검사 +- 작은 조립 fixture +- 중복 충돌 테스트 +- 기능 간 의존 fixture +- 작은 요청 fan-out fixture -### Main branch +### main 브랜치 단계 -Medium scale regression: +중간 규모 회귀: -- 1K/10K synthetic composition where appropriate, -- TypeScript diagnostic comparison, -- route/bootstrap growth checks, -- generated index validation. +- 맞는 경우, 1K/10K 합성 조립 +- TypeScript 진단 비교 +- route·bootstrap 증가 검사 +- 생성 색인 검증 -### Nightly +### nightly 단계 -Heavy synthetic and browser verification: +무거운 합성 검증과 브라우저 검증: -- 10K/100K/1M topology model, -- browser memory and route loading, -- telemetry storm, -- failure scenarios, -- longer navigation/session cycles. +- 10K/100K/1M 토폴로지 모델 +- 브라우저 메모리와 route 불러오기 +- telemetry 폭주 +- 실패 시나리오 +- 더 긴 화면 이동·세션 반복 -### Release / dedicated environment +### 릴리스 / 전용 환경 단계 -Environment-dependent checks: +환경에 따라 달라지는 검사: -- spike load, -- soak load, -- cache behavior, -- multi-replica mixed-release validation, -- CDN/LB/origin release contract. +- 급증 부하 +- soak 부하 +- cache 동작 +- 다중 replica 혼합 릴리스 검증 +- CDN·LB·origin 릴리스 계약 > 2026-11-03 현재: CI는 `pr` 단계만 돌린다(FE-GATE-005). `main`·`nightly`·`release`는 로컬 명령이다. 기준선 시간 비교가 그 기준선을 기록한 CPU에서만 성립하기 때문이다(`scripts/scale/run-scale-profile.ts`). -## 48. Benchmark Result Format +## 48. 벤치마크 결과 형식 -Scale results are machine-readable artifacts, not only console output. +규모 결과는 콘솔 출력으로만 끝내지 않고, 기계가 읽을 수 있는 산출물로 남긴다. -Example: +예: ```json { @@ -1273,121 +1275,121 @@ Example: } ``` -Store enough metadata to compare against a compatible baseline. +호환되는 기준선과 비교할 수 있을 만큼 메타데이터를 저장한다. > 2026-11-03 현재: 실제 형식은 `scripts/scale/benchmark-result.ts`의 `BenchmarkResult`(`name`·`profile`·`cardinality`·`samples`·`medianMs`·`heapBytes`·`metadata`)와 이를 담는 `BenchmarkArtifact`다. 위 JSON은 예시다. -## 49. Regression Policy +## 49. 회귀 정책 -Use three kinds of thresholds: +기준값은 세 종류를 쓴다. -1. absolute ceiling, -2. relative regression percentage, -3. growth-complexity trend. +1. 절대 상한 +2. 상대 회귀 비율 +3. 증가 복잡도 추세 -Performance measurements should use multiple runs and robust summaries such as median where environment noise is relevant. +환경 잡음이 영향을 주는 곳에서는 성능 측정을 여러 번 돌리고, 중앙값처럼 튼튼한 요약값을 쓰는 것이 맞다. -Structural failures such as cycles, duplicate IDs, cross-feature concrete imports, or cardinality-budget violations are deterministic and should fail immediately. +순환, 중복 ID, 기능 간 구체 import, 개수 예산 위반 같은 구조 실패는 결정적이다. 바로 실패해야 한다. -## 50. Required Architecture Gates +## 50. 필요한 아키텍처 게이트 -The architecture must eventually provide automated gates for: +아키텍처는 결국 아래 항목의 자동 게이트를 갖춰야 한다. -1. cross-feature concrete import prohibition, -2. cross-context concrete import prohibition, -3. cycle prohibition, -4. cardinality budgets, -5. duplicate feature/route/operation/schema IDs, -6. O(N²)-style registry regression, -7. request fan-out regression, -8. retry-budget enforcement, -9. telemetry-buffer boundedness, -10. global-to-local scale independence, -11. TypeScript/build scale regression, -12. multi-replica release coherence. +1. 기능 간 구체 import 금지 +2. context 간 구체 import 금지 +3. 순환 금지 +4. 개수 예산 +5. 기능·route·연산·schema ID 중복 +6. O(N²)식 registry 회귀 +7. 요청 fan-out 회귀 +8. 재시도 예산 강제 +9. telemetry buffer 한도 +10. 전역 규모와 로컬 규모의 독립 +11. TypeScript·빌드 규모 회귀 +12. 다중 replica 릴리스 일관성 > 2026-11-03 현재: 1~3번은 `.dependency-cruiser.json`의 `features-do-not-import-other-features`, `contexts-do-not-import-other-contexts`, `no-circular-dependencies`다. 11번(TypeScript 규모)은 `main` 단계에만 있어 CI에서 돌지 않는다(§47). -## 51. Compatibility With Current Template Strengths +## 51. 현재 템플릿 강점과의 호환 -This design preserves and extends current strengths rather than replacing them: +이 설계는 현재 강점을 갈아엎지 않는다. 지키면서 넓힌다. -- Clean Architecture layer rules, -- capability-driven adapter composition, -- HTTP operation contracts, -- bounded response handling, -- retry/idempotency semantics, -- TanStack Query cache ownership, -- scope fencing/generation behavior, -- release/build/config coherence, -- immutable static asset release model. +- Clean Architecture 계층 규칙 +- capability 기준 adapter 조립 +- HTTP 연산 계약 +- 한도가 있는 응답 처리 +- 재시도·idempotency 의미 +- TanStack Query cache 소유 +- scope fencing·generation 동작 +- 릴리스·빌드·설정 일관성 +- immutable 정적 asset 릴리스 모델 -The implementation should refactor composition and introduce platform policies without unnecessary UI/design changes. +구현은 불필요한 UI·디자인 변경 없이 조립을 리팩터링하고 플랫폼 정책을 들여온다. -## 52. Explicit Non-Goals +## 52. 명시적으로 하지 않는 것 -This design does not require: +이 설계가 요구하지 않는 것: -- one SPA containing 1M TypeScript features, -- runtime discovery of arbitrary remote code, -- Module Federation or micro-frontends as the default starting point, -- a global mega-registry, -- a global mega-error union, -- a global telemetry schema union, -- vendor-specific observability APIs in feature code, -- frontend validation as a replacement for backend validation. +- TypeScript 기능 100만 개를 담은 SPA 하나 +- runtime에 임의의 원격 코드 찾기 +- 기본 출발점으로서의 Module Federation이나 micro-frontend +- 전역 초대형 registry +- 전역 초대형 오류 union +- 전역 telemetry schema union +- 기능 코드 안의 vendor 전용 관측 API +- 백엔드 검증을 대신하는 프론트엔드 검증 -Remote/micro-frontend deployment can remain an optional future escalation when organizational or deployment boundaries require independent teams/releases. It is not required to solve the current scaling architecture. +원격·micro-frontend 배포는 나중에 고를 수 있는 단계로 남긴다. 조직 경계나 배포 경계 때문에 팀·릴리스를 따로 가져가야 할 때다. 지금의 규모 아키텍처를 푸는 데는 필요 없다. -## 53. Implementation Sequence Constraints +## 53. 구현 순서 제약 -Implementation should be incremental and preserve behavior. +구현은 조금씩 하고 동작을 지킨다. -A safe high-level sequence is: +안전한 큰 순서는 아래와 같다. -1. establish deterministic architecture/scale tests around current behavior, -2. remove known O(N²) and repeated-membership composition paths, -3. introduce feature-owned descriptor boundaries, -4. generate static product/context indexes, -5. enforce cross-feature/context dependency rules, -6. introduce hierarchical route composition, -7. introduce cardinality budgets, -8. introduce execution context and traffic budgets, -9. normalize error and validation boundaries, -10. introduce telemetry port/pipeline/budgets, -11. add scale/chaos/soak/release gates by CI tier. +1. 현재 동작을 감싸는 결정적 아키텍처·규모 테스트를 세운다. +2. 알려진 O(N²) 조립 경로와 포함 검사를 반복하는 조립 경로를 없앤다. +3. 기능이 소유하는 descriptor 경계를 들여온다. +4. 정적 product·context 색인을 생성한다. +5. 기능 간·context 간 의존성 규칙을 강제한다. +6. 계층형 route 조립을 들여온다. +7. 개수 예산을 들여온다. +8. 실행 context와 트래픽 예산을 들여온다. +9. 오류 경계와 검증 경계를 정리한다. +10. telemetry port·파이프라인·예산을 들여온다. +11. CI 단계별로 규모·카오스·soak·릴리스 게이트를 더한다. -The detailed implementation plan must decompose these into test-first tasks and identify exact existing files after re-reading the live repository state. +자세한 구현 계획은 이 순서를 테스트 먼저(test-first) 작업으로 쪼개야 한다. 그리고 지금 repo 상태를 다시 읽은 뒤 고칠 기존 파일을 정확히 짚어야 한다. -## 54. Acceptance Criteria +## 54. 완료 기준 -The design is considered implemented only when all of the following are true: +아래가 모두 참일 때만 이 설계를 구현했다고 본다. -- Adding a normal feature does not require editing a collection of central handwritten installation registries. -- Composition does not contain known quadratic accumulation patterns. -- Membership checks on scale-sensitive paths use appropriate indexed structures. -- Concrete imports across unrelated features fail architecture checks. -- Context/app cardinality ceilings are explicit and testable. -- An unchanged local app does not grow materially when global logical topology grows toward S3/S4 fixtures. -- Initial routing is hierarchical/lazy rather than a product-wide flat feature table. -- User interactions carry bounded request, retry, concurrency, cancellation, and deadline semantics. -- Representative collections do not create frontend N+1 request fan-out. -- Errors remain local and typed without constructing a global union of all feature errors. -- External data is validated at trust boundaries with bounded payload/structure cost. -- Feature code emits observability through a platform port rather than vendor SDKs. -- Telemetry is redacted, deduplicated, sampled, buffered, and rate-limited with bounded memory. -- Telemetry failure does not fail business behavior. -- Failure boundaries prevent one feature/context from unnecessarily collapsing unrelated UI. -- Spike and sustained-load tests detect request, retry, telemetry, and memory amplification. -- Multi-replica release tests verify fail-closed coherence and old-asset reachability. +- 보통의 기능을 더할 때 손으로 쓴 중앙 설치 registry 여러 개를 고치지 않는다. +- 조립에 알려진 제곱 누적 패턴이 없다. +- 규모에 민감한 경로의 포함 검사는 알맞은 색인 구조를 쓴다. +- 관계없는 기능 사이의 구체 import는 아키텍처 검사에서 실패한다. +- context·app 개수 한도가 드러나 있고 테스트할 수 있다. +- 전역 논리 토폴로지가 S3/S4 fixture 쪽으로 커져도, 바뀌지 않은 로컬 app은 눈에 띄게 커지지 않는다. +- 초기 라우팅은 제품 전체의 평평한 기능 표가 아니라 계층형·지연 로딩이다. +- 사용자 interaction은 한도가 있는 요청·재시도·동시 실행·취소·마감 시간 의미를 지닌다. +- 대표 collection은 프론트엔드 N+1 요청 fan-out을 만들지 않는다. +- 오류는 모든 기능 오류를 모은 전역 union 없이, 로컬에서 타입을 가진 채 남는다. +- 외부 데이터는 신뢰 경계에서 검증한다. payload·구조 비용에는 한도가 있다. +- 기능 코드는 vendor SDK가 아니라 플랫폼 port로 관측 데이터를 보낸다. +- telemetry는 한도가 있는 메모리 안에서 redact, 중복 제거, sampling, buffering, rate limit을 거친다. +- telemetry 실패가 업무 동작을 실패시키지 않는다. +- 실패 경계 덕분에 기능·context 하나가 관계없는 UI까지 괜히 무너뜨리지 않는다. +- 급증·지속 부하 테스트가 요청, 재시도, telemetry, 메모리 증폭을 잡아낸다. +- 다중 replica 릴리스 테스트가 fail-closed 일관성과 예전 asset 도달 가능성을 확인한다. -## 55. Design Summary +## 55. 설계 요약 -The architecture is based on one rule: +이 아키텍처는 규칙 하나에 기댄다. -> Global scale must be partitioned into bounded local scale, and every remaining local cardinality must have an explicit budget. +> 전역 규모는 한도가 있는 로컬 규모로 나눠야 한다. 그리고 남은 로컬 개수에는 모두 명시적인 예산이 있어야 한다. -Therefore the platform avoids: +그래서 플랫폼은 아래를 피한다. ```text unbounded registry @@ -1403,4 +1405,4 @@ unbounded memory growth unbounded failure propagation ``` -This allows the product ecosystem to grow from hundreds toward hundreds of thousands or millions of logical domains without requiring a single browser, TypeScript compiler invocation, router, or runtime registry to directly carry that global cardinality. +그래서 제품 생태계는 논리 도메인 수백 개에서 수십만, 수백만 개로 커질 수 있다. 브라우저 하나, TypeScript 컴파일러 실행 한 번, 라우터 하나, runtime registry 하나가 그 전역 개수를 직접 떠안지 않아도 된다. diff --git a/docs/architecture/starter-experience.md b/docs/architecture/starter-experience.md index f6224048..264586ec 100644 --- a/docs/architecture/starter-experience.md +++ b/docs/architecture/starter-experience.md @@ -1,11 +1,10 @@ -# Starter experience contract +# 스타터 경험 계약 -The repository provides a runnable, domain-neutral application rather than -only infrastructure contracts. The starter experience is intentionally -replaceable at the page level while the shell, providers, boundaries, -primitives, and state surfaces remain reusable. +이 repo는 인프라 계약만 주지 않는다. 바로 실행되는 앱을 준다. 이 앱은 특정 도메인에 묶이지 않는다. +스타터 경험(starter experience)은 일부러 페이지 단위로 갈아 끼울 수 있게 만들었다. +셸, provider, 경계, UI primitive, 상태 화면(state surface)은 그대로 다시 쓴다. -## Runtime composition +## runtime 조립 ```text validated config + coherent release manifest @@ -19,281 +18,253 @@ validated config + coherent release manifest -> lazy route boundary ``` -Boot stops before product mount when configuration or release coherence fails. -Each lazy page renders inside Suspense and a telemetry-aware route boundary. -Route changes move focus to the new page heading; the skip link and landmarks -remain stable in the shell. +설정 검증이나 release 정합성 검사가 실패하면 부팅은 제품 화면을 마운트하기 전에 멈춘다. +지연 로드(lazy) 페이지는 각각 Suspense와 telemetry를 남기는 라우트 경계 안에서 렌더링된다. +라우트가 바뀌면 포커스가 새 페이지 제목으로 옮겨진다. +건너뛰기 링크(skip link)와 랜드마크는 셸에 고정되어 바뀌지 않는다. -## Registered routes +## 등록된 라우트 -The route list is `ROUTE_REGISTRY` (`src/features/installed-feature-contracts.ts`): -the platform routes of `src/contracts/routes.ts` plus the routes of every -installed feature. The platform overview page (`/examples/platform`) shows the -composed list at runtime, so this document does not keep a copy of it. +라우트 목록은 `ROUTE_REGISTRY`(`src/features/installed-feature-contracts.ts`)다. +`src/contracts/routes.ts`의 플랫폼 라우트에, 설치된 모든 feature의 라우트를 더한 것이다. +플랫폼 개요 페이지(`/examples/platform`)가 조립된 목록을 실행 중에 보여 준다. +그래서 이 문서는 목록을 따로 복사해 두지 않는다. -Navigation labels and order come from `ROUTE_REGISTRY`; the sidebar does not -maintain a second route list. The client access decision never claims to be -authorization. +내비게이션의 이름과 순서는 `ROUTE_REGISTRY`에서 온다. 사이드바는 라우트 목록을 따로 두지 않는다. +클라이언트가 내리는 접근 판단은 어디서도 인가(authorization)라고 내세우지 않는다. -## Authentication seam +## 인증 연결 지점 -The session port exposes state subscription, sign-in start, sign-out, -credential attachment, recovery, and unauthenticated notification. Credentials -remain opaque to the application and presentation layers. +세션 port가 제공하는 것은 상태 구독, 로그인 시작, 로그아웃, 자격 증명(credential) 붙이기, 세션 복구, 미인증 알림이다. +application 계층과 presentation 계층은 자격 증명의 내용을 들여다보지 않는다. -- `demo`: local/development-only state transition with no credentials -- `external`: delegates to `globalThis.__CA_FRONTEND_AUTH_OWNER__` -- missing/invalid external owner: fails closed as `integration-failed` +- `demo`: 로컬·개발 환경에서만 쓰는 상태 전환이다. 자격 증명이 없다. +- `external`: `globalThis.__CA_FRONTEND_AUTH_OWNER__`에 맡긴다. +- 외부 owner가 없거나 잘못됐을 때: `integration-failed`로 막고 실패한다(fail closed). -An external owner implements `readState`, `readSubject`, `subscribe`, -`beginSignIn`, `signOut`, `attachCredential`, `recoverSession`, and -`notifyUnauthenticated`. It owns token acquisition and storage. An owner that -lacks any of these methods is rejected, and the session fails closed as -`integration-failed`. +외부 owner는 `readState`, `readSubject`, `subscribe`, +`beginSignIn`, `signOut`, `attachCredential`, `recoverSession`, +`notifyUnauthenticated`를 구현한다. 토큰을 받아 오고 저장하는 일은 owner가 맡는다. +이 메서드 중 하나라도 빠진 owner는 거부된다. 그러면 세션은 `integration-failed`로 막힌다(fail closed). -The state transitions an owner makes, and what `recover()` leaves behind for -each answer, are written on `SessionState` and `SessionGateway.recover` in -`src/application/ports/auth-session-port.ts`. For the paired backend's two -authentication modes there are owners to copy, not to write: -`recipes/session-owners/oidc-pkce-session-owner.ts` (JWT mode: Keycloak, -authorization code with PKCE, `EXTERNAL_BEARER`) and -`recipes/session-owners/cookie-session-owner.ts` (Redis session mode: the -session cookie, plus `SESSION_COOKIE_*` profiles and the `X-XSRF-TOKEN` -provider). `docs/manual/04-paired-backend-session.md` wires them and lists -what the backend template does not ship (a browser client in its realm; the -sign-in, sign-out and session endpoints). +owner가 일으키는 상태 전환과, 응답마다 `recover()`가 남기는 상태는 +`src/application/ports/auth-session-port.ts`의 `SessionState`와 `SessionGateway.recover`에 적혀 있다. +짝 백엔드(paired backend)의 두 인증 모드에는 새로 쓰지 않고 복사하면 되는 owner가 있다. +JWT 모드는 `recipes/session-owners/oidc-pkce-session-owner.ts`다(Keycloak, PKCE를 쓰는 authorization code, `EXTERNAL_BEARER`). +Redis 세션 모드는 `recipes/session-owners/cookie-session-owner.ts`다(세션 쿠키, 그리고 `SESSION_COOKIE_*` 프로필과 `X-XSRF-TOKEN` provider). +`docs/manual/04-paired-backend-session.md`가 이 둘을 연결한다. +백엔드 템플릿이 주지 않는 것도 이 문서에 적혀 있다. realm 안의 브라우저 클라이언트, 그리고 로그인·로그아웃·세션 endpoint다. -`readSubject()` is required. The server-state cache is cleared only when the -session state or the subject changes, so a token refresh for the same user -keeps cached data. `readSubject()` must return: +`readSubject()`는 필수다. subject는 로그인한 사용자를 가리키는 식별자다. +서버 상태 캐시는 세션 상태나 subject가 바뀔 때만 비운다. +그래서 같은 사용자의 토큰을 갱신해도 캐시된 데이터는 남는다. `readSubject()`는 다음을 돌려줘야 한다. -- an opaque, non-empty string that stays the same for one user across token - refreshes and differs between users: the OIDC `sub` claim, Supabase - `session.user.id`, or Firebase `user.uid` -- `null` when nobody is signed in -- never an access token, refresh token, or any other credential +- 내용을 해석하지 않는 빈 값이 아닌 문자열. 한 사용자는 토큰을 갱신해도 값이 같고, + 사용자끼리는 값이 달라야 한다. 예: OIDC `sub` claim, Supabase + `session.user.id`, Firebase `user.uid` +- 아무도 로그인하지 않았으면 `null` +- access token, refresh token, 그 밖의 어떤 자격 증명도 돌려주지 않는다 -If `readSubject()` returns `null` or `""` while the owner reports -`authenticated`, the runtime cannot tell a refresh from an account switch. It -fails closed: every such notification clears server state, and each one records -the `cache.operation.failed` diagnostic with `operation: SCOPE_FENCE` and -`reason: SUBJECT_MISSING`. Seeing that diagnostic means the owner is not -reporting its subject. The `demo` adapter reports one fixed demo user as its -subject. +owner가 `authenticated`를 알리는데 `readSubject()`가 `null`이나 `""`를 돌려주면, +runtime은 토큰 갱신과 계정 전환을 구별하지 못한다. 이때는 막힌 쪽으로 실패한다(fail closed). +그런 알림이 올 때마다 서버 상태를 비운다. 그리고 매번 +`cache.operation.failed` 진단을 `operation: SCOPE_FENCE`, `reason: SUBJECT_MISSING`과 함께 남긴다. +이 진단이 보이면 owner가 subject를 알려 주지 않는다는 뜻이다. +`demo` adapter는 고정된 데모 사용자 하나를 subject로 알린다. -Migration: `readSubject()` used to be optional. An owner written for an earlier -release must add it; without it the owner is rejected at startup (the session -becomes `integration-failed`) and a TypeScript owner no longer compiles -against `ExternalSessionOwner`. A code path that implements `AuthSessionPort` -or `SessionGateway` directly must add `getSubject()` the same way. +마이그레이션: 예전에는 `readSubject()`가 선택이었다. 이전 release에 맞춰 쓴 owner는 이 메서드를 더해야 한다. +없으면 시작할 때 owner가 거부된다(세션이 `integration-failed`가 된다). +TypeScript로 쓴 owner는 `ExternalSessionOwner`에 맞춰 더는 컴파일되지 않는다. +`AuthSessionPort`나 `SessionGateway`를 직접 구현한 코드도 같은 식으로 `getSubject()`를 더해야 한다. -## Extending the starter +## 스타터 확장 -New platform work should follow -[routing, page templates, and reusable patterns](../design/2026-07-26-routing-pages-and-patterns-design.md) -and the -[TypeScript, state, and data-flow target](../design/2026-07-26-typescript-state-and-data-flow-design.md) -rather than adding another independent route or data-loading convention. +새 플랫폼 작업은 따로 노는 라우트 규칙이나 데이터 로딩 규칙을 하나 더 만들지 않는다. +대신 [라우팅, 페이지 템플릿, 재사용 패턴](../design/2026-07-26-routing-pages-and-patterns-design.md)과 +[TypeScript, 상태, 데이터 흐름 목표](../design/2026-07-26-typescript-state-and-data-flow-design.md)를 따른다. -### Replacing the starter screens +### 스타터 화면 바꾸기 -`/` (`src/presentation/pages/home-page.tsx`) is the platform's `APP_HOME`; a -feature takes it over by declaring that route id (see "Product home and -layouts"). Its starter links are the first three screens of the navigation. +`/`(`src/presentation/pages/home-page.tsx`)는 플랫폼의 `APP_HOME`이다. +feature가 그 route id를 선언하면 이 자리를 넘겨받는다("제품 홈과 레이아웃" 참고). +홈에 있는 스타터 링크는 내비게이션의 처음 세 화면이다. -The template ships no example feature. Its example screens (`/examples/ui`, -`/examples/states`, `/examples/auth`) and its reference sample were deleted on -2026-11-07: the design-system and screen-state galleries are workshop stories -(`src/presentation/design-system/galleries.stories.tsx`), and the manual -(`docs/manual/`) with `create:feature` shows how a feature is built. A sample a -product keeps for a while is listed in -`scripts/lib/removable-template-features.ts`: `verify:documentation` checks its -paths while it is installed and accepts them once its `feature-module.ts` is -gone (1105/14-01), and `corepack pnpm test:sample-removal` removes it in a copy -of the repository and runs the gates there. +템플릿은 예제 feature를 주지 않는다. 예제 화면(`/examples/ui`, +`/examples/states`, `/examples/auth`)과 참조 샘플은 2026-11-07에 지웠다. +디자인 시스템 갤러리와 화면 상태 갤러리는 workshop story +(`src/presentation/design-system/galleries.stories.tsx`)다. +feature를 만드는 방법은 매뉴얼(`docs/manual/`)과 `create:feature`가 보여 준다. +제품이 한동안 남겨 두는 샘플은 `scripts/lib/removable-template-features.ts`에 적는다. +`verify:documentation`은 샘플이 설치돼 있는 동안 그 경로를 검사한다. +샘플의 `feature-module.ts`가 없어지면 그 경로를 받아들인다(1105/14-01). +`corepack pnpm test:sample-removal`은 repo 복사본에서 샘플을 지우고 그 복사본에서 gate를 돌린다. -The platform overview (`/examples/platform`, -`src/presentation/examples/platform-overview-page.tsx`) stays a platform -route. It describes the installed registries, and the lab gate (FE-GATE-026) -times entering it: a feature route's first entry also loads its context's -routes module before the page, a second request round the 200 ms budget does -not fit. Its tests are the `tests/component/starter-*.test.tsx` files. +플랫폼 개요(`/examples/platform`, +`src/presentation/examples/platform-overview-page.tsx`)는 플랫폼 라우트로 남는다. +이 페이지는 설치된 registry를 보여 준다. lab gate(FE-GATE-026)는 이 페이지에 들어가는 시간을 잰다. +feature 라우트라면 처음 들어갈 때 페이지보다 먼저 그 context의 routes 모듈도 불러온다. +이 두 번째 요청 왕복은 200 ms budget 안에 들어가지 않는다. +이 페이지의 테스트는 `tests/component/starter-*.test.tsx` 파일들이다. -The platform's component tests (router, boundaries, shell, runtime tree) run -on the pages of the test-only feature in `tests/helpers/fixture-feature.tsx`. -The browser-level checks in `tests/e2e` and `tests/visual` use the home page, -the platform overview and the gallery stories; what needs a feature -(`tests/e2e/generated-feature.spec.ts`, the chunk recovery spec) builds a copy -of the repository with the one `create:feature` writes -(`scripts/lib/generated-feature.ts`). +플랫폼의 component 테스트(router, 경계, 셸, runtime 트리)는 +`tests/helpers/fixture-feature.tsx`에 있는 테스트 전용 feature의 페이지에서 돈다. +`tests/e2e`와 `tests/visual`의 브라우저 수준 검사는 홈 페이지, 플랫폼 개요, 갤러리 story를 쓴다. +feature가 있어야 하는 검사(`tests/e2e/generated-feature.spec.ts`, chunk 복구 spec)는 +`create:feature`가 쓰는 feature를 넣은 repo 복사본을 만든다(`scripts/lib/generated-feature.ts`). -### Ownership declarations +### 소유 선언 -Features, contexts and apps are discovered by -`scripts/generate-product-feature-index.ts`. Each boundary declares only its -parent, as exported string or integer literals the generator reads: +`scripts/generate-product-feature-index.ts`가 feature, context, app을 찾아낸다. +각 경계는 자기 부모만 선언한다. 선언은 생성기가 읽는, export된 문자열 리터럴이나 정수 리터럴이다. -| File | Exports | +| 파일 | export | | --- | --- | | `src/apps//app-module.ts` | `APP_MODULE_ID`, `APP_MAX_CONTEXTS` | | `src/contexts//context-module.ts` | `CONTEXT_MODULE_ID`, `CONTEXT_APP_ID`, `CONTEXT_ROUTE_PATH`, `CONTEXT_MAX_FEATURES` | | `src/features//feature-module.ts` | `FEATURE_MODULE_ID`, `FEATURE_CONTEXT_ID`, `FEATURE_MODULE` | -| `src/features//feature-runtime.ts` | `FEATURE_RUNTIME` (imported only by `feature-module.ts`, dynamically) | +| `src/features//feature-runtime.ts` | `FEATURE_RUNTIME` (`feature-module.ts`만 동적으로 import한다) | | `src/features//context-routes.ts` | `FEATURE_CONTEXT_ROUTES` | -| `src/contexts//context-layout.tsx` (optional) | `CONTEXT_LAYOUT`, the context's own layout ("Product home and layouts") | +| `src/contexts//context-layout.tsx` (선택) | `CONTEXT_LAYOUT`, 그 context 고유의 레이아웃("제품 홈과 레이아웃") | -The generator writes `src/.generated/` (git-ignored): the feature index the -installed catalogs import, the context index the router loads lazily, and the -selected app. Every build and check script runs it first; run it yourself with -`corepack pnpm generate:feature-index`. It fails, naming the file, when: +생성기는 `src/.generated/`(git이 무시한다)에 세 가지를 쓴다. +설치 카탈로그가 import하는 feature 색인, router가 지연 로드하는 context 색인, 선택된 app이다. +모든 빌드·검사 script가 생성기를 먼저 돌린다. 직접 돌리려면 +`corepack pnpm generate:feature-index`를 쓴다. 다음 경우에 생성기는 해당 파일 이름을 대며 실패한다. -- a directory under `src/features/` has no `feature-module.ts`. Code that - is no feature (the IndexedDB consumer the tests compose, - `tests/fixtures/indexeddb-consumer`) lives outside `src/features/`; -- a feature names an undeclared context, or a context an undeclared app; -- a context or app exceeds its declared budget; -- `VITE_PRODUCT_FEATURES` names a feature the app does not declare. The - variable narrows the installed set here, before anything is compiled. +- `src/features/` 아래 디렉터리에 `feature-module.ts`가 없을 때. feature가 아닌 코드 + (테스트가 조립하는 IndexedDB 소비자, + `tests/fixtures/indexeddb-consumer`)는 `src/features/` 밖에 둔다. +- feature가 선언되지 않은 context를 가리키거나, context가 선언되지 않은 app을 가리킬 때. +- context나 app이 선언한 budget을 넘을 때. +- `VITE_PRODUCT_FEATURES`가 app이 선언하지 않은 feature를 가리킬 때. + 이 변수는 무엇이든 컴파일하기 전에, 여기서 설치할 feature 집합을 줄인다. -### Adding a feature +### feature 추가 -1. Create `src/features//feature-module.ts`. Build `FEATURE_MODULE` - with `defineFeatureModule` (`src/features/feature-module.ts`). This is the - feature's declaration, and it is in the initial chunk, so it holds data - only: the declaration contract (routes, route runtime contracts, - invalidation, topic versions and the external `contractPackages` the - release manifest is checked against at boot), its message catalogs, and - `loadRuntime`, which imports `feature-runtime.ts` dynamically. - `create:feature` writes a complete one. -2. Create `src/features//feature-runtime.ts` with - `defineFeatureRuntime`: the `schemas` (FE-REG-SCHEMA rows for the - feature's route and API schemas), the adapter contributions - (`defineFeatureAdapterContribution`, with `needs` naming the platform - capabilities it receives) and the contract contributions (the HTTP - operations). The router loads - it (`application.features.load`) when one of the feature's routes is - entered. Do not import it statically from anywhere: each feature would add - its whole executable code to the initial chunk again, about 3.9 KB gzip - (`tests/unit/feature-shape-growth.test.ts` bounds one feature at 1 KiB). - An HTTP API is written once, as its contract contribution descriptor: it - executes, and `check:registries` governs the FE-REG-API row projected from - it (`projectApiOperationRows` in `src/contracts/api-operations.ts`). - A product feature's contract contribution uses an `EXTERNAL_PACKAGE` - source. `TEMPLATE_FIXTURE` was the template's reference sample source; it - never joins the release contract set, and the composer rejects it in any - product feature. -3. Create `src/features//context-routes.ts` exporting - `FEATURE_CONTEXT_ROUTES`. Page components are imported lazily here, and each - route handle carries the route's params/search `codecs`; the owning context - loads this file only when its route root is visited - (a `create:feature --with-create` feature's `context-routes.ts`). Each handle's - `routeId` must be a route of a feature contract in the same context; the - context refuses the routes when they load, naming the route, context and - features (`src/contexts/bounded-context-module.ts`). -4. Name the owning context in `FEATURE_CONTEXT_ID`. Use an existing context or - add `src/contexts//context-module.ts` owned by the app. - Every route path in the feature contract must sit at or under that - context's `CONTEXT_ROUTE_PATH` and must not fall under another context's - identical or more specific root: the router renders feature routes only - inside the owning context. No platform route may answer it either: the - router tries `AppShell`'s platform routes first, so the same path as a - platform route, `/` under an id other than `APP_HOME`, or a `*` root - without a layout (the not-found route takes every URL) never renders the - feature. The app module refuses anything else when it loads, naming the - route, feature and context (`src/apps/deployable-app-module.ts`). A route - that takes over the platform home is the exception ("Product home and - layouts"). -5. If the feature has application input, augment `ApplicationFeatureInputs` - from the feature (the IndexedDB consumer fixture does it in - `tests/fixtures/indexeddb-consumer/application/local-draft-api.ts`). -6. Run `corepack pnpm check:architecture`, `corepack pnpm check:types`, - `corepack pnpm check:registries` and the tests. `tests/unit/two-feature-install-typecheck.test.ts` - keeps the installed catalogs compiling with more than one feature. -7. Run `corepack pnpm test:sample-removal -- --feature=` to prove - the product still builds and passes its gates without the feature. +1. `src/features//feature-module.ts`를 만든다. `defineFeatureModule` + (`src/features/feature-module.ts`)로 `FEATURE_MODULE`을 만든다. 이 파일은 + feature의 선언이고 초기 chunk에 들어간다. 그래서 데이터만 담는다. + 담는 것은 셋이다. 첫째, 선언 계약이다(라우트, 라우트 runtime 계약, + 무효화(invalidation), topic 버전, 부팅 때 release manifest와 맞춰 보는 외부 `contractPackages`). + 둘째, message 카탈로그다. 셋째, `feature-runtime.ts`를 동적으로 import하는 + `loadRuntime`이다. `create:feature`가 완성된 파일을 써 준다. +2. `defineFeatureRuntime`으로 `src/features//feature-runtime.ts`를 만든다. + 담는 것은 셋이다. `schemas`(feature의 라우트 schema와 API schema에 대한 FE-REG-SCHEMA 행), + adapter contribution(`defineFeatureAdapterContribution`. `needs`에 받을 플랫폼 capability를 적는다), + contract contribution(HTTP operation)이다. + feature의 라우트 하나에 들어갈 때 router가 이 파일을 불러온다(`application.features.load`). + 어디에서도 이 파일을 정적으로 import하지 않는다. 그러면 feature마다 실행 코드 전체가 + 다시 초기 chunk에 들어간다. 대략 gzip 3.9 KB다 + (`tests/unit/feature-shape-growth.test.ts`는 feature 하나의 상한을 1 KiB로 둔다). + HTTP API는 contract contribution descriptor로 한 번만 쓴다. 이 descriptor가 실제로 실행된다. + 그리고 여기서 뽑아낸 FE-REG-API 행을 `check:registries`가 관리한다 + (`src/contracts/api-operations.ts`의 `projectApiOperationRows`). + 제품 feature의 contract contribution은 `EXTERNAL_PACKAGE` source를 쓴다. + `TEMPLATE_FIXTURE`는 템플릿의 참조 샘플이 쓰던 source다. 이 source는 release 계약 집합에 + 절대 들어가지 않는다. composer는 어느 제품 feature에서든 이 source를 거부한다. +3. `FEATURE_CONTEXT_ROUTES`를 export하는 `src/features//context-routes.ts`를 만든다. + 페이지 컴포넌트는 여기서 지연 import한다. 각 route handle은 그 라우트의 params/search `codecs`를 갖는다. + 소유 context는 자기 route root에 들어갈 때만 이 파일을 불러온다 + (예: `create:feature --with-create`로 만든 feature의 `context-routes.ts`). + 각 handle의 `routeId`는 같은 context에 있는 feature 계약의 라우트여야 한다. + 아니면 context가 라우트를 불러올 때 거부하고, 라우트·context·feature 이름을 댄다 + (`src/contexts/bounded-context-module.ts`). +4. `FEATURE_CONTEXT_ID`에 소유 context를 적는다. 있는 context를 쓰거나, + app이 소유하는 `src/contexts//context-module.ts`를 더한다. + feature 계약의 라우트 경로는 모두 그 context의 `CONTEXT_ROUTE_PATH`이거나 그 아래여야 한다. + 또 다른 context의 같은 root나 더 구체적인 root 아래에 들어가면 안 된다. + router는 feature 라우트를 소유 context 안에서만 렌더링하기 때문이다. + 플랫폼 라우트가 그 경로에 응답해서도 안 된다. router는 `AppShell`의 플랫폼 라우트를 먼저 시도한다. + 그래서 다음 경로에서는 feature가 렌더링되지 않는다. 플랫폼 라우트와 같은 경로, + `APP_HOME`이 아닌 id로 쓴 `/`, 레이아웃 없는 `*` root(찾을 수 없음 라우트가 모든 URL을 가져간다)다. + 이 규칙을 어긴 라우트는 app 모듈이 불러올 때 거부하고, 라우트·feature·context 이름을 댄다 + (`src/apps/deployable-app-module.ts`). 플랫폼 홈을 넘겨받는 라우트는 예외다 + ("제품 홈과 레이아웃"). +5. feature에 application 입력이 있으면 feature 쪽에서 `ApplicationFeatureInputs`를 + 확장(augment)한다(IndexedDB 소비자 fixture가 + `tests/fixtures/indexeddb-consumer/application/local-draft-api.ts`에서 이렇게 한다). +6. `corepack pnpm check:architecture`, `corepack pnpm check:types`, + `corepack pnpm check:registries`와 테스트를 돌린다. `tests/unit/two-feature-install-typecheck.test.ts`는 + feature가 둘 이상일 때도 설치 카탈로그가 컴파일되는지 지킨다. +7. `corepack pnpm test:sample-removal -- --feature=`를 돌린다. + 이 feature를 빼도 제품이 빌드되고 gate를 통과하는지 확인한다. -Files outside the feature directory. Everything else a feature needs is in -`src/features//` and `tests/features//`. +feature 디렉터리 밖 파일은 아래 표에 있다. feature에 필요한 나머지는 모두 +`src/features//`와 `tests/features//` 안에 있다. -| File | When | What fails without it | +| 파일 | 언제 | 없으면 실패하는 것 | | --- | --- | --- | -| `src/.generated/*` | never by hand: every build and check script regenerates it | — | -| `public/release-manifest.json` (tracked, the dev server's manifest) | every added or removed feature: `create:feature` rewrites it (`node scripts/write-dev-release-manifest.ts`). Commit it with the feature. Two feature branches change its `setDigest` line; on a merge conflict take either side and run the command again (1105/16-01) | `test:unit` (`tests/unit/dev-release-manifest.test.ts`) names the command; the dev server does not boot (`CONTRACT_SET_PACKAGE_MISSING`) | -| `config/scale/feature-shape-ceilings.json` `initialJavascript` (tracked) | every added or removed feature, and every template change that moves the initial JavaScript: `node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write`. Commit it with the change; on a merge conflict run the command again | `test:unit` (the feature-shape growth test compares it with a build) | -| `src/contexts//context-module.ts` | the feature needs a new context | `generate:feature-index`: `Feature belongs to undeclared context ` | -| `src/contexts//context-layout.tsx` | the context needs its own frame instead of `AppShell` (see "Product home and layouts" below) | nothing: without it the context renders in `AppShell` | -| `artifacts/tests/a11y-manual/.md` | every route the feature adds. Copy a record and reset it to `Status: pending-manual-review` | `test:unit` (`tests/unit/manual-a11y-evidence.test.ts`), `verify:documentation` (names the route IDs) and FE-GATE-009 (`review:a11y-manual -- --format-only`). FE-GATE-028 requires the signed review at release | -| `tests/e2e/accessibility.spec.ts` | never per feature (1103/16-03): it fills every path parameter with one value and answers each API request from the installed descriptor, a list read with an empty list in its `responseEnvelope` frame. Edit it only for a protected page that sends something other than an installed GET before it renders | `test:a11y` (FE-GATE-009): a request no installed GET declares fails the route; so does an alert box (`role="alert"`) on a page that read only lists | -| `src/features/product-capabilities.ts` (product-owned) | `needs` names a capability the template does not build: type it in `ProductFeaturePlatformCapabilities`. `FeaturePlatformCapabilities` extends it, so the app, scripts and tests typecheck programs all see the key (an augmentation inside `product-composition.ts` is not seen by the scripts' program) | `check:types`: `Type '""' is not assignable to type 'keyof FeaturePlatformCapabilities'` in the feature | -| `src/bootstrap/product-composition.ts` (product-owned) | `needs` names a capability the template does not build: return the capability here, typed in `product-capabilities.ts`. `indexedDb` is built as in `recipes/frontend-capabilities/indexeddb-feature-capability.ts`. Credentials for a product auth profile are returned here too. A product that owns the session (a BFF's httpOnly cookie) returns its session owner from `composeProductSessionOwner` instead of installing it on the host global before boot | `check:types`; at runtime `feature needs , which the host did not provide`. Without the session owner, `AUTH_MODE: "external"` boots with the session `integration-failed` | -| `src/contracts/product-contracts.ts` (product-owned) | a product auth profile, or a product runtime-config key and its FE-REG-ENV row (`PRODUCT_ENV_REGISTRY`) | auth profile: every gate that loads the operation, with `Installed contract contribution is not composable: /: unknown authProfileId `. Config key: `check:types` where it is read. Give the key a `.default()` or make it `.optional()`: template tests build their config with `tests/helpers/runtime-config.ts`, which fills the product's defaults, and a required key without a default fails them. FE-REG-ENV row: `check:registries` checks its fields, and `tests/unit/env-registry-coverage.test.ts` (`test:unit`) requires a row for every key, with the schema's `required` and `defaultValue` | -| `config/runtime/.json` | optional: a `FEATURE_OVERRIDES` entry switches the feature off | nothing | -| `package.json`, the lockfile, `config/security/dependency-change-evidence.json` | the contract contribution imports a generated `@org-contracts/*` package as a production dependency | `generate:supply-chain` (in `check:bundle`): `high-risk dependency missing review: add:` | +| `src/.generated/*` | 손으로 고치지 않는다. 모든 빌드·검사 script가 다시 만든다 | — | +| `public/release-manifest.json` (추적 파일, dev server의 manifest) | feature를 더하거나 뺄 때마다. `create:feature`가 다시 쓴다(`node scripts/write-dev-release-manifest.ts`). feature와 같은 커밋에 넣는다. 두 feature 브랜치가 모두 이 파일의 `setDigest` 줄을 바꾼다. 병합 충돌이 나면 아무 쪽이나 고르고 명령을 다시 돌린다(1105/16-01) | `test:unit`(`tests/unit/dev-release-manifest.test.ts`)이 실패하며 이 명령을 알려 준다. dev server가 부팅하지 못한다(`CONTRACT_SET_PACKAGE_MISSING`) | +| `config/scale/feature-shape-ceilings.json` `initialJavascript` (추적 파일) | feature를 더하거나 뺄 때마다, 그리고 초기 JavaScript를 바꾸는 템플릿 변경마다: `node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write`. 그 변경과 같은 커밋에 넣는다. 병합 충돌이 나면 명령을 다시 돌린다 | `test:unit`(feature-shape growth 테스트가 이 값을 빌드 결과와 비교한다) | +| `src/contexts//context-module.ts` | feature에 새 context가 필요할 때 | `generate:feature-index`: `Feature belongs to undeclared context ` | +| `src/contexts//context-layout.tsx` | context에 `AppShell` 대신 자기 틀이 필요할 때(아래 "제품 홈과 레이아웃" 참고) | 없음. 파일이 없으면 context는 `AppShell` 안에서 렌더링된다 | +| `artifacts/tests/a11y-manual/.md` | feature가 더하는 라우트마다. 기록 하나를 복사해 `Status: pending-manual-review`로 되돌린다 | `test:unit`(`tests/unit/manual-a11y-evidence.test.ts`), `verify:documentation`(route ID를 댄다), FE-GATE-009(`review:a11y-manual -- --format-only`). release 때는 FE-GATE-028이 서명된 검토를 요구한다 | +| `tests/e2e/accessibility.spec.ts` | feature마다 고치지 않는다(1103/16-03). 이 파일은 모든 경로 파라미터를 한 값으로 채우고, 각 API 요청에 설치된 descriptor로 응답한다. 목록 읽기에는 `responseEnvelope` 틀에 담은 빈 목록으로 응답한다. 보호된 페이지가 렌더링 전에 설치된 GET이 아닌 요청을 보낼 때만 고친다 | `test:a11y`(FE-GATE-009): 설치된 GET 어디에도 선언되지 않은 요청이 오면 그 라우트가 실패한다. 목록만 읽은 페이지에 경고 상자(`role="alert"`)가 떠도 실패한다 | +| `src/features/product-capabilities.ts` (제품 소유) | `needs`가 템플릿이 만들지 않는 capability를 가리킬 때: `ProductFeaturePlatformCapabilities`에 그 타입을 적는다. `FeaturePlatformCapabilities`가 이를 확장하므로 app, scripts, tests의 타입 검사 프로그램이 모두 그 키를 본다(`product-composition.ts` 안에 둔 augmentation은 scripts의 프로그램이 보지 못한다) | `check:types`: feature에서 `Type '""' is not assignable to type 'keyof FeaturePlatformCapabilities'` | +| `src/bootstrap/product-composition.ts` (제품 소유) | `needs`가 템플릿이 만들지 않는 capability를 가리킬 때: 여기서 그 capability를 돌려준다. 타입은 `product-capabilities.ts`에 적는다. `indexedDb`는 `recipes/frontend-capabilities/indexeddb-feature-capability.ts`처럼 만든다. 제품 인증 프로필의 자격 증명도 여기서 돌려준다. 세션을 직접 소유하는 제품(BFF의 httpOnly 쿠키)은 부팅 전에 host 전역에 세션 owner를 설치하지 않는다. 대신 `composeProductSessionOwner`에서 돌려준다 | `check:types`. 실행 중에는 `feature needs , which the host did not provide`. 세션 owner가 없으면 `AUTH_MODE: "external"`은 세션이 `integration-failed`인 채로 부팅한다 | +| `src/contracts/product-contracts.ts` (제품 소유) | 제품 인증 프로필, 또는 제품 runtime 설정 키와 그 FE-REG-ENV 행(`PRODUCT_ENV_REGISTRY`) | 인증 프로필: 그 operation을 불러오는 모든 gate가 `Installed contract contribution is not composable: /: unknown authProfileId `로 실패한다. 설정 키: 키를 읽는 곳에서 `check:types`가 실패한다. 키에는 `.default()`를 주거나 `.optional()`로 만든다. 템플릿 테스트는 `tests/helpers/runtime-config.ts`로 설정을 만들고, 이 helper는 제품의 기본값을 채운다. 그래서 기본값 없는 필수 키는 이 테스트를 실패시킨다. FE-REG-ENV 행: `check:registries`가 행의 필드를 검사한다. `tests/unit/env-registry-coverage.test.ts`(`test:unit`)는 키마다 행이 있고, 그 행에 schema의 `required`와 `defaultValue`가 적혀 있기를 요구한다 | +| `config/runtime/.json` | 선택: `FEATURE_OVERRIDES` 항목으로 feature를 끈다 | 없음 | +| `package.json`, lockfile, `config/security/dependency-change-evidence.json` | contract contribution이 생성된 `@org-contracts/*` 패키지를 운영 의존성(production dependency)으로 import할 때 | `generate:supply-chain`(`check:bundle` 안에서 돈다): `high-risk dependency missing review: add:` | -The central catalogs (`src/features/installed-*.ts`) and the registry -governance file do not change: consumer directories there are globs over every -feature (`src/features/*/adapters`, `config/contracts/registry-governance.json`). -A route's params/search schema ids are checked against the schemas the feature -registers, and its `loadingSurface` only has to be a kebab-case name, so a -route with its own schema and loading surface needs no governance edit either. -The registry baseline does not change either. New routes, API operations, -schemas and invalidation topics, namespaces and edges are additive registry -changes; `update:registry-baseline` or breaking evidence is needed only to -remove or change a row or graph item. -`tests/unit/second-api-feature-registries.test.ts` adds such a feature (an API -operation, a route with its own search schema and loading surface, and an -invalidation topic) to a copy of the repository and runs `check:registries` on -it. +중앙 카탈로그(`src/features/installed-*.ts`)와 registry governance 파일은 바뀌지 않는다. +거기 적힌 소비자 디렉터리는 모든 feature를 덮는 glob이다 +(`src/features/*/adapters`, `config/contracts/registry-governance.json`). +라우트의 params/search schema id는 feature가 등록한 schema와 맞춰 본다. +`loadingSurface`는 kebab-case 이름이기만 하면 된다. +그래서 자기 schema와 loading surface를 가진 라우트도 governance를 고칠 필요가 없다. +registry baseline도 바뀌지 않는다. 새 라우트, API operation, +schema, 무효화 topic, namespace, edge는 registry에 더하기만 하는 변경이다. +`update:registry-baseline`이나 breaking 증거는 행이나 그래프 항목을 지우거나 바꿀 때만 필요하다. +`tests/unit/second-api-feature-registries.test.ts`는 이런 feature(API +operation 하나, 자기 search schema와 loading surface를 가진 라우트 하나, 무효화 topic 하나)를 +repo 복사본에 더하고 `check:registries`를 돌린다. -Schema, operation, mapper, route and chunk ids and invalidation topics are -global. Prefix them with the feature; `create:feature` writes -`NoRequest`, so a bare `NoRequest` would collide between features. MSW scenarios for the feature's own operations come from -`createHttpScenarioHandler` (`tests/mocks/handlers/http-scenarios.ts`) with -the feature's installed contract; the shared scenario catalog does not change. +schema, operation, mapper, 라우트, chunk의 id와 무효화 topic은 전역이다. +앞에 feature 이름을 붙인다. `create:feature`는 +`NoRequest`를 쓴다. 맨 `NoRequest`를 쓰면 feature끼리 이름이 겹친다. +feature 자기 operation의 MSW 시나리오는 feature의 설치된 계약을 넣은 +`createHttpScenarioHandler`(`tests/mocks/handlers/http-scenarios.ts`)로 만든다. +공유 시나리오 카탈로그는 바뀌지 않는다. -### Product home and layouts +### 제품 홈과 레이아웃 -A product whose home is a feature screen, or whose screens use a frame other -than `AppShell`, declares it. The router and the catalogs do not change. +홈이 feature 화면인 제품이나, 화면이 `AppShell`이 아닌 다른 틀을 쓰는 제품은 그것을 선언한다. +router와 카탈로그는 바뀌지 않는다. -- **Home.** A feature takes over the platform home by declaring a route with - the id `APP_HOME` in its contract. The platform names the routes a feature - may take over (`FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS` in - `src/contracts/routes.ts`); any other platform route id is still a - duplicate. Two features declaring `APP_HOME` fail when the catalogs load, - naming both. The router mounts the route at its own path with the owning - context, whatever that context's route root. Leaving the feature out of the - build (`VITE_PRODUCT_FEATURES`) brings the platform home back; switching it - off at runtime shows the disabled-feature page at its path. -- **Layout.** A context with `src/contexts//context-layout.tsx` - exporting `CONTEXT_LAYOUT` (a component) renders under that layout instead - of `AppShell`. The generated index loads the file lazily, when one of the - context's routes is entered. The router mounts the context at each - registered path of its features under the layout, so an unknown URL still - gets the not-found page in `AppShell`. Contexts whose layout files export the - same component keep one layout instance when the user moves between them, - so several route roots can share a layout. -- **Accessibility.** The layout renders a skip link to `#main-content` and - exactly one `
` around ``. - The router moves focus there on every route change. Layout routes are - siblings of `AppShell`, never inside it. - `tests/component/layout-landmarks.test.tsx` renders `AppShell` and the - layout of every installed context and fails one without them. -- **Failures.** A layout chunk a deploy removed gets the reload-once recovery - of a route chunk. Route and feature boundaries work as they do in - `AppShell`. -- The route root rule of step 4 spans every layout: a root takes the URLs - under it whichever layout either context has. +- **홈.** feature는 계약에 id가 `APP_HOME`인 라우트를 선언해 플랫폼 홈을 넘겨받는다. + feature가 넘겨받을 수 있는 라우트는 플랫폼이 정한다 + (`src/contracts/routes.ts`의 `FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS`). + 그 밖의 플랫폼 route id를 쓰면 여전히 중복이다. + 두 feature가 `APP_HOME`을 선언하면 카탈로그를 불러올 때 둘의 이름을 대며 실패한다. + router는 소유 context의 route root가 무엇이든, 그 라우트를 소유 context와 함께 자기 경로에 마운트한다. + 빌드에서 feature를 빼면(`VITE_PRODUCT_FEATURES`) 플랫폼 홈이 돌아온다. + 실행 중에 feature를 끄면 그 경로에 비활성 feature 페이지가 뜬다. +- **레이아웃.** `CONTEXT_LAYOUT`(컴포넌트)을 export하는 `src/contexts//context-layout.tsx`가 + 있는 context는 `AppShell` 대신 그 레이아웃 아래에서 렌더링된다. + 생성된 색인은 그 context의 라우트 하나에 들어갈 때 이 파일을 지연 로드한다. + router는 context를 그 feature들이 등록한 경로마다 레이아웃 아래에 마운트한다. + 그래서 모르는 URL은 여전히 `AppShell` 안의 찾을 수 없음 페이지로 간다. + 레이아웃 파일이 같은 컴포넌트를 export하는 context끼리는, 사용자가 그 사이를 옮겨 다녀도 + 레이아웃 인스턴스 하나를 유지한다. 그래서 여러 route root가 레이아웃 하나를 함께 쓸 수 있다. +- **접근성.** 레이아웃은 `#main-content`로 가는 건너뛰기 링크를 렌더링한다. + 그리고 ``을 감싸는 `
`을 정확히 하나 렌더링한다. + router는 라우트가 바뀔 때마다 포커스를 그곳으로 옮긴다. + 레이아웃 라우트는 `AppShell`의 형제이고, 절대 그 안에 들어가지 않는다. + `tests/component/layout-landmarks.test.tsx`는 `AppShell`과 설치된 모든 context의 + 레이아웃을 렌더링하고, 이 둘이 없는 레이아웃을 실패시킨다. +- **실패.** 배포로 사라진 레이아웃 chunk도 라우트 chunk처럼 한 번 새로고침해 복구한다. + 라우트 경계와 feature 경계는 `AppShell`에서와 똑같이 동작한다. +- 4단계의 route root 규칙은 모든 레이아웃에 걸쳐 적용된다. + 두 context가 어떤 레이아웃을 갖든, root는 그 아래 URL을 가져간다. -`tests/component/context-layouts.test.tsx` installs a product declared this -way (`tests/helpers/fixture-layout-product.tsx`). +`tests/component/context-layouts.test.tsx`는 이렇게 선언한 제품 +(`tests/helpers/fixture-layout-product.tsx`)을 설치해 본다. -### Before shipping +### 출시 전에 -- Use the semantic tokens, UI primitives, and state surfaces before adding a - project-specific variant. -- Add component behavior, all-engine E2E, automated axe, and signed manual - route evidence. +- 프로젝트 전용 변형을 더하기 전에 의미 토큰(semantic token), UI primitive, 상태 화면을 먼저 쓴다. +- component 동작 테스트, 모든 브라우저 엔진 E2E, 자동 axe 검사, 서명된 수동 라우트 증거를 더한다. -Theme preference is the public `COLOR_SCHEME` storage contract. Authentication -tokens and other secrets remain forbidden storage keys. +테마 선택은 공개된 `COLOR_SCHEME` 저장소 계약이다. +인증 토큰과 그 밖의 비밀 값은 계속 저장 금지 키다. diff --git a/docs/architecture/static-delivery.md b/docs/architecture/static-delivery.md index 7d959205..289c0b82 100644 --- a/docs/architecture/static-delivery.md +++ b/docs/architecture/static-delivery.md @@ -1,6 +1,6 @@ -# Static asset and runtime-config delivery +# 정적 자산과 runtime 설정 전달 -> **정본 안내 (non-authoritative for runtime capability decisions)** +> **정본 안내 (runtime capability 결정의 정본이 아니다)** > > Runtime Config/boot, Fetch HTTP client, Router, Query/Mutation, realtime 공통 경계, Web Worker, > Service Worker, offline command와 Background Sync의 구현 결정은 @@ -8,9 +8,9 @@ > 본 문서의 해당 서술이 정본과 충돌하면 정본을 따른다. -This Mermaid view is a repository-local implementation projection. The -`PASS_SCOPED` reviewer evidence applies only to the canonical static-delivery -draw.io scope recorded in `review-ledger.json`. +이 Mermaid 그림은 repo 안에서 구현을 옮겨 그린 투영(projection)이다. +`PASS_SCOPED` 리뷰 증거는 `review-ledger.json`에 적힌 정본 static-delivery +draw.io 범위에만 적용된다. ```mermaid sequenceDiagram @@ -29,34 +29,34 @@ sequenceDiagram CI->>Browser: boot, route, API, and reload-loop smoke ``` -In this repository the workflow deploys nothing. The upload, pointer switch -and smoke steps above belong to the project's provider adapter, which fills the -`deployment` job between `promotion` and `production_gate`. After it has -deployed the promoted release, FE-GATE-019 probes the live headers and checks -that the host serves that release; while the slot is empty FE-GATE-019 is -`UNVERIFIED` (reviews 13-05, 1101/13-01, +이 repo에서 workflow는 아무것도 배포하지 않는다. 위의 업로드, pointer 전환, +smoke 단계는 프로젝트의 provider adapter가 맡는다. 그 adapter가 `promotion`과 +`production_gate` 사이의 `deployment` job을 채운다. adapter가 promotion된 +release를 배포하고 나면, FE-GATE-019가 실제 응답 header를 검사하고 host가 그 +release를 서빙하는지 확인한다. 그 자리가 비어 있는 동안 FE-GATE-019는 +`UNVERIFIED`다(리뷰 13-05, 1101/13-01, [`release-cache-rollback.md`](../operations/release-cache-rollback.md)). -Rollback changes the active pointer only after confirming that the prior -immutable release has a coherent HTML/assets/config/API/manifest tuple. +rollback은 이전 불변 release의 HTML·asset·config·API·manifest 묶음이 서로 +맞는지 확인한 뒤에만 active pointer를 바꾼다. -Serve the app over HTTP/2 or later. The entry preloads every initial -JavaScript file in parallel (`initialJsFiles` in -`config/performance/budgets.json` bounds how many; the current count is -`initialJavascript.files` in `config/scale/feature-shape-ceilings.json`, which goes with the sample feature). Over HTTP/1.1 they queue for six connections per -host, and the first screen on Fast 3G came about one second later than with the -initial chunks grouped (2026-11-03). Over HTTP/2 the difference was under -100 ms, so the template keeps the chunks split. A product that can only serve -HTTP/1.1 groups its initial chunks in `vite.config.ts` and measures again -whenever the shell changes ("초기 청크 수와 HTTP/1.1" in -[`performance-evidence.md`](../operations/performance-evidence.md), review -1101/14.4). +앱은 HTTP/2 이상으로 서빙한다. 진입점은 모든 초기 JavaScript 파일을 병렬로 +미리 불러온다(preload). 몇 개까지 허용할지는 `config/performance/budgets.json`의 +`initialJsFiles`가 정한다. 지금 개수는 +`config/scale/feature-shape-ceilings.json`의 `initialJavascript.files`이고, 이 +값은 예시 feature를 기준으로 한다. HTTP/1.1에서는 host마다 연결이 여섯 개라 +파일이 줄을 선다. 그래서 Fast 3G에서 첫 화면이 초기 chunk를 묶었을 때보다 약 +1초 늦게 떴다(2026-11-03). HTTP/2에서는 차이가 100 ms 미만이었다. 그래서 +템플릿은 chunk를 나눈 채로 둔다. HTTP/1.1로만 서빙할 수 있는 제품은 +`vite.config.ts`에서 초기 chunk를 묶는다. 그리고 shell이 바뀔 때마다 다시 +잰다([`performance-evidence.md`](../operations/performance-evidence.md)의 +「초기 청크 수와 HTTP/1.1」, 리뷰 1101/14.4). -Serve JavaScript compressed (gzip, brotli or zstd). The bundle budget counts -gzip bytes; uncompressed, the initial JavaScript is about three times larger. -Both premises are declared in `config/hosting/cache-policy.json` -(`transport.alpnProtocols`, `hashedAsset.contentEncodings`), and the live probe -of FE-GATE-019 fails a host that does not meet them (review 1103/13-02). Every -condition the host has to meet, and what checks each one, is in 「운영 환경이 -지켜야 할 조건」 in -[`release-cache-rollback.md`](../operations/release-cache-rollback.md#운영-환경이-지켜야-할-조건). +JavaScript는 압축해서(gzip, brotli, zstd 중 하나) 서빙한다. 번들 budget은 +gzip 바이트를 센다. 압축하지 않으면 초기 JavaScript가 약 세 배 커진다. 두 +전제는 `config/hosting/cache-policy.json`에 선언되어 있다 +(`transport.alpnProtocols`, `hashedAsset.contentEncodings`). FE-GATE-019의 +실제 host 검사(live probe)는 이 전제를 지키지 않는 host를 실패시킨다(리뷰 +1103/13-02). host가 지켜야 할 조건 전부와 각 조건을 무엇이 검사하는지는 +[`release-cache-rollback.md`](../operations/release-cache-rollback.md#운영-환경이-지켜야-할-조건)의 +「운영 환경이 지켜야 할 조건」에 있다. diff --git a/docs/manual/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index cf44ae29..2f121ec5 100644 --- a/docs/manual/01-add-a-feature.md +++ b/docs/manual/01-add-a-feature.md @@ -124,7 +124,7 @@ corepack pnpm create:feature invoice-feature ② **기준** - 패키지가 아직 없으면 자리표시자로 시작한다. 3단계에서 실제 신원으로 바꾼다([02 결정표 2절](02-decision-tables.md#2-계약-출처)). -- 손으로 만드는 길도 있다. `docs/architecture/starter-experience.md`의 "Adding a feature" 절이 그 순서다. 다만 전역 ID 접두어, 무작위 topic, a11y 기록을 직접 챙겨야 한다. +- 손으로 만드는 길도 있다. `docs/architecture/starter-experience.md`의 "feature 추가" 절이 그 순서다. 다만 전역 ID 접두어, 무작위 topic, a11y 기록을 직접 챙겨야 한다. - 인자·파일·출력 전체는 [reference/create-feature.md](reference/create-feature.md)에 있다. ③ **잡는 검사 / 못 잡는 것** @@ -496,7 +496,7 @@ export function useInvoiceListFilters(): InvoiceListSearch { - 그 GET을 부르지 않는 페이지의 라우트(예: 상세 아래의 하위 항목 작성 폼 `/things/:thingId/parts/new`)는 상세 GET의 입력 스키마를 `paramsSchema`로 쓰지 않는다. 같은 스키마를 쓰면 report가 기록을 기대하는데 spec은 한 자원 응답을 보지 못해 기록을 남기지 않으므로 실패한다. 그 라우트에 자기 `paramsSchema`(예: `ThingPartCreateParams`)를 따로 둔다. - 설치된 GET이 아닌 요청을 그리기 전에 보내면 spec이 실패한다(`requests no installed list or single-resource read answers`). - spec은 h1이 보일 때까지 기다린다. 그래서 상세 페이지는 데이터가 없을 때도 h1을 그린다. 예: `heading={{ title: notice?.title ?? message("notice.detail.titlePending") }}`처럼 데이터가 없으면 고정 제목("공지")을 쓴다. -- 기능이 앱 홈(`/`)을 대신하려면 route ID `APP_HOME`을 쓴다. `docs/architecture/starter-experience.md`의 "Product home and layouts" 절을 본다. +- 기능이 앱 홈(`/`)을 대신하려면 route ID `APP_HOME`을 쓴다. `docs/architecture/starter-experience.md`의 "제품 홈과 레이아웃" 절을 본다. ③ **잡는 검사 / 못 잡는 것** diff --git a/docs/manual/03-outside-feature-folder.md b/docs/manual/03-outside-feature-folder.md index c2b47d46..4e7ae418 100644 --- a/docs/manual/03-outside-feature-folder.md +++ b/docs/manual/03-outside-feature-folder.md @@ -11,9 +11,9 @@ └─ D. 고치지 않는다 → 중앙 카탈로그, governance, 공유 mock 등 ``` -**정본 표**: 파일마다 "언제 고치나"와 "안 고치면 무엇이 실패하나"는 `docs/architecture/starter-experience.md`의 "Adding a feature" 절 표(`File | When | What fails without it`)가 정본이다. 이 문서는 그 표를 복사하지 않는다. 그 표에 없는 것만 더한다. 누가 하는지, 왜 폴더 밖인지, 사람이 하는 절차. +**정본 표**: 파일마다 "언제 고치나"와 "안 고치면 무엇이 실패하나"는 `docs/architecture/starter-experience.md`의 "feature 추가" 절 표(`파일 | 언제 | 없으면 실패하는 것`)가 정본이다. 이 문서는 그 표를 복사하지 않는다. 그 표에 없는 것만 더한다. 누가 하는지, 왜 폴더 밖인지, 사람이 하는 절차. -링크: [starter-experience.md "Adding a feature"](../architecture/starter-experience.md#adding-a-feature) +링크: [starter-experience.md "feature 추가"](../architecture/starter-experience.md#feature-추가) --- @@ -96,7 +96,7 @@ create:feature가 pending 기록을 만든다 - `@org-contracts/*` import는 이 파일에서만 된다(`external-contract-package-single-import-path`). 5. 공개 대상으로 승인 검사를 돌린다. - `APP_PROFILE=staging`으로 빌드한 뒤 `APP_PROFILE=staging RELEASE_TARGET=staging corepack pnpm check:release-admission`(FE-GATE-027)을 돌린다. - - 검사는 빌드 결과 `dist/config.json`을 읽는다. 빌드 변수는 루트 `README.md`의 "Runtime configuration" 절에 있다. + - 검사는 빌드 결과 `dist/config.json`을 읽는다. 빌드 변수는 루트 `README.md`의 「런타임 설정과 배포 변수」 절에 있다. 안 하면: FE-GATE-027이 거절한다. diff --git a/docs/manual/README.md b/docs/manual/README.md index 9f345166..effc0e1d 100644 --- a/docs/manual/README.md +++ b/docs/manual/README.md @@ -12,7 +12,7 @@ - 기능을 만드는 AI 에이전트. 단계마다 "쓸 스킬"을 적었다. - 스킬: Claude Code가 부르는 작업 지침의 이름이다. 사람이 읽을 때는 건너뛰어도 된다. -전제: 루트 `README.md`의 "Start locally"대로 로컬에서 앱이 뜬다. +전제: 루트 `README.md`의 「시작하기」대로 로컬에서 앱이 뜬다. ## 읽는 순서 @@ -75,7 +75,7 @@ README (이 문서) - 지금 구조는 `docs/architecture/layers.md`가 정본이다. - `docs/architecture/starter-experience.md`의 예전 "폴더 밖 수정" 4행 표와 "governance는 바뀌지 않는다" 문장(2026-11-01 리뷰 시점 판). - 그 판은 실제로 고쳐야 하는 파일을 다 적지 않았다. - - 지금 판의 "Adding a feature" 절 표가 정본이다. 03 문서가 이 표를 링크한다. + - 지금 판의 "feature 추가" 절 표가 정본이다. 03 문서가 이 표를 링크한다. - 템플릿이 예전에 두던 참조 샘플 기능과 예제 화면을 가리키는 문서와 리뷰 기록. - 그 샘플은 지웠다. 이 매뉴얼의 예시는 생성 명령 출력과 매뉴얼 안 코드 조각이다(`tests/unit/manual-code-blocks.test.ts`가 시험한다). @@ -83,8 +83,7 @@ README (이 문서) 코드가 맞다. 이 매뉴얼은 주장이고, 근거는 코드·설정·실행 결과다. -`docs/README.md` §1에서 이 폴더를 링크하면 `verify:documentation`(FE-GATE-017)이 이 폴더 문서에 적힌 경로·명령·게이트 ID가 있는지 검사한다. -폴더 링크는 그 폴더 바로 아래 `.md`만 검사한다. `reference/`도 검사하려면 따로 링크한다. +`verify:documentation`(FE-GATE-017)이 이 폴더(`reference/` 포함)의 모든 문서에 적힌 경로·명령·게이트 ID가 있는지 검사한다(`docs/README.md` 「5. 문서 검사」). 설명이 코드와 맞는지는 검사하지 않는다. 플랫폼 규칙(예산·실행·검증·텔레메트리)의 근거는 `docs/architecture/`의 `scale-architecture.md`에 있다. 이 매뉴얼은 `scale-architecture.md` §24처럼 절 번호로 가리킨다. diff --git a/docs/manual/reference/patterns.md b/docs/manual/reference/patterns.md index 5bfb9998..6fa3962b 100644 --- a/docs/manual/reference/patterns.md +++ b/docs/manual/reference/patterns.md @@ -14,7 +14,7 @@ |---|---|---|---| | 기능 모듈 등록 | `src/features/feature-module.ts` (`defineFeatureModule`, `defineFeatureRuntime`), 생성기 | 생성 뼈대 `feature-module.ts`, `feature-runtime.ts` | 생성기, 기능 ID와 계약 `featureId` 일치 | | context 소속 선언 | `src/contexts/bounded-context-module.ts` | 생성 뼈대 `src/contexts/-context/context-module.ts`(새 context를 만들 때) | 생성기(없는 context, 예산), 앱 모듈(루트 밖 라우트) | -| context 전용 레이아웃 | `docs/architecture/starter-experience.md` "Product home and layouts" | `tests/helpers/fixture-layout-product.tsx` (테스트 fixture) | `tests/component/context-layouts.test.tsx` | +| context 전용 레이아웃 | `docs/architecture/starter-experience.md` "제품 홈과 레이아웃" | `tests/helpers/fixture-layout-product.tsx` (테스트 fixture) | `tests/component/context-layouts.test.tsx` | | 앱 홈 대신하기 | `src/contracts/routes.ts`의 `FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS` | 없음 (기능 예제) | 조립 (두 기능이 `APP_HOME`을 선언하면 실패) | | 조립 기여(`needs`) | `src/features/feature-adapter-contribution.ts` | 생성 뼈대 `adapters/create--feature-input.ts` | 조립 (없는 capability, 다른 기능의 input) | | 제품 capability | `src/features/product-capabilities.ts`(타입), `src/bootstrap/product-composition.ts`(값), `src/bootstrap/product-composition-contract.ts` | `recipes/frontend-capabilities/indexeddb-feature-capability.ts` | `check:types` | diff --git a/scripts/create-feature.ts b/scripts/create-feature.ts index 576ce866..385734bc 100644 --- a/scripts/create-feature.ts +++ b/scripts/create-feature.ts @@ -414,7 +414,7 @@ const GENERATED = "Generated by `pnpm create:feature`."; function renderContextModule(contextId: string, appId: string, root: string): string { return `/** * Ownership declaration of the ${contextId} bounded context - * (docs/architecture/starter-experience.md, "Ownership declarations"): the + * (docs/architecture/starter-experience.md, "소유 선언"): the * app that owns it, its route root and its direct-feature budget. * ${GENERATED} */ @@ -1697,7 +1697,7 @@ async function readInstalledFacts(root: string): Promise { * and the command that writes each. A feature branch commits them with the * feature; two feature branches change the same lines, and the merge takes * the command again instead of a hand-merged value. docs/manual/03 (A) and - * the "Adding a feature" table in docs/architecture/starter-experience.md + * the "feature 추가" table in docs/architecture/starter-experience.md * list them (tests/unit/feature-tracked-files.test.ts). */ export const FEATURE_TRACKED_FILE_REWRITES = Object.freeze([ diff --git a/scripts/docs-system-exceptions.txt b/scripts/docs-system-exceptions.txt index e0c08880..70c03b8a 100644 --- a/scripts/docs-system-exceptions.txt +++ b/scripts/docs-system-exceptions.txt @@ -8,12 +8,6 @@ # - 2026-11-08 문서 체계를 켤 때의 기준선이다. 문서를 고쳐 더는 걸리지 않으면 그 줄을 지운다. language docs/accessibility/manual-checklist.md -language docs/architecture/capability-consumer-experience.md -language docs/architecture/contract-ownership.md -language docs/architecture/review-evidence.md -language docs/architecture/scale-architecture.md -language docs/architecture/starter-experience.md -language docs/architecture/static-delivery.md language docs/contracts/compatibility.md language docs/operations/adapter-remediation-ledger.md language docs/operations/release-cache-rollback.md @@ -27,7 +21,6 @@ language docs/security/supply-chain.md language docs/styling/design-tokens.md language docs/testing/taxonomy.md language src/adapters/browser-transfer/image-cdn/README.md -number docs/architecture/optional-adapter-recipes.md 12개 recipe number docs/operations/ci-quality-gates.md 4.4.3 style PRODUCT.md - **템플릿을 가져다 쓰는 개발자**: 이 템플릿으로 새 서비스를 빠르게 시작하는 사람입니다. 기본 화면(홈, 플랫폼 구성)과 Storyboo style PRODUCT.md - **파생 서비스의 최종 사용자**: 디자인 시스템(토큰, 프리미티브, 패턴, 레이아웃, 페이지 템플릿)은 이 템플릿으로 만든 서비스를 실제로 diff --git a/scripts/generate-product-feature-index.ts b/scripts/generate-product-feature-index.ts index 352b1187..2380cee2 100644 --- a/scripts/generate-product-feature-index.ts +++ b/scripts/generate-product-feature-index.ts @@ -112,7 +112,7 @@ export function renderContextIndex(entries: readonly FeatureIndexEntry[]): strin /** * Ownership declarations the generator reads, documented in - * docs/architecture/starter-experience.md ("Ownership declarations"). Each boundary + * docs/architecture/starter-experience.md ("소유 선언"). Each boundary * declares only its parent: * * src/apps//app-module.ts APP_MODULE_ID, APP_MAX_CONTEXTS diff --git a/scripts/lib/docs-system.ts b/scripts/lib/docs-system.ts index e06a0b76..c896fbb5 100644 --- a/scripts/lib/docs-system.ts +++ b/scripts/lib/docs-system.ts @@ -61,12 +61,6 @@ export const EXCEPTIONS_FILE = "scripts/docs-system-exceptions.txt"; */ export const FROZEN: ReadonlySet = new Set([ "cd62292c1faf9312", - "9ebf8141a4434f32", - "64bb8316aafc4fcc", - "80ca3b198759492f", - "89616e7ca7b409d5", - "021ee3958bdd58af", - "1f94ecba91dcd1df", "0ea431405727b1ba", "29d6b489d280d464", "f0eed09117035063", @@ -80,7 +74,6 @@ export const FROZEN: ReadonlySet = new Set([ "07db060102714081", "a42bc30fb525d6c9", "59569b9b066cffcc", - "cac81d51afa3db95", "33ba6f03c95bd8e7", "dce0f0c48d3876a4", "e1e286fae81074d4", diff --git a/src/apps/template-app/app-module.ts b/src/apps/template-app/app-module.ts index c26eb78d..76f240b8 100644 --- a/src/apps/template-app/app-module.ts +++ b/src/apps/template-app/app-module.ts @@ -1,6 +1,6 @@ /** * Ownership declaration of the template deployable app - * (docs/architecture/starter-experience.md, "Ownership declarations"). The + * (docs/architecture/starter-experience.md, "소유 선언"). The * generator reads these literals; contexts name this id as their owner. */ export const APP_MODULE_ID = "template-app"; diff --git a/tests/unit/feature-tracked-files.test.ts b/tests/unit/feature-tracked-files.test.ts index 6ef9c9ca..8464c75a 100644 --- a/tests/unit/feature-tracked-files.test.ts +++ b/tests/unit/feature-tracked-files.test.ts @@ -43,14 +43,14 @@ describe("tracked files a feature changes (1105/16-01)", () => { it("names each file and its rewrite command in the canonical table", async () => { const table = between( await readFile("docs/architecture/starter-experience.md", "utf8"), - "Files outside the feature directory.", - "The central catalogs", + "feature 디렉터리 밖 파일은 아래 표에 있다.", + "중앙 카탈로그", ); for (const file of FEATURE_TRACKED_FILE_REWRITES) { const row = table.split("\n").find((line) => line.startsWith("|") && line.includes(file.path)); expect(row, file.path).toBeDefined(); expect(row, file.path).toContain(file.command); - expect(row, file.path).toMatch(/merge conflict/u); + expect(row, file.path).toMatch(/병합 충돌/u); } }); });