diff --git a/.github/dependency-vulnerability-policy.md b/.github/dependency-vulnerability-policy.md index f046077e..cda1c924 100644 --- a/.github/dependency-vulnerability-policy.md +++ b/.github/dependency-vulnerability-policy.md @@ -1,92 +1,92 @@ -# Dependency Vulnerability Policy +# 의존성 취약점 정책 -This policy is enforced by +이 정책을 강제하는 것은 [`dependency-vulnerability.yml`](workflows/dependency-vulnerability.yml), [`dependency-review-config.yml`](dependency-review-config.yml), -[`../.trivyignore.yaml`](../.trivyignore.yaml), CODEOWNERS, and -[`../renovate.json`](../renovate.json). +[`../.trivyignore.yaml`](../.trivyignore.yaml), CODEOWNERS, +[`../renovate.json`](../renovate.json)이다. -## Execution and platform boundary +## 실행 위치와 플랫폼 경계 -Canonical workflow files live under `.github/workflows`. The current origin is Gitea and -server-side Actions is externally disabled; committing these controls does not enable or prove -remote execution. An administrator must enable Actions, provide compatible runners, configure -required checks, and require code-owner review separately. +정본 workflow 파일은 `.github/workflows` 아래에 있다. 지금 origin은 Gitea이고, 서버 쪽 Actions는 밖에서 +꺼져 있다. 이 통제를 커밋해도 원격 실행이 켜지거나 증명되지 않는다. 관리자가 따로 Actions를 켜고, 맞는 +runner를 주고, 필수 검사(required check)를 설정하고, code owner 리뷰를 필수로 해야 한다. -External actions execute only by verified full commit SHA; inline comments retain the immutable -release tag for review. GitHub dependency review publishes check output but never writes a PR -summary comment, preserving the workflow-wide `contents: read` permission. +외부 action은 확인한 전체 커밋 SHA로만 실행한다. 리뷰를 위해 같은 줄 주석에 바뀌지 않는 릴리스 태그를 +남긴다. GitHub dependency review는 검사 결과만 내고 PR 요약 댓글은 쓰지 않는다. 그래서 workflow 전체의 +`contents: read` 권한이 유지된다. -GitHub dependency review and dependency submission depend on GitHub.com APIs. They are guarded by -`github.server_url == 'https://github.com'` and intentionally skip on Gitea. `trivy-fs` is the -platform-neutral release-blocking snapshot and runs for pull requests, `main` pushes, daily -schedule, and manual dispatch. +GitHub dependency review와 dependency submission은 GitHub.com API에 기댄다. 둘은 +`github.server_url == 'https://github.com'` 조건으로 막혀 있고, Gitea에서는 일부러 건너뛴다. `trivy-fs`는 +플랫폼에 묶이지 않는, 릴리스를 막는 전체 스냅숏 검사다. pull request, `main` push, 매일 예약 실행, 손으로 +부른 실행에서 돈다. -The later supply-chain slice owns image builds/scans, SBOM, signing, provenance, tag release, and -retention. This policy does not claim those absent jobs. +이미지 빌드·스캔, SBOM, 서명, provenance, 태그 릴리스는 `workflows/release.yml`이 맡는다. 이 정책은 그 +job을 다루지 않는다. -## Severity and response +## 심각도와 대응 -| Severity | CI posture | Target remediation | +| 심각도 | CI 처리 | 고칠 기한 | | --- | --- | --- | -| KEV / Critical | block | 7 days or the CISA due date, whichever is sooner | -| High | block | 30 days | -| Medium | advisory | 90 days | -| Low | advisory | best effort | +| KEV / Critical | 막는다 | 7일 또는 CISA 기한 중 빠른 쪽 | +| High | 막는다 | 30일 | +| Medium | 알리기만 한다 | 90일 | +| Low | 알리기만 한다 | 가능한 대로 | -High/Critical is the template's release threshold. The exact threshold and remediation targets are -team policy rather than an external mandate and should be reviewed when the template is adopted. -GitHub dependency review applies the same High threshold to newly introduced runtime dependencies. +High/Critical이 이 템플릿의 릴리스 기준이다. 정확한 기준과 고칠 기한은 외부 규정이 아니라 팀 정책이다. +템플릿을 받아 쓸 때 다시 검토한다. GitHub dependency review도 새로 들어온 runtime 의존성에 같은 High +기준을 쓴다. -The Trivy JSON snapshot is also compared with the CISA Known Exploited Vulnerabilities catalog. -Any intersection blocks regardless of Trivy severity. Before intersection, CI requires nonblank -catalog metadata, a positive integral declared count, a non-empty vulnerability array whose length -matches that count, and unique CVE-pattern `cveID` values. A missing, empty, malformed, -count-inconsistent, duplicate, or unreachable KEV feed fails closed; configure the `KEV_FEED_URL` -repository variable to an approved internal mirror when direct CISA access is unavailable. +Trivy JSON 스냅숏은 CISA KEV(Known Exploited Vulnerabilities, 실제 악용이 확인된 취약점) 목록과도 +대조한다. 겹치는 항목이 있으면 Trivy 심각도와 상관없이 막는다. 대조하기 전에 CI는 KEV 목록을 확인한다. -Candidate extraction also validates Trivy's JSON first: the top level must be an object with a -non-empty `Results` array; each result is an object whose `Vulnerabilities` value is null or an -array; and every listed vulnerability has a nonblank string `VulnerabilityID`. Invalid scanner -output fails closed instead of becoming an empty candidate set. +- 목록 메타데이터가 비어 있지 않다. +- 선언한 개수가 양의 정수다. +- 취약점 배열이 비어 있지 않고 길이가 선언한 개수와 같다. +- `cveID` 값이 CVE 형식이고 서로 다르다. -## Scanner and network requirements +KEV 목록이 없거나, 비었거나, 형식이 깨졌거나, 개수가 맞지 않거나, 중복이 있거나, 받을 수 없으면 실패한다 +(fail closed). CISA에 직접 닿을 수 없으면 저장소 변수 `KEV_FEED_URL`을 승인된 내부 mirror로 설정한다. -Trivy scans the committed filesystem and Gradle lockfiles. High/Critical findings exit non-zero; -Medium/Low findings are reported with exit zero. Scanner database or tool-download failures remain -failures rather than silently producing an empty result. +후보를 뽑을 때도 Trivy JSON을 먼저 검사한다. 맨 위가 객체이고 `Results` 배열이 비어 있지 않아야 한다. +각 결과는 객체이고, `Vulnerabilities` 값은 null이거나 배열이다. 나열된 취약점마다 비어 있지 않은 문자열 +`VulnerabilityID`가 있어야 한다. 스캐너 출력이 잘못됐으면 빈 후보 목록으로 넘어가지 않고 실패한다. -Runners need HTTPS egress to: +## 스캐너와 네트워크 요구사항 -- the configured Trivy binary source (GitHub Releases by default); -- Trivy vulnerability databases (the scanner defaults, commonly OCI registries); -- jq releases, unless `JQ_DOWNLOAD_BASE_URL` points to an internal mirror; -- the CISA KEV feed, unless `KEV_FEED_URL` points to an internal mirror; -- GitHub action sources when the forge does not mirror actions. +Trivy는 커밋된 파일 시스템과 Gradle lockfile을 검사한다. High/Critical이 나오면 0이 아닌 코드로 끝나고, +Medium/Low는 보고만 하고 0으로 끝난다. 스캐너 DB나 도구를 받지 못하면 빈 결과가 아니라 실패다. -Closed networks must mirror the pinned Trivy/jq artifacts and checksums, set -`TRIVY_DOWNLOAD_BASE_URL` and `JQ_DOWNLOAD_BASE_URL`, configure Trivy's documented database mirror -environment, and set `KEV_FEED_URL`. Mirror availability and freshness are operational -dependencies; stale mirrors can delay detection. +runner는 다음 곳으로 HTTPS로 나갈 수 있어야 한다. -## Suppression governance +- 설정한 Trivy 실행 파일 출처(기본은 GitHub Releases) +- Trivy 취약점 DB(스캐너 기본값, 보통 OCI 레지스트리) +- jq 릴리스(`JQ_DOWNLOAD_BASE_URL`이 내부 mirror를 가리키면 그쪽) +- CISA KEV 목록(`KEV_FEED_URL`이 내부 mirror를 가리키면 그쪽) +- forge가 action을 mirror하지 않으면 GitHub action 출처 -The only suppression source is repository-root `.trivyignore.yaml`. Every Trivy scan passes it -explicitly with `--ignorefile .trivyignore.yaml`. Each future entry must contain an identifier, a -non-empty rationale, and a future expiry no more than 90 days away. A CODEOWNERS reviewer validates -the shape and expiry; CODEOWNERS plus branch protection controls who may approve the change. -Neither control substitutes for the other. +닫힌 네트워크에서는 고정한 Trivy·jq 산출물과 체크섬을 mirror하고, `TRIVY_DOWNLOAD_BASE_URL`과 +`JQ_DOWNLOAD_BASE_URL`을 설정하고, Trivy 문서에 있는 DB mirror 환경을 설정하고, `KEV_FEED_URL`을 설정한다. +mirror가 살아 있고 최신인지는 운영이 챙길 의존이다. 낡은 mirror는 탐지를 늦출 수 있다. -Do not use an ad-hoc ignore file or an inline scanner bypass. An expired suppression is removed or -renewed with fresh owner review and current evidence. +## 예외(suppression) 관리 -## Dependency update policy +예외의 출처는 저장소 루트 `.trivyignore.yaml` 하나다. 모든 Trivy 검사가 `--ignorefile .trivyignore.yaml`로 +그 파일을 명시한다. 앞으로 더하는 항목마다 식별자, 비어 있지 않은 이유, 90일 안의 미래 만료일이 있어야 +한다. CODEOWNERS 리뷰어가 모양과 만료일을 확인하고, CODEOWNERS와 branch protection이 누가 그 변경을 승인할 +수 있는지 정한다. 둘 중 하나가 다른 하나를 대신하지 않는다. -Renovate is the checked-in security-update bot configuration. Patch/pin/digest security updates -may auto-merge only after every configured required check succeeds; minor and major updates require -human review. Dependency declarations and all 19 `gradle.lockfile` files must move together, and -`verifyDependencyLocks` remains release-blocking. +임시 ignore 파일이나 스캐너를 건너뛰는 인라인 옵션을 쓰지 않는다. 만료된 예외는 지우거나, 소유자가 새로 +검토하고 지금의 증거를 붙여 갱신한다. -Bot alerts are not a transitive-dependency backstop on every forge. Use a Gradle constraint or -resolution rule for a vulnerable transitive dependency, refresh locks deliberately, and retain the -full-snapshot Trivy scan. +## 의존성 갱신 정책 + +Renovate가 저장소에 커밋된 보안 갱신 봇 설정이다. 보안 갱신은 갱신 종류와 상관없이 자동 병합하지 않는다 +(`renovate.json`의 `automerge: false`). Renovate는 strict lockfile을 다시 만들지 않는다. 관리자가 +`cd src && ./gradlew resolveAndLockAll --write-locks`로 잠금을 다시 만들고, 잠금 diff를 검토해 함께 +커밋한다. 의존성 선언과 모든 `gradle.lockfile`은 같이 움직이고, `verifyDependencyLocks`는 계속 릴리스를 +막는다. + +봇 알림은 모든 forge에서 전이 의존성(transitive dependency)까지 봐 주지 않는다. 취약한 전이 의존성은 +Gradle constraint나 resolution rule로 고정하고, 잠금을 의도적으로 다시 만들고, 전체 스냅숏 Trivy 검사를 +유지한다. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index b0736f82..a9b235c0 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,18 +1,17 @@ -## What changed and why +## 무엇을 왜 바꿨나 - + -## Verification +## 검증 -- [ ] I ran focused `::check` tasks for the modules I changed. -- [ ] I ran `cd src && ./gradlew architectureCheck verifyPublicPathSnapshot verifyDependencyLocks` when the change touched repository structure, dependencies, or public paths. -- [ ] I did not add an unregistered production module dependency. -- [ ] Dependency changes include refreshed `gradle.lockfile` files and a strict-lock verification. -- [ ] Trivy suppressions include an owner-reviewed reason and an expiry within 90 days. -- [ ] Any quarantined test is registered in `flaky-quarantine.yaml` with a reason, issue, and - `quarantined_since` date. -- [ ] I documented checks that could not run and their remaining risk. +- [ ] 바꾼 모듈마다 `::check`를 돌렸다. +- [ ] 저장소 구조·의존성·공개 경로를 건드렸으면 `cd src && ./gradlew architectureCheck verifyPublicPathSnapshot verifyDependencyLocks`를 돌렸다. +- [ ] registry에 없는 production 모듈 의존을 더하지 않았다. +- [ ] 의존성을 바꿨으면 다시 만든 `gradle.lockfile`과 strict lock 검증을 함께 넣었다. +- [ ] Trivy 예외(suppression)에는 소유자가 검토한 이유와 90일 안의 만료일이 있다. +- [ ] 간헐 실패 테스트는 격리하지 않고 고치거나 지웠다(격리 레지스트리는 없다). +- [ ] 돌리지 못한 검사와 그 때문에 남은 위험을 적었다. -## Compatibility and operations +## 호환성과 운영 - + diff --git a/.lycheeignore b/.lycheeignore new file mode 100644 index 00000000..82f08cd2 --- /dev/null +++ b/.lycheeignore @@ -0,0 +1,13 @@ +# lychee 링크 검사가 건너뛸 URL. 한 줄에 정규식 하나다. lychee가 저장소 루트에서 이 파일을 읽는다. +# 기록 문서 docs/design, docs/history, docs/reviews 안의 죽은 외부 링크만 여기에 더한다. +# 기록 본문은 고치지 않으니 링크 대신 이 목록을 고친다. 살아 있는 문서의 죽은 링크는 문서를 고친다. +# 규칙은 docs/README.md 문서 검사 절이다. + +# docs/design/2026-07-26-production-capability-platform-design.md +^https://www\.mongodb\.com/docs/manual/reference/write-concern/index\.html$ +# docs/design/2026-07-28-notification-production-capability-design.md +^https://docs\.aws\.amazon\.com/ses/latest/APIReference-V2/API_SendEmail\.html/$ +# docs/design/2026-07-28-notification-production-capability-design.md +^https://docs\.aws\.amazon\.com/sdk-for-java/latest/developer-guide/credentials-chain\.html/$ +# docs/reviews/2026-08-14-graphql-module-code-review.md +^https://docs\.spring\.io/spring-graphql/reference/1\.3/request-execution\.html$ diff --git a/AGENTS.md b/AGENTS.md index ce0f3085..3ae9a897 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -81,7 +81,7 @@ root `CLAUDE.md`는 작업을 시작할 때 읽는 지도이고, 이 목록을 테스트 전에 실패한다. skip된 테스트가 하나라도 있어도 실패한다(`rejectSkipped`를 따로 쓰지 않아도). 사람이 손으로 돌리는 `./gradlew performanceCheck`와 workflow가 같은 상한을 단언한다. - `verifyEnvKeys`는 app-bootstrap 태스크로 유지한다(2026-09-25 소유자 결정). 구현은 build-logic의 - `ca.config-contract`다. `src/build-tools/` included build는 비워서 삭제했다. + `ca.config-contract`다. 옛 included build `build-tools`는 지웠다(`docs/capability-status.md` 「제거된 코드」). - `src/build.gradle`: 루트 라이프사이클(`ci`, `mainCheck`, `integrationCheck`, `performanceCheck`, `releaseCheck`, `qualityCheck`, `configContractCheck`)과 버전/리비전. `verifyStrictLaneStages --dry-run`(PR 게이트)은 그 빌드에서 `explicitOnly`가 아닌 strict lane이 workflow가 실제로 실행하는 diff --git a/README.md b/README.md index 7e375860..c961aca4 100644 --- a/README.md +++ b/README.md @@ -1,161 +1,135 @@ -# ca-skeleton — Clean Architecture Spring Boot 템플릿 +# ca-skeleton — Clean Architecture Spring Boot 백엔드 템플릿 -ca-skeleton은 Java 21과 버전 카탈로그에 고정된 Spring Boot 4.x, Gradle 멀티모듈 기반의 Clean Architecture 백엔드 템플릿입니다. fork해서 도메인·패키지·엔티티·유스케이스만 교체하면 새 서비스를 시작할 수 있고, 모듈 경계와 의존 방향은 그대로 유지합니다. 기본 패키지는 `dev.caskeleton`입니다. 업무 기능의 예시는 생성 명령 `scripts/new-feature.sh`의 출력과 [docs/manual/](docs/manual/README.md)입니다. +ca-skeleton은 Java 21과 Spring Boot로 만든 Gradle 멀티모듈 백엔드 템플릿이다. 새 서비스를 만드는 개발자가 이 저장소를 복사하고, 도메인·유스케이스·adapter만 채운다. 모듈 경계와 의존 방향은 그대로 둔다. 사람과 AI 세션이 같은 규칙(`AGENTS.md`)과 같은 절차(`docs/work/`)로 일한다. 라이브러리 버전은 `src/gradle/libs.versions.toml`이 정한다. -이 문서는 전체 구조와 첫 실행만 다룹니다. 모듈별 상세 규칙과 설계 근거는 각 모듈의 README와 `CLAUDE.md`가, 빌드·환경 변수 상세는 [src/README.md](src/README.md)가 소유합니다. +## 프로젝트 구조 -## 아키텍처 한눈에 +저장소 루트에는 정해진 것만 둔다. 허용 목록 밖의 최상위 항목은 `scripts/check-repo-layout.py`가 PR에서 막는다. -의존은 항상 바깥에서 안으로 흐릅니다. adapter가 core의 port에 의존하고, core는 adapter를 알지 못합니다. 이 방향이 유지되는 한 도메인 규칙과 기술 선택(웹 프레임워크, DB, 메시징)을 서로 독립적으로 바꿀 수 있습니다. +| 폴더 | 하는 일 | 먼저 읽을 곳 | +| --- | --- | --- | +| `src/` | Gradle 루트. 모든 코드, 빌드 규칙, registry | [src/README.md](src/README.md) | +| `docs/` | 문서. 매뉴얼·계약·운영 문서·결정 기록·기록 | [docs/README.md](docs/README.md) | +| `scripts/` | Gradle 밖 스크립트. 첫 실행, 새 기능 생성, 저장소 배치·문서 검사 | `scripts/bootstrap-local.sh`, `scripts/new-feature.sh` | +| `compose.yaml` | 개발 환경. 앱 컨테이너와 뒷단 서비스(profile로 고른다) | 파일 머리의 profile 표 | +| `compose/` | `compose.yaml`이 마운트하는 보조 파일(Keycloak realm, Redis ACL, MinIO 초기화) | [compose/redis/acl/README.md](compose/redis/acl/README.md) | +| `.github/` | workflow, 공용 action, PR 양식, 의존성 취약점 정책 | [.github/dependency-vulnerability-policy.md](.github/dependency-vulnerability-policy.md) | + +`src/` 아래 폴더는 계층 leaf, 조립, 들여온 제품, Gradle 표준 폴더로 나뉜다. leaf는 Gradle 프로젝트 하나이고, leaf 목록·경로·허용 의존은 registry `src/config/architecture/modules.json`이 정한다. + +| 폴더 | 책임 | 기본 조립에 들어가나 | +| --- | --- | --- | +| `domain-core/` | 도메인 모델, 불변식, 도메인 이벤트, port. framework·transport·DB 타입을 쓰지 않는다 | 들어간다 | +| `application-core/` | command, 유스케이스, application 정책, 트랜잭션 port. inbound DTO와 persistence entity를 받지 않는다 | 들어간다 | +| `application-fileserver/`, `application-notification/`, `application-objectstorage/` | capability(부가 기능) 하나의 application 계층 | 그 capability를 켤 때 | +| `shared-contract/` | 저장소 전체의 운영 계약(오류 코드, 로그 키, 런타임 환경). 업무 개념은 두지 않는다 | 들어간다 | +| `adapter/inbound/` | HTTP·gRPC·GraphQL·WebSocket·메시징 수신 경계. DTO, 검증, 인증, 오류 매핑 | `web`만 들어간다 | +| `adapter/outbound/` | port 뒤의 구현: 영속성(JPA·MongoDB), Redis, 메시징, 알림, 객체 저장소, 파일 서버, HTTP client, identifier, 공용 기반(support) | `support`·`identifier`만 들어간다 | +| `composition/` | 조립만 하는 leaf: 서비스 런타임 배선, outbox relay, 멱등성 executor, durable operation, 알림·파일 서버 플랫폼 | `service-runtime`·`outbox-relay`·`idempotency`·`durable-operation`이 들어간다. 뒤의 셋은 필요한 port가 생기기 전에는 아무것도 만들지 않는다 | +| `app-bootstrap/` | Spring Boot 진입점과 조립 루트(composition root, 모든 모듈을 엮는 곳) | 들어간다 | +| `platforms/` | 들여온 제품: `messaging`(메시징 플랫폼), `grpc`·`grpc-advanced`(gRPC 라이브러리, 다른 빌드 `optional-build`) | 들어가지 않는다. adapter를 거쳐서만 닿는다 | +| `build-logic/`, `config/`, `gradle/` | 빌드 규칙(convention plugin), 빌드 전체 도구 설정과 registry, wrapper와 버전 카탈로그 | 빌드 도구 | + +의존은 항상 바깥에서 안으로 흐른다. adapter가 core의 port에 의존하고, core는 adapter를 모른다. ```text -app-bootstrap -> adapter:inbound:* -> application-core -> domain-core -app-bootstrap -> adapter:outbound:* -> application-core -> domain-core -모든 런타임 모듈 -> shared-contract +app-bootstrap ─▶ adapter:inbound:* ─▶ application-core ─▶ domain-core +app-bootstrap ─▶ adapter:outbound:* ─▶ application-core ─▶ domain-core +모든 런타임 모듈 ─▶ shared-contract ``` -family 수준의 책임은 다음과 같습니다. +불변식: 도메인 규칙은 `domain-core`와 `application-core`에만 있고, 기술 선택(웹, DB, 메시징)은 adapter에만 있다. -| 모듈 family | 책임 | -| --- | --- | -| `domain-core` | 순수 도메인 모델·불변식·이벤트·port. 프레임워크·transport·DB·IO 타입 금지 | -| `application-core` | command·유스케이스·application 정책·트랜잭션 port. inbound DTO·persistence entity 금지 | -| `adapter:inbound:*` | HTTP·gRPC·GraphQL·WebSocket transport 경계, DTO·validation·인증·에러 매핑 | -| `adapter:outbound:persistence-*` | JPA/PostgreSQL·MongoDB 영속 구현과 매핑·migration | -| `adapter:outbound:*` | support(공유 베이스)·messaging·cache·notification·object storage·file·HTTP client·identifier 능력을 port 뒤에서 구현. 기본 조립에는 support·identifier만 들어 있고, 나머지는 `app-bootstrap/build.gradle`의 `runtimeOnly` 한 줄로 고릅니다 | -| `shared-contract` | skeleton 전역 운영 계약. business/domain 개념 저장 금지 | -| `app-bootstrap` | Spring Boot entrypoint와 composition root | +## 시작하기 -등록된 leaf 목록과 각 leaf의 Gradle path·소스 경로·허용 production 의존 edge는 -[src/config/architecture/modules.json](src/config/architecture/modules.json)이 SSOT입니다. focused -test는 해당 Gradle path에서 `./gradlew :test --console=plain` 형태로 파생하며, root -문서나 기억에서 개별 leaf edge를 추론하지 않습니다. - -## 퀵스타트 - -전제조건은 Temurin 21(루트 [.tool-versions](.tool-versions)에 고정)과 Docker Engine 또는 Docker Desktop입니다. Gradle은 저장소 wrapper를 씁니다. 첫 실행 진입점은 하나입니다. +전제는 Temurin 21(`.tool-versions`에 고정)과 Docker Engine 또는 Docker Desktop이다. Gradle은 저장소의 wrapper를 쓴다. 첫 실행 진입점은 하나다. ```bash scripts/bootstrap-local.sh ``` -`scripts/bootstrap-local.sh`는 compile 검사, PostgreSQL Compose 기동, 애플리케이션 이미지 build·기동, `GET /api/healthcheck` HTTP smoke를 순서대로 실행합니다. 쓰는 compose 파일은 저장소 루트의 `compose.yaml` 하나입니다. 각 단계가 `bootstrap N/4` 줄을 찍고 실패하면 그 단계에서 멈추므로 실패 단계가 드러납니다. 기동을 확인하려면 health endpoint를 호출합니다. +이 스크립트는 네 단계를 차례로 돈다: 컴파일, PostgreSQL 기동, 앱 이미지 빌드와 기동, `GET /api/healthcheck` 확인. 단계마다 `bootstrap N/4` 줄을 찍고, 실패하면 그 단계에서 멈춘다. 쓰는 compose 파일은 루트의 `compose.yaml` 하나다. + +성공하면 이 명령이 HTTP 200을 돌려준다. ```bash curl -fsS http://localhost:8080/api/healthcheck ``` -로컬 스택을 내릴 때는 저장소 루트에서 실행합니다. +내릴 때는 저장소 루트에서 `--profile '*'`를 붙인다. 붙이지 않으면 profile로 띄운 `db` 같은 서비스가 남는다. ```bash docker compose --profile '*' down ``` -`--profile '*'`가 없으면 profile이 달린 `db`가 남습니다. compose는 켜진 profile의 서비스만 내립니다. +환경 변수는 `src/.env`(로컬 실행 입력)와 `src/.env.example`(배포 환경 변수의 복사·검증 계약)에 있다. 키 목록과 설명은 [src/README.md](src/README.md)와 [docs/registries/env-keys.yaml](docs/registries/env-keys.yaml)이다. -Redis·Kafka·MongoDB 같은 뒷단 서비스는 `compose.yaml`의 profile로 고릅니다(`docker compose --profile redis up -d --wait`). profile 목록은 그 파일 머리에 있습니다. +## 기능 켜고 끄기 -`src/.env.example`은 배포 환경 변수의 추적 가능한 복사/검증 계약이고 `src/.env`는 로컬 실행 입력입니다. 전체 환경 변수 목록과 조정 시점은 [src/README.md](src/README.md)와 [docs/registries/env-keys.yaml](docs/registries/env-keys.yaml)에 있습니다. +기본 조립(`bootJar`)은 web, 운영 관측(actuator·metrics·tracing·로그), core들, `support`·`identifier`뿐이다. 그래서 DB·Redis·Kafka 없이 뜬다. `cd src && ./gradlew :app-bootstrap:bootRun`으로 바로 실행할 수 있다. -### 기본 조립과 부가 기능 +DB, Redis, Kafka, 알림, 파일 서버 같은 부가 기능(capability)은 `src/app-bootstrap/build.gradle`에 주석 처리된 `runtimeOnly` 한 줄씩으로 있다. -기본 조립(`bootJar`)은 web, 관측, `domain-core`·`application-core`·`shared-contract`, support, -identifier뿐이라 DB·Redis·Kafka 없이 기동합니다. +- 켜기: 그 줄의 주석을 풀고 필요한 env 키를 넣는다. 모듈이 classpath에 있으면 켜진다. +- 끄기: 줄을 지운다. 기능·설정·의존성이 함께 빠진다. 줄을 둔 채 끄려면 그 모듈의 `enabled` 키를 `false`로 둔다. +- 줄마다 필요한 env 키와 끄는 키: [src/README.md](src/README.md) 「기능 추가 = 한 줄 + env」 표. +- 기능마다 조립·검증 상태: [docs/capability-status.md](docs/capability-status.md). +- capability 모듈이 지켜야 하는 규칙: [AGENTS.md](AGENTS.md) 「부가 기능(capability) 모듈 규칙」. + +뒷단 서비스는 `compose.yaml`의 profile로 고른다(`docker compose --profile redis up -d --wait`). profile 목록은 그 파일 머리에 있다. + +## 문서 지도 + +모든 문서 폴더의 지도는 [docs/README.md](docs/README.md)다. 무엇을 하려는지에 따라 여기서 시작한다. + +| 하려는 일 | 시작할 곳 | +| --- | --- | +| 이 저장소에서 일하기(새 기능, 개선, 조사, 문서, 운영, 일 나누기) | 작업 매뉴얼 [docs/work/README.md](docs/work/README.md). 지도는 [CLAUDE.md](CLAUDE.md) | +| 새 업무 기능 만들기 | 개발 매뉴얼 [docs/manual/README.md](docs/manual/README.md)와 생성 명령 `scripts/new-feature.sh` | +| 계약 확인하기(HTTP, 오류 코드, env 키, 메트릭, 헤더) | [docs/web/http-contract.md](docs/web/http-contract.md), `docs/registries/` | +| 기능 운영하기(설정, 장애 대응) | 영역 운영 문서(`docs/jpa/`, `docs/redis/` 등), 장애 코드별 런북 `docs/runbooks/` | +| 왜 이렇게 정했는지 보기 | 결정 기록 `docs/adr/` | +| 예전 설계·계획·리뷰 찾기 | 기록 `docs/design/`, `docs/history/`, `docs/reviews/`. 쓴 때의 글이고 지금 동작은 각 머리 블록의 「현재 정본」을 읽는다 | +| 템플릿 변경을 파생 서비스에 받기 | `docs/upgrade/` | + +각 모듈의 규칙과 설계 근거는 그 모듈 폴더의 `CLAUDE.md`와 README에 있다(예: [domain-core](src/domain-core/README.md), [app-bootstrap](src/app-bootstrap/README.md)). + +## 검증 + +명령은 `src/`에서 돌린다. 일상 피드백은 바꾼 leaf 하나와 아키텍처 검사다. leaf의 Gradle 경로는 registry의 `gradle_path`에서 읽는다. ```bash cd src -./gradlew :app-bootstrap:bootRun +./gradlew :app-bootstrap:check --console=plain +./gradlew architectureCheck --console=plain ``` -DB, Redis, Kafka, 알림, 파일 서버 같은 부가 기능은 `app-bootstrap/build.gradle`에 주석 처리된 -`runtimeOnly` 한 줄씩으로 있습니다. 줄의 주석을 풀고 필요한 env를 넣으면 켜지고, 줄을 지우면 사라집니다. -줄마다 필요한 env와 끄는 키는 [src/README.md](src/README.md)의 "기능 추가 = 한 줄 + env" 표에 있습니다. +`./gradlew test`는 모든 leaf의 `test`를 돌리므로 일상 명령으로 쓰지 않는다. PR·main·태그 단계에서 무엇이 도는지, 바꾼 것에 맞춰 무엇을 더 돌릴지는 [docs/work/reference/gates.md](docs/work/reference/gates.md)가 정한다. 게이트 태스크 하나하나의 설명은 [src/README.md](src/README.md) 「build.gradle — 빌드 / 검증 게이트」다. -| 프로파일 | 데이터스토어 (persistence-jpa 줄을 넣었을 때) | 스키마 소유자 | -| --- | --- | --- | -| `local` | Compose PostgreSQL (`./gradlew :app-bootstrap:bootRunH2`는 줄 없이도 모듈을 자기 classpath에 올려 H2 in-memory로 실행) | Flyway (H2는 Hibernate `create-drop`) | -| `dev` | PostgreSQL | Flyway | -| `prod` | PostgreSQL | Flyway | +문서를 고쳤으면 저장소 루트에서 `python3 scripts/check-docs.py`를 돌린다. 규칙은 [docs/README.md](docs/README.md) 「문서 검사」다. -H2 실행은 wiring과 애플리케이션 동작만 검증하고, migration과 vendor 동작은 검증하지 않습니다. 프로파일별 설정은 [src/app-bootstrap/src/main/resources/](src/app-bootstrap/src/main/resources/)의 `application-{local,dev,prod}.yml`이, 상세 설명은 [src/README.md](src/README.md)가 소유합니다. +## 새 서비스로 시작하기 -## 새 프로젝트로 시작하기 +이 저장소를 새 서비스의 출발점으로 쓸 때의 순서다. 전체 체크리스트는 [AGENTS.md](AGENTS.md) 「템플릿 재사용 체크리스트」다. -이 저장소를 새 서비스의 출발점으로 쓸 때 핵심 단계는 다음과 같습니다. 전체 체크리스트는 [AGENTS.md](AGENTS.md)의 "템플릿 재사용 체크리스트"에 있습니다. - -1. [src/settings.gradle](src/settings.gradle)의 `rootProject.name`을 새 서비스 이름으로 바꿉니다. -2. 패키지 루트 `dev.caskeleton`을 조직·서비스 패키지로 바꿉니다. 소스뿐 아니라 빌드·설정 파일의 참조도 함께 바꿔야 `mainClass`·`group`이 어긋나 `bootstrap`이 깨지지 않습니다. +1. `src/settings.gradle`의 `rootProject.name`을 새 서비스 이름으로 바꾼다. +2. 패키지 루트 `dev.caskeleton`을 서비스 패키지로 바꾼다. Java 소스만이 아니라 `AutoConfiguration.imports`·`spring.factories`·빌드 스크립트·설정 파일·생성 명령 템플릿도 이 이름을 쓴다. 바꿀 파일은 이 명령으로 찾는다. ```bash - cd src - find . -type f \( -name '*.java' -o -name '*.gradle' -o -name '*.yml' \) -print0 | xargs -0 sed -i 's/dev.caskeleton/com.yourorg.yourservice/g' + git grep -l 'dev\.caskeleton' -- src scripts ``` - 애플리케이션 이름 등 나머지 rename 단계는 위 체크리스트를 따릅니다. +3. `CaSkeletonApplication`을 새 애플리케이션 이름으로 바꾼다. +4. 새 업무 기능은 `scripts/new-feature.sh `으로 만들고 [docs/manual/README.md](docs/manual/README.md) 순서대로 채운다. 모듈 이름과 경계는 그대로 둔다. +5. 쓰는 capability의 `runtimeOnly` 줄만 켠다. 켜지 않은 capability leaf는 산출물에 들어가지 않으니 지우지 않아도 된다. -3. `CaSkeletonApplication`을 새 애플리케이션 이름으로 바꾸고, 목표 도메인의 엔티티·repository port·유스케이스·adapter를 production 모듈에 추가합니다. 새 업무 기능은 `scripts/new-feature.sh `으로 만듭니다. -4. 모듈 이름과 경계는 그대로 유지합니다. +복사한 뒤 지워도 되는 것은 템플릿의 기록(`docs/design/`, `docs/history/`, `docs/reviews/`)이다. 서비스의 지금 동작을 설명하지 않는다. 지우면 그 기록을 가리키던 살아 있는 문서가 깨지므로 `python3 scripts/check-docs.py`와 링크 검사([docs/work/reference/gates.md](docs/work/reference/gates.md) 「링크 검사」)로 찾아 고친다. 템플릿을 upstream으로 두고 merge해 받으면 그 폴더에서 충돌이 날 수 있다(`docs/upgrade/2026-11-docs-records.md`). -검증은 먼저 composition root의 빠른 테스트와 아키텍처 검사를 확인합니다. 루트에서 -`./gradlew test`를 호출하면 등록된 모든 하위 프로젝트의 `test`를 실행하므로 일상적인 로컬 -피드백 명령으로 사용하지 않습니다. 저장소 전체 qualification은 CI 또는 명시적인 `ci` task가 -담당합니다. +이름을 바꾼 뒤에는 위 「검증」의 두 명령과 `./gradlew :app-bootstrap:test --console=plain`을 돌린다. -```bash -cd src -./gradlew :app-bootstrap:test -./gradlew architectureCheck -``` +## 규칙과 기여 -병합 전 저장소 전체 검증이 필요하면 `./gradlew ci`를 실행합니다. - -## 아키텍처 규칙과 검증 - -애플리케이션이 동작하더라도 아래를 어기면 병합하지 않습니다. HARD-STOP 7개 조건의 정본 로컬 -정책 권위는 [AGENTS.md](AGENTS.md)이며, [CLAUDE.md](CLAUDE.md)는 작업을 시작할 때 읽는 지도입니다. -일의 종류별 절차는 [docs/work/](docs/work/README.md)에 있습니다. - -- `domain-core`는 Spring·JPA·Servlet·HTTP·DB·cloud SDK 타입을 import하지 않습니다. -- controller는 repository를 직접 호출하거나 persistence entity를 반환하지 않습니다. -- inbound DTO는 `application-core`나 `domain-core`로 들어가지 않습니다. -- 비즈니스 정책은 mapper·filter·config·settings·controller에 두지 않습니다. -- 새 외부 시스템 연동은 domain/application port와 adapter 모듈로 표현합니다. - -이 규칙은 두 축으로 자동 강제합니다. `:app-bootstrap:architectureTest`의 분할된 ArchUnit 규칙들이 컴파일된 소스 의존성을, -`verifyCleanArchitectureDependencies` 게이트가 JSON registry의 허용 Gradle project edge를 -검사합니다. - -```bash -cd src -./gradlew verifyCleanArchitectureDependencies -``` - -두 검증 축은 [ci-quality-gates.yml](.github/workflows/ci-quality-gates.yml)의 release gate에 연결되어, 규칙 위반이 병합·릴리스를 막습니다. - -## 수동 전용 Gradle 태스크 - -아래 태스크는 **어떤 워크플로도 실행하지 않으며, 그게 의도다.** 자동 실행이 틀린 이유를 적어 둔다. - -여기 적힌 태스크 이름이 실재하는지 검사하던 `verifyReadmeCommands`는 삭제했다. 그건 이 문서의 -```bash 블록을 직접 파싱해 `./gradlew`·`docker compose`·`make` 토큰을 실제 태스크 그래프와 대조하는 -Markdown 명령 파서였고, 그 결과 "README에 무엇을 쓸 수 있는가"가 그 파서가 읽을 수 있는 문법의 -함수가 됐다. 문서와 코드가 어긋나는 것은 결함이지만, 빌드를 실패시켜서 고칠 일은 아니다. - -```bash -cd src -./gradlew :grpc:grpc-testkit:grpcPerformanceTest -``` - -- `grpcPerformanceTest` — latency percentile·saturation·drain budget을 **측정**한다. 공유 CI - runner의 측정값은 흔들리고, 흔들리는 게이트는 결국 꺼진다. leaf `build.gradle`이 이 태스크의 - 태그를 `test`에서 제외하는 이유도 같다. 성능 회귀가 의심될 때 사람이 이름으로 부른다. - - -## 더 알아보기 - -- 빌드·검증 게이트·환경 변수 상세: [src/README.md](src/README.md) -- 모듈 레지스트리(등록 leaf SSOT): [src/config/architecture/modules.json](src/config/architecture/modules.json) -- 에이전트·기여자 작업 규칙: [AGENTS.md](AGENTS.md) · [CLAUDE.md](CLAUDE.md) -- release/publish 자동화는 `.github/workflows/release.yml`이 소유하며, release provenance·SBOM· - 이미지 build/push를 해당 workflow의 명시적 권한과 게이트 아래에서 수행합니다. -- 모듈별 설계 결정: [domain-core](src/domain-core/README.md) · [application-core](src/application-core/README.md) · [adapter:inbound:web](src/adapter/inbound/web/README.md) · [adapter:outbound:persistence-jpa](src/adapter/outbound/persistence-jpa/README.md) · [shared-contract](src/shared-contract/README.md) · [app-bootstrap](src/app-bootstrap/README.md) +- 규칙의 정본은 [AGENTS.md](AGENTS.md)다. 「Prime Directive」의 HARD-STOP 조건을 어기면 동작하더라도 병합하지 않는다. +- 일을 시작할 때 읽는 지도는 [CLAUDE.md](CLAUDE.md)다. 일의 종류별 절차는 [docs/work/README.md](docs/work/README.md)다. +- 각 모듈의 지역 규칙은 가장 가까운 `src/**/CLAUDE.md`다. +- 커밋 정책과 메시지 형식은 [docs/work/README.md](docs/work/README.md) 「커밋」이다. PR은 [.github/pull_request_template.md](.github/pull_request_template.md) 양식을 채운다. diff --git a/compose/keycloak/README.md b/compose/keycloak/README.md index 57266885..c44a9531 100644 --- a/compose/keycloak/README.md +++ b/compose/keycloak/README.md @@ -1,37 +1,33 @@ -# Keycloak realm artifact +# Keycloak realm 파일 -`realms/ca-skeleton-realm.json` is imported by the `keycloak` service in the root `compose.yaml` -and is the same realm every GraphQL qualification lane authenticates against. +루트 `compose.yaml`의 `keycloak` 서비스가 `realms/ca-skeleton-realm.json`을 가져온다(import). 모든 GraphQL +qualification lane이 인증하는 realm도 이 파일이다. -## The client secret is a reference, never a value +## client secret은 값이 아니라 참조다 -The confidential client `ca-skeleton-api` carries `"secret": "${KEYCLOAK_GRAPHQL_SMOKE_CLIENT_SECRET}"`. -`entrypoint.sh` reads the value from the Compose secret mounted at -`/run/secrets/keycloak-graphql-smoke-client-secret`, exports it, and execs `kc.sh start-dev ---import-realm`, so the value never reaches Git, a rendered Compose config, a command line, or an -evidence file. A realm file with a working credential in it is a credential in the repository, and -"it is only for smoke tests" is not something a scanner or a fork can tell. +confidential client `ca-skeleton-api`는 `"secret": "${KEYCLOAK_GRAPHQL_SMOKE_CLIENT_SECRET}"`를 가진다. +`entrypoint.sh`가 `/run/secrets/keycloak-graphql-smoke-client-secret`에 마운트된 Compose secret에서 값을 읽어 +export하고, `kc.sh start-dev --import-realm`을 exec한다. 그래서 값이 Git, 렌더링된 Compose 설정, 명령줄, +증거 파일 어디에도 닿지 않는다. 동작하는 자격 증명이 든 realm 파일은 저장소 안의 자격 증명이다. 「smoke +테스트에만 쓴다」는 사정은 스캐너도 fork도 알 수 없다. -## No comment keys in the realm JSON +## realm JSON에 주석 키를 두지 않는다 -Keycloak deserializes this file into `RealmRepresentation` with unknown fields **rejected**, not -ignored. A `"_comment"` key here fails the whole import with `Unrecognized field "_comment"`, the -container exits 1, and the lane fails on Keycloak rather than on anything it was testing. That is -why this rationale lives in Markdown next to the artifact instead of inside it. +Keycloak은 이 파일을 `RealmRepresentation`으로 역직렬화할 때 모르는 필드를 무시하지 않고 **거절한다**. +`"_comment"` 키 하나가 `Unrecognized field "_comment"`로 import 전체를 실패시키고, 컨테이너가 1로 끝나고, +lane은 시험하던 것이 아니라 Keycloak에서 실패한다. 그래서 이 근거를 파일 안이 아니라 옆의 Markdown에 둔다. -## What the realm grants +## realm이 주는 권한 -- realm role `user` — the baseline role the application authorizes ordinary calls on -- client role `ca-skeleton-api:graphql-query` — permission to execute a GraphQL query -- client roles `notification-submit`, `notification-template-publish`, `operation-submit` — the - platform permissions `security.yml` maps them to -- client roles `ROLE_FILE_READ` and `ROLE_FILE_WRITE` — the fileserver's read and write tiers, which - `security.yml` also maps to `file:read` and to `file:upload`, `file:delete`, `file:copy`, - `file:move`; `ROLE_FILE_ADMIN` (`file:admin`) is defined but not granted to the service account, - since the management plane is off by default -- a service account for the client-credentials grant the qualification lane uses -- audience and realm/client role mappers, so the issued token carries what the resource server - validates +- realm role `user`: 애플리케이션이 보통 호출을 허가하는 기본 role +- client role `ca-skeleton-api:graphql-query`: GraphQL query를 실행할 권한 +- client role `notification-submit`, `notification-template-publish`, `operation-submit`: `security.yml`이 + 플랫폼 권한으로 바꾸는 role +- client role `ROLE_FILE_READ`, `ROLE_FILE_WRITE`: 파일 서버의 읽기·쓰기 등급. `security.yml`이 각각 + `file:read`와 `file:upload`·`file:delete`·`file:copy`·`file:move`로 바꾼다. `ROLE_FILE_ADMIN` + (`file:admin`)은 정의만 하고 service account에 주지 않는다. 관리 기능은 기본으로 꺼져 있다 +- qualification lane이 쓰는 client credentials grant용 service account +- audience mapper와 realm·client role mapper. 발급한 토큰에 resource server가 검증하는 값이 실린다 -Standard flow and direct access grants are disabled: the lane authenticates as a service, and an -enabled password grant is a second way in that nothing tests. +standard flow와 direct access grant는 꺼 두었다. lane은 서비스로 인증하고, 켜 둔 password grant는 아무도 +시험하지 않는 두 번째 입구가 된다. diff --git a/compose/redis/acl/README.md b/compose/redis/acl/README.md index adfc2118..01a388bc 100644 --- a/compose/redis/acl/README.md +++ b/compose/redis/acl/README.md @@ -1,58 +1,64 @@ -# ACL accounts — test fixtures, not a deployment file +# ACL 계정 — 배포 파일이 아니라 시험용 fixture -**Nothing in this directory is loaded by a deployment.** Every file here is a fixture for the local -and test lanes: its passwords are public (`fixture-*`, written in this repository), and -`lane-fixture-accounts.acl` also provisions three accounts that only a lane topology needs — among -them `ca-skeleton-cluster-bootstrap`, which has `~* &* +@all`, every command on every key. Loaded into -a real Redis, that line alone gives anyone who can reach the server and read this repository full -control of it (`CONFIG`, `MODULE`, every key). A deployment writes its own ACL file of the same -shape: the application accounts it actually uses, passwords from its secret store, and none of the -lane-only accounts (review 2026-11-03 RR-07-04). The application enforces its half of that: under -the `prod` runtime profile it refuses to start while a secret holds a value beginning with -`fixture-` (`SecretSourceValidator`): a key the secrets registry classifies `secret`, a variable a -module's `RequiredProductionSecrets` bean names, or the variable a `secret://…/` credential -reference in the environment names. A reference held in code — the typed SDK's admin account, -contributed as a `RedisAccountContribution` bean — is none of those: the composer names its variable -in a `RequiredProductionSecrets` bean too (`src/adapter/outbound/redis-sdk/README.md`), or the -`fixture-admin` password passes. A deployment that copied a lane's -`APP_REDIS_AUTHENTICATION_*_REFERENCE` and `REDIS_LANE_*` values stops before it connects. Values -that are not secrets — a pod's `HOSTNAME`, an application name — are not read, because `fixture-` -is an ordinary word as well. +**이 폴더의 어떤 파일도 배포에서 읽지 않는다.** 모든 파일이 로컬·테스트 lane용 fixture다. -One file per `CommandAccess` level. Each account is deliberately narrower than the SDK's own rules: -the account is the last enforcement boundary and a permit issued inside the process never widens it, -so a mistake in the SDK is still refused by the server. +- 비밀번호가 공개돼 있다(`fixture-*`, 이 저장소에 적혀 있다). +- `lane-fixture-accounts.acl`은 lane 구성에만 필요한 계정 셋도 만든다. 그중 + `ca-skeleton-cluster-bootstrap`은 `~* &* +@all`, 곧 모든 key에 모든 명령을 가진다. +- 이 줄 하나를 실제 Redis에 올리면, 서버에 닿을 수 있고 이 저장소를 읽을 수 있는 누구나 서버 전체 + (`CONFIG`, `MODULE`, 모든 key)를 다룰 수 있다. -A Redis ACL file accepts nothing but complete `user` lines — no comments and no line continuations — -which is why the rationale lives here instead of inline. +배포는 같은 모양의 자기 ACL 파일을 쓴다. 실제로 쓰는 애플리케이션 계정만 두고, 비밀번호는 자기 secret +store에서 가져오고, lane 전용 계정은 두지 않는다(review 2026-11-03 RR-07-04). -Every account here carries a **fixture** password (`fixture-*`). They are written down rather than -left as `nopass` because an account that accepts any password makes every assertion about -authentication pass for the same reason a typo would have — and because these files are what a fork -copies. The four per-role files carried `nopass` long after the combined lane file had been fixed; -a fork that copied one of them got an open account and a green lane. +애플리케이션도 자기 몫을 강제한다. `prod` 런타임 profile에서 비밀값이 `fixture-`로 시작하면 기동을 +거부한다(`SecretSourceValidator`). 보는 비밀값은 셋이다. -| File | Account | Grants | +- 비밀 레지스트리가 `secret`으로 분류한 키 +- 모듈의 `RequiredProductionSecrets` bean이 이름을 댄 변수 +- 환경 안의 `secret://…/` 자격 증명 참조가 가리키는 변수 + +코드에 있는 참조(typed SDK의 admin 계정을 `RedisAccountContribution` bean으로 기여하는 경우)는 이 셋 중 +어디에도 들지 않는다. 조립하는 쪽이 그 변수도 `RequiredProductionSecrets` bean에 적어야 한다 +(`src/adapter/outbound/redis-sdk/README.md`). 그러지 않으면 `fixture-admin` 비밀번호가 통과한다. +lane의 `APP_REDIS_AUTHENTICATION_*_REFERENCE`와 `REDIS_LANE_*` 값을 복사한 배포는 연결하기 전에 멈춘다. +비밀이 아닌 값(pod의 `HOSTNAME`, 애플리케이션 이름)은 읽지 않는다. `fixture-`는 보통 낱말이기도 하다. + +`CommandAccess` 등급마다 파일이 하나다. 각 계정은 SDK 자체 규칙보다 일부러 더 좁다. 계정이 마지막 +강제 경계이고 프로세스 안에서 내준 허가는 그 경계를 넓히지 못한다. 그래서 SDK에 실수가 있어도 서버가 +거절한다. + +Redis ACL 파일은 완전한 `user` 줄만 받는다. 주석도, 줄 이어 쓰기도 안 된다. 그래서 근거를 파일 안이 +아니라 여기에 둔다. + +여기의 모든 계정은 **fixture** 비밀번호(`fixture-*`)를 가진다. `nopass`로 두지 않고 적어 둔 이유는 둘이다. + +- 아무 비밀번호나 받는 계정에서는 인증에 대한 모든 단언이 오타가 있어도 통과한다. +- fork가 복사하는 것이 이 파일들이다. 역할별 파일 넷은 합친 lane 파일을 고친 뒤에도 오래 `nopass`였고, + 그중 하나를 복사한 fork는 열린 계정과 녹색 lane을 함께 얻었다. + +| 파일 | 계정 | 주는 권한 | | --- | --- | --- | -| `application.acl` | `CommandAccess.APPLICATION` | the typed data-structure commands over `prod:*`, with the dangerous and deprecated names denied | -| `application-advanced.acl` | `APPLICATION_ADVANCED` | the above plus pub/sub, transactions, and the registered-script path. `EVAL` is absent: only `EVALSHA` of an already loaded digest is reachable. `+time` is granted because the rate-limit and idempotency scripts read the server clock with `redis.call('TIME')`, and `TIME` is in no data category (`@read`/`@write`): without it every such script fails with an ACL error. The startup SCRIPT probe runs `TIME` so a template missing it fails at boot | -| `raw-gateway.acl` | `RAW_GATEWAY` | exactly the commands the catalog classifies `RAW_ONLY`, and nothing else | -| `lane-fixture-accounts.acl` | – | what the lanes load (Redis takes one `aclfile`): `user default off`, the four per-role accounts of this table, and three lane-only accounts — `ca-skeleton-replication` (replica sync) and `ca-skeleton-sentinel` for the replicated and sentinel topologies, `ca-skeleton-cluster-bootstrap` (`+@all`) to create the cluster lane's slots. Never a deployment file | -| `admin-readonly.acl` | `ADMIN_READONLY` | read-only diagnostics. Every destructive counterpart is denied here and blocked in the command policy catalog — two independent controls for the same rule | +| `application.acl` | `CommandAccess.APPLICATION` | `prod:*` 위의 typed 자료구조 명령. 위험한 명령과 폐기된 명령 이름은 막는다 | +| `application-advanced.acl` | `APPLICATION_ADVANCED` | 위 권한에 pub/sub, 트랜잭션, 등록된 script 경로를 더한다. `EVAL`은 없다: 이미 올린 digest의 `EVALSHA`만 닿는다. `+time`을 주는 이유: rate-limit·idempotency script가 `redis.call('TIME')`으로 서버 시계를 읽는데, `TIME`은 어떤 데이터 범주(`@read`/`@write`)에도 없다. 없으면 그런 script가 모두 ACL 오류로 실패한다. 기동 때의 SCRIPT 확인이 `TIME`을 돌려서, 이 권한이 빠진 템플릿은 기동에서 실패한다 | +| `raw-gateway.acl` | `RAW_GATEWAY` | catalog가 `RAW_ONLY`로 분류한 명령만, 그 밖에는 없다 | +| `lane-fixture-accounts.acl` | – | lane이 읽는 파일(Redis는 `aclfile` 하나만 받는다): `user default off`, 이 표의 역할별 계정 넷, lane 전용 계정 셋 — `ca-skeleton-replication`(replica 동기화)과 `ca-skeleton-sentinel`(replicated·sentinel 구성용), `ca-skeleton-cluster-bootstrap`(`+@all`, cluster lane의 slot을 만든다). 배포 파일이 아니다 | +| `admin-readonly.acl` | `ADMIN_READONLY` | 읽기 전용 진단. 파괴적인 짝 명령은 모두 여기서 막고 명령 정책 catalog에서도 막는다 — 같은 규칙에 서로 독립인 통제 둘 | +| `sentinel-accounts.acl` | – | sentinel 프로세스용 계정(`ca-skeleton-sentinel-client`, `ca-skeleton-sentinel-peer`, `ca-skeleton-sentinel-operator`). 지금 이 파일을 `aclfile`로 읽는 compose 파일은 없다 | -## Who loads `lane-fixture-accounts.acl` +## 누가 `lane-fixture-accounts.acl`을 읽나 -The Redis topology lanes (`src/adapter/outbound/redis-sdk/compose/{standalone,sentinel,cluster,tls}`), the -application's Compose lanes that switch Redis on (`local-redis`, `all-adapters` in -`src/app-bootstrap/compose-lanes/compose-profile-contracts.json`), and the development stack's -`redis` service (root `compose.yaml`). They all mount this directory read-only; neither -keeps a copy, because a second copy of these lines is a second place for a password or a key -pattern to drift. +- Redis 구성(topology) lane: `src/adapter/outbound/redis-sdk/compose/{standalone,sentinel,cluster,tls}` +- Redis를 켜는 애플리케이션 Compose lane: `src/app-bootstrap/compose-lanes/compose-profile-contracts.json`의 + `local-redis`, `all-adapters` +- 개발 환경의 `redis` 서비스(루트 `compose.yaml`) -The Compose lanes connect the application as `ca-skeleton-application` and -`ca-skeleton-application-advanced`, through `secret://@environment/` references -whose variables carry the fixture passwords above. They run with the Redis namespace environment -`prod`, because every account here is fenced to `~prod:*`. `scripts/verify-compose-profile-contracts.sh` -compares each Redis lane's references, passwords and namespace with the account lines in this file, -so changing a password or a key pattern here without the lanes fails that check rather than the -lane's first command. +모두 이 폴더를 읽기 전용으로 마운트한다. 복사본을 두지 않는다. 이 줄들의 두 번째 사본은 비밀번호나 key +패턴이 따로 어긋날 두 번째 자리다. + +Compose lane은 애플리케이션을 `ca-skeleton-application`과 `ca-skeleton-application-advanced`로 연결한다. +연결은 `secret://@environment/` 참조를 거치고, 그 변수가 위 fixture 비밀번호를 가진다. +여기의 모든 계정이 `~prod:*`로 묶여 있어서, lane은 Redis namespace 환경을 `prod`로 두고 돈다. +`scripts/verify-compose-profile-contracts.sh`가 Redis lane마다 참조·비밀번호·namespace를 이 파일의 계정 줄과 +비교한다. 그래서 lane을 고치지 않고 여기의 비밀번호나 key 패턴만 바꾸면, lane의 첫 명령이 아니라 그 검사가 +실패한다. diff --git a/docs/README.md b/docs/README.md index 54351e62..effd1865 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,60 +1,107 @@ # docs -저장소의 모든 문서는 이 디렉터리 아래에 있다. 규칙은 둘이다: 어떤 문서를 어디에 두는지(아래 표), -문서의 수명에 따라 무엇을 어떤 언어로 고치는지(「문서 수명과 언어」). 파일 목록은 디렉터리를 직접 읽는다. -개수를 여기에 적으면 다음 문서가 추가되는 순간 틀린 글이 된다. +저장소의 모든 문서는 이 폴더 아래에 있다. 이 README는 두 가지를 정한다. -## 어댑터별 운영 문서 +- 어떤 문서가 어느 폴더에 있나: 아래 「문서 지도」. 지금 있는 모든 문서 폴더를 덮는다. +- 문서의 수명에 따라 무엇을 어떤 언어로 고치나: 「문서 수명과 언어」. -각 어댑터의 지원 범위, 설정, 보안, 운영, 마이그레이션 문서다. 코드와 함께 갱신되어야 하는 문서이고, -`docs/httpclient/` 는 `scripts/verify-httpclient-docs.py` 가 코드에서 뽑은 이름과 대조한다. +파일 목록과 개수는 여기에 적지 않는다. 적으면 다음 문서가 더해지는 순간 틀린 글이 된다. 파일은 폴더를 직접 읽는다. -| 디렉터리 | 대상 | +## 문서 지도 + +- 표의 첫 칸이 폴더다(`docs/` 기준 경로). +- 새 문서 폴더를 만들면 같은 변경에서 이 지도에 행을 더한다. 폴더를 지우거나 옮기면 그 행도 고친다. +- `python3 scripts/check-docs.py`의 `map` 검사가 지도에 없는 폴더와, 지도에 있지만 없는 폴더를 막는다(「문서 검사」). + +### 매뉴얼 + +일하는 순서와 판단 지점이다. 사람과 AI 세션이 같이 쓴다. + +| 폴더 | 무엇 | | --- | --- | -| `fileserver/` | 파일 서버 어댑터 | -| `httpclient/` | HTTP 클라이언트 플랫폼 | -| `jpa/` | JPA·PostgreSQL 영속성 | -| `messaging/` | 메시징 어댑터 | -| `mongodb/` | MongoDB 문서 영속성 (`advanced/`, `runbooks/` 포함) | -| `notification/` | 알림 전달 플랫폼 (`adr/` 포함) | -| `redis/` | Redis 캐시·세션 | - -## 횡단 문서 - -| 디렉터리 | 대상 | -| --- | --- | -| `adr/` | 아키텍처 결정 기록 | -| `architecture/` | 공개 API 표면 스냅숏 | -| `work/` | 작업 매뉴얼: 이 repo에서 하는 일(새 기능, 개선, 조사·설계, 문서 작성, 운영, 총괄)의 절차서. 루트 `CLAUDE.md` 다음에 읽는다 | +| `work/` | 작업 매뉴얼: 이 repo에서 하는 일(새 기능, 개선, 조사·설계, 문서 작성, 운영, 일 나누기)의 절차서. 루트 `CLAUDE.md` 다음에 읽는다 | | `manual/` | 개발 매뉴얼: 새 기능을 만드는 순서와 판단 지점, 생성 명령(`scripts/new-feature.sh`). 입구는 `work/new-feature.md` | -| `registries/` | env 키·에러 코드·메트릭·헤더 등 레지스트리 SSOT | -| `reviews/` | 모듈 코드 리뷰 결과 | -| `runbooks/` | 장애 코드별 대응 런북 (`template.md` 기준) | -| `security/` | 공개 경로 스냅숏 | +| `testing/` | 테스트 전략: 테스트 종류 다섯, source set, 어떤 테스트를 어디에 두나, Gradle 실행 계층 | -## 설계와 기록 +### 계약과 스냅숏 + +코드와 테스트가 대조하는 정본이다. 바꾸면 공개 계약이 바뀔 수 있다(`work/README.md` 2절). + +| 폴더 | 무엇 | +| --- | --- | +| `registries/` | 레지스트리: env 키, 오류 코드, 메트릭, HTTP 헤더, 로그(MDC) 키, 비밀 분류, use case capability, 객체 저장소 준비도. 테스트가 코드와 대조한다 | +| `web/` | HTTP wire 계약(`web/http-contract.md`), PATCH·스트리밍 계약, 선택형 web 기능(`web-advanced`), web 장애 대응 | +| `architecture/` | 공개 API 표면 스냅숏(`*-api-surface.txt`). API surface 검사가 대조한다 | +| `security/` | 기본 공개 경로 스냅숏. `verifyPublicPathSnapshot`이 대조한다 | +| `observability/` | 구조화 로그 필드 사전 | +| `compatibility/` | gRPC 플랫폼 지원 매트릭스(무엇에 대해 인증했고 무엇은 지켜보기만 하나) | + +### 영역 운영 문서 + +capability(부가 기능) 하나의 지원 범위, 설정, 보안, 운영, 마이그레이션이다. 코드와 같은 변경에서 고친다. +`httpclient/`는 `scripts/verify-httpclient-docs.py`가 코드에서 뽑은 이름과 대조한다. + +| 폴더 | 무엇 | +| --- | --- | +| `fileserver/` | 파일 서버 | +| `httpclient/` | 외부 HTTP 호출(HTTP client 플랫폼) | +| `jpa/` | JPA·PostgreSQL 영속성 | +| `messaging/` | 메시징 adapter | +| `mongodb/` | MongoDB 문서 영속성 | +| `mongodb/advanced/` | MongoDB 고급 기능(암호화, 멀티 테넌시, 샤딩). 설정 키가 아니라 라이브러리 API로 켠다 | +| `mongodb/runbooks/` | MongoDB 장애 대응 | +| `mongo/` | MongoDB 영속성 설정 예시 파일(Spring이 읽지 않는 예시) | +| `notification/` | 알림 전달 플랫폼 | +| `objectstorage/` | 객체 저장소의 설정 필드와 env 이름 표(`env-fields.yaml`) | +| `redis/` | Redis 캐시·세션 | +| `websocket/` | WebSocket handler 장애 대응 | + +### 운영과 전달 + +| 폴더 | 무엇 | +| --- | --- | +| `runbooks/` | 오류 코드별 장애 대응 런북(`runbooks/template.md` 형식) | +| `ci-cd/` | CI/CD 경계: 검증·빌드(CI)와 배포(CD)의 경계, 템플릿과 파생 서비스가 각각 돌릴 검증 | +| `upgrade/` | 파생 서비스용 변경 안내: 템플릿 변경을 받을 때 서비스가 할 일 | +| `roadmap/` | 아직 구현하지 않은 다음 단계와 그 조건 | + +### 결정 기록 + +| 폴더 | 무엇 | +| --- | --- | +| `adr/` | 결정 기록(ADR). 영역마다 파일 이름 앞머리가 다르다(`ADR-JPA-`, `NOTIF-ADR-` 등) | + +### 설계와 기록 설계서와 기록은 쓴 때의 글이다. 지금 동작을 설명하지 않는다. 그래서 살아 있는 문서와 다른 폴더에 둔다. -| 디렉터리 | 대상 | +| 폴더 | 무엇 | | --- | --- | | `design/` | 설계서. `YYYY-MM-DD-<주제>-design.md` | | `history/plans/` | 구현·확장 계획서. `YYYY-MM-DD-<주제>-plan.md` | | `history/packages/` | 외부에서 납품된 설계 패키지의 README와 정적 검증 결과 | | `history/evidence/` | 작업 단계별 증거·체크포인트 | | `history/study/` | 학습 문서. 쓴 때의 코드를 따라 읽은 기록이다 | +| `reviews/` | 코드 리뷰 결과. 라운드마다 폴더 하나(README가 결정과 남은 것을 적는다) 또는 리뷰 문서 하나 | -`history/packages/<어댑터>/` 는 설계서가 처음 전달됐을 때의 안내와 `VALIDATION.md` 검증 이력을 -남긴 기록 보관소다. 설계서·계획서 본문은 전부 `design/` 과 `history/plans/` 에 있으므로 이 디렉터리에서 +`history/packages/<어댑터>/`는 설계서가 처음 전달됐을 때의 안내와 `VALIDATION.md` 검증 이력을 +남긴 기록 보관소다. 설계서·계획서 본문은 전부 `design/`과 `history/plans/`에 있으므로 이 폴더에서 문서를 찾을 필요는 없다. 각 README 상단의 보존 안내가 무엇이 옮겨졌고 무엇이 제거됐는지 밝힌다. -`history/packages/*-superpowers-package/` 셋은 납품된 묶음 그대로이고, 그 안의 `MANIFEST.sha256` 은 +`history/packages/*-superpowers-package/` 셋은 납품된 묶음 그대로이고, 그 안의 `MANIFEST.sha256`은 납품 당시 바이트의 해시다. 계획서 본문에는 당시 계획한 경로와 명령이 그대로 남아 있다. 그중 일부는 실제 구현에서 다른 위치로 조정됐고, 저장소에 어떻게 대응시켰는지는 각 어댑터의 `repository-adaptation.md` 또는 -`module-mapping.md` 가 기록한다. 계획서를 사후에 고치지 않는 이유는 그렇게 하면 계획의 기록이 아니라 +`module-mapping.md`가 기록한다. 계획서를 나중에 고치지 않는 이유는 그렇게 하면 계획의 기록이 아니라 결과를 계획처럼 보이게 만든 글이 되기 때문이다. +### 폴더 밖 문서 + +| 문서 | 무엇 | +| --- | --- | +| [capability-status.md](capability-status.md) | capability마다 코드가 있나·조립되나·실제 제공자로 검증됐나, 그리고 지운 코드의 표(「제거된 코드」) | +| [storage-capability-boundary.md](storage-capability-boundary.md) | 파일 서버와 객체 저장소가 각각 맡는 경계 | + ## 문서 수명과 언어 규칙의 정본은 design-docs `conventions/docs-system.md`다. 이 절은 이 repo에 적용한 내용이고, @@ -63,17 +110,19 @@ | 수명 | 문서 | 위치 | 언어 | 고치는 법 | | --- | --- | --- | --- | --- | | 살아 있음 | README, `CLAUDE.md`, `AGENTS.md`, 매뉴얼(`manual/`, `work/`), 영역 운영 문서, `registries/`, `runbooks/`, `upgrade/` | 제자리 | 한국어 | 코드와 같은 변경에서 고친다 | -| 결정 | 결정 기록(ADR) | `adr/`, `notification/adr/` | 한국어 | 본문은 고치지 않는다. 일부가 바뀌면 상태를 「채택(보완)」으로 하고 보완 절을 덧붙인다. 크게 바뀌면 새 ADR을 쓰고 옛 ADR을 「대체됨」으로 한다 | +| 결정 | 결정 기록(ADR) | `adr/` | 한국어 | 본문은 고치지 않는다. 일부가 바뀌면 상태를 「채택(보완)」으로 하고 보완 절을 덧붙인다. 크게 바뀌면 새 ADR을 쓰고 옛 ADR을 「대체됨」으로 한다 | | 기록 | 설계서, 계획서, 납품 패키지, 증거, 학습 문서, 리뷰 | `design/`, `history/`, `reviews/` | 머리 블록은 한국어, 본문은 쓴 때의 원문 | 머리 블록의 칸만 고친다 | - 코드 식별자, 명령, 경로, 설정 키, 오류 코드, 로그·출력 인용, 제품 이름은 원문으로 둔다. - 문체는 「~한다」다. 한 문서 안에서 「~합니다」와 섞지 않는다. -- 아직 한국어로 옮기지 않은 살아 있는 문서와 ADR은 문서 검사의 예외 목록에 있다(「문서 검사」). +- 살아 있는 문서와 ADR 본문은 2026-11-07에 모두 한국어로 옮겼다. 문서 검사의 예외 목록은 비어 있다(「문서 검사」). +- ADR 본문의 번역은 뜻을 바꾸지 않은 옮김이다. 옮기기 전 원문은 커밋 `03a313ed`에 있다(알림 ADR은 그때 다른 + 폴더에 있었다. 옛 경로는 `docs/upgrade/2026-11-docs-records.md`). ## 기록 문서의 머리 블록 -`design/`, `history/`, `adr/`, `notification/adr/`의 `.md` 파일은 맨 위에 이 블록을 둔다. -블록을 빼면 원문 그대로다(옮길 때 깨진 상대 링크의 대상만 고쳤다). +`design/`, `history/`, `adr/`의 `.md` 파일은 맨 위에 이 블록을 둔다. +블록을 빼면 원문 그대로다(옮길 때 깨진 상대 링크의 대상만 고쳤다). ADR만은 본문을 한국어로 옮겼다(「문서 수명과 언어」). ```text @@ -118,11 +167,12 @@ - 숫자·버전을 복사하지 않는다. Spring Boot 버전은 `src/gradle/libs.versions.toml`, leaf 목록과 개수는 registry(`src/config/architecture/modules.json`)를 가리킨다. - 루트 README는 「프로젝트 구조」(최상위 폴더와 `src/` 폴더가 하는 일)와 「문서 지도」(매뉴얼·계약·운영·결정·기록이 - 어디 있나) 절을 반드시 둔다. 전체 절 목록과 순서는 design-docs `conventions/docs-system.md` 6절이다. + 어디 있나) 절을 반드시 둔다. 전체 절 목록과 순서의 정본은 design-docs `conventions/docs-system.md` 6.1절이고, + `readme` 검사가 그 목록(`scripts/check-docs.py`의 `README_SECTIONS`)을 본다. ## 문서 검사 -`python3 scripts/check-docs.py`가 위 규칙 중 기계로 볼 수 있는 넷을 본다. PR마다 workflow `docs-check`가 +`python3 scripts/check-docs.py`가 위 규칙 중 기계로 볼 수 있는 여섯을 본다. PR마다 workflow `docs-check`가 돌리고, 하나라도 걸리면 실패한다. 경로 필터가 없다: 코드에서 파일이나 Gradle 프로젝트를 지우는 변경이 문서를 낡게 만든다. @@ -131,14 +181,20 @@ | `language` | 살아 있는 문서와 ADR 본문이 한국어인가(코드·명령·경로·인용은 세지 않는다) | | `head` | 기록과 ADR 맨 위의 머리 블록: 칸, 상태 어휘, 날짜, 한국어 요약, 현재 정본·대체됨 경로가 있는지 | | `reference` | 살아 있는 문서의 인라인 코드 안 경로(`src/`, `docs/`, `scripts/`, `compose/`, `.github/`로 시작하는 것과 지운 infra 폴더 아래 경로)와 Gradle 경로가 지금 트리·registry에 있는가. 코드 블록, `> 이력` 인용 블록, 제거 표, `upgrade/`는 보지 않는다 | -| `number` | 살아 있는 문서가 Spring Boot 버전이나 leaf 개수를 복사했는가 | +| `number` | 살아 있는 문서가 Spring Boot 버전이나 leaf 개수를 복사했는가. Spring Boot 버전은 이름 바로 뒤(「Spring Boot」나 「Boot」 뒤의 세 자리 버전), `Spring Boot` 칸이 있는 표 행의 세 자리 버전, 정본(`src/gradle/libs.versions.toml`의 `springBoot`)과 같은 버전 문자열(굵은 글씨·표 칸·코드 안 포함)을 잡는다. 결정 기록, 제거 표, `upgrade/`는 보지 않는다 | +| `map` | 이 README의 「문서 지도」가 `docs/` 아래 모든 폴더를 덮는가(표 첫 칸의 `폴더/`). 파일 없이 폴더만 가진 묶음 폴더(`history/`)는 그 바로 아래 폴더가 대신한다. 지도에 있지만 없는 폴더도 실패다 | +| `readme` | 루트 README가 첫 줄 제목, 그 아래 한 문단, 정해진 `##` 절을 정해진 순서로 가지는가 | - 하나만 돌리기: `python3 scripts/check-docs.py --only head`. +- 소스 세트의 resources 폴더 아래 `.md`(`src/**/src/<세트>/resources/`)는 테스트가 읽는 입력이라 문서로 보지 않는다. - 예외 목록 `scripts/check-docs-exceptions.txt`는 2026-11-07의 기준선이고 줄기만 한다. 문서를 번역하거나 고쳐서 더는 걸리지 않으면 그 줄을 지운다(남겨 두면 실패한다). 목록에 새 줄을 더하면 실패한다. 기준선을 늘리는 것은 규칙을 바꾸는 일이라 소유자 결정이 필요하다. +- 줄을 지우면 같은 변경에서 `scripts/check-docs.py`의 `FROZEN`에서 그 줄의 지문도 뺀다. 남겨 두면 실패한다(남은 + 지문은 지운 줄을 다시 더하는 길이다). 2026-11-07 번역 단계에서 목록과 `FROZEN`이 모두 비었다. - 검사 자신의 시험: `python3 -m unittest discover -s scripts/tests`. -- 마크다운 상대 링크는 이 검사가 아니라 lychee(`link-check` workflow)와 `scripts/check-work-docs.py --links`가 본다. +- 마크다운 링크는 이 검사가 아니라 lychee(`link-check` workflow)와 `scripts/check-work-docs.py --links`가 본다. + 기록 안의 외부 링크가 죽어도 기록 본문은 고치지 않는다. 그 URL을 저장소 루트의 `.lycheeignore`에 더한다. ## 여기에 없는 것 diff --git a/docs/adr/ADR-BUILD-001-one-convention-for-shared-test-code.md b/docs/adr/ADR-BUILD-001-one-convention-for-shared-test-code.md index 2e109b0a..e2292be7 100644 --- a/docs/adr/ADR-BUILD-001-one-convention-for-shared-test-code.md +++ b/docs/adr/ADR-BUILD-001-one-convention-for-shared-test-code.md @@ -7,122 +7,110 @@ - 현재 정본: `src/build-logic/README.md` -# ADR-BUILD-001: `java-test-fixtures` is the standard for shared test code +# ADR-BUILD-001: 공유 시험 코드의 표준은 `java-test-fixtures`다 -- Status: Accepted -- Date: 2026-09-07 -- Scope: every leaf that publishes or consumes shared test code -- Source: `docs/reviews/2026-09-07-app-bootstrap-module-code-review.md` BOOT-015 +- 상태: 채택 +- 날짜: 2026-09-07 +- 범위: 공유 시험 코드를 내놓거나 쓰는 모든 leaf +- 출처: `docs/reviews/2026-09-07-app-bootstrap-module-code-review.md` BOOT-015 -## Context +## 배경 -Two conventions do the same job in this repository. +이 저장소에서 같은 일을 하는 규약이 둘 있다. -`ca.testkit-publisher` — a convention plugin — gives a leaf a `testkit` source set, wires its output -onto the lanes that leaf names, and optionally publishes it as a consumable configuration. Five -leaves use it: `persistence-jpa` (published as `jpaTestkit`), `web` (`webTestkit`), `websocket` -(`websocketTestkit`), `persistence-mongo` and `httpclient` (both unpublished). +`ca.testkit-publisher` — 규약 플러그인 — 는 leaf에 `testkit` source set을 주고, 그 출력을 leaf가 이름을 댄 lane에 +배선하고, 원하면 쓸 수 있는 configuration으로 내놓는다. 다섯 leaf가 쓴다: `persistence-jpa`(`jpaTestkit`으로 내놓음), +`web`(`webTestkit`), `websocket`(`websocketTestkit`), `persistence-mongo`와 `httpclient`(둘 다 내놓지 않음). -`java-test-fixtures` — Gradle's own plugin — gives a leaf a `testFixtures` source set, puts it on -`test`'s classpath automatically, and always publishes it as a variant consumers reach with -`testFixtures(project(':x'))`. One leaf uses it: `graphql`, which additionally fails its build when a -fixture is written outside `src/testFixtures/java`. +`java-test-fixtures` — Gradle 자신의 플러그인 — 는 leaf에 `testFixtures` source set을 주고, 그것을 `test`의 +classpath에 자동으로 올리고, 쓰는 쪽이 `testFixtures(project(':x'))`로 닿는 variant로 언제나 내놓는다. 한 leaf가 +쓴다: `graphql`. 이 leaf는 fixture를 `src/testFixtures/java` 밖에 쓰면 빌드를 실패시키기도 한다. -Two conventions for one purpose is the defect. A contributor adding shared test code has to know -which leaf they are in before they know where the file goes, and the two answers are not -interchangeable: a consumer of the first writes `project(path: ':x', configuration: 'jpaTestkit')` -and has to know the configuration's name, while a consumer of the second writes -`testFixtures(project(':x'))` and does not. +한 목적에 규약 둘이 있는 것이 결함이다. 공유 시험 코드를 더하는 사람은 파일을 어디 둘지 알기 전에 자기가 어느 +leaf에 있는지 알아야 하고, 두 답은 서로 바꿔 쓸 수 없다: 첫째를 쓰는 쪽은 +`project(path: ':x', configuration: 'jpaTestkit')`를 쓰고 configuration 이름을 알아야 하지만, 둘째를 쓰는 쪽은 +`testFixtures(project(':x'))`를 쓰고 그럴 필요가 없다. -## Decision +## 결정 -**`java-test-fixtures` is the standard.** New shared test code goes in `src/testFixtures/java`, and a -consumer depends on it with `testFixtures(project(':x'))`. +**`java-test-fixtures`가 표준이다.** 새 공유 시험 코드는 `src/testFixtures/java`에 두고, 쓰는 쪽은 +`testFixtures(project(':x'))`로 의존한다. -Three reasons, in order of weight: +이유 셋, 무게 순으로: -1. **The consumer side describes itself.** `testFixtures(project(':adapter:inbound:web'))` says what - it is. `project(path: ':adapter:inbound:web', configuration: 'webTestkit')` says where to look, - and only after the reader has learned that `webTestkit` is a testkit rather than a lane. -2. **The enforcement already exists and is copyable.** `graphql`'s build fails when a fixture is - declared in the wrong place. The same guard applies unchanged to any leaf that adopts the plugin. -3. **It is one fewer local concept.** A convention plugin that reimplements a Gradle plugin has to be - maintained against it. +1. **쓰는 쪽이 스스로를 설명한다.** `testFixtures(project(':adapter:inbound:web'))`는 그것이 무엇인지 말한다. + `project(path: ':adapter:inbound:web', configuration: 'webTestkit')`는 어디를 볼지 말하고, 읽는 사람이 + `webTestkit`이 lane이 아니라 testkit임을 배운 뒤에야 뜻이 통한다. +2. **강제 장치가 이미 있고 복사할 수 있다.** `graphql`의 빌드는 fixture를 엉뚱한 곳에 선언하면 실패한다. 같은 + guard를 플러그인을 쓰는 어느 leaf에든 바꾸지 않고 적용한다. +3. **지역 개념이 하나 준다.** Gradle 플러그인을 다시 구현한 규약 플러그인은 그 플러그인에 맞춰 계속 관리해야 한다. -## What the local plugin does better, and how it is replaced +## 지역 플러그인이 더 잘하는 것과 그것을 대신하는 방법 -This is worth writing down, because the review that prompted this ADR recommended the migration -before reading `ca.testkit-publisher`, and the plugin turns out to encode two deliberate decisions -rather than being an oversight. +이것은 적어 둘 만하다. 이 ADR을 낳은 리뷰는 `ca.testkit-publisher`를 읽기 전에 옮기기를 권했고, 읽어 보니 그 +플러그인은 빠뜨린 것이 아니라 일부러 정한 결정 둘을 담고 있었다. -**Publishing is opt-in.** `persistence-mongo` and `httpclient` have a testkit and publish nothing; -`persistence-jpa` publishes. The plugin's own comment names this as "a real difference in what each -leaf offers rather than an oversight to normalise away". `java-test-fixtures` always creates the -variant, so the distinction is lost — a leaf that never meant to offer its fixtures will offer them. +**내놓기는 고를 때만 한다.** `persistence-mongo`와 `httpclient`는 testkit이 있지만 아무것도 내놓지 않는다. +`persistence-jpa`는 내놓는다. 플러그인 자신의 주석이 이것을 "a real difference in what each leaf offers rather than +an oversight to normalise away"(각 leaf가 주는 것의 실제 차이이지, 맞춰 없앨 빠뜨림이 아니다)라고 부른다. +`java-test-fixtures`는 언제나 variant를 만드니 이 구별이 사라진다 — fixture를 줄 생각이 없던 leaf도 주게 된다. -> Replacement: none at the build level. The distinction moves to review: the fixtures of a leaf that -> nobody consumes are simply unconsumed. This is a real, accepted loss. +> 대신하는 것: 빌드 수준에서는 없다. 구별은 리뷰로 옮긴다: 아무도 쓰지 않는 leaf의 fixture는 그냥 쓰이지 않는다. +> 실제 손실이고, 받아들인 손실이다. -**Lane consumption is declared.** `persistence-jpa` says `consumedBy 'test', 'postgresqlIntegrationTest'`. -`java-test-fixtures` puts fixtures on `test` only, so every other lane needs the output added -explicitly. +**lane이 쓰는 것을 선언한다.** `persistence-jpa`는 `consumedBy 'test', 'postgresqlIntegrationTest'`라고 말한다. +`java-test-fixtures`는 fixture를 `test`에만 올리니, 다른 모든 lane에는 출력을 명시해서 더해야 한다. -> Replacement: `strictTestLanes`' existing `compilesAgainst` expresses this unchanged — a lane -> declares `compilesAgainst 'main', 'testFixtures'`. The first draft of this ADR assumed the DSL -> would need a change, because `sourceSet(name)` creates what it is given and `testFixtures` already -> exists. The `persistence-mongo` migration showed otherwise: `compilesAgainst` only *looks a source -> set up*, so naming a plugin-created one works as-is. What the leaf drops is the -> `sourceSet('testkit')` declaration, not the lane's. +> 대신하는 것: `strictTestLanes`의 기존 `compilesAgainst`가 바꾸지 않고 이것을 나타낸다 — lane이 +> `compilesAgainst 'main', 'testFixtures'`를 선언한다. 이 ADR의 첫 초안은 DSL을 바꿔야 한다고 가정했다. +> `sourceSet(name)`은 받은 것을 만들고 `testFixtures`는 이미 있기 때문이다. `persistence-mongo`를 옮겨 보니 아니었다: +> `compilesAgainst`는 source set을 *찾기만* 하므로, 플러그인이 만든 것의 이름을 대도 그대로 된다. leaf가 버리는 것은 +> lane의 선언이 아니라 `sourceSet('testkit')` 선언이다. -## Migration: done, and what it cost +## 옮기기: 끝났고, 든 비용 -Five leaves, eleven lanes, two published testkits, all migrated leaf by leaf with the suite run -between each. `ca.testkit-publisher` is deleted. +leaf 다섯, lane 열하나, 내놓은 testkit 둘을 leaf 하나씩, 그 사이마다 suite를 돌리며 모두 옮겼다. +`ca.testkit-publisher`는 지웠다. -The order was chosen so a mistake would be cheap: unpublished leaves first, published ones last with -their consumer in the same step. +순서는 실수가 싸게 끝나도록 골랐다: 내놓지 않는 leaf를 먼저, 내놓는 leaf를 마지막에 그 쓰는 쪽과 같은 단계에서. -1. `persistence-mongo` — one leaf, two lanes, no cross-module consumer; the proof the path works. - What it took, per leaf: - - `apply plugin: 'java-test-fixtures'` at the top of the leaf build file; +1. `persistence-mongo` — leaf 하나, lane 둘, 다른 모듈의 쓰는 쪽 없음. 길이 되는지 보는 증명이다. + leaf마다 든 일: + - leaf 빌드 파일 맨 위에 `apply plugin: 'java-test-fixtures'`; - `git mv src/testkit src/testFixtures`; - - drop `sourceSet('testkit')` and the whole `testkitPublisher` block; keep every other lane's - `compilesAgainst`, renaming `'testkit'` to `'testFixtures'`; - - rename `testkitImplementation` to `testFixturesImplementation`, **and add what the old source - set was inheriting silently**. This is the one non-mechanical step: `testkit*` extended - `testImplementation`, so the fixtures saw every test library the leaf declared. Mongo's needed - four more lines (AssertJ, BSON, Spring Data commons, Toxiproxy) — none of which the leaf had - ever stated the fixtures depended on; - - regenerate the leaf's lock state. -2. `httpclient`, then `websocket` — unpublished as well, more lanes. -3. `web` and `persistence-jpa` with `app-bootstrap`'s two consumer declarations, which became - `testImplementation(testFixtures(project(':…')))`. -4. `ca.testkit-publisher` deleted, along with its `plugins {}` entry and its application in the root - build. + - `sourceSet('testkit')`와 `testkitPublisher` 블록 전체를 버린다. 다른 모든 lane의 `compilesAgainst`는 두고 + `'testkit'`을 `'testFixtures'`로 이름을 바꾼다; + - `testkitImplementation`을 `testFixturesImplementation`으로 이름을 바꾸고, **옛 source set이 소리 없이 + 물려받던 것을 더한다**. 기계적이지 않은 단계는 이것 하나다: `testkit*`는 `testImplementation`을 상속해서, + fixture가 leaf가 선언한 모든 시험 라이브러리를 봤다. Mongo는 네 줄(AssertJ, BSON, Spring Data commons, + Toxiproxy)이 더 필요했다 — leaf가 fixture의 의존으로 적은 적이 한 번도 없는 것들이다; + - leaf의 잠금 상태를 다시 만든다. +2. `httpclient`, 그다음 `websocket` — 역시 내놓지 않고, lane이 더 많다. +3. `web`과 `persistence-jpa`, 그리고 `app-bootstrap`의 쓰는 쪽 선언 둘. 그 선언은 + `testImplementation(testFixtures(project(':…')))`가 됐다. +4. `ca.testkit-publisher`를 지웠다. 그 `plugins {}` 항목과 루트 빌드의 적용도 함께. -### Two things the migration broke, and what they taught +### 옮기기가 깨뜨린 것 둘과 그것이 가르친 것 -Both were caught by tests that exist to catch exactly this, which is the argument for having them. +둘 다 바로 이것을 잡으려고 있는 시험이 잡았다. 그런 시험을 둘 이유가 그것이다. -**ArchUnit corpora went wrong in opposite directions.** `httpclient`'s boundary rules *excluded* -`build/classes/java/testkit`; after the move the fixtures arrived as a `…-test-fixtures.jar` on the -same classpath, so the exclusion missed them and 258 fixture-to-fixture calls were reported as -production depending on the testkit. `persistence-jpa`'s rules *included* only -`build/classes/java/main`; applying `java-test-fixtures` makes the module's own test classpath carry -the module as a **jar** rather than as a class directory, so its corpus became empty. The second is -the dangerous one — an empty corpus makes every `noClasses()` rule pass — and it surfaced only -because that suite asserts its corpus is non-empty before asserting anything about it. +**ArchUnit 대상 묶음이 반대 방향으로 틀어졌다.** `httpclient`의 경계 규칙은 `build/classes/java/testkit`을 +*뺐다*. 옮긴 뒤 fixture는 같은 classpath에 `…-test-fixtures.jar`로 들어왔고, 그래서 빼기가 그것을 놓쳤으며 +fixture 사이 호출 258개가 운영 코드가 testkit에 의존한다고 보고됐다. `persistence-jpa`의 규칙은 +`build/classes/java/main`만 *넣었다*. `java-test-fixtures`를 적용하면 모듈 자신의 시험 classpath가 모듈을 class +디렉터리가 아니라 **jar**로 싣는다. 그래서 대상 묶음이 비었다. 위험한 쪽은 둘째다 — 빈 묶음이면 모든 +`noClasses()` 규칙이 통과한다 — 그리고 그 suite가 무엇이든 단언하기 전에 묶음이 비어 있지 않음을 단언했기 +때문에만 드러났다. -**Fixtures had invisible dependencies.** `testkit*` configurations extended `testImplementation`, so -the fixtures compiled against every test library their leaf declared without ever naming one. Making -them explicit took roughly thirty `testFixturesImplementation` lines across the five leaves — -Micrometer, Spring Web, Netty, logback, Jackson, JUnit, AssertJ, Spring Data. None of them were -wrong; none of them were stated. +**fixture에 보이지 않는 의존이 있었다.** `testkit*` configuration은 `testImplementation`을 상속해서, fixture는 이름 +한 번 대지 않고 leaf가 선언한 모든 시험 라이브러리에 대고 컴파일됐다. 그것을 명시하는 데 다섯 leaf에 걸쳐 +`testFixturesImplementation` 줄이 대략 서른 개 들었다 — Micrometer, Spring Web, Netty, logback, Jackson, JUnit, AssertJ, +Spring Data. 틀린 것은 없었다. 적힌 것도 없었다. -## Consequences +## 결과 -- `docs/testing/TESTING_STRATEGY.md` §5 records the standard; this ADR records why and at what cost. -- Until step 5, two conventions remain visible. The strategy document says so explicitly, so a - contributor reading it is not left to infer which one is current. -- The opt-in-publishing distinction is given up. If it later proves load-bearing — a leaf whose - fixtures genuinely must not be reachable — the answer is a separate module, not a third convention. +- `docs/testing/TESTING_STRATEGY.md` §5가 표준을 적는다. 이 ADR은 왜, 어떤 비용으로인지를 적는다. +- 5단계까지는 규약 둘이 보이는 채로 남는다. 전략 문서가 그것을 분명히 말하므로, 읽는 사람이 어느 것이 지금 + 것인지 짐작하게 두지 않는다. +- 고를 때만 내놓는 구별은 포기한다. 나중에 그것이 꼭 필요한 것으로 드러나면 — fixture에 정말 닿으면 안 되는 + leaf — 답은 세 번째 규약이 아니라 따로 둔 모듈이다. diff --git a/docs/adr/ADR-GQL-001-graphql-context-and-storage-ownership.md b/docs/adr/ADR-GQL-001-graphql-context-and-storage-ownership.md index 57af5bc7..d228397c 100644 --- a/docs/adr/ADR-GQL-001-graphql-context-and-storage-ownership.md +++ b/docs/adr/ADR-GQL-001-graphql-context-and-storage-ownership.md @@ -7,73 +7,63 @@ - 현재 정본: `src/adapter/inbound/graphql/README.md` -# ADR-GQL-001 — GraphQL context stays inbound; object authorization moves to application-core; the persisted-operation store stays an inbound SPI +# ADR-GQL-001 — GraphQL 문맥은 inbound에 머물고, 객체 인가는 application-core로 옮기며, persisted operation 저장소는 inbound SPI로 남는다 -- Status: Accepted -- Date: 2026-08-24 -- Review: `docs/reviews/2026-08-14-graphql-module-code-review.md` GQL-026 +- 상태: 채택 +- 날짜: 2026-08-24 +- 리뷰: `docs/reviews/2026-08-14-graphql-module-code-review.md` GQL-026 -## Context +## 배경 -The GraphQL leaf's own documentation described three things crossing its boundary: a -`GraphQlRequestContext` with a deadline propagated into application, JPA, Mongo and the HTTP client; -object authorization decided inside the transport; and a persisted-operation registry implemented by -an external durable store. +GraphQL leaf 자신의 문서는 경계를 넘는 것 셋을 적었다: application, JPA, Mongo, HTTP client로 deadline을 전파하는 +`GraphQlRequestContext`, 전송 계층 안에서 정하는 객체 인가, 외부 durable 저장소가 구현하는 persisted operation +registry. -Two of those invert the dependency direction. If `application-core` or an outbound adapter -implements a type that lives in `adapter:inbound:graphql`, the registry edge that says inbound -depends on application is satisfied while the real compile-time dependency runs the other way. +그중 둘은 의존 방향을 뒤집는다. `application-core`나 outbound 어댑터가 `adapter:inbound:graphql`에 있는 타입을 +구현하면, inbound가 application에 의존한다는 registry edge는 만족되지만 실제 컴파일 의존은 반대로 간다. -The third is a business rule in the wrong layer: whether an actor may see an object is a decision -about the domain, and GraphQL is one of four transports this skeleton ships. +셋째는 엉뚱한 계층의 업무 규칙이다: actor가 객체를 볼 수 있는지는 도메인에 대한 판단이고, GraphQL은 이 골격이 +싣는 전송 계층 넷 중 하나다. -## Decision +## 결정 -Three different answers, because the three problems are not the same problem. +세 문제가 같은 문제가 아니므로 답도 셋이다. -**GraphQL context stays inbound-local.** It is mapped explicitly onto application command fields — -actor, tenant, deadline — rather than travelling as a type. Nothing outside the leaf references -`GraphQlRequestContext`, and the boundary test is that grep returns nothing outside it. +**GraphQL 문맥은 inbound 안에 머문다.** 타입으로 실려 다니지 않고 application command 필드 — actor, tenant, +deadline — 로 명시해 대응시킨다. leaf 밖의 어떤 것도 `GraphQlRequestContext`를 참조하지 않고, 경계 시험은 leaf +밖에서 grep이 아무것도 돌려주지 않는 것이다. -**Object authorization moves to `application-core`.** `ObjectAccessPolicy`, `ObjectAccessRequest` -and `ObjectAccessDecision` are transport-neutral and live with the other application policies; -`ApplicationObjectAuthorization` in the GraphQL leaf is the bridge that calls them. This is the one -of the three that was a real layering defect, and it is fixed rather than documented. +**객체 인가는 `application-core`로 옮긴다.** `ObjectAccessPolicy`, `ObjectAccessRequest`, `ObjectAccessDecision`은 +전송 중립이고 다른 애플리케이션 정책과 함께 있다. GraphQL leaf의 `ApplicationObjectAuthorization`이 그것을 부르는 +다리다. 셋 중 이것이 실제 계층 결함이었고, 적어 두지 않고 고친다. -**The persisted-operation store stays an inbound-owned SPI.** `GraphQlPersistedOperationRegistry` -remains in `advanced/persisted`, and no leaf outside GraphQL implements it. +**persisted operation 저장소는 inbound가 가진 SPI로 남는다.** `GraphQlPersistedOperationRegistry`는 +`advanced/persisted`에 남고, GraphQL 밖의 어떤 leaf도 그것을 구현하지 않는다. -## Consequences +## 결과 -The third decision is the one that needs defending, because it leaves the reported risk in place -rather than removing it. +변호가 필요한 것은 셋째 결정이다. 보고된 위험을 없애지 않고 그 자리에 두기 때문이다. -The risk is conditional: the direction inverts only when something outside the leaf implements the -interface. Nothing does. The template ships an in-memory registry and no durable one, because it -ships no persisted-operation store at all. +위험은 조건부다: leaf 밖의 무엇이 그 인터페이스를 구현할 때만 방향이 뒤집힌다. 그런 것은 없다. 템플릿은 메모리 +registry를 싣고 durable registry는 싣지 않는다. persisted operation 저장소를 아예 싣지 않기 때문이다. -The alternative was to introduce a generic operational key-value store port owned by a neutral -contract holder, with the GraphQL adapter owning only the key and value mapping. That port would -have exactly one interface, zero implementations and one speculative consumer — a new abstraction -whose shape is guessed from a requirement nobody has stated. This repository has spent a full -remediation pass deleting controls that existed and were reached by nothing, and inventing a port -for a store that does not exist is how the next one of those gets written. +대안은 중립 계약 보유자가 가진 범용 운영 key-value 저장소 포트를 들이고, GraphQL 어댑터는 키와 값 대응만 가지는 +것이었다. 그 포트는 인터페이스 정확히 하나, 구현 0개, 짐작으로 정한 쓰는 쪽 하나를 가졌을 것이다 — 아무도 말하지 +않은 요구에서 모양을 짐작한 새 추상이다. 이 저장소는 있었지만 아무것도 닿지 않던 통제를 지우는 데 수정 한 바퀴를 +통째로 썼다. 없는 저장소를 위해 포트를 지어내는 것이 그런 것을 다음에 또 쓰는 길이다. -So the decision is to leave the SPI where it is and to move it when a durable store is actually -built. Moving it then is a rename across one leaf and one new adapter, which is cheaper than -carrying a wrong abstraction until then. What must not happen in the meantime is an outbound leaf -implementing the inbound interface, because that is the moment the direction actually inverts, and -it would happen in a commit whose diff looks like an implementation rather than a layering change. +그래서 결정은 SPI를 있는 곳에 두고, durable 저장소를 실제로 만들 때 옮기는 것이다. 그때 옮기는 일은 leaf 하나와 +새 어댑터 하나에 걸친 이름 바꾸기이고, 그때까지 틀린 추상을 끌고 다니는 것보다 싸다. 그동안 일어나면 안 되는 것은 +outbound leaf가 inbound 인터페이스를 구현하는 것이다. 그때가 방향이 실제로 뒤집히는 순간이고, 그것은 계층 변경이 +아니라 구현처럼 보이는 diff의 커밋에서 일어날 것이다. -The composition root wires these and owns no business or storage policy of its own. +조립 루트가 이것들을 배선하고, 자기 업무·저장 정책은 가지지 않는다. -## Enforcement +## 강제 -`verifyCleanArchitectureDependencies` and `modules.json` hold the leaf's edges to -`domain-core`, `application-core` and `shared-contract`. `ObjectAccessPolicyTest` covers the -application-side policy and `ApplicationObjectAuthorizationTest` the bridge. +`verifyCleanArchitectureDependencies`와 `modules.json`이 leaf의 `domain-core`, `application-core`, `shared-contract` +edge를 지킨다. `ObjectAccessPolicyTest`가 application 쪽 정책을, `ApplicationObjectAuthorizationTest`가 다리를 덮는다. -The condition this ADR turns on — that nothing outside the GraphQL leaf implements the -persisted-operation SPI — is a claim about the whole repository, so it is checked at the -composition root rather than inside the leaf, next to the other GraphQL boundary rules in -`app-bootstrap`'s architecture suite. +이 ADR이 기대는 조건 — GraphQL leaf 밖의 어떤 것도 persisted operation SPI를 구현하지 않는다 — 은 저장소 전체에 +대한 주장이다. 그래서 leaf 안이 아니라 조립 루트에서, `app-bootstrap` architecture suite의 다른 GraphQL 경계 규칙 +옆에서 검사한다. diff --git a/docs/adr/ADR-GRPC-001-platform-family-and-registry-shape.md b/docs/adr/ADR-GRPC-001-platform-family-and-registry-shape.md index c45ff9c8..617992bf 100644 --- a/docs/adr/ADR-GRPC-001-platform-family-and-registry-shape.md +++ b/docs/adr/ADR-GRPC-001-platform-family-and-registry-shape.md @@ -7,58 +7,51 @@ - 현재 정본: `docs/compatibility/grpc-support-matrix.md` -# ADR-GRPC-001: The gRPC platform ships as a registered family, not as one adapter leaf +# ADR-GRPC-001: gRPC 플랫폼은 adapter leaf 하나가 아니라 등록된 family로 싣는다 -- Status: accepted -- Date: 2026-08-30 -- Scope: `:grpc:*`, `:grpc-advanced:*`, `src/config/architecture/modules.json` +- 상태: 채택 +- 날짜: 2026-08-30 +- 범위: `:grpc:*`, `:grpc-advanced:*`, `src/config/architecture/modules.json` -## Context +## 배경 -The two source plans describe a type-safe gRPC execution platform with its own API, SPI, adapters and -composition root: fifteen Stable modules under `modules/grpc` and sixteen Advanced ones under -`modules/grpc-advanced`, on Gradle Kotlin DSL, in package `io.backend.skeleton.grpc`, against -Spring Boot 4.1. +두 원본 계획은 자기 API, SPI, 어댑터, 조립 루트를 가진 타입 안전 gRPC 실행 플랫폼을 설명한다: `modules/grpc` 아래 +Stable 모듈 열다섯과 `modules/grpc-advanced` 아래 Advanced 모듈 열여섯, Gradle Kotlin DSL, 패키지 +`io.backend.skeleton.grpc`, Spring Boot 4.1 기준. -None of that layout exists here. This repository uses Groovy DSL, a fail-closed module registry that -owns the leaf list, package root `dev.caskeleton`, and Spring Boot 4.0.8. The plans anticipate this: -their last Global Constraint says that when the repository structure differs, file paths are remapped -and the public contracts, invariants and test meanings are not changed. +그 배치는 여기 하나도 없다. 이 저장소는 Groovy DSL, leaf 목록을 가진 실패하면 닫히는 모듈 registry, 패키지 루트 +`dev.caskeleton`, Spring Boot 4.0.8을 쓴다. 계획은 이것을 예상한다: 마지막 Global Constraint가, 저장소 구조가 다르면 +파일 경로를 다시 대응시키고 공개 계약·불변식·시험의 뜻은 바꾸지 않는다고 말한다. -Two shapes were available. Fold the platform into the existing `:adapter:inbound:grpc` leaf as -packages — which is what the JPA, GraphQL, WebSocket and HTTP platforms did here — or register it as -a family the way `messaging:*` is registered. +고를 수 있는 모양은 둘이었다. 플랫폼을 기존 `:adapter:inbound:grpc` leaf에 패키지로 접어 넣기 — JPA, GraphQL, +WebSocket, HTTP 플랫폼이 여기서 그렇게 했다 — 또는 `messaging:*`를 등록한 방식대로 family로 등록하기. -## Decision +## 결정 -Register it as a family: twelve Stable leaves under `src/grpc/` and six Advanced ones under -`src/grpc-advanced/`. +family로 등록한다: `src/grpc/` 아래 Stable leaf 열둘과 `src/grpc-advanced/` 아래 Advanced leaf 여섯. -The deciding property is that this is not a layer of this application. Root `CLAUDE.md` already -describes `messaging:*` as "a vendored messaging platform: a product with its own API, SPI, adapters -and composition boundary, not a layer of this application", and the gRPC platform is the same shape -for the same reason — the application is meant to reach it the way it reaches a library, through an -application-owned port. The four platforms that became packages are all layers of this application; -this one is not. +결정을 가른 성질은 이것이 이 애플리케이션의 계층이 아니라는 점이다. 루트 `CLAUDE.md`는 이미 `messaging:*`를 "a +vendored messaging platform: a product with its own API, SPI, adapters and composition boundary, not a layer of this +application"(들여온 메시징 플랫폼: 자기 API, SPI, 어댑터, 조립 경계를 가진 제품이고 이 애플리케이션의 계층이 +아니다)이라고 설명하고, gRPC 플랫폼은 같은 이유로 같은 모양이다 — 애플리케이션은 라이브러리에 닿듯, 애플리케이션이 +가진 포트를 거쳐 그것에 닿아야 한다. 패키지가 된 네 플랫폼은 모두 이 애플리케이션의 계층이다. 이것은 아니다. -The split between `src/grpc/` and `src/grpc-advanced/` is not organisational. The Stable plan -requires that the Stable starter's build fail if it reaches an Advanced module, and separate Gradle -path prefixes make that a `verifyCleanArchitectureDependencies` failure rather than a review note: -`grpc-spring-boot-starter`'s registry entry names no advanced id, and it cannot acquire one silently. +`src/grpc/`와 `src/grpc-advanced/`의 분리는 정리용이 아니다. Stable 계획은 Stable starter의 빌드가 Advanced 모듈에 +닿으면 실패해야 한다고 요구하고, Gradle 경로 접두어를 따로 두면 그것이 리뷰 메모가 아니라 +`verifyCleanArchitectureDependencies` 실패가 된다: `grpc-spring-boot-starter`의 registry 항목은 advanced id를 하나도 +대지 않고, 소리 없이 얻을 수도 없다. -## Consequences +## 결과 -**The registry grew from 44 leaves to 62.** That is a large registry change, made deliberately and in -one place. Every new leaf is `runtime_memberships: []`, so nothing ships until a second, explicit -decision moves it. +**registry가 leaf 44개에서 62개로 늘었다.** 큰 registry 변경이고, 일부러 한곳에서 했다. 새 leaf는 모두 +`runtime_memberships: []`라서, 두 번째로 명시한 결정이 옮기기 전까지 아무것도 실리지 않는다. -**The advanced boundary is checked twice.** Once by the registry at build time, and once by -`GrpcStableBuildInvariant` at runtime, because a fat jar or a shaded artifact is assembled by -something the registry never sees. +**advanced 경계는 두 번 검사한다.** 빌드 때 registry가 한 번, 런타임에 `GrpcStableBuildInvariant`가 한 번. fat jar나 +shaded artifact는 registry가 보지 못하는 무언가가 조립하기 때문이다. -**Four testkit modules became four test lanes.** The plan's split exists so in-process results cannot -be mistaken for network results; this repository expresses that with `ca.strict-test-lane`, whose -lanes fail when they discover nothing and never serve an up-to-date result. `GrpcEvidenceGrade` keeps -the same rule inside the code, so a report cannot cite a contract run as transport evidence. +**testkit 모듈 넷은 시험 lane 넷이 됐다.** 계획이 나눈 이유는 프로세스 안 결과를 네트워크 결과로 착각하지 못하게 +하려는 것이다. 이 저장소는 그것을 `ca.strict-test-lane`으로 나타낸다. 그 lane은 아무것도 찾지 못하면 실패하고, +up-to-date 결과를 내주지 않는다. `GrpcEvidenceGrade`가 코드 안에서 같은 규칙을 지키므로, 보고서가 계약 실행을 전송 +증거로 인용할 수 없다. -**Codegen is not wired.** See ADR-GRPC-002. +**codegen은 배선하지 않았다.** ADR-GRPC-002를 본다. diff --git a/docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md b/docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md index 82641867..67320b8e 100644 --- a/docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md +++ b/docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md @@ -8,74 +8,65 @@ - 대체됨: `docs/capability-status.md` -# ADR-GRPC-002: Schema governance runs without protoc and without the Buf CLI +# ADR-GRPC-002: schema 관리는 protoc 없이, Buf CLI 없이 돈다 -- Status: **superseded (2026-09-28)** by owner decision 18 of the 2026-09-25 review follow-up -- Date: 2026-08-30 -- Scope: `:grpc:grpc-proto-contract`, `:grpc:grpc-codegen` (both removed) +- 상태: **대체됨(2026-09-28)** — 2026-09-25 리뷰 후속의 소유자 결정 18 +- 날짜: 2026-08-30 +- 범위: `:grpc:grpc-proto-contract`, `:grpc:grpc-codegen`(둘 다 지움) -> **Superseded.** The regex `.proto` validator and the Java re-implementation of Buf's rules were -> deleted. The schema now lives in `:grpc:grpc-contract` (`src/grpc/grpc-contract/src/main/proto`), -> compiled by the Gradle protobuf plugin (`com.google.protobuf`, version pinned in -> `src/gradle/libs.versions.toml`; protoc and the protobuf-java runtime are both `protobufGrpc`). -> Generated sources are excluded from Spotless, Checkstyle and Error Prone in that leaf only. -> `buf lint` and `buf breaking` (`src/grpc/grpc-contract/buf.yaml`, STANDARD lint, FILE breaking) -> run in CI, job `grpc-proto-buf` in `.github/workflows/ci-quality-gates.yml`. The proto organization -> is `caskeleton` (was `hyeonworks`). The text below is kept as the record of the original decision. +> **대체됨.** 정규식 `.proto` 검증기와 Buf 규칙의 Java 재구현은 지웠다. schema는 이제 `:grpc:grpc-contract` +> (`src/grpc/grpc-contract/src/main/proto`)에 있고 Gradle protobuf 플러그인(`com.google.protobuf`, 버전은 +> `src/gradle/libs.versions.toml`에 고정. protoc와 protobuf-java runtime은 둘 다 `protobufGrpc`)이 컴파일한다. 생성된 +> 소스는 그 leaf에서만 Spotless, Checkstyle, Error Prone에서 뺀다. `buf lint`와 `buf breaking` +> (`src/grpc/grpc-contract/buf.yaml`, STANDARD lint, FILE breaking)은 CI의 `.github/workflows/ci-quality-gates.yml` +> job `grpc-proto-buf`에서 돈다. proto organization은 `caskeleton`이다(예전에는 `hyeonworks`). 아래 글은 원래 결정의 +> 기록으로 남긴다. -## Context +## 배경 -Stable Tasks 8 through 11 require proto style rules, Buf format/lint/breaking governance, a single -Java codegen owner, and a descriptor artifact whose consumer-compile result gates a release. +Stable Task 8부터 11은 proto 문체 규칙, Buf format·lint·breaking 관리, Java codegen 소유자 하나, 그리고 쓰는 쪽 +컴파일 결과가 릴리스를 막는 descriptor artifact를 요구한다. -Two of the tools those tasks name are absent from this toolchain. The Buf CLI is not installed. And -`protoc` is available through the Gradle protobuf plugin, but every leaf in this repository passes -spotless with google-java-format, checkstyle, SpotBugs at HIGH confidence, Error Prone and `-Werror` -— and generated protobuf sources pass none of them. Turning codegen on means excluding a source set -from five quality gates. +그 Task가 이름을 대는 도구 중 둘이 이 toolchain에 없다. Buf CLI는 설치돼 있지 않다. 그리고 `protoc`는 Gradle +protobuf 플러그인으로 쓸 수 있지만, 이 저장소의 모든 leaf는 google-java-format을 쓴 spotless, checkstyle, HIGH +confidence의 SpotBugs, Error Prone, `-Werror`를 통과하는데 — 생성된 protobuf 소스는 그중 어느 것도 통과하지 못한다. +codegen을 켜면 source set 하나를 품질 게이트 다섯에서 빼야 한다. -There is precedent for such an exclusion: the `jmh` source set has `spotbugsJmh` and `checkstyleJmh` -disabled and Error Prone off. So the carve-out is available. It is also a decision about the quality -baseline of a leaf, taken for one task, and outside what this work was asked to change. +그런 예외에는 선례가 있다: `jmh` source set은 `spotbugsJmh`와 `checkstyleJmh`를 끄고 Error Prone도 끈다. 그러니 빼는 +길은 있다. 하지만 그것은 Task 하나를 위해 leaf의 품질 기준선에 대해 내리는 결정이고, 이 일이 바꾸라고 받은 범위 +밖이다. -`adapter:inbound:grpc` also carries a recorded decision in the opposite direction: its `CLAUDE.md` -forbids the protobuf plugin and `.proto` in that leaf, on the grounds that a consuming feature module -should own its schema. +`adapter:inbound:grpc`에도 반대 방향으로 기록된 결정이 있다: 그 `CLAUDE.md`는 쓰는 기능 모듈이 자기 schema를 가져야 +한다는 이유로 그 leaf에서 protobuf 플러그인과 `.proto`를 금지한다. -## Decision +## 결정 -Commit the `.proto` sources and implement every rule the tasks require as executable Java, with no -protoc run and no Buf CLI invocation. +`.proto` 소스를 커밋하고, Task가 요구하는 모든 규칙을 protoc 실행도 Buf CLI 호출도 없이 실행되는 Java로 구현한다. -`GrpcProtoContractValidator` reads `.proto` text and enforces proto3 syntax, the -`{organization}.{domain}.v{major}` package rule, `java_multiple_files`, a generated Java package -disjoint from the hand-written one, `_UNSPECIFIED` enum zero values, `reserved` declarations checked -against a supplied removal history, a well-known-type allowlist and a map-field allowlist. It runs -against the committed schema in its own test, so the shipped `.proto` files are live rather than -decorative. +`GrpcProtoContractValidator`는 `.proto` 글을 읽고 다음을 강제한다: proto3 문법, `{organization}.{domain}.v{major}` +패키지 규칙, `java_multiple_files`, 손으로 쓴 것과 겹치지 않는 생성 Java 패키지, `_UNSPECIFIED` enum 0값, 받은 삭제 +이력과 대조한 `reserved` 선언, well-known type 허용 목록, map 필드 허용 목록. 자기 시험에서 커밋한 schema에 대고 +돌므로, 출하하는 `.proto` 파일은 장식이 아니라 살아 있다. -`GrpcBufPolicy` fixes the breaking gate at Buf's `FILE` category and names the four lifecycle stages -a compliant pipeline registers. `GrpcCodegenManifest` fixes one codegen owner and refuses a literal -generator version. `GrpcDescriptorArtifact`, `GrpcConsumerFixture` and `GrpcSchemaArtifactPublisher` -carry the schema hash, the descriptor digest and the per-consumer source-break report, and refuse a -publish that breaks a consumer or republishes a released version with different bytes. +`GrpcBufPolicy`는 breaking gate를 Buf의 `FILE` category로 고정하고, 규칙을 따르는 pipeline이 등록하는 lifecycle 단계 +넷을 이름으로 댄다. `GrpcCodegenManifest`는 codegen 소유자를 하나로 고정하고 리터럴 생성기 버전을 거절한다. +`GrpcDescriptorArtifact`, `GrpcConsumerFixture`, `GrpcSchemaArtifactPublisher`는 schema hash, descriptor digest, 쓰는 +쪽별 소스 깨짐 보고를 싣고, 쓰는 쪽을 깨뜨리는 게시나 이미 릴리스한 버전을 다른 바이트로 다시 게시하는 것을 +거절한다. -The committed `buf.yaml` states the same rules, so running the CLI in an environment that has it -reaches the same verdict. +커밋한 `buf.yaml`도 같은 규칙을 적으므로, CLI가 있는 환경에서 돌리면 같은 판정에 닿는다. -## Consequences +## 결과 -**The invariants are enforced; the process is not run.** Everything Tasks 8 to 11 are about — which -schema changes are refused, which consumer breaks block a release, who owns generation — is a -build-checkable rule here. What is missing is the protoc invocation and the Buf binary. +**불변식은 강제하고, 과정은 돌리지 않는다.** Task 8부터 11이 다루는 모든 것 — 어떤 schema 변경을 거절하는지, 어떤 +쓰는 쪽 깨짐이 릴리스를 막는지, 생성을 누가 가지는지 — 이 여기서는 빌드로 검사하는 규칙이다. 빠진 것은 protoc +호출과 Buf 바이너리다. -**Turning codegen on is a bounded change.** `GrpcCodegenManifest.caSkeleton()` already names the -owner, the managed version source, the build-directory output paths and the disjoint package policy -that a real plugin configuration has to satisfy. The work is a source-set carve-out and a plugin -block, not a redesign. +**codegen을 켜는 것은 한계 있는 변경이다.** `GrpcCodegenManifest.caSkeleton()`이 이미 실제 플러그인 설정이 만족해야 +할 소유자, 관리되는 버전 출처, 빌드 디렉터리 출력 경로, 겹치지 않는 패키지 정책을 이름으로 댄다. 할 일은 source set +예외와 플러그인 블록이지 재설계가 아니다. -**The fixtures use a text codec.** `GrpcTextCodec` gives the testkit a UTF-8 marshaller so the -in-process and Netty lanes can exercise interceptors, status mapping, metadata limits and stream -sequencing without generated stubs. Those contracts are properties of the platform and the transport, -not of any message shape, so the substitution costs nothing — and the lanes run today rather than -after codegen lands. +**fixture는 텍스트 codec을 쓴다.** `GrpcTextCodec`이 testkit에 UTF-8 marshaller를 줘서, 프로세스 안 lane과 Netty +lane이 생성된 stub 없이 interceptor, status 대응, metadata 한계, stream 순서를 시험할 수 있다. 그 계약은 메시지 +모양이 아니라 플랫폼과 전송의 성질이므로 바꿔 넣어도 잃는 것이 없다 — 그리고 lane이 codegen이 들어온 뒤가 아니라 +오늘 돈다. diff --git a/docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md b/docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md index 9a944e96..c40c9fd9 100644 --- a/docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md +++ b/docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md @@ -7,53 +7,48 @@ - 현재 정본: `docs/compatibility/grpc-support-matrix.md` -# ADR-GRPC-003: Transport, business and stream evidence are three axes, and none implies another +# ADR-GRPC-003: 전송·업무·stream 증거는 세 축이고, 어느 것도 다른 것을 뜻하지 않는다 -- Status: accepted -- Date: 2026-08-30 -- Scope: `:grpc:grpc-core-api`, `:grpc:grpc-runtime` (was `grpc-policy`), `:grpc:grpc-testkit` +- 상태: 채택 +- 날짜: 2026-08-30 +- 범위: `:grpc:grpc-core-api`, `:grpc:grpc-runtime`(예전 `grpc-policy`), `:grpc:grpc-testkit` -## Context +## 배경 -A failed RPC produces a status code, and a status code is not an answer to the question the caller -actually has. `DEADLINE_EXCEEDED` on a mutation does not say whether the mutation happened; -`UNAVAILABLE` after the request was sent does not say the server never saw it; response headers -arriving does not say a transaction committed. +실패한 RPC는 status code를 낸다. 그리고 status code는 호출자가 실제로 가진 질문의 답이 아니다. 변경 요청의 +`DEADLINE_EXCEEDED`는 변경이 일어났는지 말하지 않는다. 요청을 보낸 뒤의 `UNAVAILABLE`은 서버가 그것을 한 번도 보지 +않았다고 말하지 않는다. 응답 header가 도착했다고 트랜잭션이 커밋된 것은 아니다. -Every one of those is a place where a plausible inference produces a duplicate write or a lost one, -and none of them is visible in a test that only exercises the happy path. +그 하나하나가 그럴듯한 추론이 중복 쓰기나 잃은 쓰기를 낳는 자리이고, 성공 경로만 시험하는 시험에서는 하나도 보이지 +않는다. -## Decision +## 결정 -Model what happened as three independent axes, and refuse the inferences between them. +일어난 일을 서로 독립인 세 축으로 모델링하고, 축 사이의 추론을 거절한다. -`GrpcTransportEvidence` records what the client observed on the wire, and distinguishes `NOT_SENT` — -the client watched its own send fail — from `UNOBSERVED`, which is every other case where nothing is -known. `GrpcBusinessEvidence` records what the application confirmed, with `COMMIT_UNKNOWN` as a real -state rather than a placeholder. `GrpcStreamEvidence` is a sealed hierarchy whose non-empty cases all -carry a position, because "partial" without a last sequence can be neither resumed nor reconciled. +`GrpcTransportEvidence`는 client가 wire에서 본 것을 기록하고, `NOT_SENT` — client가 자기 보내기가 실패하는 것을 봤다 +— 와, 아무것도 모르는 다른 모든 경우인 `UNOBSERVED`를 구별한다. `GrpcBusinessEvidence`는 애플리케이션이 확인한 것을 +기록하고, `COMMIT_UNKNOWN`은 자리표시가 아니라 실제 상태다. `GrpcStreamEvidence`는 sealed 계층이고, 비어 있지 않은 +경우는 모두 위치를 싣는다. 마지막 순번 없는 「부분」은 이어 가지도 맞춰 보지도 못하기 때문이다. -`GrpcExecutionEvidence` holds all three and rejects combinations nobody could have observed: a unary -call with stream evidence, or a request the client watched fail to send that nonetheless carries -business evidence. Promoting response headers to a confirmed commit is possible only by editing -`withResponseHeadersSeen`, which is one method rather than a plausible line in an interceptor. +`GrpcExecutionEvidence`는 셋을 모두 가지고, 아무도 볼 수 없었을 조합을 거절한다: stream 증거가 있는 unary 호출, 또는 +client가 보내기 실패를 봤는데도 업무 증거를 실은 요청. 응답 header를 확인된 커밋으로 올리는 것은 +`withResponseHeadersSeen`을 고쳐야만 할 수 있다. 그것은 interceptor 안의 그럴듯한 한 줄이 아니라 메서드 하나다. -`GrpcCompletionOutcome.forMutation` derives what a caller may conclude, and defaults -`DEADLINE_EXCEEDED` and post-send `UNAVAILABLE` on a mutation to `COMPLETION_UNKNOWN`. +`GrpcCompletionOutcome.forMutation`이 호출자가 결론 내릴 수 있는 것을 끌어내고, 변경 요청의 `DEADLINE_EXCEEDED`와 +보낸 뒤의 `UNAVAILABLE`을 기본으로 `COMPLETION_UNKNOWN`으로 둔다. -The same types are used by the failure model and by the observation convention, so an incident has -one account of a call rather than two. +실패 모델과 관측 규약이 같은 타입을 쓰므로, 사고 때 호출 하나에 대한 설명이 둘이 아니라 하나다. -## Consequences +## 결과 -**A whole class of retry bug becomes unrepresentable.** `GrpcRetryEligibility` reads all three axes -plus the idempotency profile; a caller cannot reach "retry" from a status alone because the status -alone is not an input. +**재시도 결함의 한 종류를 아예 나타낼 수 없게 된다.** `GrpcRetryEligibility`는 세 축 모두와 멱등성 profile을 읽는다. +status만으로는 입력이 아니므로, 호출자는 status만 보고 「재시도」에 닿을 수 없다. -**The fault lane has something to check.** `GrpcTransportEvidenceClassifier` turns a client's -observations into evidence and refuses to infer `NOT_SENT` from an unobserved state — and the lane -exercises it against a real connection dropped mid-call, not against a mock. +**장애 lane에 검사할 것이 생긴다.** `GrpcTransportEvidenceClassifier`가 client의 관찰을 증거로 바꾸고, 관찰하지 않은 +상태에서 `NOT_SENT`를 추론하기를 거절한다 — 그리고 lane은 mock이 아니라 호출 중간에 끊은 실제 연결에 대고 그것을 +시험한다. -**Callers must handle a third outcome.** `COMPLETION_UNKNOWN` is not a failure and not a success, and -a caller that treats it as either is wrong. `GrpcOperationStatusQuery` and `GrpcCompletionReconciler` -exist so that resolving it is a supported path rather than an exercise for the caller. +**호출자는 세 번째 결과를 다뤄야 한다.** `COMPLETION_UNKNOWN`은 실패도 성공도 아니고, 둘 중 하나로 다루는 호출자는 +틀렸다. `GrpcOperationStatusQuery`와 `GrpcCompletionReconciler`는 그것을 푸는 일이 호출자에게 맡긴 숙제가 아니라 +지원하는 경로가 되게 하려고 있다. diff --git a/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md b/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md index 00a03ed1..f86b2b31 100644 --- a/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md +++ b/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md @@ -7,129 +7,106 @@ - 현재 정본: `docs/compatibility/grpc-support-matrix.md` -# ADR-GRPC-004: One retry owner, and keyed mutations need a durable ledger +# ADR-GRPC-004: 재시도 소유자는 하나이고, 키가 있는 변경에는 durable 원장이 필요하다 -- Status: accepted -- Date: 2026-08-30 -- Scope: `:grpc:grpc-runtime` (was `grpc-policy`), `:grpc:grpc-operation-ledger-jpa`, `:grpc:grpc-core-api` +- 상태: 채택 +- 날짜: 2026-08-30 +- 범위: `:grpc:grpc-runtime`(예전 `grpc-policy`), `:grpc:grpc-operation-ledger-jpa`, `:grpc:grpc-core-api` -## Context +## 배경 -Three layers can retry a gRPC call: the application, the channel's service config, and a service -mesh. Their effects multiply. Three attempts at each layer is twenty-seven requests for one call, and -the load arrives exactly when the dependency is already failing. +gRPC 호출을 재시도할 수 있는 계층이 셋 있다: 애플리케이션, channel의 service config, service mesh. 그 효과는 곱해진다. +계층마다 세 번 시도하면 호출 하나에 요청 스물일곱 개이고, 그 부하는 의존 대상이 이미 실패하고 있을 바로 그때 온다. -Separately, a mutation that is safe to repeat needs somewhere to record that it ran. Without one, a -retry after a lost response either duplicates the effect or drops it, and nothing distinguishes the -two afterwards. +따로, 되풀이해도 안전한 변경에는 그것이 돌았다는 기록을 둘 곳이 필요하다. 없으면 응답을 잃은 뒤의 재시도는 효과를 +겹치게 하거나 버리게 되고, 나중에 둘을 구별할 것이 없다. -## Decision +## 결정 -**Exactly one retry owner per channel.** `GrpcRetryOwner` has four values including `NONE`, which is a -decision rather than an omission. `GrpcServiceConfigPolicy` refuses an in-process retry entry when the -owner is the mesh or nobody, and `GrpcRetryOwnershipValidator` compares the service config's method -names against the policy catalog — a renamed method leaves its retry entry matching nothing, silently, -and the method then runs with channel defaults. +**channel마다 재시도 소유자는 정확히 하나다.** `GrpcRetryOwner`에는 `NONE`을 포함해 값이 넷 있고, `NONE`은 빠뜨림이 +아니라 결정이다. `GrpcServiceConfigPolicy`는 소유자가 mesh이거나 아무도 아닐 때 프로세스 안 재시도 항목을 거절하고, +`GrpcRetryOwnershipValidator`는 service config의 메서드 이름을 정책 catalog와 대조한다 — 이름이 바뀐 메서드는 그 재시도 +항목이 소리 없이 아무것과도 맞지 않게 되고, 그 메서드는 channel 기본값으로 돈다. -**Retry eligibility reads the method, the evidence and the status together.** -`GrpcRetryEligibility` refuses a non-idempotent method outright, refuses any call whose stream -delivered a prefix, and turns a `DEADLINE_EXCEEDED` or post-send `UNAVAILABLE` mutation into -"resolve the completion first" rather than a retry. +**재시도 자격은 메서드, 증거, status를 함께 읽는다.** `GrpcRetryEligibility`는 멱등이 아닌 메서드를 바로 거절하고, +stream이 앞부분을 전달한 호출을 모두 거절하며, 변경 요청의 `DEADLINE_EXCEEDED`나 보낸 뒤의 `UNAVAILABLE`을 재시도가 +아니라 「먼저 완료를 풀어라」로 바꾼다. -**A keyed mutation is retryable only with both a caller key and a durable ledger.** -`GrpcOperationLedger` is a port in `grpc-core-api`, so the policy layer can require durable -idempotency without depending on a database. Its `claim` contract is a single atomic insert-or-read -against a unique constraint: `JpaGrpcOperationLedger` inserts first and reads on constraint violation, -because a read-then-insert implementation has a window exactly as wide as the race it closes and -passes every test that does not run two attempts concurrently. +**키가 있는 변경은 호출자 키와 durable 원장이 둘 다 있을 때만 재시도할 수 있다.** `GrpcOperationLedger`는 +`grpc-core-api`의 포트라서, 정책 계층이 데이터베이스에 의존하지 않고 durable 멱등성을 요구할 수 있다. 그 `claim` 계약은 +unique 제약에 대한 원자적 insert-or-read 하나다: `JpaGrpcOperationLedger`는 먼저 insert하고 제약 위반이면 읽는다. +read-then-insert 구현에는 그것이 닫으려는 경쟁만큼 넓은 창이 있고, 두 시도를 동시에 돌리지 않는 모든 시험을 +통과하기 때문이다. -The identity is caller fingerprint plus full method plus hashed key. All three are load-bearing: -without the caller, one tenant's key suppresses another's write; without the method, a key reused -across operations makes the second a replay of the first. +identity는 호출자 fingerprint + 전체 메서드 + hash한 키다. 셋 모두 꼭 필요하다: 호출자가 없으면 한 테넌트의 키가 다른 +테넌트의 쓰기를 막는다. 메서드가 없으면 operation 사이에서 다시 쓴 키 때문에 둘째가 첫째의 재생이 된다. -## Consequences +## 결과 -**A budget bounds retries as a fraction of traffic.** `GrpcRetryBudget` degrades to roughly no -retries when everything is failing, which is the behaviour that lets a dependency recover. +**예산이 재시도를 traffic의 비율로 묶는다.** `GrpcRetryBudget`은 모든 것이 실패할 때 재시도가 거의 없는 쪽으로 +떨어진다. 그것이 의존 대상이 회복하게 하는 동작이다. -**The ledger and the mutation should commit together.** `JpaGrpcOperationLedger` carries no -transaction annotations, deliberately: a `REQUIRES_NEW` would put the claim in its own transaction and -reintroduce the window where the write is durable and the claim is not. +**원장과 변경은 함께 커밋해야 한다.** `JpaGrpcOperationLedger`는 일부러 트랜잭션 애너테이션을 달지 않는다: +`REQUIRES_NEW`는 claim을 자기 트랜잭션에 넣어서, 쓰기는 durable한데 claim은 아닌 창을 다시 들인다. -**A claim expires instead of blocking its key forever** (review 2026-11-01, 03-10). A claim still -`IN_PROGRESS` after the claim TTL is presumed abandoned by a dead owner, and the next retry of the same -request takes it over with `GrpcOperationLedger.reclaimStale` — one conditional -`UPDATE … WHERE state = 'IN_PROGRESS' AND claimed_at < :cutoff`, so of two concurrent takeovers exactly -one wins, the same shape as `reclaimFailed`. The TTL is the `claimTtl` argument of -`GrpcIdempotencyInterceptor`, refused at construction when it is not longer than every keyed method's -deadline. Since the 03-11 follow-up the starter assembles the interceptor when -`app.grpc.platform.operation-ledger-enabled=true` and takes the TTL from -`app.grpc.platform.operation-ledger-claim-ttl` (default 5m); a TTL the constructor refuses fails startup -naming that key, and an enabled flag without a `GrpcOperationLedger` bean fails startup too. +**claim은 키를 영원히 막지 않고 만료된다**(review 2026-11-01, 03-10). claim TTL이 지난 뒤에도 `IN_PROGRESS`인 claim은 +죽은 주인이 버린 것으로 보고, 같은 요청의 다음 재시도가 `GrpcOperationLedger.reclaimStale`로 넘겨받는다 — 조건부 +`UPDATE … WHERE state = 'IN_PROGRESS' AND claimed_at < :cutoff` 하나라서, 동시에 넘겨받기 둘이 오면 정확히 하나가 이긴다. +`reclaimFailed`와 같은 모양이다. TTL은 `GrpcIdempotencyInterceptor`의 `claimTtl` 인자이고, 키가 있는 모든 메서드의 +deadline보다 길지 않으면 만들 때 거절한다. 03-11 후속부터 starter는 `app.grpc.platform.operation-ledger-enabled=true`이면 +interceptor를 조립하고 TTL을 `app.grpc.platform.operation-ledger-claim-ttl`(기본 5m)에서 가져온다. 생성자가 거절하는 +TTL은 그 키 이름을 대며 기동을 실패시키고, `GrpcOperationLedger` bean 없이 flag를 켜도 기동이 실패한다. -The takeover is safe only because the commit is recorded in the mutation's own transaction: then a -claim still `IN_PROGRESS` means the mutation never committed. An adopter that commits them separately -turns an abandoned claim into an unknown outcome, and a takeover can run the mutation twice. A takeover -of an owner that is merely slow does the same, which is why the TTL must exceed the slowest keyed -method and not just its deadline. +넘겨받기가 안전한 것은 커밋을 변경 자신의 트랜잭션 안에서 기록하기 때문뿐이다: 그러면 아직 `IN_PROGRESS`인 claim은 +변경이 한 번도 커밋되지 않았다는 뜻이다. 둘을 따로 커밋하는 채택자는 버려진 claim을 모르는 결과로 만들고, 넘겨받기가 +변경을 두 번 돌릴 수 있다. 그저 느린 주인을 넘겨받아도 같은 일이 생긴다. 그래서 TTL은 deadline만이 아니라 키가 있는 +가장 느린 메서드보다 길어야 한다. -Rejected: an owner token with a heartbeat lease (the outbox lease model) — needed only when a keyed -method can run longer than any fixed TTL; revisit when one exists. A sweeper job that deletes stale -rows — it needs a scheduler this family does not have, and deleting a claim makes the next retry a -fresh claim with no record that an attempt was abandoned. +버린 것: heartbeat lease를 단 owner token(outbox lease 모델) — 키가 있는 메서드가 어떤 고정 TTL보다 오래 돌 수 있을 때만 +필요하다. 그런 메서드가 생기면 다시 본다. 낡은 행을 지우는 sweeper job — 이 family에 없는 scheduler가 필요하고, +claim을 지우면 다음 재시도가 시도를 버렸다는 기록 없는 새 claim이 된다. -**A taken-over owner is fenced by a claim token** (re-review 2026-11-03, RR-02-04). The owner a -takeover presumes dead may only be slow. Without knowing which attempt held the claim, its late -`markFailed` turned the new attempt's claim `FAILED_TERMINAL`, the next retry re-claimed it, and two -attempts ran the mutation at once; its late `markCommitted` committed beside the new attempt. Every -claim now carries a `GrpcClaimToken` (`claim_attempt`, migration V003): 1 for the first claim, one more -for each `reclaimFailed` or `reclaimStale`. `decide` returns it on `PROCEED`, and `recordCommit` / -`recordFailure` hand it back. A commit or a failure is one conditional -`UPDATE … WHERE state = 'IN_PROGRESS' AND claim_attempt = :attempt`: a commit by an attempt that lost -the claim is refused with an exception, so its business transaction rolls back; a failure by one is -ignored (`markFailed` returns false). The same conditional update closes the JPA commit race — -load-check-save let two commits that both read `IN_PROGRESS` both write; now exactly one matches. -A claim whose conflicting row is purged between insert and read retries the insert once instead of -failing the call. +**넘겨받긴 주인은 claim token으로 막는다**(re-review 2026-11-03, RR-02-04). 넘겨받기가 죽었다고 보는 주인은 그저 느릴 +수 있다. 어느 시도가 claim을 쥐었는지 모르면, 그 주인의 늦은 `markFailed`가 새 시도의 claim을 `FAILED_TERMINAL`로 +만들었고, 다음 재시도가 그것을 다시 claim해서 두 시도가 동시에 변경을 돌렸다. 늦은 `markCommitted`는 새 시도 옆에서 +커밋했다. 이제 모든 claim은 `GrpcClaimToken`(`claim_attempt`, migration V003)을 싣는다: 첫 claim은 1이고, +`reclaimFailed`나 `reclaimStale`마다 하나씩 늘어난다. `decide`는 `PROCEED`에서 그것을 돌려주고, `recordCommit` / +`recordFailure`가 그것을 되돌려 준다. 커밋이나 실패는 조건부 +`UPDATE … WHERE state = 'IN_PROGRESS' AND claim_attempt = :attempt` 하나다: claim을 잃은 시도의 커밋은 예외로 거절해서 +그 업무 트랜잭션이 롤백되고, 그런 시도의 실패는 무시한다(`markFailed`가 false를 돌려준다). 같은 조건부 update가 JPA +커밋 경쟁도 닫는다 — load-check-save에서는 둘 다 `IN_PROGRESS`를 읽은 커밋 둘이 둘 다 썼다. 이제 정확히 하나만 맞는다. +insert와 read 사이에 충돌 행이 지워진 claim은 호출을 실패시키지 않고 insert를 한 번 다시 시도한다. -`release(identity, claimToken)` is fenced the same way (re-review 2026-11-03 round 2, RR-01-15): it is a -conditional `DELETE … WHERE state = 'IN_PROGRESS' AND claim_attempt = :attempt` and returns whether it -deleted. It used to delete by key alone, so any caller could erase the claim of the attempt that held -it, or a finished record a retry replays. The counter lives in the row, so a deleted row's key starts -again at attempt 1: the token separates the attempts of one row, not attempts across a delete. Both -deletions are limited accordingly — release only for a claim whose owner is known to be gone, purge -only for rows finished longer ago than any retry. Rejected: dropping `release` from the port -(`markFailed` then `reclaimFailed` keeps the counter, but a deployment that must free a key for a -different request has no other path), and a tombstone row that keeps the counter (a second state to -purge, for a window the two limits already close). +`release(identity, claimToken)`도 같은 방식으로 막는다(re-review 2026-11-03 round 2, RR-01-15): 조건부 +`DELETE … WHERE state = 'IN_PROGRESS' AND claim_attempt = :attempt`이고 지웠는지를 돌려준다. 예전에는 키만으로 지웠기 +때문에, 아무 호출자나 그것을 쥔 시도의 claim이나 재시도가 재생하는 끝난 레코드를 지울 수 있었다. counter는 행 안에 +있으므로 지운 행의 키는 다시 attempt 1에서 시작한다: token은 행 하나의 시도들을 가르지, 삭제를 넘는 시도들을 가르지 +않는다. 그래서 두 삭제를 모두 제한한다 — release는 주인이 사라졌다고 아는 claim에만, purge는 어떤 재시도보다 오래 전에 +끝난 행에만. 버린 것: 포트에서 `release`를 빼기(`markFailed` 뒤 `reclaimFailed`는 counter를 지키지만, 다른 요청을 위해 +키를 풀어야 하는 배포에는 다른 길이 없다), counter를 지키는 tombstone 행(지울 두 번째 상태가 생기는데, 그 창은 두 제한이 +이미 닫는다). -Chosen over the claim moment as the token (`WHERE claimed_at = :claimedAt`), which needs no column: -PostgreSQL stores microseconds while `Instant` carries nanoseconds, so the token a caller holds and -the one stored can differ by rounding, and two processes' clocks can give two attempts the same -moment. The counter has neither problem. The heartbeat lease above stays rejected for the same reason -as before; the token fences without one. +token으로 claim 시각(`WHERE claimed_at = :claimedAt`)을 쓰는 안보다 이것을 골랐다. 시각은 열이 따로 필요 없지만, +PostgreSQL은 마이크로초를 저장하고 `Instant`는 나노초를 싣는다. 그래서 호출자가 쥔 token과 저장된 것이 반올림만큼 +다를 수 있고, 두 프로세스의 시계가 두 시도에 같은 시각을 줄 수 있다. counter에는 두 문제가 다 없다. 위 heartbeat lease는 +앞과 같은 이유로 계속 버린다. token은 그것 없이 막는다. -**What `operation-ledger-enabled=true` promises (03-11 (b), recorded 2026-11-03, RR-02-07).** The -2026-11-01 review offered (a) delete the flag and judge by whether a ledger bean exists, or (b) keep the -flag and have the starter assemble the decision function from it. (b) is kept: the assembly and the -TTL validation live in one place instead of in every adopter. (a) was rejected because it removes the -false promise only by removing the assembly with it. The limit stays and is stated where an operator -meets it: the starter builds no server, so the flag assembles the decision function only, and keys are -honoured once the adopter's `IDEMPOTENCY` stage interceptor or service adapter calls `decide` and -`recordCommit`. `GrpcPlatformStartupValidator`'s refusal for a keyed method says exactly that; a running -process cannot see whether the stage exists, so the validator does not claim to check it. +**`operation-ledger-enabled=true`가 약속하는 것(03-11 (b), 2026-11-03 기록, RR-02-07).** 2026-11-01 리뷰는 (a) flag를 +지우고 원장 bean이 있는지로 판단하기와 (b) flag를 두고 starter가 그것으로 판정 함수를 조립하기를 내놓았다. (b)를 +지킨다: 조립과 TTL 검증이 채택자마다가 아니라 한곳에 있다. (a)는 거짓 약속을 없애되 조립까지 함께 없애기 때문에 +버렸다. 한계는 남고, 운영자가 그것을 만나는 곳에 적는다: starter는 서버를 만들지 않으므로 flag는 판정 함수만 +조립하고, 채택자의 `IDEMPOTENCY` 단계 interceptor나 service adapter가 `decide`와 `recordCommit`을 부를 때 비로소 키가 +지켜진다. 키가 있는 메서드에 대한 `GrpcPlatformStartupValidator`의 거절이 바로 그것을 말한다. 돌고 있는 프로세스는 그 +단계가 있는지 볼 수 없으니, validator는 그것을 검사한다고 주장하지 않는다. -**Finished rows are purged after a retention; in-progress rows never are** (03-10 follow-up). -`GrpcOperationLedger.purgeCompletedBefore(cutoff, limit)` deletes at most `limit` `COMMITTED` or -`FAILED_TERMINAL` rows that completed before the cutoff, oldest first — on PostgreSQL one bounded -`DELETE … WHERE storage_key IN (SELECT … LIMIT … FOR UPDATE SKIP LOCKED)` served by the partial index -of migration V002. `GrpcOperationLedgerRetention.purgeExpired(now)` applies -`app.grpc.platform.operation-ledger-retention` (default 24h, the HTTP idempotency replay TTL) in -batches. A retry after its record was purged is a fresh claim and runs again, so the retention must -exceed the callers' retry window. The adopter schedules the purge; the starter assembles the policy -only, because a scheduled bean would force a scheduler onto every deployment and the starter cannot -know which replica should run it. +**끝난 행은 보존 기간 뒤에 지우고, 진행 중인 행은 절대 지우지 않는다**(03-10 후속). +`GrpcOperationLedger.purgeCompletedBefore(cutoff, limit)`는 cutoff 전에 끝난 `COMMITTED`나 `FAILED_TERMINAL` 행을 오래된 +것부터 많아야 `limit`개 지운다 — PostgreSQL에서는 migration V002의 부분 index가 받쳐 주는 한계 있는 +`DELETE … WHERE storage_key IN (SELECT … LIMIT … FOR UPDATE SKIP LOCKED)` 하나다. +`GrpcOperationLedgerRetention.purgeExpired(now)`가 `app.grpc.platform.operation-ledger-retention`(기본 24h, HTTP 멱등성 +재생 TTL)을 batch로 적용한다. 레코드가 지워진 뒤의 재시도는 새 claim이고 다시 돈다. 그래서 보존 시간은 호출자의 재시도 +창보다 길어야 한다. 지우기 일정은 채택자가 잡는다. starter는 정책만 조립한다. 예약된 bean은 모든 배포에 scheduler를 +강요하고, starter는 어느 replica가 돌려야 하는지 알 수 없기 때문이다. -**A key reused for a different request is a caller error, not a duplicate.** The stored request -fingerprint turns that into `FAILED_PRECONDITION` rather than silently returning the first request's -answer. +**다른 요청에 다시 쓴 키는 중복이 아니라 호출자 오류다.** 저장된 요청 fingerprint가 그것을 소리 없이 첫 요청의 답을 +돌려주는 대신 `FAILED_PRECONDITION`으로 바꾼다. diff --git a/docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md b/docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md index 712eddf8..a210de5d 100644 --- a/docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md +++ b/docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md @@ -7,53 +7,46 @@ - 현재 정본: `docs/compatibility/grpc-support-matrix.md` -# ADR-GRPC-005: One writer per stream, a bounded queue, and resume that refuses to guess +# ADR-GRPC-005: stream마다 쓰는 쪽 하나, 한계 있는 queue, 짐작하기를 거절하는 resume -- Status: accepted -- Date: 2026-08-30 -- Scope: `:grpc:grpc-runtime` (was `grpc-policy`) +- 상태: 채택 +- 날짜: 2026-08-30 +- 범위: `:grpc:grpc-runtime`(예전 `grpc-policy`) -## Context +## 배경 -`StreamObserver` is not thread-safe, and the failure when two producers call `onNext` concurrently is -not an exception — it is interleaved bytes, which a client decodes as a corrupt message or, worse, as -a valid one it should never have received. +`StreamObserver`는 thread-safe가 아니다. 두 producer가 동시에 `onNext`를 부를 때의 실패는 예외가 아니다 — 섞인 바이트이고, +client는 그것을 깨진 메시지로, 더 나쁘게는 받지 말았어야 할 유효한 메시지로 decode한다. -Two further properties of server streams are easy to get wrong in ways that look healthy. A consumer -that falls behind either terminates the stream or silently loses messages, and the second leaves a -client with a stream that appears fine and is missing changes. And a reconnect either continues from -a position the server can still replay, or skips whatever is no longer there. +server stream에는 건강해 보이는 방식으로 틀리기 쉬운 성질이 둘 더 있다. 뒤처진 소비자는 stream을 끝내거나 메시지를 소리 +없이 잃는데, 둘째는 client에게 멀쩡해 보이지만 변경이 빠진 stream을 남긴다. 그리고 재연결은 서버가 아직 재생할 수 있는 +위치에서 이어 가거나, 더는 없는 것을 건너뛴다. -## Decision +## 결정 -**A bounded queue drained by one writer.** `GrpcSerializedStreamWriter` accepts messages from any -thread and hands them to the transport only from `flush`, which is synchronized. `write` returning -`ACCEPTED` means queued, and the name is deliberately not `sent`: the transport call returns as soon -as bytes are handed over, so no method here can honestly report delivery. +**쓰는 쪽 하나가 비우는 한계 있는 queue.** `GrpcSerializedStreamWriter`는 어느 스레드에서든 메시지를 받고, synchronized인 +`flush`에서만 전송에 넘긴다. `write`가 `ACCEPTED`를 돌려주는 것은 줄 세웠다는 뜻이고, 이름을 일부러 `sent`로 하지 +않았다: 전송 호출은 바이트를 넘기자마자 돌아오므로, 여기 어떤 메서드도 전달을 정직하게 알릴 수 없다. -**Both a message bound and a byte bound.** Either alone is unbounded in the other dimension. -`GrpcFlowControlPolicy` also takes the transport's own readiness signal, because a writer that relies -only on its queue bound produces as fast as it can allocate. +**메시지 한계와 바이트 한계를 둘 다.** 하나만 두면 다른 차원으로는 한계가 없다. `GrpcFlowControlPolicy`는 전송 자신의 +readiness 신호도 받는다. queue 한계에만 기대는 쓰는 쪽은 메모리를 할당할 수 있는 만큼 빨리 만들어 내기 때문이다. -**Termination is the default for a slow consumer.** `GrpcSlowConsumerPolicy.DROP_OLDEST` exists for -feeds whose business meaning tolerates loss, and is not the default, because a client cannot detect -dropped messages: the sequence numbers it sees are the ones it was sent. +**느린 소비자에게는 끝내기가 기본이다.** `GrpcSlowConsumerPolicy.DROP_OLDEST`는 업무 뜻이 손실을 견디는 feed를 위해 +있고 기본값이 아니다. client는 버려진 메시지를 알아챌 수 없기 때문이다: client가 보는 순번은 보내진 것의 순번이다. -**Resume is refused rather than faked.** `GrpcStreamGapDetector` requires a signed, unexpired token -whose caller and filter fingerprints match the current request, refuses one whose snapshot version -moved, and returns `FULL_RESYNC_REQUIRED` when the cursor predates retained history. `GrpcResumeToken` -carries a key id so the signing key can rotate without invalidating every outstanding token. +**resume은 꾸며 내지 않고 거절한다.** `GrpcStreamGapDetector`는 서명됐고 만료되지 않았으며 호출자·필터 fingerprint가 +지금 요청과 맞는 token을 요구하고, snapshot version이 움직인 token을 거절하며, cursor가 보존한 이력보다 앞서면 +`FULL_RESYNC_REQUIRED`를 돌려준다. `GrpcResumeToken`은 key id를 싣는다. 그래서 서명 키를 바꿔도 아직 쓰이는 모든 token이 +무효가 되지 않는다. -## Consequences +## 결과 -**A stream carries an envelope, not a bare payload.** `GrpcStreamEnvelope` holds the stream id, -generation, sequence, snapshot version and resume token, because resume, gap detection and drain all -need a position and a generation. +**stream은 맨 payload가 아니라 envelope을 싣는다.** `GrpcStreamEnvelope`은 stream id, generation, 순번, snapshot version, +resume token을 가진다. resume, 빈틈 찾기, 비우기가 모두 위치와 generation을 필요로 하기 때문이다. -**Four clocks, not one.** `GrpcStreamLifetimePolicy` separates setup deadline, idle timeout, max -duration and heartbeat interval, and refuses combinations where one can never fire. Merging any pair -produces a familiar bug: an idle timeout used as a max duration kills healthy busy streams. +**시계는 하나가 아니라 넷이다.** `GrpcStreamLifetimePolicy`는 준비 deadline, idle timeout, 최대 지속 시간, heartbeat +간격을 나누고, 하나가 절대 울릴 수 없는 조합을 거절한다. 어느 둘을 합치든 익숙한 결함이 나온다: 최대 지속 시간으로 쓴 +idle timeout은 건강하게 바쁜 stream을 죽인다. -**A heartbeat is a liveness signal and nothing else.** It is not an application acknowledgement and -not an ordering guarantee; `GrpcStreamHeartbeat` says so in the place somebody would otherwise reuse -it. +**heartbeat는 살아 있다는 신호이고 그 밖의 무엇도 아니다.** 애플리케이션 확인 응답도 순서 보장도 아니다. +`GrpcStreamHeartbeat`가 누가 그것을 다르게 다시 쓸 법한 자리에서 그렇게 말한다. diff --git a/docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md b/docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md index 17e677a6..c58764b0 100644 --- a/docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md +++ b/docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md @@ -7,71 +7,61 @@ - 현재 정본: `docs/compatibility/grpc-support-matrix.md` -# ADR-GRPC-006: Stable discovery is DNS and static, and a Kubernetes profile names who balances +# ADR-GRPC-006: Stable discovery는 DNS와 static이고, Kubernetes profile은 누가 분산하는지 이름으로 댄다 -- Status: accepted -- Date: 2026-08-31 -- Scope: `:grpc:grpc-runtime` (was `grpc-discovery`, `grpc-client`) +- 상태: 채택 +- 날짜: 2026-08-31 +- 범위: `:grpc:grpc-runtime`(예전 `grpc-discovery`, `grpc-client`) -## Context +## 배경 -A gRPC channel's discovery configuration has a failure mode with no runtime symptom: it works, and -it does not do what the dashboard says it does. +gRPC channel의 discovery 설정에는 런타임 증상이 없는 실패 방식이 있다: 동작은 하는데, 대시보드가 말하는 일을 하지 않는다. -The specific case is `round_robin` over a Kubernetes Service ClusterIP. The Service is one virtual -address, so the resolver returns one endpoint and the client-side balancer has nothing to rotate -across; kube-proxy picks a pod at connect time, and an HTTP/2 connection is long-lived, so every -request from that client goes to the same pod for the life of the connection. Nothing fails. The -configuration says `round_robin`, the metrics show requests spread across clients rather than pods, -and the conclusion "we have client-side load balancing" is wrong in a way nobody is prompted to -check. +구체적인 경우는 Kubernetes Service ClusterIP 위의 `round_robin`이다. Service는 가상 주소 하나라서 resolver가 endpoint 하나를 +돌려주고 client 쪽 분산기는 돌려 가며 보낼 대상이 없다. kube-proxy는 연결할 때 pod를 고르고, HTTP/2 연결은 오래 살기 +때문에, 그 client의 모든 요청이 연결이 사는 동안 같은 pod로 간다. 실패하는 것은 없다. 설정은 `round_robin`이라고 말하고, +metric은 요청이 pod가 아니라 client 사이에 퍼진 것을 보여 주며, 「client 쪽 부하 분산을 한다」는 결론은 아무도 확인할 +계기가 없는 방식으로 틀렸다. -The mirror-image mistake is `pick_first` over a headless record, which pins a client to one pod out -of many. +거울상 실수는 headless record 위의 `pick_first`다. 많은 pod 중 하나에 client를 묶는다. -Separately, a service mesh changes who owns retries, and a deployment that adds mesh routing without -removing its own retry policy has two retriers whose effects multiply. +따로, service mesh는 재시도를 누가 가지는지 바꾸고, mesh 라우팅을 더하면서 자기 재시도 정책을 빼지 않은 배포는 효과가 +곱해지는 재시도자 둘을 가진다. -## Decision +## 결정 -**Stable resolvers are Static, DNS and Unix domain socket; Stable load balancing is `pick_first` and -`round_robin`.** `GrpcDiscoveryPolicyValidator.requireStableScheme` refuses `xds`, `consul`, `etcd` -and `eureka` by name, with a message saying they are Advanced capabilities with their own control -plane and promotion gate rather than unknown schemes. +**Stable resolver는 Static, DNS, Unix domain socket이고, Stable 부하 분산은 `pick_first`와 `round_robin`이다.** +`GrpcDiscoveryPolicyValidator.requireStableScheme`은 `xds`, `consul`, `etcd`, `eureka`를 이름으로 거절하고, 그것이 모르는 +scheme이 아니라 자기 control plane과 승격 gate를 가진 Advanced capability라고 메시지로 말한다. -**The pairing is checked against the resolved address count, not against intent.** -`GrpcResolverProfile` carries `expectedAddressCount`, and `GrpcStableLoadBalancer.effective` answers -whether the policy distributes anything over that many endpoints. A `round_robin` profile over one -address is a reported violation whose message says it describes spreading that is not happening. +**짝 맞춤은 의도가 아니라 해석된 주소 수와 대조한다.** `GrpcResolverProfile`은 `expectedAddressCount`를 싣고, +`GrpcStableLoadBalancer.effective`가 그 수의 endpoint 위에서 정책이 무언가를 분산하는지 답한다. 주소 하나 위의 +`round_robin` profile은 보고되는 위반이고, 그 메시지는 그것이 일어나지 않는 퍼뜨리기를 설명한다고 말한다. -**A Kubernetes deployment names its routing mode**, and the mode implies both the balancer and the -retry owner. `GrpcKubernetesRoutingMode` has three values — `K8S_VIP`, `K8S_HEADLESS`, `MESH` — and -`GrpcKubernetesProfile` refuses a mesh profile whose retry owner retries in-process. +**Kubernetes 배포는 자기 라우팅 모드를 이름으로 대고**, 그 모드가 분산기와 재시도 소유자를 둘 다 정한다. +`GrpcKubernetesRoutingMode`에는 값이 셋 있다 — `K8S_VIP`, `K8S_HEADLESS`, `MESH` — 그리고 `GrpcKubernetesProfile`은 재시도 +소유자가 프로세스 안에서 재시도하는 mesh profile을 거절한다. -**A profile that carries long-lived streams must state a reconnect budget and a readiness drain -grace.** A stream pins a client to one pod for its whole life, so every rollout, eviction and -scale-down ends it. `GrpcKubernetesProfileValidator` additionally reports a VIP profile carrying -long streams, and a drain grace shorter than the reconnect budget — the second means the pod stops -serving before its clients have finished reconnecting elsewhere. +**오래 사는 stream을 싣는 profile은 재연결 예산과 readiness 비우기 유예를 밝혀야 한다.** stream은 사는 내내 client를 pod +하나에 묶으므로, 모든 rollout, eviction, scale-down이 그것을 끝낸다. `GrpcKubernetesProfileValidator`는 긴 stream을 싣는 +VIP profile과, 재연결 예산보다 짧은 비우기 유예도 알린다 — 후자는 client가 다른 곳으로 재연결을 마치기 전에 pod가 응답을 +멈춘다는 뜻이다. -**A DNS profile must refresh.** `GrpcResolverProfile` refuses a zero refresh interval on DNS, -because a channel that resolved once at startup keeps sending to addresses that stopped existing an -hour ago, and the resulting `UNAVAILABLE` looks like an unhealthy deployment long after the rollout -finished. +**DNS profile은 새로 고쳐야 한다.** `GrpcResolverProfile`은 DNS에서 새로 고침 간격 0을 거절한다. 기동 때 한 번 해석한 +channel은 한 시간 전에 없어진 주소로 계속 보내고, 그 결과인 `UNAVAILABLE`은 rollout이 끝난 지 한참 뒤에도 건강하지 않은 +배포처럼 보인다. -## Consequences +## 결과 -**Two validators, not one.** `GrpcDiscoveryPolicyValidator` asks whether a balancer does anything -over the addresses it will see; `GrpcKubernetesProfileValidator` asks whether the deployment shape, -the retry owner and the stream obligations agree. A deployment can have a coherent resolver profile -and still have put retries in two places, so merging them would let one answer hide the other. +**validator는 하나가 아니라 둘이다.** `GrpcDiscoveryPolicyValidator`는 분산기가 자기가 볼 주소 위에서 무언가를 하는지 +묻는다. `GrpcKubernetesProfileValidator`는 배포 모양, 재시도 소유자, stream 의무가 맞는지 묻는다. 배포는 resolver profile이 +앞뒤가 맞으면서도 재시도를 두 곳에 둘 수 있다. 그래서 둘을 합치면 한 답이 다른 답을 가린다. -**`expectedAddressCount` has to come from somewhere.** It is a declared number, and a declaration can -be wrong. It is still better than the alternative, which is not comparing anything: a wrong -declaration is a wrong statement somebody wrote down, and a missing one is a question nobody asked. -`GrpcChannelProfileValidator` takes resolved counts where they are known at startup and skips the -check where they are not, rather than guessing and failing on a name that cannot be resolved yet. +**`expectedAddressCount`는 어딘가에서 와야 한다.** 선언한 숫자이고, 선언은 틀릴 수 있다. 그래도 아무것도 비교하지 않는 +대안보다 낫다: 틀린 선언은 누가 적어 둔 틀린 말이고, 빠진 선언은 아무도 묻지 않은 질문이다. +`GrpcChannelProfileValidator`는 기동 때 알 수 있는 곳에서는 해석된 수를 받고, 알 수 없는 곳에서는 짐작해서 아직 해석할 수 +없는 이름에서 실패하는 대신 검사를 건너뛴다. -**xDS is reachable, and not by this route.** It lives in `grpc-advanced` (package `resilience`/`xds`) behind its -capability flag and its production approval, and `GrpcXdsStartupGuard.advertisableAsStableSupport()` -returns false so the Stable support statement cannot widen quietly. See ADR-GRPC-ADV-001. +**xDS에는 닿을 수 있지만, 이 길로는 아니다.** xDS는 `grpc-advanced`(패키지 `resilience`/`xds`)에서 자기 capability flag와 +운영 승인 뒤에 있고, `GrpcXdsStartupGuard.advertisableAsStableSupport()`가 false를 돌려주므로 Stable 지원 설명이 조용히 +넓어질 수 없다. ADR-GRPC-ADV-001을 본다. diff --git a/docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md b/docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md index 63e6bfde..07decf9c 100644 --- a/docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md +++ b/docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md @@ -7,60 +7,51 @@ - 현재 정본: `docs/compatibility/grpc-advanced-support-matrix.md` -# ADR-GRPC-ADV-001: Each advanced capability has its own flag, its own grade and its own promotion +# ADR-GRPC-ADV-001: advanced capability마다 자기 flag, 자기 등급, 자기 승격이 있다 -- Status: accepted -- Date: 2026-08-30 -- Scope: `:grpc-advanced:*` +- 상태: 채택 +- 날짜: 2026-08-30 +- 범위: `:grpc-advanced:*` -## Context +## 배경 -The advanced plan covers sixteen capabilities that differ by orders of magnitude in what they bring -with them. gRPC-Web adds a proxy. Reactor adds a dependency. xDS adds a control plane, its outage -modes, its own security boundary and its own version skew. Hedging duplicates production traffic. +advanced 계획은 capability 열여섯을 다룬다. 그것들이 함께 가져오는 것은 몇 자릿수씩 다르다. gRPC-Web은 proxy를 더한다. +Reactor는 의존 하나를 더한다. xDS는 control plane, 그 장애 방식, 자기 보안 경계, 자기 버전 어긋남을 더한다. hedging은 운영 +traffic을 겹친다. -Bundling them under one flag makes enabling the cheapest of those the same decision as enabling the -most consequential. +그것들을 flag 하나로 묶으면 가장 싼 것을 켜는 일이 가장 무거운 것을 켜는 일과 같은 결정이 된다. -## Decision +## 결정 -**One flag per capability**, under `ca-skeleton.grpc.advanced..enabled`, all off by -default. +**capability마다 flag 하나.** `ca-skeleton.grpc.advanced..enabled` 아래에 있고, 기본은 모두 꺼짐이다. -**Four grades.** `ADVANCED_STABLE` starts on its flag; `EXPERIMENTAL` additionally needs a separate -production approval, because the flag says somebody wanted the feature and the approval says somebody -accepted that its failure modes are not fully characterised; `WATCH` cannot start at all; `DISABLED` -is withdrawn. +**등급 넷.** `ADVANCED_STABLE`은 flag로 시작한다. `EXPERIMENTAL`은 따로 운영 승인도 필요하다. flag는 누가 그 기능을 원했다는 +뜻이고, 승인은 누가 그 장애 방식이 다 밝혀지지 않았음을 받아들였다는 뜻이기 때문이다. `WATCH`는 아예 시작할 수 없다. +`DISABLED`는 거둬들인 것이다. -`GrpcAdvancedModuleGuard` distinguishes the three refusals — flag unset, grade unstartable, -production unapproved — because the remedy differs in each case. +`GrpcAdvancedModuleGuard`는 세 거절 — flag 없음, 시작할 수 없는 등급, 운영 승인 없음 — 을 구별한다. 경우마다 고치는 법이 +다르기 때문이다. -**Promotion evidence is per capability.** `GrpcAdvancedPromotionEvidence` is one record per -capability, so no promotion can drag another along; -`GrpcAdvancedPromotionGate.capabilitiesDraggedAlong` returns an empty list, and that is a tested -property rather than a claim. (2026-09-28: the gate classes were removed because nothing outside -their own tests called them — review 2026-09-24 S5-lead-4. The per-capability rule stands as a -review rule in `docs/runbooks/grpc-advanced-capabilities.md`.) Two thresholds: seven days of soak plus complete evidence for -`ADVANCED_STABLE`, thirty for a Stable default, because the second means every deployment gets the -capability's dependencies and its failure modes. +**승격 증거는 capability마다다.** `GrpcAdvancedPromotionEvidence`는 capability마다 record 하나라서, 어떤 승격도 다른 것을 +끌고 가지 못한다. `GrpcAdvancedPromotionGate.capabilitiesDraggedAlong`은 빈 목록을 돌려주고, 그것은 주장이 아니라 시험한 +성질이다. (2026-09-28: gate 클래스는 자기 시험 밖에서 부르는 것이 없어서 지웠다 — review 2026-09-24 S5-lead-4. +capability별 규칙은 `docs/runbooks/grpc-advanced-capabilities.md`의 리뷰 규칙으로 남는다.) 문턱은 둘이다: +`ADVANCED_STABLE`에는 7일 soak와 완전한 증거, Stable 기본값에는 30일. 후자는 모든 배포가 그 capability의 의존과 장애 방식을 +받는다는 뜻이기 때문이다. -**Infrastructure is named per capability.** `GrpcAdvancedInfrastructureTestkit` records that -gRPC-Web needs a proxy, Servlet needs a container, xDS needs a stoppable control plane and Kotlin -needs a toolchain. A suite that runs without its infrastructure passes and establishes nothing, which -is worse than not having one. +**기반 시설은 capability마다 이름으로 댄다.** `GrpcAdvancedInfrastructureTestkit`은 gRPC-Web에는 proxy가, Servlet에는 +container가, xDS에는 멈출 수 있는 control plane이, Kotlin에는 toolchain이 필요하다고 적는다. 기반 시설 없이 도는 suite는 +통과하고 아무것도 세우지 않는다. 없는 것보다 나쁘다. -## Consequences +## 결과 -**The Kotlin adapter fails closed here, and says why.** This repository has no Kotlin toolchain, so -`GrpcKotlinCompatibilityGate.supportableHere()` returns false. The four contract requirements — one -schema source, coroutine cancellation propagation, Flow backpressure inside the Stable bounds, -platform evidence types preserved — are checkable and are checked; only the compile lane is missing. +**Kotlin 어댑터는 여기서 실패하면 닫히고, 이유를 말한다.** 이 저장소에는 Kotlin toolchain이 없어서 +`GrpcKotlinCompatibilityGate.supportableHere()`가 false를 돌려준다. 계약 요구 넷 — schema 출처 하나, coroutine 취소 전파, +Stable 한계 안의 Flow backpressure, 플랫폼 증거 타입 보존 — 은 검사할 수 있고 검사한다. 빠진 것은 compile lane뿐이다. -**Edition 2026 cannot be used however its watch report reads.** `GrpcEdition2026Guard` is not -conditional on the report, because letting a status record also authorise use means a schema moves -onto an edition the moment somebody marks four fields SUPPORTED, with no promotion decision, no -consumer migration and no ADR. +**Edition 2026은 그 watch 보고가 무어라 하든 쓸 수 없다.** `GrpcEdition2026Guard`는 보고에 따라 달라지지 않는다. 상태 기록이 +사용까지 허락하게 두면, 누가 필드 넷을 SUPPORTED로 표시하는 순간 schema가 승격 결정도, 쓰는 쪽 옮기기도, ADR도 없이 그 +edition으로 옮겨 가기 때문이다. -**xDS is not part of the Stable support statement.** It works, behind its flag and its approval; -`GrpcXdsStartupGuard.advertisableAsStableSupport()` returns false so a support matrix cannot widen -quietly. +**xDS는 Stable 지원 설명의 일부가 아니다.** flag와 승인 뒤에서 동작한다. `GrpcXdsStartupGuard.advertisableAsStableSupport()`가 +false를 돌려주므로 support matrix가 조용히 넓어질 수 없다. diff --git a/docs/adr/ADR-JPA-001-domain-owns-persistence-model.md b/docs/adr/ADR-JPA-001-domain-owns-persistence-model.md index 24a06a89..65d7427e 100644 --- a/docs/adr/ADR-JPA-001-domain-owns-persistence-model.md +++ b/docs/adr/ADR-JPA-001-domain-owns-persistence-model.md @@ -7,38 +7,34 @@ - 현재 정본: `docs/jpa/repository-adaptation.md` -# ADR-JPA-001 — The domain owns the persistence model +# ADR-JPA-001 — 영속 모델은 도메인이 가진다 -- Status: Accepted -- Date: 2026-08-11 -- Design: §10.1, §23.3 +- 상태: 채택 +- 날짜: 2026-08-11 +- 설계: §10.1, §23.3 -## Context +## 배경 -A persistence platform can either own the repository abstraction — a `GenericRepository` -every aggregate inherits — or provide only the pieces domains assemble themselves. +영속 플랫폼은 repository 추상 — 모든 aggregate가 상속하는 `GenericRepository` — 을 가질 수도 있고, 도메인이 스스로 +조립할 조각만 줄 수도 있다. -## Decision +## 결정 -The domain owns entities, embeddables, repositories, queries, index requirements, and lock, -soft-delete, and audit policy. The platform provides no generic CRUD repository and no base -repository. `JpaRepositoryFragmentSupport` exists, has no `save`, `findById`, `findAll`, or -`delete`, and is enforced not to acquire them. +엔티티, embeddable, repository, query, index 요구, lock·soft-delete·감사 정책은 도메인이 가진다. 플랫폼은 범용 CRUD +repository도 기반 repository도 주지 않는다. `JpaRepositoryFragmentSupport`는 있지만 `save`, `findById`, `findAll`, `delete`가 +없고, 그것을 얻지 못하게 강제한다. -## Consequences +## 결과 -A generic base repository has one property that looks like a benefit and is not: every aggregate -gets the same operations. That means each aggregate is offered operations that may be wrong for it — -a `delete` on an append-only ledger, a `findAll` on a table that will never be small — and, worse, -one aggregate's later requirement changes the shared base and therefore changes behaviour for -aggregates nobody reviewed. +범용 기반 repository에는 이득처럼 보이지만 이득이 아닌 성질이 하나 있다: 모든 aggregate가 같은 operation을 받는다. 그러면 +aggregate마다 자기에게 틀릴 수 있는 operation을 받게 된다 — append-only 원장의 `delete`, 결코 작지 않을 테이블의 `findAll` — +그리고 더 나쁘게, 한 aggregate의 나중 요구가 공용 기반을 바꾸고 그래서 아무도 리뷰하지 않은 aggregate의 동작을 바꾼다. -Spring Data already implements CRUD. Re-implementing it adds a layer whose only function is to be -harder to opt out of. +Spring Data는 이미 CRUD를 구현한다. 그것을 다시 구현하면 빠져나가기 더 어렵게 만드는 것만이 하는 일인 계층이 더해진다. -The cost is a small amount of repetition: each domain declares the repository interface it needs. -That repetition is the thing that makes each aggregate's persistence surface reviewable. +비용은 약간의 되풀이다: 도메인마다 필요한 repository 인터페이스를 선언한다. 그 되풀이가 aggregate마다 영속 surface를 리뷰할 +수 있게 만든다. -## Enforcement +## 강제 -`JpaArchitectureRules.noGenericRepository()`; `JpaRepositoryFragmentSupportTest`. +`JpaArchitectureRules.noGenericRepository()`, `JpaRepositoryFragmentSupportTest`. diff --git a/docs/adr/ADR-JPA-002-full-transaction-retry.md b/docs/adr/ADR-JPA-002-full-transaction-retry.md index a2491bce..fb5f1e36 100644 --- a/docs/adr/ADR-JPA-002-full-transaction-retry.md +++ b/docs/adr/ADR-JPA-002-full-transaction-retry.md @@ -8,43 +8,39 @@ - 대체됨: `docs/capability-status.md` -# ADR-JPA-002 — Retry re-runs the whole use case +# ADR-JPA-002 — 재시도는 유스케이스 전체를 다시 돌린다 -- Status: Superseded (2026-09-25) — the retry engine this ADR describes - (`FullTransactionRetryCoordinator`, `JpaTransactionExecutor`) was removed. `SpringTransactionPort` - retries nothing; a caller that retries still re-runs the whole use case, which is the part of this - decision that stands. The last commit is in `docs/capability-status.md`. -- Date: 2026-08-11 -- Design: §19.2 +- 상태: 대체됨(2026-09-25) — 이 ADR이 설명하는 재시도 엔진(`FullTransactionRetryCoordinator`, `JpaTransactionExecutor`)은 + 지웠다. `SpringTransactionPort`는 아무것도 재시도하지 않는다. 재시도하는 호출자는 여전히 유스케이스 전체를 다시 돌리고, + 이 결정 중 그 부분이 남는다. 마지막 커밋은 `docs/capability-status.md`에 있다. +- 날짜: 2026-08-11 +- 설계: §19.2 -## Context +## 배경 -Optimistic conflicts, deadlocks, and serialization failures are recoverable. The question is what -unit gets retried: the failed statement, the transaction, or the use case. +낙관적 충돌, 교착, serialization 실패는 회복할 수 있다. 질문은 무엇을 단위로 재시도하느냐다: 실패한 문장, 트랜잭션, 또는 +유스케이스. -## Decision +## 결정 -The whole use case, in a new transaction with a new Persistence Context. -`FullTransactionRetryCoordinator` re-enters `JpaTransactionExecutor` for every attempt, and the -retry advice is ordered outside Spring's transaction advice so each attempt begins a new -transaction. +유스케이스 전체를, 새 Persistence Context를 가진 새 트랜잭션에서. `FullTransactionRetryCoordinator`는 시도마다 +`JpaTransactionExecutor`에 다시 들어가고, 재시도 advice는 Spring 트랜잭션 advice 바깥으로 순서를 잡아 시도마다 새 +트랜잭션을 시작한다. -## Consequences +## 결과 -Statement-level retry is wrong for exactly the failures being retried. An optimistic conflict means -the state the attempt computed against is no longer the committed state; re-issuing the same -statement computes the same wrong answer against a version that has moved on. The domain rules have -to run again over reloaded data, which means the whole use case. +문장 단위 재시도는 바로 재시도하려는 실패에 틀린 답이다. 낙관적 충돌은 시도가 계산의 바탕으로 삼은 상태가 더는 커밋된 +상태가 아니라는 뜻이다. 같은 문장을 다시 내면 이미 움직인 version에 대고 같은 틀린 답을 계산한다. 도메인 규칙은 다시 읽은 +데이터 위에서 다시 돌아야 하고, 그것은 유스케이스 전체라는 뜻이다. -Reusing the Persistence Context would be equally wrong: the second attempt would read the first -attempt's stale entities out of the first-level cache. And with the advice ordering inverted, the -retry loop would run inside one transaction that has already been marked rollback-only, so the -second attempt fails immediately without executing anything. +Persistence Context를 다시 쓰는 것도 똑같이 틀렸다: 두 번째 시도가 1차 cache에서 첫 시도의 낡은 엔티티를 읽게 된다. 그리고 +advice 순서가 뒤집히면 재시도 반복문이 이미 rollback-only로 표시된 트랜잭션 하나 안에서 돌아서, 두 번째 시도가 아무것도 +실행하지 않고 바로 실패한다. -The cost is that a retryable use case must be safe to run from scratch — no irreversible external -effect before the commit. `IrreversibleSideEffectContext` lets a use case declare when that does not -hold, and the policy then refuses to retry it whatever budget remains. +비용은 재시도할 수 있는 유스케이스가 처음부터 돌려도 안전해야 한다는 것이다 — 커밋 전에 되돌릴 수 없는 외부 효과가 없어야 +한다. `IrreversibleSideEffectContext`로 유스케이스가 그렇지 않을 때를 선언할 수 있고, 그러면 정책은 남은 예산이 얼마든 그 +재시도를 거절한다. -## Enforcement +## 강제 -`FullTransactionRetryCoordinatorTest`; `RetryableJpaTransactionInterceptor.DEFAULT_ORDER`. +`FullTransactionRetryCoordinatorTest`, `RetryableJpaTransactionInterceptor.DEFAULT_ORDER`. diff --git a/docs/adr/ADR-JPA-003-completion-unknown.md b/docs/adr/ADR-JPA-003-completion-unknown.md index c283d6db..eef2a271 100644 --- a/docs/adr/ADR-JPA-003-completion-unknown.md +++ b/docs/adr/ADR-JPA-003-completion-unknown.md @@ -7,57 +7,49 @@ - 현재 정본: `docs/jpa/transaction-guide.md` -# ADR-JPA-003 — Completion unknown is never retried +# ADR-JPA-003 — 완료를 모름은 절대 재시도하지 않는다 -- Status: Accepted; amended 2026-09-25 — `TransactionCompletionResolver`, `CommitFailureClassifier` - and the retry engine were removed. The invariant holds because `SpringTransactionPort`, the only - transaction engine, retries nothing; enforcement below is updated accordingly. -- Date: 2026-08-11 -- Design: §17 +- 상태: 채택. 2026-09-25 보완 — `TransactionCompletionResolver`, `CommitFailureClassifier`, 재시도 엔진을 지웠다. 유일한 + 트랜잭션 엔진인 `SpringTransactionPort`가 아무것도 재시도하지 않으므로 불변식이 지켜진다. 아래 강제 절도 그에 맞게 + 고쳤다. +- 날짜: 2026-08-11 +- 설계: §17 -## Context +## 배경 -A connection can break while a commit is in flight. The server may have committed; the -acknowledgement may simply have been lost. The driver cannot tell the two apart. +커밋이 진행 중일 때 연결이 끊길 수 있다. 서버가 커밋했을 수도 있고, 확인 응답만 잃었을 수도 있다. driver는 둘을 구별하지 +못한다. -## Decision +## 결정 -`TransactionCompletionUnknownException` is never retried, automatically or otherwise. It is -produced only by a failure observed while the transaction phase is `COMMITTING`, and only for -SQLSTATE `40003`, a connection-class (`08*`) state, or a transport break. Recovery is -domain-specific reconciliation. +`TransactionCompletionUnknownException`은 자동이든 아니든 절대 재시도하지 않는다. 트랜잭션 단계가 `COMMITTING`인 동안 본 +실패에서만, 그리고 SQLSTATE `40003`, 연결 class(`08*`) 상태, 전송 끊김에 대해서만 만든다. 회복은 도메인별 맞춰 보기다. -## Consequences +## 결과 -Retrying a possibly-committed write is the most damaging thing this platform could do: a duplicate -payment, a duplicate order, a double decrement. There is no budget or backoff that makes it safe, -because the failure is epistemic rather than transient. +커밋됐을지 모르는 쓰기를 재시도하는 것이 이 플랫폼이 할 수 있는 가장 해로운 일이다: 중복 결제, 중복 주문, 두 번 깎기. +실패가 일시적인 것이 아니라 알 수 없는 것이라서, 그것을 안전하게 만드는 예산이나 backoff는 없다. -The invariant is enforced at the type level rather than by policy alone. `JpaFailureContext` refuses -to construct a retryable completion-unknown context, and the exception rebuilds its context through -the safe factory whatever it is handed. A future policy bug therefore cannot produce an unsafe -retry — the value it would need does not exist. +불변식은 정책만이 아니라 타입 수준에서 강제한다. `JpaFailureContext`는 재시도할 수 있는 completion-unknown 문맥을 만들기를 +거절하고, 예외는 무엇을 받든 안전한 factory로 자기 문맥을 다시 만든다. 그래서 나중의 정책 결함이 안전하지 않은 재시도를 낳을 +수 없다 — 그것에 필요한 값이 존재하지 않는다. -The rule is deliberately narrow in the other direction too. Classifying every connection failure as -completion-unknown would push ordinary pool exhaustion and server restarts into the reconciliation -queue, which trains operators to clear that queue without reading it — and then the one entry that -mattered gets cleared with the rest. +규칙은 반대 방향으로도 일부러 좁다. 모든 연결 실패를 completion-unknown으로 분류하면 보통의 pool 고갈과 서버 재시작이 맞춰 +보기 queue로 밀려 들어가고, 그것은 운영자에게 그 queue를 읽지 않고 비우도록 길들인다 — 그러면 중요했던 항목 하나가 나머지와 +함께 지워진다. -The cost is that the domain must supply the resolver. The platform cannot: only the domain knows -which idempotency record, business row, or outbox entry proves the write happened. +비용은 도메인이 resolver를 줘야 한다는 것이다. 플랫폼은 할 수 없다: 어떤 멱등성 레코드, 업무 행, outbox 항목이 쓰기가 +일어났음을 증명하는지는 도메인만 안다. -## Enforcement +## 강제 -Production path: `SpringTransaction` records when the action has returned in a write transaction it -began; a failure after that point goes through -`PersistenceExceptionTranslator#translateCommitFailure`, which builds this exception for `08*`, -`40003`, a vendor termination state (`SqlStateErrorMapping#commitOutcomeUnknownStates`, PostgreSQL -`57P01`/`57P02`) or a transport break. Hibernate's flush inside the commit is not separated from the -COMMIT itself, so a connection lost during that flush is also reported as unknown — the safe side. -Until review 04-01 (2026-11-01) nothing constructed the exception and a commit-phase `08*` reached -callers as the retryable `DB_UNAVAILABLE`. +운영 경로: `SpringTransaction`은 자기가 시작한 쓰기 트랜잭션에서 action이 돌아온 때를 기록한다. 그 뒤의 실패는 +`PersistenceExceptionTranslator#translateCommitFailure`를 거치고, 그것이 `08*`, `40003`, vendor 종료 상태 +(`SqlStateErrorMapping#commitOutcomeUnknownStates`, PostgreSQL `57P01`/`57P02`), 전송 끊김에 대해 이 예외를 만든다. 커밋 안의 +Hibernate flush는 COMMIT 자체와 나뉘지 않으므로, 그 flush 중에 잃은 연결도 모름으로 알린다 — 안전한 쪽이다. review +04-01(2026-11-01) 전까지는 아무것도 이 예외를 만들지 않았고, 커밋 단계의 `08*`가 재시도할 수 있는 `DB_UNAVAILABLE`로 호출자에게 +닿았다. -`JpaFailureContextTest`; `SpringTransactionTest`; `PersistenceExceptionTranslatorTest`; +`JpaFailureContextTest`, `SpringTransactionTest`, `PersistenceExceptionTranslatorTest`, `PostgreSqlTransactionIntegrationTest#connectionLossDuringCommitSurfacesAsCompletionUnknownAndIsNeverRetried` -(asserts `DB_COMPLETION_UNKNOWN`; also the `jpa-failure` lane, i.e. release gate -`completion-unknown-no-retry`). +(`DB_COMPLETION_UNKNOWN`을 단언한다. `jpa-failure` lane, 곧 릴리스 gate `completion-unknown-no-retry`이기도 하다). diff --git a/docs/adr/ADR-JPA-004-flyway-schema-source-of-truth.md b/docs/adr/ADR-JPA-004-flyway-schema-source-of-truth.md index 63be96de..fbd69256 100644 --- a/docs/adr/ADR-JPA-004-flyway-schema-source-of-truth.md +++ b/docs/adr/ADR-JPA-004-flyway-schema-source-of-truth.md @@ -7,41 +7,37 @@ - 현재 정본: `docs/jpa/migration-guide.md` -# ADR-JPA-004 — Flyway is the schema source of truth +# ADR-JPA-004 — schema의 정본은 Flyway다 -- Status: Accepted -- Date: 2026-08-11 -- Design: §31 +- 상태: 채택 +- 날짜: 2026-08-11 +- 설계: §31 -## Context +## 배경 -Hibernate can create and alter schema from the entity mapping. Flyway can apply versioned scripts. -Both cannot own the schema. +Hibernate는 엔티티 대응에서 schema를 만들고 바꿀 수 있다. Flyway는 버전 있는 script를 적용할 수 있다. 둘이 함께 schema를 가질 +수는 없다. -## Decision +## 결정 -Flyway owns every schema change. Hibernate validates and never mutates: `ddl-auto` is `validate` or -`none`, enforced at startup. The runtime database credential holds no DDL privilege, so the rule is -enforced by the server as well as by configuration. +모든 schema 변경은 Flyway가 가진다. Hibernate는 검증만 하고 절대 바꾸지 않는다: `ddl-auto`는 `validate`나 `none`이고, 기동 때 +강제한다. 런타임 데이터베이스 credential에는 DDL 권한이 없으므로, 규칙을 설정만이 아니라 서버도 강제한다. -## Consequences +## 결과 -`ddl-auto=update` fails in a specific and expensive way: it adds but never drops or narrows, so the -result is a schema that is neither the previous one nor the one the mappings describe — produced -silently, by whichever instance started first, with no record of what it did. +`ddl-auto=update`는 구체적이고 비싸게 실패한다: 더하기만 하고 지우거나 좁히지 않아서, 결과는 이전 것도 대응이 설명하는 것도 +아닌 schema다 — 먼저 시작한 인스턴스가 무엇을 했는지 기록도 없이 소리 없이 만든다. -Two credentials rather than one is what makes this more than a convention. A configuration rule can -be overridden by a property; a role without `CREATE` cannot be overridden by anything the -application does. +credential을 하나가 아니라 둘 두는 것이 이것을 관례 이상으로 만든다. 설정 규칙은 속성 하나로 덮을 수 있다. `CREATE`가 없는 +role은 애플리케이션이 무엇을 하든 덮을 수 없다. -Validation fails closed and never repairs. `repair` rewrites the schema history to match the scripts -on disk, which resolves a checksum mismatch by deleting the evidence of which change is missing. +검증은 실패하면 닫히고 절대 고치지 않는다. `repair`는 schema 이력을 디스크의 script에 맞게 다시 쓰는데, 그것은 어떤 변경이 +빠졌는지의 증거를 지워서 checksum 불일치를 푸는 것이다. -The cost is that a schema change requires a migration script and a deployment step. That is the -intended cost: it makes schema change reviewable and reversible. +비용은 schema 변경에 migration script와 배포 단계가 필요하다는 것이다. 그것이 의도한 비용이다: schema 변경을 리뷰할 수 있고 +되돌릴 수 있게 만든다. -## Enforcement +## 강제 -`JpaDangerousConfigurationGuard`; `FlywaySchemaPolicy`; `FlywayValidationGate` (testkit, used by the -migration contract tests); `PostgreSqlRuntimeRoleVerifier`; release gates `flyway-validate` and -`runtime-role-no-ddl`. +`JpaDangerousConfigurationGuard`, `FlywaySchemaPolicy`, `FlywayValidationGate`(testkit, migration 계약 시험이 쓴다), +`PostgreSqlRuntimeRoleVerifier`, 릴리스 gate `flyway-validate`와 `runtime-role-no-ddl`. diff --git a/docs/adr/ADR-JPA-005-postgresql-real-contract.md b/docs/adr/ADR-JPA-005-postgresql-real-contract.md index 116d2487..26223db6 100644 --- a/docs/adr/ADR-JPA-005-postgresql-real-contract.md +++ b/docs/adr/ADR-JPA-005-postgresql-real-contract.md @@ -7,41 +7,36 @@ - 현재 정본: `docs/jpa/support-matrix.md` -# ADR-JPA-005 — Contracts run against real PostgreSQL +# ADR-JPA-005 — 계약은 실제 PostgreSQL에 대고 돈다 -- Status: Accepted -- Date: 2026-08-11 -- Design: §40 +- 상태: 채택 +- 날짜: 2026-08-11 +- 설계: §40 -## Context +## 배경 -An in-memory database makes tests fast and hermetic. A container makes them slow and requires -Docker. +메모리 데이터베이스는 시험을 빠르고 밀폐되게 만든다. container는 느리게 만들고 Docker를 요구한다. -## Decision +## 결정 -Every persistence contract runs against real PostgreSQL 16, 17, and 18 in containers. H2 remains a -local-development convenience and never satisfies a contract. The lanes fail closed when Docker is -absent rather than skipping. +모든 영속 계약은 container 안의 실제 PostgreSQL 16, 17, 18에 대고 돈다. H2는 로컬 개발 편의로 남고 어떤 계약도 만족시키지 +않는다. Docker가 없으면 lane은 건너뛰지 않고 실패하면 닫힌다. -## Consequences +## 결과 -The behaviours these contracts verify either do not exist in H2 or differ there: SQLSTATE values for -the same violation, `FOR UPDATE SKIP LOCKED` semantics, JSONB operators, range types, concurrent -index builds, `search_path` privileges, and the generated SQL for a paged collection fetch. A green -H2 run is evidence that the code compiles and runs — not that any of the above holds. +이 계약이 검증하는 동작은 H2에 없거나 다르다: 같은 위반의 SQLSTATE 값, `FOR UPDATE SKIP LOCKED`의 뜻, JSONB 연산자, 범위 타입, +concurrent index 만들기, `search_path` 권한, page를 나눈 컬렉션 fetch의 생성 SQL. H2 실행이 초록이면 코드가 컴파일되고 돈다는 +증거이지 — 위 어느 것이 지켜진다는 증거가 아니다. -Three versions rather than one because the platform claims three. A contract suite that ran only on -16 would make "Stable on 17 and 18" an assumption. +버전을 하나가 아니라 셋 두는 것은 플랫폼이 셋을 주장하기 때문이다. 16에서만 도는 계약 suite는 「17과 18에서 Stable」을 가정으로 +만든다. -Skipping on missing Docker is the failure mode this decision most wants to avoid: a skipped contract -reports success, and CI eventually inherits that silence. `PostgreSqlContainerFactory.assertDockerAvailable()` -throws instead. +Docker가 없을 때 건너뛰는 것이 이 결정이 가장 피하려는 실패 방식이다: 건너뛴 계약은 성공을 알리고, CI는 결국 그 침묵을 +물려받는다. `PostgreSqlContainerFactory.assertDockerAvailable()`은 대신 던진다. -The cost is that the contract lanes need Docker and take minutes. The unit lane stays hermetic and -fast, and is where most tests live; the container lanes verify the things only a real server can -answer. +비용은 계약 lane에 Docker가 필요하고 몇 분이 걸린다는 것이다. 단위 lane은 밀폐되고 빠른 채로 남고 대부분의 시험이 거기 있다. +container lane은 실제 서버만 답할 수 있는 것을 검증한다. -## Enforcement +## 강제 -`PostgreSqlVersion.stable()`; `PostgreSqlContainerFactory`; release gate `postgresql-contract`. +`PostgreSqlVersion.stable()`, `PostgreSqlContainerFactory`, 릴리스 gate `postgresql-contract`. diff --git a/docs/adr/ADR-JPA-006-canonical-technical-audit.md b/docs/adr/ADR-JPA-006-canonical-technical-audit.md index 80aadd31..476d9ce3 100644 --- a/docs/adr/ADR-JPA-006-canonical-technical-audit.md +++ b/docs/adr/ADR-JPA-006-canonical-technical-audit.md @@ -7,68 +7,58 @@ - 현재 정본: `docs/jpa/repository-adaptation.md` -# ADR-JPA-006 — `audit` is the sole technical audit model +# ADR-JPA-006 — 기술 감사 모델은 `audit` 하나뿐이다 -- Status: Accepted -- Date: 2026-08-24 -- Review: `docs/reviews/2026-08-14-jpa-module-code-review.md` JPA-022 +- 상태: 채택 +- 날짜: 2026-08-24 +- 리뷰: `docs/reviews/2026-08-14-jpa-module-code-review.md` JPA-022 -## Context +## 배경 -Two complete technical-audit mechanisms live in this leaf and they disagree about the schema. +이 leaf에 완전한 기술 감사 장치가 둘 있고, 둘은 schema에 대해 의견이 다르다. -`audit/AuditableEntity` stamps `created_at`/`created_by`/`updated_at`/`updated_by` with an actor -column of length 256, captured through explicit `initializeAudit`/`applyModification` calls and an -`AuditContextPort`. `auditing/AuditMetadata` is a Spring Data embeddable that stamps -`created_*`/`modified_*` with an actor column of length 64, captured by `@CreatedDate` and friends -through an `AuditorAware`. +`audit/AuditableEntity`는 길이 256의 actor 열과 함께 `created_at`/`created_by`/`updated_at`/`updated_by`를 넣고, 명시적인 +`initializeAudit`/`applyModification` 호출과 `AuditContextPort`로 값을 잡는다. `auditing/AuditMetadata`는 길이 64의 actor 열과 +함께 `created_*`/`modified_*`를 넣는 Spring Data embeddable이고, `AuditorAware`를 거쳐 `@CreatedDate` 같은 것으로 값을 잡는다. -Only the first is real: it is what the sample entities extend and what the migrations were written -for. `JpaAuditingConfiguration` is not a Spring `@Configuration`, and nothing in production -constructs any of the three `auditing` types. +실제로 쓰이는 것은 첫째뿐이다: 샘플 엔티티가 상속하는 것이고 migration도 그것을 위해 썼다. `JpaAuditingConfiguration`은 Spring +`@Configuration`이 아니고, 운영 코드의 어떤 것도 `auditing` 타입 셋 중 하나를 만들지 않는다. -The review asked for one canonical model with a migration or activation decision. The failure mode -it was protecting against is specific: an author of a new entity picks whichever package they find -first, and column names, actor lengths and capture lifecycles then diverge per table. +리뷰는 migration이나 켜기 결정이 붙은 정해진 모델 하나를 요구했다. 막으려던 실패 방식은 구체적이다: 새 엔티티를 쓰는 사람이 +먼저 찾은 패키지를 고르고, 그러면 열 이름, actor 길이, 값 잡는 lifecycle이 테이블마다 갈라진다. -## Decision +## 결정 -`audit/AuditableEntity` is canonical and the unused `auditing/*` implementation is removed. +`audit/AuditableEntity`가 정본이고, 쓰지 않는 `auditing/*` 구현은 지운다. -Keeping a complete, incompatible implementation as a dormant candidate created exactly the -ambiguity the review warned about: a new entity could choose a package by autocomplete and silently -change column names, actor bounds and capture lifecycle. A future move to Spring Data auditing is a -migration of the canonical model, not activation of a second model that has drifted beside it. +완전하고 호환되지 않는 구현을 잠든 후보로 두는 것이 바로 리뷰가 경고한 모호함을 만들었다: 새 엔티티가 자동 완성으로 패키지를 +고르고 열 이름, actor 한계, 값 잡는 lifecycle을 소리 없이 바꿀 수 있었다. 나중에 Spring Data auditing으로 옮기는 것은 정본 +모델의 migration이지, 옆에서 어긋나 온 두 번째 모델을 켜는 것이 아니다. -That future migration must preserve `created_*`/`updated_*`, the 256-character actor contract, -`AuditContextPort`, and the shared `Clock`; listener wiring and entity conversion land atomically. +그 나중의 migration은 `created_*`/`updated_*`, 256자 actor 계약, `AuditContextPort`, 공용 `Clock`을 지켜야 한다. listener 배선과 +엔티티 변환은 한 번에 들어온다. -## Consequences +## 결과 -Two audit mechanisms remain readable in one leaf, and a reader has to be told which one is live. -That cost is paid in this document, in the package javadoc and in a test whose name says so. +감사 장치 둘이 한 leaf 안에 읽을 수 있게 남고, 읽는 사람에게 어느 것이 살아 있는지 알려야 한다. 그 비용은 이 문서, 패키지 +javadoc, 그리고 이름이 그것을 말하는 시험이 낸다. -Two failure modes stay silent unless they are asserted, so both are: +단언하지 않으면 소리 없이 남는 실패 방식이 둘 있으므로, 둘 다 단언한다: -- The candidate acquires a stereotype and starts stamping in every deployment that has this module - on the classpath, including the ones whose tables have no `modified_*` columns — where the result - is a failed startup rather than a feature. -- Somebody "harmonises" the two by editing one side's column names, at which point the schema a - deployed table was migrated for and the schema its entity expects diverge with no migration - between them. +- 후보가 stereotype을 얻어 이 모듈이 classpath에 있는 모든 배포에서 값을 넣기 시작한다. 테이블에 `modified_*` 열이 없는 배포도 + 포함된다 — 거기서 결과는 기능이 아니라 기동 실패다. +- 누가 한쪽 열 이름을 고쳐 둘을 「맞춘다」. 그러면 배포된 테이블이 migration된 schema와 그 엔티티가 기대하는 schema가 둘 사이 + migration 없이 갈라진다. -If the candidate is ever promoted, it is promoted atomically: forward migration, sample conversion, -`AuditContextPort → AuditorAware` and `Clock → DateTimeProvider` bridges land together, and this -ADR is superseded rather than amended. +후보를 언젠가 승격하면 한 번에 승격한다: 앞으로 가는 migration, 샘플 변환, `AuditContextPort → AuditorAware`와 +`Clock → DateTimeProvider` 다리가 함께 들어오고, 이 ADR은 보완이 아니라 대체된다. -Bulk and native updates stamp nothing under either mechanism. That is a property of JPA, not of the -choice made here, so it is enforced separately rather than assumed away. +bulk·native update는 어느 장치에서든 아무것도 넣지 않는다. 그것은 여기서 고른 것의 성질이 아니라 JPA의 성질이므로, 없다고 +치지 않고 따로 강제한다. -## Enforcement +## 강제 -`JpaAuditMechanismRule.entitiesUseExactlyOneAuditMechanism` and -`bulkUpdatesOfAuditedEntitiesStampAudit`, run against the real production graph by -`JpaProductionArchitectureTest` at the composition root — not against fixtures, which is how the -earlier version of this rule pack passed while applying to nothing. `AuditingCandidateStatusTest` -asserts the candidate carries no composing stereotype and that the two column sets stay distinct. -`JpaAuditMechanismRuleTest` exercises the rules' own negative cases. +`JpaAuditMechanismRule.entitiesUseExactlyOneAuditMechanism`과 `bulkUpdatesOfAuditedEntitiesStampAudit`를 조립 루트의 +`JpaProductionArchitectureTest`가 실제 운영 그래프에 대고 돌린다 — fixture가 아니다. 이 규칙 묶음의 앞 버전은 fixture에 대고 +돌아서 아무것에도 적용되지 않은 채 통과했다. `AuditingCandidateStatusTest`가 후보에 조립하는 stereotype이 없고 두 열 집합이 +따로 남는다고 단언한다. `JpaAuditMechanismRuleTest`가 규칙 자신의 부정 경우를 시험한다. diff --git a/docs/adr/ADR-MONGO-001-platform-boundary.md b/docs/adr/ADR-MONGO-001-platform-boundary.md index 62358927..7da70fc2 100644 --- a/docs/adr/ADR-MONGO-001-platform-boundary.md +++ b/docs/adr/ADR-MONGO-001-platform-boundary.md @@ -7,66 +7,59 @@ - 현재 정본: `docs/mongodb/repository-adaptation.md` -# ADR-MONGO-001 — MongoDB platform boundary +# ADR-MONGO-001 — MongoDB 플랫폼 경계 -- **Status:** Accepted -- **Date:** 2026-08-13 -- **Design source:** `docs/superpowers/specs/2026-08-11-mongodb-document-persistence-platform-design.md` §1, §2 (D-01, D-04, D-05), §5, §6 +- **상태:** 채택 +- **날짜:** 2026-08-13 +- **설계 출처:** `docs/superpowers/specs/2026-08-11-mongodb-document-persistence-platform-design.md` §1, §2 (D-01, D-04, D-05), §5, §6 -## Context +## 배경 -Two failure modes are common when a team wraps MongoDB. +팀이 MongoDB를 감쌀 때 흔한 실패 방식이 둘 있다. -The first is flattening: a shared `CommonMongoRepository` and a generic CRUD facade, which -forces every collection to share an id strategy, a consistency profile and a query surface. MongoDB's -single-document atomicity, aggregation model and change streams stop being reachable, and the first -collection that needs something different gets a cast or a leaky generic. +첫째는 납작하게 만들기다: 공용 `CommonMongoRepository`와 범용 CRUD 창구. 모든 collection이 id 전략, 일관성 profile, +query surface를 같이 쓰게 강요한다. MongoDB의 단일 문서 원자성, aggregation 모델, change stream에 더는 닿을 수 없고, 다른 것이 +필요한 첫 collection은 cast나 새는 제네릭을 받는다. -The second is unrestricted exposure: the driver and `runCommand` available everywhere. Then any -service can drop a collection, run an unbounded pipeline, or issue an admin command from a request -thread, and no review catches it because there is nothing structural to catch. +둘째는 제한 없는 노출이다: driver와 `runCommand`를 어디서나 쓸 수 있다. 그러면 어느 서비스든 요청 스레드에서 collection을 +지우거나, 한계 없는 pipeline을 돌리거나, admin 명령을 낼 수 있고, 구조로 잡을 것이 없으니 어떤 리뷰도 잡지 못한다. -## Decision +## 결정 -The domain owns its documents; the platform owns the cross-cutting decisions. Four exposure planes: +도메인이 자기 문서를 가지고, 플랫폼이 가로지르는 결정을 가진다. 노출 plane 넷: -| Plane | Contents | Client | +| plane | 내용 | client | |---|---|---| -| D1 Standard document persistence | Spring Data repositories, typed queries, mapping manifest, atomic update primitives, optimistic revision | Stable API V1, `apiStrict=true` | -| D2 Advanced document operations | `MongoTemplate`, transactions/sessions, bulk, aggregation, keyset cursors, change streams | Stable API V1, `apiStrict=true` | -| D3 Explicit Mongo capability | Native BSON, time series, search/vector, CSFLE/QE, shard-aware operations | Separate capability client | -| D4 Admin plane | Collection, validator, index, migration, shard, repair | Separate admin client and credential | +| D1 표준 문서 영속 | Spring Data repository, 타입 있는 query, 대응 manifest, 원자 update 기본 장치, 낙관적 revision | Stable API V1, `apiStrict=true` | +| D2 고급 문서 연산 | `MongoTemplate`, 트랜잭션·세션, bulk, aggregation, keyset cursor, change stream | Stable API V1, `apiStrict=true` | +| D3 명시적 Mongo capability | native BSON, time series, search·vector, CSFLE·QE, shard를 아는 연산 | 따로 둔 capability client | +| D4 admin plane | collection, validator, index, migration, shard, repair | 따로 둔 admin client와 credential | -Specifically: +구체적으로: -1. **No `CommonMongoRepository`.** Each aggregate declares its own repository. -2. **D1/D2 run on Stable API V1 with `apiStrict=true`,** so a command outside the versioned API fails - at development time instead of on the next server upgrade. -3. **D3 is not a raw-client escape.** Every call passes a fixed admission order: capability registered - → database profile → collection allowlist → operation name → timeout → consistency profile → - result limit → trace → redaction → command category → admin-command refusal → execute. -4. **D4 is a separate client with a separate credential.** No application-plane path reaches it; - `PolicyAwareMongoNativeGateway` refuses admin-category commands regardless of capability. -5. **Advanced and Experimental capabilities are opt-in modules**, never transitive dependencies of the - Stable surface. +1. **`CommonMongoRepository`가 없다.** aggregate마다 자기 repository를 선언한다. +2. **D1·D2는 `apiStrict=true`인 Stable API V1에서 돈다.** 그래서 버전 있는 API 밖의 명령은 다음 서버 업그레이드 때가 아니라 + 개발 때 실패한다. +3. **D3는 raw client로 빠져나가는 길이 아니다.** 모든 호출이 정해진 허가 순서를 지난다: capability 등록 → 데이터베이스 + profile → collection 허용 목록 → operation 이름 → timeout → 일관성 profile → 결과 한계 → trace → 가리기 → 명령 category → + admin 명령 거절 → 실행. +4. **D4는 따로 둔 credential을 가진 따로 둔 client다.** 애플리케이션 plane 경로는 그것에 닿지 않는다. + `PolicyAwareMongoNativeGateway`는 capability와 관계없이 admin category 명령을 거절한다. +5. **Advanced와 Experimental capability는 골라 쓰는 모듈이고**, Stable surface의 전이 의존이 되지 않는다. -## Consequences +## 결과 -**Positive.** MongoDB's semantics stay reachable. Misuse is refused structurally rather than reviewed -for. A server upgrade cannot silently change D1/D2 behaviour. Admin operations have their own audit -trail and credential. +**좋은 점.** MongoDB의 뜻에 계속 닿을 수 있다. 잘못된 사용은 리뷰로 찾지 않고 구조로 거절한다. 서버 업그레이드가 D1·D2 +동작을 소리 없이 바꿀 수 없다. admin 연산은 자기 감사 흔적과 credential을 가진다. -**Negative.** Every operation needs a registered name and profile, so a new query is a small amount of -configuration rather than zero. A genuinely new capability requires a registration before it can be -used. Both are deliberate: the cost is paid once per operation, at review time. +**나쁜 점.** 모든 operation에 등록된 이름과 profile이 필요해서, 새 query에는 0이 아니라 약간의 설정이 든다. 정말 새 capability는 +쓰기 전에 등록이 필요하다. 둘 다 일부러다: 비용은 operation마다 한 번, 리뷰 때 낸다. -**Rejected alternative — "expose the driver, rely on code review."** Review does not scale to every -query in every service, and the operations that matter (unbounded pipeline, `dropCollection`, -unanchored regex on user input) look unremarkable in a diff. +**버린 대안 — 「driver를 내놓고 코드 리뷰에 기댄다」.** 리뷰는 모든 서비스의 모든 query로 늘어나지 못하고, 중요한 연산 +(한계 없는 pipeline, `dropCollection`, 사용자 입력에 대한 anchor 없는 정규식)은 diff에서 눈에 띄지 않는다. -## Repository adaptation +## 저장소에 맞추기 -The design assumes 19 Gradle modules under `modules/mongodb/`. This repository's fail-closed registry -declares exactly 19 leaf identities, so the modules became package boundaries inside -`:adapter:outbound:persistence-mongo`, enforced by ArchUnit. See -[docs/mongodb/repository-adaptation.md](../mongodb/repository-adaptation.md). +설계는 `modules/mongodb/` 아래 Gradle 모듈 19개를 가정한다. 이 저장소의 실패하면 닫히는 registry는 정확히 19개의 leaf identity를 +선언하므로, 그 모듈들은 `:adapter:outbound:persistence-mongo` 안의 패키지 경계가 됐고 ArchUnit이 강제한다. +[docs/mongodb/repository-adaptation.md](../mongodb/repository-adaptation.md)를 본다. diff --git a/docs/adr/ADR-MONGO-002-bson-representation.md b/docs/adr/ADR-MONGO-002-bson-representation.md index 73e478a7..a53a5915 100644 --- a/docs/adr/ADR-MONGO-002-bson-representation.md +++ b/docs/adr/ADR-MONGO-002-bson-representation.md @@ -7,61 +7,53 @@ - 현재 정본: `docs/mongodb/bson-mapping-guide.md` -# ADR-MONGO-002 — BSON representation is a pinned manifest +# ADR-MONGO-002 — BSON 표현은 고정한 manifest다 -- **Status:** Accepted -- **Date:** 2026-08-13 -- **Design source:** design §10, decision D-06 +- **상태:** 채택 +- **날짜:** 2026-08-13 +- **설계 출처:** 설계 §10, 결정 D-06 -## Context +## 배경 -How a Java value is represented in BSON is a data contract, but nothing in the default toolchain -treats it as one. Spring Data and the MongoDB driver both have defaults, and those defaults have -changed across versions. A `BigDecimal` can land as a `Double`, a `String` or a `Decimal128`; a `UUID` -can land as `Binary` subtype 3 or subtype 4; an `Instant` can land as a `Date` or a `String`. +Java 값을 BSON으로 어떻게 나타내는지는 데이터 계약인데, 기본 toolchain의 어떤 것도 그것을 계약으로 다루지 않는다. Spring Data와 +MongoDB driver에는 둘 다 기본값이 있고, 그 기본값은 버전마다 바뀌어 왔다. `BigDecimal`은 `Double`, `String`, `Decimal128` 중 +무엇으로든 들어갈 수 있다. `UUID`는 `Binary` subtype 3이나 subtype 4로 들어갈 수 있다. `Instant`는 `Date`나 `String`으로 들어갈 +수 있다. -The consequences are asymmetric. A representation change is invisible in a value-equality test — -`12.30` looks like `12.30` whether it is a double or a `Decimal128` — but once a collection holds -production data, changing it is a full migration. And the UUID case is worse than a migration: legacy -Java representation byte-swaps two halves of the UUID, so a document written under one representation -and read under the other yields a *different, valid-looking* UUID. Nothing errors. You get the wrong -record. +결과는 비대칭이다. 표현이 바뀌어도 값 동등 시험에는 보이지 않는다 — `12.30`은 double이든 `Decimal128`이든 `12.30`처럼 보인다 — +하지만 collection에 운영 데이터가 들면 그것을 바꾸는 것은 전체 migration이다. 그리고 UUID 경우는 migration보다 나쁘다: 옛 Java +표현은 UUID의 두 절반을 byte-swap하므로, 한 표현으로 쓰고 다른 표현으로 읽은 문서는 *다르지만 유효해 보이는* UUID를 낸다. +오류는 없다. 엉뚱한 레코드를 받는다. -## Decision +## 결정 -`MongoTypeRepresentationManifest` pins the representation for every type the platform maps, and -`MongoMappingConfiguration` builds the Spring Data converters from it. Nothing relies on a library -default. +`MongoTypeRepresentationManifest`가 플랫폼이 대응시키는 모든 타입의 표현을 고정하고, `MongoMappingConfiguration`이 그것으로 +Spring Data converter를 만든다. 라이브러리 기본값에 기대는 것은 없다. -| Java | BSON | Rationale | +| Java | BSON | 근거 | |---|---|---| -| `UUID` | `Binary` subtype 4 (`STANDARD`) | Subtype 3 byte-swaps; cross-representation reads are silently wrong. | -| `BigDecimal` | `Decimal128` | A double cannot represent `12.30`; money compared as a double is eventually wrong by a cent. | -| `BigInteger` | `Decimal128`, or declared `String` when out of range | 34 significant digits; out of range fails on write instead of rounding. | -| `Instant` / `OffsetDateTime` / `ZonedDateTime` | UTC `Date` | One instant, one representation. | -| `LocalDate` | declared per field | A calendar day is not an instant. | -| `LocalDateTime` | **refused** | No offset: the stored value depends on the writing JVM's default zone. | -| `enum` | `String` name | Ordinals renumber when someone inserts a constant. | +| `UUID` | `Binary` subtype 4(`STANDARD`) | subtype 3은 byte-swap한다. 표현을 넘나드는 읽기는 소리 없이 틀린다. | +| `BigDecimal` | `Decimal128` | double은 `12.30`을 나타내지 못한다. double로 비교한 돈은 결국 1원씩 틀린다. | +| `BigInteger` | `Decimal128`, 범위를 넘으면 선언한 `String` | 유효 숫자 34자리. 범위를 넘으면 반올림하지 않고 쓰기에서 실패한다. | +| `Instant` / `OffsetDateTime` / `ZonedDateTime` | UTC `Date` | 시각 하나, 표현 하나. | +| `LocalDate` | 필드마다 선언 | 달력의 날은 시각이 아니다. | +| `LocalDateTime` | **거절** | offset이 없다: 저장 값이 쓰는 JVM의 기본 시간대에 따라 달라진다. | +| `enum` | `String` 이름 | 누가 상수를 끼워 넣으면 ordinal이 다시 매겨진다. | -Type metadata follows `MongoTypeMetadataPolicy` — `NONE`, `ALIAS` or `CLASS_NAME`. A -`@LongLivedMongoDocument` type may not use `CLASS_NAME`: writing a FQCN into a million documents makes -a package rename a data migration. +타입 metadata는 `MongoTypeMetadataPolicy` — `NONE`, `ALIAS`, `CLASS_NAME` — 를 따른다. `@LongLivedMongoDocument` 타입은 +`CLASS_NAME`을 쓰면 안 된다: 문서 백만 개에 FQCN을 쓰면 패키지 이름 바꾸기가 데이터 migration이 된다. -The manifest is enforced by a golden gate. `MongoBsonSnapshot` canonicalises a stored document, -preserving BSON types and keeping missing distinct from null, and -`MongoBsonSnapshotAssert.hasTypeSignature(...)` fails on any representation change. The registry -pins `UuidCodec(STANDARD)` explicitly rather than inheriting a default, since inheriting the default -is the exact drift the gate exists to catch. +manifest는 golden gate가 강제한다. `MongoBsonSnapshot`이 저장된 문서를 정규화하면서 BSON 타입을 지키고 없음과 null을 구별해 +두며, `MongoBsonSnapshotAssert.hasTypeSignature(...)`가 표현이 바뀌면 실패한다. registry는 기본값을 물려받지 않고 +`UuidCodec(STANDARD)`를 명시해 고정한다. 기본값을 물려받는 것이 바로 gate가 잡으려는 어긋남이기 때문이다. -## Consequences +## 결과 -**Positive.** A library upgrade cannot move a representation without failing a test. Money is exact. -UUIDs read back as themselves. Class moves stay refactors. +**좋은 점.** 라이브러리 업그레이드가 시험을 실패시키지 않고 표현을 옮길 수 없다. 돈이 정확하다. UUID가 자기 자신으로 다시 +읽힌다. 클래스 옮기기는 리팩터링으로 남는다. -**Negative.** Every representation-affecting change requires updating a snapshot *and* writing a -migration. A new mapped type needs a manifest entry before it can be used. This is the intended -friction: the alternative is discovering the change in production. +**나쁜 점.** 표현에 영향을 주는 모든 변경에 snapshot 갱신 *그리고* migration 작성이 필요하다. 새로 대응시키는 타입은 쓰기 전에 +manifest 항목이 필요하다. 의도한 마찰이다: 대안은 운영에서 변경을 발견하는 것이다. -**Rejected alternative — "snapshot the JSON."** JSON destroys exactly the distinctions the gate -protects: `Decimal128` and `String` both render as text, `Binary` UUID and `ObjectId` both render as -hex, and missing and null both disappear. +**버린 대안 — 「JSON을 snapshot한다」.** JSON은 gate가 지키는 바로 그 구별을 없앤다: `Decimal128`과 `String`은 둘 다 글로 +나오고, `Binary` UUID와 `ObjectId`는 둘 다 hex로 나오며, 없음과 null은 둘 다 사라진다. diff --git a/docs/adr/ADR-MONGO-003-transaction-retry.md b/docs/adr/ADR-MONGO-003-transaction-retry.md index 7d675461..ec655164 100644 --- a/docs/adr/ADR-MONGO-003-transaction-retry.md +++ b/docs/adr/ADR-MONGO-003-transaction-retry.md @@ -7,33 +7,29 @@ - 현재 정본: `docs/mongodb/consistency-transaction-guide.md` -# ADR-MONGO-003 — Transaction body retry and commit retry are separate loops +# ADR-MONGO-003 — 트랜잭션 본문 재시도와 커밋 재시도는 따로 도는 반복문이다 -- **Status:** Accepted -- **Date:** 2026-08-13 -- **Design source:** design §14–§16, decisions D-07 through D-10 +- **상태:** 채택 +- **날짜:** 2026-08-13 +- **설계 출처:** 설계 §14–§16, 결정 D-07부터 D-10 -## Context +## 배경 -MongoDB reports two transaction failures that look similar and must be handled in opposite ways. +MongoDB는 비슷해 보이지만 정반대로 다뤄야 하는 트랜잭션 실패 둘을 알린다. -`TransientTransactionError` means the transaction definitively did not commit. The correct response is -to run the whole thing again. +`TransientTransactionError`는 트랜잭션이 분명히 커밋되지 않았다는 뜻이다. 맞는 대응은 전체를 다시 돌리는 것이다. -`UnknownTransactionCommitResult` means the commit **may already have applied** — typically because the -primary changed while the commit was in flight. The correct response is to retry *the commit*, which -is a no-op if it already succeeded. +`UnknownTransactionCommitResult`는 커밋이 **이미 적용됐을 수 있다**는 뜻이다 — 보통 커밋이 진행 중일 때 primary가 바뀌었기 +때문이다. 맞는 대응은 *커밋*을 재시도하는 것이고, 이미 성공했다면 그것은 아무 일도 하지 않는다. -The common implementation wraps everything in one retry loop. That loop replays the body after an -unknown commit, and if the commit did apply, the body applies twice. In a payment or notification path -that is a duplicate charge or a duplicate message, produced by the error handler. +흔한 구현은 모든 것을 재시도 반복문 하나로 감싼다. 그 반복문은 모르는 커밋 뒤에 본문을 다시 돌리고, 커밋이 적용됐었다면 본문이 +두 번 적용된다. 결제나 알림 경로에서 그것은 오류 handler가 만든 중복 청구나 중복 메시지다. -The related trap is session reuse: retrying on the same session after an abort carries the aborted -transaction's state into the retry. +관련된 함정은 세션 다시 쓰기다: abort 뒤에 같은 세션으로 재시도하면 abort된 트랜잭션의 상태가 재시도로 넘어간다. -## Decision +## 결정 -`MongoTransactionRetryCoordinator` implements two loops with different scopes. +`MongoTransactionRetryCoordinator`가 범위가 다른 반복문 둘을 구현한다. ``` for each body attempt within the budget: @@ -44,34 +40,30 @@ for each body attempt within the budget: UnknownTransactionCommitResult -> retry the COMMIT ONLY, same session ``` -Rules that follow, all of them load-bearing: +따라 나오는 규칙. 모두 꼭 필요하다: -1. **A new session per body attempt.** No aborted state leaks into a retry. -2. **The body is never replayed after a commit ambiguity.** `MongoRetryScope.COMMIT_ONLY` is a - distinct value from `BODY` precisely so this cannot be collapsed by accident. -3. **One budget bounds both loops.** `MongoRetryBudget` limits attempts *and* elapsed time, with - jittered backoff, so a struggling primary is not retried into the ground by every instance at once. -4. **An exhausted commit retry surfaces `TRANSACTION_COMMIT_UNKNOWN`,** never a generic failure. An - ambiguous outcome reported as a failure invites the caller to retry — the one thing that must not - happen. See [docs/mongodb/runbooks/unknown-commit.md](../mongodb/runbooks/unknown-commit.md). -5. **Transaction bodies write a deterministic marker** so `MongoCommitReconciler` can establish what - actually happened. A transaction that cannot be reconciled has no recovery path. -6. **Classification reads labels before codes.** Server error labels are the authoritative statement - about retryability; error codes vary by version. +1. **본문 시도마다 새 세션.** abort된 상태가 재시도로 새지 않는다. +2. **커밋이 모호해진 뒤에는 본문을 절대 다시 돌리지 않는다.** `MongoRetryScope.COMMIT_ONLY`가 `BODY`와 다른 값인 것은 바로 + 이것이 실수로 뭉개지지 않게 하려는 것이다. +3. **예산 하나가 두 반복문을 묶는다.** `MongoRetryBudget`이 시도 수 *그리고* 흐른 시간을 jitter 있는 backoff와 함께 제한한다. + 그래서 힘든 primary를 모든 인스턴스가 한꺼번에 재시도로 짓밟지 않는다. +4. **바닥난 커밋 재시도는 일반 실패가 아니라 `TRANSACTION_COMMIT_UNKNOWN`으로 드러난다.** 실패로 알린 모호한 결과는 호출자에게 + 재시도를 부른다 — 일어나면 안 되는 바로 그 일이다. + [docs/mongodb/runbooks/unknown-commit.md](../mongodb/runbooks/unknown-commit.md)를 본다. +5. **트랜잭션 본문은 결정적인 표지를 쓴다.** 그래서 `MongoCommitReconciler`가 실제로 무엇이 일어났는지 세울 수 있다. 맞춰 볼 수 + 없는 트랜잭션에는 회복 길이 없다. +6. **분류는 코드보다 label을 먼저 읽는다.** 서버 오류 label이 재시도 가능성에 대한 정본 진술이고, 오류 코드는 버전마다 다르다. -Surrounding decisions that reduce how often this path is reached at all: single-document atomic -operations are preferred over transactions (D-09), partial changes use update operators rather than -`save()` (D-07), and whole-document replacement requires an optimistic revision (D-08). +이 경로에 닿는 횟수 자체를 줄이는 주변 결정: 트랜잭션보다 단일 문서 원자 연산을 고른다(D-09), 부분 변경은 `save()`가 아니라 +update 연산자를 쓴다(D-07), 문서 전체 바꾸기에는 낙관적 revision이 필요하다(D-08). -## Consequences +## 결과 -**Positive.** A commit ambiguity cannot become a duplicate effect. The ambiguity reaches the caller as -an ambiguity. The retry budget is bounded in both attempts and time. +**좋은 점.** 커밋 모호함이 중복 효과가 될 수 없다. 모호함이 모호함으로 호출자에게 닿는다. 재시도 예산이 시도 수와 시간 둘 다에서 +한계를 가진다. -**Negative.** Callers must handle a third outcome beyond success and failure. Transaction bodies must -write a marker they would not otherwise need. Both costs are small compared with reconciling -duplicated financial effects after the fact. +**나쁜 점.** 호출자는 성공과 실패 밖의 세 번째 결과를 다뤄야 한다. 트랜잭션 본문은 그렇지 않으면 필요 없을 표지를 써야 한다. 두 +비용 모두 중복된 금전 효과를 나중에 맞춰 보는 것에 비하면 작다. -**Rejected alternative — "one retry loop, at-least-once everywhere."** It requires every transaction -body to be fully idempotent, which is a much stronger and much less checkable property than writing -one marker, and it is silently violated the first time someone adds a non-idempotent step. +**버린 대안 — 「재시도 반복문 하나, 어디서나 at-least-once」.** 모든 트랜잭션 본문이 완전히 멱등이어야 한다. 표지 하나를 쓰는 +것보다 훨씬 강하고 훨씬 검사하기 어려운 성질이고, 누가 멱등이 아닌 단계를 처음 더하는 순간 소리 없이 깨진다. diff --git a/docs/adr/ADR-MONGO-004-index-schema-admin-plane.md b/docs/adr/ADR-MONGO-004-index-schema-admin-plane.md index eeb2896c..f26ca08d 100644 --- a/docs/adr/ADR-MONGO-004-index-schema-admin-plane.md +++ b/docs/adr/ADR-MONGO-004-index-schema-admin-plane.md @@ -7,65 +7,55 @@ - 현재 정본: `docs/mongodb/schema-index-migration-guide.md` -# ADR-MONGO-004 — Index and schema changes belong to the admin plane +# ADR-MONGO-004 — index와 schema 변경은 admin plane의 것이다 -- **Status:** Accepted -- **Date:** 2026-08-13 -- **Design source:** design §21–§25, decisions D-11, D-13 +- **상태:** 채택 +- **날짜:** 2026-08-13 +- **설계 출처:** 설계 §21–§25, 결정 D-11, D-13 -## Context +## 배경 -Spring Data can create indexes automatically from annotations. On a laptop this is convenient. On a -collection with a hundred million documents, an index build is a capacity event: it consumes CPU, IO -and memory on the primary for minutes to hours, and it starts because a pod restarted. +Spring Data는 애너테이션에서 index를 자동으로 만들 수 있다. 노트북에서는 편하다. 문서 1억 개가 든 collection에서 index 만들기는 +용량 사건이다: primary의 CPU, IO, 메모리를 몇 분에서 몇 시간 동안 쓰고, pod 하나가 재시작했다는 이유로 시작된다. -Worse, it starts N times when N pods restart, and there is no approval step, no ordering relative to -the code that needs the index, and no record afterwards of what was created. +더 나쁘게, pod N개가 재시작하면 N번 시작하고, 승인 단계도, 그 index가 필요한 코드와의 순서도, 나중에 무엇을 만들었는지의 기록도 +없다. -Schema validators have the same shape with a sharper edge: tightening a validator on a collection with -existing data rejects writes to documents that were legal when they were written. +schema validator도 같은 모양인데 날이 더 서 있다: 데이터가 있는 collection에서 validator를 조이면, 쓸 때는 적법했던 문서에 대한 +쓰기를 거절한다. -TTL has a third shape. It looks like a scheduler and is not one: the TTL monitor runs about once a -minute and deletes in batches, so an expired document routinely remains readable for minutes or hours. +TTL은 세 번째 모양이다. scheduler처럼 보이지만 아니다: TTL monitor는 대략 1분에 한 번 돌고 batch로 지우므로, 만료된 문서가 몇 +분에서 몇 시간 동안 읽히는 것이 예사다. -## Decision +## 결정 -**Indexes and validators are declared in a manifest and applied by the admin plane (D4).** Automatic -index creation in production is disabled. +**index와 validator는 manifest에 선언하고 admin plane(D4)이 적용한다.** 운영에서 자동 index 만들기는 끈다. -1. `MongoManifestRegistry` holds the declared indexes (`MongoIndexManifest`) and validator - (`MongoSchemaManifest`) per collection. The manifest is the source of truth, reviewed in a pull - request. -2. `MongoIndexDiffEngine` compares manifest against observed state and reports missing, extra and - *changed* indexes. Changed ones are reported rather than re-issued: MongoDB will not silently - rebuild an index whose definition moved. -3. `MongoIndexApplyPolicy` sets what an environment may do — `APPLY` (local), `APPLY_WITH_DIFF` - (staging), `DIFF_WITH_APPROVED_APPLY` (production), `REPORT_ONLY` (audit). -4. **Ownership gates every drop.** `MongoMetadataOwnership` distinguishes `APPLICATION_MANAGED` from - `SEARCH_MANAGED`, `ENCRYPTION_MANAGED` and `EXTERNAL`. Only application-managed objects are - droppable on drift. A diff engine without ownership eventually proposes dropping - `enxcol_.customers.esc`, and "the drift tool cleaned it up" is a very bad incident summary. -5. **Retirement is staged.** `MongoIndexRetirementState` moves an index declared → hidden → - observed-unused → droppable, one deployment per transition. Hiding is instantly reversible; - dropping is a rebuild. -6. **Stable validation actions are `error` and `warn` only.** `errorAndLog` is not part of the Stable - contract on 7.0 or 8.0 and is refused. Tightening goes `warn`+`MODERATE` → confirm zero warnings → - `error`+`STRICT`, in two deployments. -7. **TTL is physical cleanup only** (D-13). `MongoExpirationAccessPolicy` states the rule: a - document's presence is not authorization and its absence is not a deadline. Access control checks - the expiry field; scheduling uses a scheduler. -8. **Migrations are checksummed, locked, precondition-checked and resumable.** - `MongoMigrationRunner` fails hard when an applied id's checksum changed — two environments running - different code under one id is worse than a failed deploy. +1. `MongoManifestRegistry`가 collection마다 선언한 index(`MongoIndexManifest`)와 validator(`MongoSchemaManifest`)를 가진다. + manifest가 정본이고 pull request에서 리뷰한다. +2. `MongoIndexDiffEngine`이 manifest를 관찰한 상태와 비교해 빠진 index, 남는 index, *바뀐* index를 알린다. 바뀐 것은 다시 내지 + 않고 알린다: MongoDB는 정의가 움직인 index를 소리 없이 다시 만들지 않는다. +3. `MongoIndexApplyPolicy`가 환경이 할 수 있는 것을 정한다 — `APPLY`(로컬), `APPLY_WITH_DIFF`(staging), + `DIFF_WITH_APPROVED_APPLY`(운영), `REPORT_ONLY`(감사). +4. **모든 drop은 소유권이 막는다.** `MongoMetadataOwnership`이 `APPLICATION_MANAGED`를 `SEARCH_MANAGED`, `ENCRYPTION_MANAGED`, + `EXTERNAL`과 구별한다. 어긋났을 때 지울 수 있는 것은 애플리케이션이 관리하는 객체뿐이다. 소유권 없는 diff 엔진은 결국 + `enxcol_.customers.esc`를 지우자고 제안하고, 「drift 도구가 치웠다」는 아주 나쁜 사고 요약이다. +5. **은퇴는 단계를 밟는다.** `MongoIndexRetirementState`가 index를 선언됨 → 숨김 → 안 쓰는 것 확인 → 지울 수 있음으로 옮기고, + 전이마다 배포 한 번이다. 숨기기는 바로 되돌릴 수 있다. 지우기는 다시 만들기다. +6. **Stable validation action은 `error`와 `warn`뿐이다.** `errorAndLog`는 7.0이나 8.0에서 Stable 계약에 속하지 않아 거절한다. + 조이기는 `warn`+`MODERATE` → 경고 0 확인 → `error`+`STRICT`로, 배포 두 번에 걸쳐 간다. +7. **TTL은 물리적 치우기일 뿐이다**(D-13). `MongoExpirationAccessPolicy`가 규칙을 말한다: 문서가 있다고 인가가 아니고, 없다고 + 기한이 아니다. 접근 통제는 만료 필드를 검사하고, 일정은 scheduler를 쓴다. +8. **migration은 checksum을 두고, 잠그고, 전제 조건을 검사하고, 이어서 할 수 있다.** `MongoMigrationRunner`는 적용한 id의 + checksum이 바뀌면 단단히 실패한다 — 두 환경이 id 하나 아래 다른 코드를 돌리는 것은 실패한 배포보다 나쁘다. -## Consequences +## 결과 -**Positive.** Index builds are scheduled by people who know the capacity. Rollback is possible at -every step. Drift is visible without being dangerous. Nothing drops what it does not own. +**좋은 점.** index 만들기 일정은 용량을 아는 사람이 잡는다. 모든 단계에서 되돌릴 수 있다. drift는 위험하지 않게 보인다. 아무것도 +자기가 가지지 않은 것을 지우지 않는다. -**Negative.** Adding an index is a manifest change plus an apply, not an annotation. Local development -uses `APPLY` so the friction is confined to environments where it is warranted. +**나쁜 점.** index 더하기는 애너테이션이 아니라 manifest 변경 + 적용이다. 로컬 개발은 `APPLY`를 쓰므로 마찰은 그것이 정당한 +환경에만 머문다. -**Rejected alternative — "auto-create with a feature flag."** The flag is either on in production, -which is the problem, or off, in which case the manifest is the real mechanism and the annotation is a -second, divergent source of truth. +**버린 대안 — 「feature flag와 함께 자동으로 만들기」.** flag가 운영에서 켜져 있으면 그것이 문제이고, 꺼져 있으면 manifest가 +실제 장치이고 애너테이션은 두 번째의 갈라진 정본이다. diff --git a/docs/adr/ADR-MONGO-ADV-001-capability-promotion.md b/docs/adr/ADR-MONGO-ADV-001-capability-promotion.md index 9b3bc6b3..1ac930b9 100644 --- a/docs/adr/ADR-MONGO-ADV-001-capability-promotion.md +++ b/docs/adr/ADR-MONGO-ADV-001-capability-promotion.md @@ -7,90 +7,78 @@ - 현재 정본: `docs/mongodb/support-matrix.md` -# ADR-MONGO-ADV-001 — Advanced capability promotion +# ADR-MONGO-ADV-001 — Advanced capability 승격 -- **Status:** Accepted -- **Date:** 2026-08-13 -- **Design source:** design §2 (D-15), §3.2–§3.3; Advanced expansion plan Task 15 -- **Amended 2026-09-25:** the `ca-skeleton.persistence-mongo.advanced.*.enabled` binding - (`MongoAdvancedConfiguration`/`MongoAdvancedSettings`) was imported by nothing, so no deployment - property ever reached the flags; it was removed together with `propertyFor`. The flags are now - built in code by the adapter that constructs an entry point. `MongoAdvancedPromotionGate`, - `MongoAdvancedPromotionEvidence`, `MongoVectorSearchBenchmarkGate` and the search, vector, time - series and GridFS packages (interfaces with no implementation) were removed. The evidence - categories below remain a review obligation; no class checks them. +- **상태:** 채택 +- **날짜:** 2026-08-13 +- **설계 출처:** 설계 §2 (D-15), §3.2–§3.3. Advanced 확장 계획 Task 15 +- **2026-09-25 보완:** `ca-skeleton.persistence-mongo.advanced.*.enabled` 바인딩(`MongoAdvancedConfiguration`/ + `MongoAdvancedSettings`)은 아무것도 import하지 않아서 어떤 배포 속성도 flag에 닿지 않았다. `propertyFor`와 함께 지웠다. flag는 + 이제 entry point를 만드는 어댑터가 코드로 만든다. `MongoAdvancedPromotionGate`, `MongoAdvancedPromotionEvidence`, + `MongoVectorSearchBenchmarkGate`, 그리고 search, vector, time series, GridFS 패키지(구현 없는 인터페이스)를 지웠다. 아래 증거 + category는 리뷰 의무로 남는다. 그것을 검사하는 클래스는 없다. -## Context +## 배경 -Sharding, time series, CSFLE, Queryable Encryption, search, vector search and multi-tenancy each work -in a demo within an afternoon. What they do not do is behave the same way in production, and the -differences are not discovered by functional tests: +sharding, time series, CSFLE, Queryable Encryption, search, vector search, multi-tenancy는 하나같이 오후 한나절이면 demo에서 +동작한다. 하지 않는 것은 운영에서 같은 방식으로 동작하는 것이고, 그 차이는 기능 시험으로 찾지 못한다: -- Sharding changes which queries are efficient. A query that misses the shard key becomes - scatter-gather, which passes every test on a one-shard cluster. -- Encryption's failure modes are KMS failure modes — wrong key, revoked permission, mid-rotation — - none of which occur against a local key provider. -- Search and vector search can be functionally correct and useless: the index returns results, and - the results are not relevant. Recall is not visible in a pass/fail assertion. -- Database-per-tenant works until the tenant count crosses what the connection and file-handle - budget supports, which is an operational property, not a code property. +- sharding은 어떤 query가 효율적인지 바꾼다. shard key를 놓친 query는 scatter-gather가 되는데, shard 하나짜리 cluster에서는 + 모든 시험을 통과한다. +- 암호화의 실패 방식은 KMS의 실패 방식이다 — 틀린 키, 거둬들인 권한, 교체 중 — 로컬 키 provider에 대고는 하나도 일어나지 않는다. +- search와 vector search는 기능상 맞으면서 쓸모없을 수 있다: index는 결과를 돌려주는데 결과가 관련이 없다. recall은 통과·실패 + 단언에 보이지 않는다. +- 테넌트마다 데이터베이스는 테넌트 수가 연결·파일 handle 예산이 받쳐 주는 수를 넘을 때까지 동작한다. 그것은 코드가 아니라 운영의 + 성질이다. -The failure mode this ADR prevents is a capability marked "done" on the strength of a green test that -never touched the environment where it will run. +이 ADR이 막는 실패 방식은 그것이 돌 환경을 한 번도 건드리지 않은 초록 시험을 근거로 capability를 「끝남」으로 표시하는 것이다. -## Decision +## 결정 -Every Advanced and Experimental capability is an **opt-in module behind its own flag**, and promotion -requires evidence, not confidence. +모든 Advanced·Experimental capability는 **자기 flag 뒤의 골라 쓰는 모듈**이고, 승격에는 자신감이 아니라 증거가 필요하다. -### Enablement +### 켜기 -`MongoAdvancedCapabilityFlags` gates construction of every Advanced entry point. A disabled capability -does not produce a runtime warning — the type refuses to be constructed, naming the property that -enables it (`MongoAdvancedCapabilityFlags.propertyFor(capability)`). Being on the classpath is not -being enabled, and `stableNeverDependsOnAdvanced` (ArchUnit) keeps the Stable surface free of them. +`MongoAdvancedCapabilityFlags`가 모든 Advanced entry point의 생성을 막는다. 꺼진 capability는 런타임 경고를 내지 않는다 — 타입이 +그것을 켜는 속성 이름을 대며 만들어지기를 거절한다(`MongoAdvancedCapabilityFlags.propertyFor(capability)`). classpath에 있다고 +켜진 것이 아니고, `stableNeverDependsOnAdvanced`(ArchUnit)가 Stable surface에서 그것을 떼어 둔다. -### Promotion evidence +### 승격 증거 -`MongoAdvancedPromotionGate.verify(evidence)` requires every category: +`MongoAdvancedPromotionGate.verify(evidence)`는 모든 category를 요구한다: -| Category | Means | +| category | 뜻 | |---|---| -| `stable-platform` | The Stable release gate passed on the same revision. | -| `actual-topology` | The capability ran on the real topology — a real sharded cluster, the real KMS, the actual target deployment. Atlas Local is a pull-request convenience and explicitly not release evidence (`MongoAtlasCapabilityContractSuite.Environment.ATLAS_LOCAL`). | -| `security` | Privileges reviewed; the capability's admin role is separate from the application role. | -| `migration` | A documented path in and, where the capability is irreversible, an explicit statement that there is no path back. | -| `failure` | Negative cases fail closed: wrong key, missing permission, rotation, non-ready index, unrouted query. | -| `runbook` | A runbook exists for the capability's characteristic incident. | +| `stable-platform` | 같은 revision에서 Stable 릴리스 gate가 통과했다. | +| `actual-topology` | capability가 실제 topology에서 돌았다 — 실제 sharded cluster, 실제 KMS, 실제 대상 배포. Atlas Local은 pull request용 편의이고 릴리스 증거가 아님을 명시한다(`MongoAtlasCapabilityContractSuite.Environment.ATLAS_LOCAL`). | +| `security` | 권한을 리뷰했다. capability의 admin role은 애플리케이션 role과 따로다. | +| `migration` | 들어가는 길을 적었고, capability가 되돌릴 수 없으면 돌아오는 길이 없다고 명시했다. | +| `failure` | 부정 경우가 실패하면 닫힌다: 틀린 키, 빠진 권한, 교체, 준비되지 않은 index, 라우팅되지 않은 query. | +| `runbook` | capability의 대표 사고를 위한 runbook이 있다. | -### Additional per-capability requirements +### capability별 추가 요구 -- **Search / vector search:** relevance and performance evidence, not functional success alone. - `MongoVectorSearchBenchmarkGate` requires recall alongside latency and index size; a gate that - measures only latency certifies a fast wrong answer. -- **Database-per-tenant and reshard orchestration remain Experimental** until operational scale - evidence exists. Both are correct in the small and unbounded in the large. -- **Reshard requires an explicit `ReshardApproval`** — a named approver and a stated window. It - rewrites the collection. +- **search / vector search:** 기능 성공만이 아니라 관련성과 성능 증거. `MongoVectorSearchBenchmarkGate`는 지연 시간·index 크기와 + 함께 recall을 요구한다. 지연 시간만 재는 gate는 빠른 틀린 답을 인증한다. +- **테넌트마다 데이터베이스와 reshard 조율은 운영 규모 증거가 생길 때까지 Experimental로 남는다.** 둘 다 작게는 맞고 크게는 + 한계가 없다. +- **reshard에는 명시한 `ReshardApproval`이 필요하다** — 이름 있는 승인자와 밝힌 시간 창. reshard는 collection을 다시 쓴다. -### Promotion does not change the dependency boundary +### 승격은 의존 경계를 바꾸지 않는다 -A capability promoted to Stable **remains an opt-in module** unless a later starter ADR changes the -dependency boundary. Promotion is a statement about evidence, not an invitation to add a transitive -dependency to every service. +Stable로 승격한 capability도 나중의 starter ADR이 의존 경계를 바꾸지 않는 한 **골라 쓰는 모듈로 남는다**. 승격은 증거에 대한 +진술이지, 모든 서비스에 전이 의존을 더하라는 초대가 아니다. -## Consequences +## 결과 -**Positive.** No capability reaches production on the strength of a container-only test. The evidence -list is the same for every capability, so promotion is reviewable rather than negotiated. +**좋은 점.** container 전용 시험을 근거로 운영에 닿는 capability는 없다. 증거 목록이 모든 capability에 같으므로, 승격은 흥정이 +아니라 리뷰할 수 있는 것이 된다. -**Negative.** Promotion requires access to real infrastructure — a sharded cluster, a real KMS, the -target deployment. That is the cost of the guarantee: the alternative is finding out in production, -where encryption and sharding are both expensive to reverse. +**나쁜 점.** 승격에는 실제 기반 시설 — sharded cluster, 실제 KMS, 대상 배포 — 에 대한 접근이 필요하다. 그것이 보장의 비용이다: +대안은 운영에서 알게 되는 것이고, 거기서는 암호화와 sharding 둘 다 되돌리기 비싸다. -## Verification +## 검증 -`scripts/verify-mongodb-advanced.sh` enforced this ADR until it was removed on 2026-08-15. The -promotion evidence categories this ADR requires are therefore no longer checked by any automated -gate; they are a review obligation until one is rebuilt. See `docs/mongodb/repository-adaptation.md` -§5 for the Gradle lanes the script wrapped. +`scripts/verify-mongodb-advanced.sh`가 2026-08-15에 지워질 때까지 이 ADR을 강제했다. 그래서 이 ADR이 요구하는 승격 증거 +category는 이제 어떤 자동 gate도 검사하지 않는다. 다시 만들 때까지 리뷰 의무다. 그 script가 감싸던 Gradle lane은 +`docs/mongodb/repository-adaptation.md` §5를 본다. diff --git a/docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md b/docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md index 8883fe61..d83135de 100644 --- a/docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md +++ b/docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md @@ -7,73 +7,62 @@ - 현재 정본: `docs/web/streaming-contract.md` -# ADR-WEB-ADV-001: Streaming is live delivery, and the web module stores no history +# ADR-WEB-ADV-001: streaming은 실시간 전달이고, web 모듈은 이력을 저장하지 않는다 -- Status: Accepted -- Date: 2026-08-25 -- Scope: `adapter:inbound:web` — `advanced.stream.**` +- 상태: 채택 +- 날짜: 2026-08-25 +- 범위: `adapter:inbound:web` — `advanced.stream.**` -## Context +## 배경 -Advanced Tasks 6–13 add SSE, NDJSON and JSON text sequences, with a `Last-Event-ID` resume path. +Advanced Task 6–13은 `Last-Event-ID` resume 경로와 함께 SSE, NDJSON, JSON text sequence를 더한다. -One fact drives every decision here: **after the first byte, the HTTP status is 200 and cannot -change.** A stream that ends because a dependency failed and one that ends because it finished are -identical at the transport layer — both are a closed connection after a 200. So is a stream that was -cut off mid-flight. +여기의 모든 결정을 이끄는 사실은 하나다: **첫 바이트 뒤에 HTTP status는 200이고 바꿀 수 없다.** 의존 대상이 실패해서 끝난 +stream과 다 마쳐서 끝난 stream은 전송 계층에서 똑같다 — 둘 다 200 뒤에 닫힌 연결이다. 도중에 잘린 stream도 그렇다. -The second fact is that a resume path invites the web module to remember things. It must not: the -messaging platform already owns durable event history, and a second copy would have its own -retention, its own eviction and its own opinion about ordering. +둘째 사실은 resume 경로가 web 모듈에게 무언가를 기억하라고 꾄다는 것이다. 그러면 안 된다: durable 이벤트 이력은 이미 메시징 +플랫폼이 가지고, 두 번째 사본은 자기 보존 기간, 자기 eviction, 순서에 대한 자기 의견을 가질 것이다. -## Decision +## 결정 -**Three outcomes, expressed in the stream rather than in the status.** The wire record (for NDJSON, -`NdjsonRecord`) is an item, a failure or a completion. A client that sees neither terminal record -has been cut off, and that third case is recorded as `ABRUPT_CLOSE` rather than counted as a -completion — which is where a rising rate of mid-stream failures would otherwise hide. +**결과는 셋이고, status가 아니라 stream 안에서 나타낸다.** wire record(NDJSON이면 `NdjsonRecord`)는 항목, 실패, 완료 중 하나다. +끝 record를 하나도 보지 못한 client는 잘린 것이고, 그 셋째 경우는 완료로 세지 않고 `ABRUPT_CLOSE`로 기록한다 — 그렇지 않으면 +도중 실패 비율이 오르는 것이 거기 숨는다. -**Nothing writes an error body onto a committed response.** Before commit, a failure is an ordinary -HTTP error (the `Envelope`) with a real status; after, a terminal record. Attempting both produces a -body that is half stream and half JSON, which no client parses and every proxy caches as a success. -(The mapper that encoded this, `WebStreamTerminationMapper`, was removed on 2026-09-25 with the -problem-document vocabulary it returned; the rule stands.) +**커밋된 응답 위에 오류 body를 쓰는 것은 없다.** 커밋 전의 실패는 실제 status를 가진 보통 HTTP 오류(`Envelope`)이고, 커밋 뒤에는 +끝 record다. 둘 다 하려 하면 반은 stream이고 반은 JSON인 body가 나오는데, 어떤 client도 그것을 파싱하지 못하고 모든 proxy가 +성공으로 cache한다. (이것을 인코딩하던 mapper `WebStreamTerminationMapper`는 그것이 돌려주던 problem document 어휘와 함께 +2026-09-25에 지웠다. 규칙은 남는다.) -**Positions are monotonic, and it is enforced.** `WebStreamEvidence.recordDelivered` refuses a -repeated or regressing position. A client deduplicating on position would silently drop the second -item. +**위치는 단조 증가하고, 그것을 강제한다.** `WebStreamEvidence.recordDelivered`는 되풀이되거나 뒤로 가는 위치를 거절한다. 위치로 +중복을 거르는 client는 두 번째 항목을 소리 없이 버리게 된다. -**A slow consumer is disconnected, not buffered.** `WebStreamPolicy.maxBufferedItems` is a hard -bound. Backpressure protects the reactive pipeline; it does not protect the server's heap from a -consumer that reads slowly for an hour. +**느린 소비자는 buffer에 담지 않고 연결을 끊는다.** `WebStreamPolicy.maxBufferedItems`는 단단한 한계다. backpressure는 reactive +pipeline을 지키지만, 한 시간 동안 천천히 읽는 소비자로부터 서버 heap을 지키지는 않는다. -**Every stream is in a registry, and shutdown drains it.** A node with a hundred open streams and no -other traffic looks idle by request rate. `WebStreamDrainCoordinator` stops accepting first, asks -clients to reconnect, and only then forces the remainder — because a client whose socket is cut -retries immediately, and if every socket is cut at once, every client retries at once. +**모든 stream은 registry에 있고, 종료가 그것을 비운다.** 열린 stream 백 개 말고 다른 traffic이 없는 노드는 요청 비율로 보면 놀고 +있는 것처럼 보인다. `WebStreamDrainCoordinator`는 먼저 받기를 멈추고, client에게 다시 연결하라고 요청하고, 그다음에야 나머지를 +강제로 끊는다 — socket이 끊긴 client는 바로 다시 시도하고, 모든 socket을 한꺼번에 끊으면 모든 client가 한꺼번에 다시 시도하기 +때문이다. -**The web module stores no durable history.** `WebStreamReplaySource` is an interface this module -implements nowhere. An expired cursor raises `ReplayCursorExpiredException` rather than resuming from -the oldest retained position, because that delivers a stream with a hole the client cannot see. +**web 모듈은 durable 이력을 저장하지 않는다.** `WebStreamReplaySource`는 이 모듈이 어디에서도 구현하지 않는 인터페이스다. 만료된 +cursor는 보존한 가장 오래된 위치에서 이어 가지 않고 `ReplayCursorExpiredException`을 올린다. 그렇게 하면 client가 볼 수 없는 +구멍이 있는 stream을 전달하기 때문이다. -**The replay-to-live seam is watched.** `GapAndDuplicateGuard` detects both directions. Neither is -visible in either half on its own. +**재생에서 실시간으로 넘어가는 이음매를 지켜본다.** `GapAndDuplicateGuard`가 두 방향을 모두 찾는다. 어느 쪽도 한 절반만 보면 +보이지 않는다. -## Consequences +## 결과 -- Clients must handle three outcomes. A client that treats a closed connection as completion will be - wrong, and no server change can fix that for it. -- An expired `Last-Event-ID` costs the client a full re-read. That is the honest answer. -- JSON-seq is preferred over NDJSON where truncation matters: its separator comes first, so a parser - resynchronises at the next record. NDJSON's delimiter is the thing that gets truncated away. +- client는 결과 셋을 다뤄야 한다. 닫힌 연결을 완료로 다루는 client는 틀리고, 서버가 무엇을 바꿔도 그것을 대신 고칠 수 없다. +- 만료된 `Last-Event-ID`는 client에게 전체 다시 읽기를 치르게 한다. 그것이 정직한 답이다. +- 잘림이 중요한 곳에서는 NDJSON보다 JSON-seq를 고른다: 구분자가 앞에 오므로 parser가 다음 record에서 다시 맞춘다. NDJSON의 + 구분자는 잘려 나가는 바로 그것이다. -## Alternatives considered +## 따져 본 대안 -- **Emit a problem document when a stream fails after commit.** Rejected: the body becomes - unparseable and the 200 is cached. -- **Resume from the oldest retained position when the cursor expires.** Rejected: positions are - contiguous from where the replay started, so nothing in the data says events are missing. -- **Store replay history in the web module.** Rejected: a second source of truth that drifts - invisibly. -- **Unbounded buffering for slow consumers.** Rejected: it moves the client's slowness into the - server's heap. +- **커밋 뒤에 stream이 실패하면 problem document를 낸다.** 버렸다: body가 파싱할 수 없게 되고 200이 cache된다. +- **cursor가 만료되면 보존한 가장 오래된 위치에서 이어 간다.** 버렸다: 위치는 재생이 시작된 곳부터 이어지므로, 데이터 안의 어떤 + 것도 이벤트가 빠졌다고 말하지 않는다. +- **재생 이력을 web 모듈에 저장한다.** 버렸다: 보이지 않게 어긋나는 두 번째 정본이다. +- **느린 소비자를 위한 한계 없는 buffer.** 버렸다: client의 느림을 서버 heap으로 옮긴다. diff --git a/docs/adr/ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md b/docs/adr/ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md index fafaeeae..4f3a9397 100644 --- a/docs/adr/ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md +++ b/docs/adr/ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md @@ -7,73 +7,60 @@ - 현재 정본: `docs/web/virtual-thread-profile.md` -# ADR-WEB-ADV-002: Virtual threads change scheduling, not the concurrency budget +# ADR-WEB-ADV-002: virtual thread는 스케줄링을 바꾸지 동시성 예산을 바꾸지 않는다 -- Status: Accepted -- Date: 2026-08-25 -- Scope: `adapter:inbound:web` — `advanced.virtualthread`, `advanced.blockingbridge` +- 상태: 채택 +- 날짜: 2026-08-25 +- 범위: `adapter:inbound:web` — `advanced.virtualthread`, `advanced.blockingbridge` -## Context +## 배경 -Advanced Task 2 offers a virtual-thread executor for MVC; Task 3 offered a bounded blocking bridge -for WebFlux. (The WebFlux adapter for it was removed on 2026-09-25 — the template is servlet only; -`advanced.blockingbridge` remains as library code.) +Advanced Task 2는 MVC용 virtual thread executor를 준다. Task 3은 WebFlux용 한계 있는 blocking bridge를 줬다. (그 WebFlux 어댑터는 +2026-09-25에 지웠다 — 템플릿은 servlet만이다. `advanced.blockingbridge`는 라이브러리 코드로 남는다.) -A platform-thread MVC deployment has an implicit concurrency limit — the thread pool — and that -limit is usually what has been protecting the database pool, the outbound HTTP bulkhead and every -downstream service from the full arrival rate. Nobody wrote it down as an admission policy; it was a -side effect of the pool size. +platform thread MVC 배포에는 숨은 동시성 한계 — thread pool — 가 있고, 보통 그 한계가 데이터베이스 pool, outbound HTTP +bulkhead, 모든 하류 서비스를 전체 도착 비율로부터 지켜 왔다. 아무도 그것을 admission 정책으로 적지 않았다. pool 크기의 +부작용이었다. -Switching to virtual threads deletes that limit without deleting anything that depended on it. +virtual thread로 바꾸면 그 한계가 지워지는데, 그것에 기대던 것은 하나도 지워지지 않는다. -## Decision +## 결정 -**An explicit admission limit is required when virtual threads are enabled.** -`VirtualThreadProfile` refuses construction without one. Without it the deployment accepts every -arrival, queues all of them on the downstream budgets, and times out work that would have succeeded -had it been refused. The load that used to be shed at the front door is shed at the back, after the -cost of accepting it. +**virtual thread를 켜면 명시적 admission 한계가 필요하다.** `VirtualThreadProfile`은 그것 없이는 만들어지기를 거절한다. 없으면 +배포는 모든 도착을 받고, 그것을 모두 하류 예산 위에 줄 세우며, 거절됐으면 성공했을 일을 timeout으로 끝낸다. 예전에 정문에서 +덜어 내던 부하를, 받아들이는 비용을 치른 뒤 뒷문에서 덜어 낸다. -**The limit bounds concurrent use cases, not threads.** `VirtualThreadAdmissionGuard` is a fair -semaphore, not a pool. Bounding threads would put the waiting back and throw away what virtual -threads bought. Ten thousand virtual threads may exist while a hundred hold permits. +**한계는 스레드가 아니라 동시 유스케이스를 묶는다.** `VirtualThreadAdmissionGuard`는 pool이 아니라 공정한 semaphore다. 스레드를 +묶으면 기다림을 되돌려 놓고 virtual thread가 산 것을 버린다. virtual thread 만 개가 있어도 허가를 쥔 것은 백 개일 수 있다. -**The downstream budgets are carried in the profile and stated as unchanged.** The whole point is -that they did not grow. `admissionFitsDownstreamBudgets()` reports when the admission limit exceeds -them, without refusing — a deployment can legitimately admit more than its pool when the work is not -all database-bound, and that should be a choice rather than an accident. +**하류 예산은 profile에 싣고 바뀌지 않았다고 밝힌다.** 요점은 그것이 늘지 않았다는 것이다. `admissionFitsDownstreamBudgets()`는 +admission 한계가 그것을 넘으면 거절하지 않고 알린다 — 일이 모두 데이터베이스에 묶인 것이 아니면 배포가 pool보다 많이 받는 +것이 정당할 수 있고, 그것은 사고가 아니라 선택이어야 한다. -**Blocking offloads are registered, bounded and timed out.** `boundedElastic()` is available from -anywhere and unbounded in practice, so a controller that calls it has silently opted the whole -application into an unbounded pool. `BlockingBridgeProfile` names the operations permitted to -offload; `BlockingBridgeBudget` bounds the concurrency and refuses a caller that cannot get a slot -in time, because otherwise a slow dependency's callers accumulate until the heap does and the fast -dependencies starve behind them. +**blocking offload는 등록하고, 한계를 두고, timeout을 둔다.** `boundedElastic()`은 어디서나 쓸 수 있고 실제로는 한계가 없어서, +그것을 부르는 controller는 애플리케이션 전체를 소리 없이 한계 없는 pool에 들여놓는다. `BlockingBridgeProfile`이 offload해도 되는 +operation을 이름으로 대고, `BlockingBridgeBudget`이 동시성을 묶으며 제때 자리를 얻지 못한 호출자를 거절한다. 그렇지 않으면 느린 +의존 대상의 호출자가 heap이 찰 때까지 쌓이고 빠른 의존 대상이 그 뒤에서 굶는다. -> 2026-09-25: `advanced.blockingbridge` was removed. Its WebFlux adapter went with the WebFlux twin -> (D4), and a budget for a bridge that no longer exists bounded nothing. +> 2026-09-25: `advanced.blockingbridge`를 지웠다. 그 WebFlux 어댑터는 WebFlux 쌍둥이와 함께 갔고(D4), 더는 없는 bridge의 예산은 +> 아무것도 묶지 않았다. -**Pinning is observed, not assumed away.** `VirtualThreadProfile.requiredObservations()` lists what -has to be watched — `jdk.VirtualThreadPinned` above all. A synchronized block held across a blocking -call pins the carrier thread, the carrier pool is bounded by CPU count, and enough pinned carriers is -a deadlock a thread dump does not obviously show. +**pinning은 없다고 치지 않고 관찰한다.** `VirtualThreadProfile.requiredObservations()`가 지켜봐야 할 것 — 무엇보다 +`jdk.VirtualThreadPinned` — 을 적는다. blocking 호출을 가로질러 쥔 synchronized 블록은 carrier thread를 고정하고, carrier pool은 +CPU 수로 묶여 있으며, 고정된 carrier가 충분히 많으면 thread dump로도 잘 드러나지 않는 교착이 된다. -## Consequences +## 결과 -- Enabling virtual threads is a two-part change: the executor and the admission limit. The profile - will not let it be one. -- Refusals rise under load, and that is correct. A request refused in a millisecond is better for - the client than the same request accepted and timed out thirty seconds later behind a full pool. - An operator seeing 503s climb should read them as the limit working. -- `VirtualThreadAdmissionGuard.peakActive()` exists so a load test can assert the limit was applied. - It is invisible from throughput, which is why a load test that only measures throughput would pass - with the guard removed. +- virtual thread 켜기는 두 부분짜리 변경이다: executor와 admission 한계. profile은 그것이 한 부분이 되게 두지 않는다. +- 부하 아래에서 거절이 오르고, 그것이 맞다. 1밀리초 안에 거절된 요청이, 꽉 찬 pool 뒤에서 받아들여졌다가 30초 뒤 timeout된 같은 + 요청보다 client에게 낫다. 503이 오르는 것을 본 운영자는 그것을 한계가 동작하는 것으로 읽어야 한다. +- `VirtualThreadAdmissionGuard.peakActive()`는 부하 시험이 한계가 적용됐음을 단언할 수 있게 하려고 있다. 처리량에서는 보이지 + 않는다. 그래서 처리량만 재는 부하 시험은 guard를 빼도 통과한다. -## Alternatives considered +## 따져 본 대안 -- **Enable virtual threads and raise the downstream budgets to match.** Rejected: the budgets are - sized to what the dependencies can serve, not to what the web tier can accept. -- **Bound the virtual threads themselves with a fixed-size executor.** Rejected: that is a platform - thread pool with extra steps. -- **Let controllers call `boundedElastic()` directly.** Rejected: every such call site is invisible - until the pool is the thing consuming the heap. +- **virtual thread를 켜고 하류 예산을 거기 맞춰 올린다.** 버렸다: 예산은 web 계층이 받을 수 있는 양이 아니라 의존 대상이 감당할 + 수 있는 양에 맞춘 것이다. +- **고정 크기 executor로 virtual thread 자체를 묶는다.** 버렸다: 단계만 더 많은 platform thread pool이다. +- **controller가 `boundedElastic()`을 직접 부르게 둔다.** 버렸다: 그런 호출 자리는 pool이 heap을 먹는 범인이 될 때까지 하나도 + 보이지 않는다. diff --git a/docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md b/docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md index d850da30..32782c1e 100644 --- a/docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md +++ b/docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md @@ -7,62 +7,51 @@ - 현재 정본: `docs/web/openapi-32-compatibility.md` -# ADR-WEB-ADV-003: OpenAPI 3.2 is generated in parallel and stays experimental +# ADR-WEB-ADV-003: OpenAPI 3.2는 나란히 생성하고 실험용으로 남는다 -- Status: Accepted -- Date: 2026-08-25 -- Scope: `adapter:inbound:web` — `advanced.openapi` +- 상태: 채택 +- 날짜: 2026-08-25 +- 범위: `adapter:inbound:web` — `advanced.openapi` -## Context +## 배경 -Advanced Task 17 adds an OpenAPI 3.2 generation lane beside the Stable 3.1.2 snapshot. +Advanced Task 17은 Stable 3.1.2 snapshot 옆에 OpenAPI 3.2 생성 lane을 더한다. -Generating 3.2 is cheap. Adopting it is not, and the two get conflated because the generated -document looks fine. The value of an API description is entirely in what consumes it, and a document -in a version a client generator does not fully understand produces a client that compiles and is -wrong — which is worse than no document at all. +3.2 생성은 싸다. 채택은 싸지 않고, 생성된 문서가 멀쩡해 보여서 둘이 뒤섞인다. API 설명의 가치는 전부 그것을 쓰는 쪽에 있고, +client 생성기가 다 이해하지 못하는 버전의 문서는 컴파일되지만 틀린 client를 낳는다 — 문서가 아예 없는 것보다 나쁘다. -## Decision +## 결정 -**3.1.2 remains the release artifact.** `OpenApiVersionLane.STABLE_3_1.releaseArtifact()` is true and -`EXPERIMENTAL_3_2`'s is false. This is a property of the type, not a configuration setting. +**3.1.2가 릴리스 artifact로 남는다.** `OpenApiVersionLane.STABLE_3_1.releaseArtifact()`는 true이고 `EXPERIMENTAL_3_2`의 것은 +false다. 이것은 설정이 아니라 타입의 성질이다. -**Generating 3.2 must not change the 3.1 snapshot.** Both are produced from the same model, so a -contributor that mutates it on the way to 3.2 changes the artifact that is actually shipped — -silently, and only when the experimental lane runs. `OpenApi32CompatibilityReport` compares the -snapshot hash before and after and makes a difference a promotion blocker. +**3.2를 생성해도 3.1 snapshot이 바뀌면 안 된다.** 둘은 같은 모델에서 만들어지므로, 3.2로 가는 길에 모델을 바꾸는 기여자는 실제로 +출하하는 artifact를 바꾼다 — 소리 없이, 실험 lane이 돌 때만. `OpenApi32CompatibilityReport`가 전후의 snapshot hash를 비교하고, +차이를 승격을 막는 것으로 만든다. -> 2026-09-25: `OpenApi32CompatibilityReport` and `OpenApiToolchainMatrix` were removed — promotion -> checks kept in production code, called only by their own tests. `WebOpenApi32Generator` remains -> as library code in `adapter:inbound:web-advanced`; the decision below is unchanged. +> 2026-09-25: `OpenApi32CompatibilityReport`와 `OpenApiToolchainMatrix`를 지웠다 — 운영 코드에 둔 승격 검사인데 자기 시험만 +> 불렀다. `WebOpenApi32Generator`는 `adapter:inbound:web-advanced`에 라이브러리 코드로 남는다. 아래 결정은 바뀌지 않았다. -**Four kinds of tool are checked separately.** A parser reports structural errors; a linter applies -style rules and accepts documents a parser rejects; a generator produces client code, and this is -where an unsupported construct surfaces — not as an error but as a method with the wrong signature; -a compile of that generated code is the only step that catches it. "OpenAPI 3.2 works" is not a -statement anybody can make. "This document is read correctly by these four tools at these versions" -is. +**도구 네 종류를 따로 검사한다.** parser는 구조 오류를 알린다. linter는 문체 규칙을 적용하고 parser가 거절하는 문서도 받는다. +생성기는 client 코드를 만들고, 지원되지 않는 구문이 드러나는 곳이 여기다 — 오류가 아니라 시그니처가 틀린 메서드로. 그 생성 코드를 +컴파일하는 것이 그것을 잡는 유일한 단계다. 「OpenAPI 3.2가 된다」는 누구도 할 수 있는 말이 아니다. 「이 문서를 이 버전의 이 네 +도구가 맞게 읽는다」는 할 수 있다. -**Promotion requires an accepted ADR regardless of how green the matrix is.** -`promotionBlockers(false)` always contains that blocker. A machine-checkable matrix cannot decide -whether the consumer population is ready. +**표가 얼마나 초록이든 승격에는 채택된 ADR이 필요하다.** `promotionBlockers(false)`는 언제나 그 막음을 담는다. 기계로 검사하는 +표는 쓰는 쪽 집단이 준비됐는지 정할 수 없다. -**Streaming description differences are reported separately.** They are the substantive difference -between the two versions for this application, and folding them into a pass/fail hides what -changed. +**streaming 설명의 차이는 따로 알린다.** 이 애플리케이션에서 두 버전의 실질적 차이가 그것이고, 통과·실패 하나로 접으면 무엇이 +바뀌었는지 가려진다. -## Consequences +## 결과 -- The 3.2 document is published as an artifact of the experimental workflow, never of the release - workflow. -- A client generator that only understands 3.1 is unaffected, which is the point. -- Adopting 3.2 later is a documented decision with a named consumer matrix behind it. +- 3.2 문서는 릴리스 workflow가 아니라 실험 workflow의 artifact로만 게시한다. +- 3.1만 이해하는 client 생성기는 영향을 받지 않는다. 그것이 요점이다. +- 나중에 3.2를 채택하는 것은 이름 있는 쓰는 쪽 표를 뒤에 둔, 문서로 남긴 결정이다. -## Alternatives considered +## 따져 본 대안 -- **Switch to 3.2 and keep a 3.1 downgrade.** Rejected: the downgrade is lossy in exactly the - constructs 3.2 was wanted for, so it would ship a description that is wrong for both audiences. -- **Generate only 3.2 and let consumers cope.** Rejected: the failure mode is a generated client - that compiles and misbehaves. -- **Skip the client-compile step in the matrix.** Rejected: it is the only one that catches the - failure the others miss. +- **3.2로 바꾸고 3.1로 낮춘 것을 둔다.** 버렸다: 낮추기는 바로 3.2를 원한 이유인 구문에서 손실이 있어서, 두 독자 모두에게 틀린 + 설명을 출하하게 된다. +- **3.2만 생성하고 쓰는 쪽이 알아서 하게 둔다.** 버렸다: 실패 방식은 컴파일되고 잘못 동작하는 생성 client다. +- **표에서 client 컴파일 단계를 건너뛴다.** 버렸다: 다른 단계가 놓치는 실패를 잡는 유일한 단계다. diff --git a/docs/adr/ADR-WS-001-platform-as-packages-and-its-boundaries.md b/docs/adr/ADR-WS-001-platform-as-packages-and-its-boundaries.md index 69cc7efb..81465281 100644 --- a/docs/adr/ADR-WS-001-platform-as-packages-and-its-boundaries.md +++ b/docs/adr/ADR-WS-001-platform-as-packages-and-its-boundaries.md @@ -8,62 +8,51 @@ - 대체됨: `docs/capability-status.md` -# ADR-WS-001: The WebSocket platform ships as packages in one leaf, with machine-checked boundaries +# ADR-WS-001: WebSocket 플랫폼은 leaf 하나 안의 패키지로 싣고, 경계는 기계로 검사한다 -- Status: Superseded 2026-09-25 — the eighteen-package platform was cut to the parts a Spring - configuration or a real-container lane reaches: the `stomp` channel and the servlet handler - library (`servlet`, `outbound`, `budget`). The Advanced packages, the reactive runtime and the - `WebSocketArchitectureRules` pack went with the rest (see `docs/capability-status.md`). -- Date: 2026-08-25 -- Scope: `:adapter:inbound:websocket` +- 상태: 대체됨 2026-09-25 — 패키지 열여덟 개짜리 플랫폼을 Spring 설정이나 실제 container lane이 닿는 부분으로 잘랐다: `stomp` + 채널과 servlet handler 라이브러리(`servlet`, `outbound`, `budget`). Advanced 패키지, reactive runtime, `WebSocketArchitectureRules` + 묶음은 나머지와 함께 갔다(`docs/capability-status.md`를 본다). +- 날짜: 2026-08-25 +- 범위: `:adapter:inbound:websocket` -## Context +## 배경 -The realtime connection platform design models itself as eighteen Gradle modules under -`modules/websocket`, each with a declared purity grade and a declared set of allowed dependencies. -This repository's `src/config/architecture/modules.json` is a fail-closed registry that owns the -leaf list; adding eighteen leaves is a registry change of a size that needs its own decision, and -HARD-STOP #5 forbids doing it implicitly. +실시간 연결 플랫폼 설계는 스스로를 `modules/websocket` 아래 Gradle 모듈 열여덟 개로 모델링하고, 모듈마다 순수성 등급과 허용 의존 +집합을 선언한다. 이 저장소의 `src/config/architecture/modules.json`은 leaf 목록을 가진 실패하면 닫히는 registry다. leaf 열여덟 개를 +더하는 것은 자기 결정이 필요한 크기의 registry 변경이고, HARD-STOP #5가 그것을 은근슬쩍 하는 것을 금지한다. -Three earlier platforms in this repository — JPA, GraphQL, and the HTTP platform — met the same -situation and resolved it the same way. +이 저장소의 앞선 플랫폼 셋 — JPA, GraphQL, HTTP 플랫폼 — 이 같은 상황을 만났고 같은 방식으로 풀었다. -## Decision +## 결정 -The eighteen design modules ship as packages inside the single registered leaf. `WebSocketStableModule` -declares each one's package, purity grade and exact allowed edges, and `WebSocketModuleBoundaryTest` -scans the production tree and fails when the declaration and the tree disagree in either direction. +설계 모듈 열여덟 개를 등록된 leaf 하나 안의 패키지로 싣는다. `WebSocketStableModule`이 모듈마다 패키지, 순수성 등급, 정확한 허용 +edge를 선언하고, `WebSocketModuleBoundaryTest`가 운영 트리를 scan해 선언과 트리가 어느 방향으로든 다르면 실패한다. -Three deviations from the design's module map were forced by the check and are recorded in -`docs/websocket/repository-adaptation.md`: `WebSocketSubprotocolName` moved to `core` and the codec -moved to its own FRAMEWORK_BOUND module, both to avoid cycles the design's placement created here; -and the `budget -> core` edge was inverted because `budget` imports nothing from `core`. +검사가 강요한, 설계 모듈 지도와 다른 점 셋은 `docs/websocket/repository-adaptation.md`에 적었다: `WebSocketSubprotocolName`을 +`core`로 옮겼고 codec을 자기 FRAMEWORK_BOUND 모듈로 옮겼다. 둘 다 설계의 배치가 여기서 만든 순환을 피하려는 것이다. 그리고 +`budget`이 `core`에서 아무것도 import하지 않으므로 `budget -> core` edge를 뒤집었다. -## Consequences +## 결과 -**The boundary is enforced, not documented.** Six violations were caught during implementation that -a document would not have: two would-be cycles, a duplicate module declaration where two ids claimed -one package, and three undeclared edges. The duplicate is the instructive one — with two ids on one -package, ownership depends on iteration order and one module's rules silently apply to nothing. A -guard against it is now part of the boundary test. +**경계를 문서로 두지 않고 강제한다.** 구현 중에 문서라면 잡지 못했을 위반 여섯 개를 잡았다: 순환이 될 뻔한 것 둘, id 둘이 패키지 +하나를 주장한 중복 모듈 선언, 선언하지 않은 edge 셋. 배울 것이 있는 쪽은 중복이다 — 패키지 하나에 id가 둘이면 소유가 반복 순서에 +달리고 한 모듈의 규칙이 소리 없이 아무것에도 적용되지 않는다. 그것을 막는 guard가 이제 경계 시험의 일부다. -**The detector had a hole.** Its framework-import list named `com.fasterxml` (Jackson 2) and not -`tools.jackson` (Jackson 3), which is what Spring 7 actually uses — so a CORE module could have -imported a mapper unnoticed. Fixed here and in the HTTP platform, which shared the list. +**찾는 장치에 구멍이 있었다.** 그 프레임워크 import 목록은 `com.fasterxml`(Jackson 2)를 대고 Spring 7이 실제로 쓰는 +`tools.jackson`(Jackson 3)을 대지 않았다 — 그래서 CORE 모듈이 mapper를 import해도 들키지 않을 수 있었다. 여기와, 그 목록을 같이 쓰던 +HTTP 플랫폼에서 고쳤다. -**Promotion stays cheap.** Each enum constant is already shaped like a leaf specification, so -splitting one out later is a registry edit rather than an archaeology exercise. +**승격은 싸게 남는다.** enum 상수 하나하나가 이미 leaf 명세 모양이라서, 나중에 하나를 떼어 내는 것은 고고학이 아니라 registry +수정이다. -**The design's own rules were kept where they cost something.** `core` names no framework, so the -same decisions serve both runtimes and are testable without a server; no Java class name reaches the -wire; the payload is an encoded string rather than a map; and handlers are given no way to write, -which is what makes ordering and backpressure guarantees rather than conventions. +**비용이 드는 곳에서도 설계 자신의 규칙을 지켰다.** `core`는 어떤 프레임워크도 이름으로 대지 않으므로 같은 결정이 두 runtime에 +쓰이고 서버 없이 시험할 수 있다. Java 클래스 이름이 wire에 닿지 않는다. payload는 map이 아니라 인코딩한 문자열이다. 그리고 +handler에게는 쓸 길을 주지 않는다. 그것이 순서와 backpressure를 관례가 아니라 보장으로 만든다. -## Alternatives considered +## 따져 본 대안 -**Register eighteen leaves.** Faithful to the design and a large change to a fail-closed registry -for a platform that ships as one artifact either way. Rejected as disproportionate; the boundary -test provides the property the modules were for. +**leaf 열여덟 개를 등록한다.** 설계에 충실하지만, 어느 쪽이든 artifact 하나로 싣는 플랫폼을 위해 실패하면 닫히는 registry를 크게 +바꾼다. 지나치다고 보고 버렸다. 경계 시험이 모듈이 주려던 성질을 준다. -**Ship the modules as packages with no enforcement.** Cheapest, and it makes the boundary a claim. -The six violations found during implementation are the argument against it. +**모듈을 강제 없는 패키지로 싣는다.** 가장 싸지만 경계를 주장으로 만든다. 구현 중에 찾은 위반 여섯 개가 그것에 반대하는 근거다. diff --git a/docs/adr/ADR-WS-002-resume-and-cluster.md b/docs/adr/ADR-WS-002-resume-and-cluster.md index 6f089e9d..30ad5578 100644 --- a/docs/adr/ADR-WS-002-resume-and-cluster.md +++ b/docs/adr/ADR-WS-002-resume-and-cluster.md @@ -8,64 +8,56 @@ - 대체됨: `docs/capability-status.md` -# ADR-WS-002: Resume and cluster state are caches, and are treated as caches +# ADR-WS-002: resume와 cluster 상태는 cache이고, cache로 다룬다 -- Status: Superseded 2026-09-25 — `advanced.resume`, `advanced.cluster` and `advanced.presence` - were removed: nothing assembled them (see `docs/capability-status.md`). -- Date: 2026-08-25 -- Scope: `adapter:inbound:websocket` — `advanced.resume`, `advanced.cluster`, `advanced.presence` +- 상태: 대체됨 2026-09-25 — `advanced.resume`, `advanced.cluster`, `advanced.presence`를 지웠다: 아무것도 그것을 조립하지 + 않았다(`docs/capability-status.md`를 본다). +- 날짜: 2026-08-25 +- 범위: `adapter:inbound:websocket` — `advanced.resume`, `advanced.cluster`, `advanced.presence` -## Context +## 배경 -Advanced Tasks 2–8 add three things that all look like state and are not: a resume token that says -where a client got to, a cluster index that says which node holds a session, and a presence summary -derived from that index. +Advanced Task 2–8은 모두 상태처럼 보이지만 상태가 아닌 것 셋을 더한다: client가 어디까지 왔는지 말하는 resume token, 어느 노드가 +세션을 가졌는지 말하는 cluster index, 그 index에서 끌어낸 presence 요약. -Each is a statement about the past. The resume token was minted before the disconnect; the index -entry was written by a node that may since have died; presence is a read of the index and inherits -everything wrong with it. The failure this ADR exists to prevent is treating any of them as current -fact, because each reads as one at the call site. +하나하나가 과거에 대한 진술이다. resume token은 연결이 끊기기 전에 만들어졌다. index 항목은 그 뒤에 죽었을 수 있는 노드가 썼다. +presence는 index를 읽은 것이고 그것의 틀린 점을 모두 물려받는다. 이 ADR이 막으려는 실패는 그중 어느 것이든 지금의 사실로 다루는 +것이다. 부르는 자리에서는 하나같이 사실처럼 읽히기 때문이다. -## Decision +## 결정 -**Resume is bounded by what the replay store actually holds, not by what the token claims.** -`ResumeCoordinator` consults `ReplayAvailability` before honouring a position. A token that names a -position the store has evicted produces a resynchronise, not a gap-filled stream. The alternative — -trusting the token — silently delivers a stream with a hole in it, which is worse than an explicit -resynchronise because the client believes it is complete. +**resume은 token이 주장하는 것이 아니라 replay 저장소가 실제로 가진 것으로 묶는다.** `ResumeCoordinator`는 위치를 받아 주기 전에 +`ReplayAvailability`를 묻는다. 저장소가 이미 버린 위치를 대는 token은 빈틈을 메운 stream이 아니라 다시 맞추기를 낸다. 대안 — token을 +믿기 — 은 구멍 난 stream을 소리 없이 전달하고, client가 그것이 완전하다고 믿으므로 명시적 다시 맞추기보다 나쁘다. -**Cluster index entries carry an observation time and are checked against it on every read.** -`ExternalSessionSummary.staleAt` exists so that "the index says edge-2" cannot be used without also -answering "as of when". An entry whose node stopped reporting is not evidence that the node holds -the session. +**cluster index 항목은 관찰 시각을 싣고, 읽을 때마다 그것과 대조한다.** `ExternalSessionSummary.staleAt`은 「index가 edge-2라고 +한다」를 「언제 기준으로」에 답하지 않고는 쓸 수 없게 하려고 있다. 보고를 멈춘 노드의 항목은 그 노드가 세션을 가졌다는 증거가 +아니다. -**Durable fan-out is deduplicated by stream position, not by message id.** At-least-once is the -contract, so redelivery is normal operation: a redeploy, a slow consumer or a broker rebalance all -produce it. `FanoutDeduplicator` keys on `(stream, position)` and advances a high-water mark under -`compute`, so two consumer threads cannot both deliver the same position. +**durable fan-out의 중복은 message id가 아니라 stream 위치로 거른다.** 계약이 at-least-once이므로 재전달은 보통 동작이다: 재배포, +느린 소비자, broker rebalance가 모두 그것을 낳는다. `FanoutDeduplicator`는 `(stream, position)`을 키로 쓰고 `compute` 아래에서 +high-water mark를 올리므로, 소비자 스레드 둘이 같은 위치를 둘 다 전달할 수 없다. -**Presence has four states, not two.** `OFFLINE` is a reported fact; `STALE` is the absence of one. -Collapsing them reports every user as disconnected during a Redis partition, when what happened is -that the index went dark and the connections are fine. +**presence에는 상태가 둘이 아니라 넷이다.** `OFFLINE`은 보고된 사실이고, `STALE`은 사실이 없는 것이다. 둘을 합치면 Redis partition +동안 모든 사용자를 연결 끊김으로 알리는데, 실제로 일어난 일은 index가 어두워졌고 연결은 멀쩡한 것이다. -**Nothing security-relevant may depend on presence.** An attacker who can make a node stop reporting -can move the platform's belief about who is present. Presence answers "show a green dot". +**보안에 관련된 어떤 것도 presence에 기대면 안 된다.** 노드가 보고를 멈추게 할 수 있는 공격자는 누가 있는지에 대한 플랫폼의 믿음을 +움직일 수 있다. presence는 「초록 점을 보여 줄까」에 답한다. -## Consequences +## 결과 -- A resume that cannot be honoured is visible to the client as a resynchronise. Clients must - implement one; there is no mode in which the platform silently pretends. -- Every read of the cluster index needs a clock. This is deliberate friction. -- `PresenceSummary.classify` refuses an idle window at or past the stale window, because otherwise - `IDLE` is unreachable and the caller believes it has a four-state model when it has three. -- Fan-out envelopes carry a bounded reference and the catalog-encoded document, never a business - object. A rolling deploy has two versions of the code reading the same envelope. +- 받아 줄 수 없는 resume은 client에게 다시 맞추기로 보인다. client는 그것을 구현해야 한다. 플랫폼이 소리 없이 시늉하는 모드는 없다. +- cluster index를 읽을 때마다 시계가 필요하다. 일부러 둔 마찰이다. +- `PresenceSummary.classify`는 stale 창 이상인 idle 창을 거절한다. 그렇지 않으면 `IDLE`에 닿을 수 없고, 호출자는 상태 셋짜리를 + 가지고 넷짜리 모델이라고 믿는다. +- fan-out envelope은 한계 있는 참조와 catalog로 인코딩한 문서를 싣고, 업무 객체는 싣지 않는다. rolling deploy에서는 코드 두 버전이 + 같은 envelope을 읽는다. -## Alternatives considered +## 따져 본 대안 -- **Trust the resume token.** Rejected: it makes a gap indistinguishable from a complete stream. -- **Deduplicate by message id.** Rejected: a broker that redelivers may re-mint ids, and a producer - that retries certainly does. Position is the property the ordering actually has. -- **A single `online` boolean.** Rejected for the partition case above. -- **Write presence separately from the session index.** Rejected: two sources of truth for "who is - connected" drift, and the drift is invisible — both look plausible and nothing reconciles them. +- **resume token을 믿는다.** 버렸다: 빈틈을 완전한 stream과 구별할 수 없게 만든다. +- **message id로 중복을 거른다.** 버렸다: 재전달하는 broker는 id를 다시 만들 수 있고, 재시도하는 producer는 반드시 그렇게 한다. + 위치가 순서가 실제로 가진 성질이다. +- **`online` boolean 하나.** 위 partition 경우 때문에 버렸다. +- **presence를 세션 index와 따로 쓴다.** 버렸다: 「누가 연결돼 있나」의 정본이 둘이면 어긋나고, 그 어긋남은 보이지 않는다 — 둘 다 + 그럴듯해 보이고 아무것도 둘을 맞추지 않는다. diff --git a/docs/adr/ADR-WS-003-stomp-and-broker-relay.md b/docs/adr/ADR-WS-003-stomp-and-broker-relay.md index fab91a73..b87857ec 100644 --- a/docs/adr/ADR-WS-003-stomp-and-broker-relay.md +++ b/docs/adr/ADR-WS-003-stomp-and-broker-relay.md @@ -8,78 +8,66 @@ - 대체됨: `docs/capability-status.md` -# ADR-WS-003: STOMP is an Advanced adapter with a declared destination catalog +# ADR-WS-003: STOMP는 destination catalog를 선언한 Advanced 어댑터다 -- Status: Superseded 2026-09-25 — `advanced.stomp` and `advanced.stomp.rabbit` were removed; the - `stomp` package is the only STOMP channel (see `docs/capability-status.md`). -- Date: 2026-08-25 -- Scope: `adapter:inbound:websocket` — `advanced.stomp`, `advanced.stomp.rabbit` +- 상태: 대체됨 2026-09-25 — `advanced.stomp`와 `advanced.stomp.rabbit`을 지웠다. `stomp` 패키지가 유일한 STOMP 채널이다 + (`docs/capability-status.md`를 본다). +- 날짜: 2026-08-25 +- 범위: `adapter:inbound:websocket` — `advanced.stomp`, `advanced.stomp.rabbit` -## Context +## 배경 -Advanced Tasks 9–13 add STOMP 1.2 alongside the platform's own protocol, plus a RabbitMQ broker -relay and cross-node user destinations. +Advanced Task 9–13은 플랫폼 자신의 프로토콜 옆에 STOMP 1.2를 더하고, RabbitMQ broker relay와 노드를 가로지르는 user destination도 +더한다. -This leaf already ships an older STOMP-over-SockJS channel (`stomp`, gated on -`app.websocket.enabled`). Two `@EnableWebSocketMessageBroker` configurations in one context -do not conflict loudly — both contribute a configurer, both call `configureMessageBroker`, and the -broker that results is whichever ran last. Nothing errors and nothing logs. +이 leaf는 이미 더 오래된 STOMP-over-SockJS 채널(`stomp`, `app.websocket.enabled`로 막는다)을 싣는다. 한 context 안의 +`@EnableWebSocketMessageBroker` 설정 둘은 시끄럽게 충돌하지 않는다 — 둘 다 configurer를 기여하고, 둘 다 +`configureMessageBroker`를 부르며, 결과 broker는 마지막에 돈 쪽의 것이다. 오류도 로그도 없다. -STOMP also brings a destination model that is a free string from the client. Without a catalog, the -set of reachable destinations is whatever the broker accepts, which for the simple broker is every -string. +STOMP는 client에게서 오는 자유 문자열인 destination 모델도 가져온다. catalog가 없으면 닿을 수 있는 destination 집합은 broker가 받는 +모든 것이고, simple broker에게 그것은 모든 문자열이다. -## Decision +## 결정 -**The Advanced adapter is its own module (`advanced-stomp`), separate from `advanced`.** It is the -one Advanced capability that cannot be pure — STOMP here *is* the Spring Messaging types — and -folding it into `advanced` would relax that module's purity for every capability in it. +**Advanced 어댑터는 `advanced`와 따로 둔 자기 모듈(`advanced-stomp`)이다.** 순수할 수 없는 유일한 Advanced capability다 — 여기서 +STOMP는 곧 Spring Messaging 타입이다 — 그리고 `advanced`에 접어 넣으면 그 모듈의 모든 capability에 대해 순수성을 느슨하게 만든다. -**The relay is a further module (`advanced-stomp-rabbit`).** The adapter parses a protocol; the -relay opens a TCP connection to somebody else's broker and makes every delivery depend on it. -Different blast radius, different decision, different module. +**relay는 그다음 모듈(`advanced-stomp-rabbit`)이다.** 어댑터는 프로토콜을 파싱한다. relay는 남의 broker에 TCP 연결을 열고 모든 +전달을 그것에 기대게 만든다. 피해 범위가 다르고, 결정이 다르고, 모듈이 다르다. -**Destinations are declared, per operation.** `StompDestinationCatalog` maps `(operation, -destination)` to a required permission. Undeclared is refused. `SUBSCRIBE` and `SEND` are separate -declarations, because reading a feed and publishing into it are different rights. +**destination은 operation마다 선언한다.** `StompDestinationCatalog`는 `(operation, destination)`을 필요한 권한에 대응시킨다. 선언하지 +않은 것은 거절한다. `SUBSCRIBE`와 `SEND`는 따로 선언한다. feed를 읽는 것과 거기에 게시하는 것은 다른 권리이기 때문이다. -**The authorization decision is a value, not an interceptor method.** `StompAuthorizationPolicy` -returns a `StompAuthorizationDecision`; `StompSecurityInterceptor` only extracts and enforces. A rule -reachable only through a `MessageChannel` gets tested for the cases somebody built a channel for. +**인가 판정은 interceptor 메서드가 아니라 값이다.** `StompAuthorizationPolicy`가 `StompAuthorizationDecision`을 돌려주고, +`StompSecurityInterceptor`는 꺼내서 강제하기만 한다. `MessageChannel`을 거쳐서만 닿는 규칙은 누가 channel을 만들어 둔 경우만 +시험된다. -**Only one STOMP runtime may run.** `StompBrokerExclusivity` fails the context when both channels -are enabled, when both brokers are, or when the adapter is enabled with no broker behind it. +**STOMP runtime은 하나만 돌 수 있다.** `StompBrokerExclusivity`는 두 채널이 모두 켜졌을 때, 두 broker가 모두 켜졌을 때, 또는 뒤에 +broker 없이 어댑터가 켜졌을 때 context를 실패시킨다. -**A `RECEIPT` is never promoted to a commit.** `StompEvidence` has six stages and -`StompAckPolicy.evidenceForReceipt()` is fixed at `PROTOCOL_RECEIPT`. The receipt is written by the -protocol layer, which knows nothing about whether the work succeeded. +**`RECEIPT`는 절대 커밋으로 올리지 않는다.** `StompEvidence`에는 단계가 여섯 있고 `StompAckPolicy.evidenceForReceipt()`는 +`PROTOCOL_RECEIPT`로 고정이다. receipt는 프로토콜 계층이 쓰고, 그 계층은 일이 성공했는지 아무것도 모른다. -**The simple broker declares what it cannot do.** `SimpleBrokerProfile` cannot be constructed -claiming cluster support or durable acks, and refuses activation outside local/test — in a -multi-node deployment it does not error, it delivers to whichever fraction of users is on the -publishing node. +**simple broker는 할 수 없는 것을 선언한다.** `SimpleBrokerProfile`은 cluster 지원이나 durable ack를 주장하며 만들 수 없고, +local·test 밖에서 켜기를 거절한다 — 여러 노드 배포에서 그것은 오류를 내지 않고, 게시한 노드에 있는 사용자 일부에게만 전달한다. -**Unresolved user destinations are broadcast once and then dead-lettered.** -`MultiNodeUserDestination` distinguishes a message that arrived *via* the broadcast from one that did -not. Without that, every node rebroadcasts every unresolvable message on receipt. +**풀리지 않은 user destination은 한 번 broadcast한 뒤 dead-letter로 보낸다.** `MultiNodeUserDestination`은 broadcast를 *거쳐* 온 +메시지와 그렇지 않은 메시지를 구별한다. 그렇지 않으면 모든 노드가 풀 수 없는 메시지를 받을 때마다 다시 broadcast한다. -## Consequences +## 결과 -- Enabling Advanced STOMP requires disabling the legacy channel. There is no migration path that - runs both; the exclusivity check makes that explicit at startup rather than at 3am. -- A deployment must write its own catalog. There is deliberately no default: an empty one refuses - every frame and reads as a broken adapter, and a non-empty one publishes destinations nobody chose. -- The relay's cost is one broker connection per authenticated session plus one system connection. - `brokerConnectionsFor` exists so this is computed before the first outage. -- User-destination metrics are tagged with `UserDestinationAction`, never the destination — a user - destination contains a user identifier by construction. +- Advanced STOMP를 켜려면 옛 채널을 꺼야 한다. 둘을 함께 돌리는 옮기기 길은 없다. 배타성 검사가 그것을 새벽 3시가 아니라 기동 + 때 분명히 한다. +- 배포는 자기 catalog를 써야 한다. 일부러 기본값이 없다: 빈 catalog는 모든 frame을 거절해서 고장 난 어댑터처럼 읽히고, 비어 있지 + 않은 기본 catalog는 아무도 고르지 않은 destination을 게시한다. +- relay의 비용은 인증된 세션마다 broker 연결 하나 + 시스템 연결 하나다. `brokerConnectionsFor`는 첫 장애 전에 그것을 계산하려고 + 있다. +- user destination metric은 destination이 아니라 `UserDestinationAction`으로 tag를 단다 — user destination은 구조상 사용자 식별자를 + 담는다. -## Alternatives considered +## 따져 본 대안 -- **Extend the existing `stomp` package.** Rejected: it is Stable, and WS-ARCH-6 forbids a Stable - module naming an Advanced one. Making the legacy channel profile-driven would have required that - edge. -- **One `advanced-stomp` module including the relay.** Rejected: the relay is a separate operational - decision and deserves to be refusable on its own. -- **Allow undeclared destinations with a wildcard permission.** Rejected: the wildcard becomes the - default and the catalog becomes documentation. +- **기존 `stomp` 패키지를 넓힌다.** 버렸다: 그것은 Stable이고, WS-ARCH-6은 Stable 모듈이 Advanced 모듈 이름을 대는 것을 금지한다. + 옛 채널을 profile로 움직이게 하려면 그 edge가 필요했다. +- **relay를 포함한 `advanced-stomp` 모듈 하나.** 버렸다: relay는 따로 정할 운영 결정이고, 그것만 따로 거절할 수 있어야 한다. +- **wildcard 권한으로 선언하지 않은 destination을 허용한다.** 버렸다: wildcard가 기본이 되고 catalog는 문서가 된다. diff --git a/docs/adr/NOTIF-ADR-001-durable-acceptance.md b/docs/adr/NOTIF-ADR-001-durable-acceptance.md new file mode 100644 index 00000000..de2293f7 --- /dev/null +++ b/docs/adr/NOTIF-ADR-001-durable-acceptance.md @@ -0,0 +1,34 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-14 +- 요약: 알림 submit()은 영속적으로 받아들였다는 뜻이라는 결정이다. +- 현재 정본: `docs/notification/support-matrix.md` + + +# NOTIF-ADR-001 — `submit()`은 durable 접수를 뜻한다 + +## 상태 + +채택. + +## 배경 + +알림 플랫폼의 뻔한 API는 성공이나 실패를 돌려주는 `send()`다. 이 플랫폼이 지원하는 모든 채널이 그 반환값을 거짓말로 만든다: + +- SES는 요청을 받고 `MessageId`를 돌려준 뒤에도 보내기를 거절할 수 있다. +- Twilio는 `accepted`, `sent`, `delivered`를 따로따로, 나중에 오는 이벤트로 나눈다. +- APNs는 알림을 받은 뒤 전달하거나, 저장하거나, 버릴 수 있다. +- Web Push는 프로토콜 수준에서 push service의 접수와 user agent의 확인 응답을 나눈다. + +## 결정 + +`submit()`과 `schedule()`은 논리 요청과 그 수신자 job이 데이터베이스에 커밋되면 돌아온다. 접수증은 `notificationId`, +`RequestStatus`, `acceptedAt`을 싣고, `delivered`·`sent`·`read` 요소가 없다. 트랜잭션이 열려 있는 동안에는 어떤 provider에도 +연락하지 않는다. + +## 결과 + +타입이 그렇게 읽을 길을 주지 않으므로, 호출자는 접수를 전달로 착각할 수 없다. 전달 상태는 provider 이벤트 원장에서 만든 +projection에 대한 따로 둔 query다. 비용은 「도착했나?」가 두 번째 질문이라는 것이다 — 그것이 정직한 질문 수다. diff --git a/docs/adr/NOTIF-ADR-002-event-ledger-projection.md b/docs/adr/NOTIF-ADR-002-event-ledger-projection.md new file mode 100644 index 00000000..bcbf6ada --- /dev/null +++ b/docs/adr/NOTIF-ADR-002-event-ledger-projection.md @@ -0,0 +1,31 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-14 +- 요약: 알림 상태를 덧붙이기만 하는 이벤트 원장과 채널별 projector로 둔다는 결정이다. +- 현재 정본: `docs/notification/support-matrix.md` + + +# NOTIF-ADR-002 — 채널 projector를 둔 append-only 이벤트 원장 + +## 상태 + +채택. + +## 배경 + +선형 전달 상태 하나는 제자리에서 고쳐야 하고, 그러면 새 이벤트가 저장된 것보다 앞서는지 정할 규칙이 필요하다. 자연스러운 규칙 — +ordinal 비교 — 은 실제 provider traffic에서 틀린다. Twilio는 callback 순서를 보장하지 않아서 `sent`가 `delivered` 뒤에 온다. email은 +전달 뒤에 불만 신고를 낸다. 두 경우 모두 ordinal 규칙 아래에서 정보를 잃는다. + +## 결정 + +provider 이벤트는 어떤 projection이 돌기 전에 바뀌지 않는 원장에 덧붙인다. 채널별 projector가 명시한 전이 표로 이벤트를 +`SubmissionOutcome`, `DeliveryOutcome`, `EvidenceLevel`, `EngagementFacts`, `SuppressionFacts`로 합친다. projection은 멱등이고 원장에서 +다시 돌릴 수 있다. + +## 결과 + +중복, 순서가 뒤바뀐, 늦은 이벤트는 결함이 아니라 보통 입력이다. 잘못 project한 이벤트가 아직 저장돼 있으므로 projector 결함은 +회복할 수 있다. projector 버전은 다시 돌려서 옮길 수 있다. 비용은 이벤트마다 두 번째 쓰기와, 원장보다 늦을 수 있는 projection이다. diff --git a/docs/adr/NOTIF-ADR-003-ambiguous-submission.md b/docs/adr/NOTIF-ADR-003-ambiguous-submission.md new file mode 100644 index 00000000..08bf8113 --- /dev/null +++ b/docs/adr/NOTIF-ADR-003-ambiguous-submission.md @@ -0,0 +1,42 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-14 +- 요약: 결과가 모호한 제출을 정식 상태로 둔다는 결정이다. +- 현재 정본: `docs/notification/support-matrix.md` + + +# NOTIF-ADR-003 — 모호한 제출은 정식 상태다 + +## 상태 + +채택. + +## 배경 + +가장 흔한 심각한 실패는 거절이 아니다. body는 provider에 닿았는데 응답이 돌아오지 않은 요청이다. 플랫폼에는 provider 요청 id가 없고, +사용자는 알림을 받았을 수도 안 받았을 수도 있다. + +그것을 실패로 다루면 중복이 생긴다: 재시도가 두 번째 메시지를 보내고, 채널을 넘는 대체가 이미 도착한 push 옆에 SMS를 보낸다. 성공으로 +다루면 실제 실패를 잃는다. + +## 결정 + +`AMBIGUOUS`는 저장되는 `SubmissionOutcome`이자 `AttemptConfirmation`이다. 시도는 `requestStarted`, `requestBodyCommitted`, +`providerResponseReceived`를 기록하고, 각각 `PROVEN`, `INFERRED`, `UNKNOWN` 중 하나의 `EvidenceCertainty`를 가진다. 그래서 모르는 +어댑터가 `false`로 답하도록 강요받지 않는다. + +수신자 전달에 모호한 시도가 있는 동안에는: + +- provider가 요청별 멱등성을 증명하지 않으면 자동 재시도를 막는다 +- 채널을 넘는 자동 대체는 조건 없이 막는다 +- provider가 상태 query를 지원하면 맞춰 보기를 돌린다 +- 그렇지 않으면 전달을 멈추고 운영자를 기다린다 + +모호한 시도를 운영자가 다시 보내려면 중복 위험을 명시해 승인해야 한다. + +## 결과 + +어떤 알림은 사람이나 맞춰 보기 한 바퀴가 필요한 상태에서 멈춘다. 그것이 의도한 거래다: 풀리지 않은 모름이 보장된 중복보다 싸고, +상태는 어느 쪽으로든 소리 없이 풀리지 않고 보인다. diff --git a/docs/adr/NOTIF-ADR-004-fcm-fid-primary.md b/docs/adr/NOTIF-ADR-004-fcm-fid-primary.md new file mode 100644 index 00000000..4a885de3 --- /dev/null +++ b/docs/adr/NOTIF-ADR-004-fcm-fid-primary.md @@ -0,0 +1,33 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-14 +- 요약: FCM 대상은 installation id를 먼저 쓴다는 결정이다. +- 현재 정본: `docs/notification/provider-runbooks.md` + + +# NOTIF-ADR-004 — FCM installation id가 주 대상이다 + +## 상태 + +채택. + +## 배경 + +Firebase는 이제 installation id(FID)를 권하고 registration token multicast 경로를 옛것으로 다룬다. `token` 문자열 하나 위에 세운 +contact point 모델은 옛 모델을 유일한 것으로 담게 되고, 나중의 옮기기는 런타임 해석 문제가 된다: 같은 문자열 필드가 행마다 다른 +뜻이 된다. + +## 결정 + +`MobilePushTarget`은 `FcmInstallationId`, `LegacyFcmRegistrationToken`, `ApnsDeviceToken`으로 된 sealed 계층이다. 종류는 문자열 필드 +하나의 구분자가 아니라 따로 둔 타입이고, 각각 자기 `ContactPointType`을 싣는다. 그래서 유일성 범위와 암호화 associated data가 다르다. + +APNs token은 환경도 싣는다. sandbox와 production은 flag가 아니라 따로 둔 namespace이기 때문이다. + +## 결과 + +대상 종류를 옮기는 것은 런타임 짐작이 아니라 빠짐없는 `switch`를 쓴 컴파일 시점 변경이다. 어댑터가 종류마다 자기 wire 표현으로 +대응시키므로, provider가 한 경로를 바꿔도 다른 경로가 소리 없이 바뀌지 않는다. 비용은 문자열 필드보다 타입이 하나 더 필요하다는 +것이다. diff --git a/docs/notification/adr/NOTIF-ADR-005-canonical-namespace.md b/docs/adr/NOTIF-ADR-005-canonical-namespace.md similarity index 94% rename from docs/notification/adr/NOTIF-ADR-005-canonical-namespace.md rename to docs/adr/NOTIF-ADR-005-canonical-namespace.md index 299363ac..a6b6e491 100644 --- a/docs/notification/adr/NOTIF-ADR-005-canonical-namespace.md +++ b/docs/adr/NOTIF-ADR-005-canonical-namespace.md @@ -11,7 +11,7 @@ ## 상태 -Accepted (2026-08-15). NTF-018 대응. +채택(2026-08-15). NTF-018 대응. **갱신 (2026-09-25):** R1 type은 삭제됐다. production consumer가 끝까지 0건이었고 fake로만 증명된 계약이라, 새 consumer를 막는 ArchUnit 규칙을 유지할 이유가 없어졌다. 남은 것은 adapter core의 @@ -47,9 +47,10 @@ bridge도 import도 없다. reconciliation을 실제 PostgreSQL 레인으로 증명한다(NOTIF-ADR-001~003). R1은 fake로 증명된 R1 계약이며 스스로 그렇게 선언한다 — `application-core/CLAUDE.md`가 "R1 application contract proven with fakes. It does not claim PostgreSQL schema/locking, provider protocol, cryptographic verifier, or runtime -wiring qualification"이라고 적어 둔 그대로다. +wiring qualification"(fake로 증명한 R1 애플리케이션 계약이다. PostgreSQL schema·locking, provider 프로토콜, 암호 +검증기, 런타임 배선 검증은 주장하지 않는다)이라고 적어 둔 그대로다. -## Disposition +## 처분 R1 public type 100개의 처분은 네 가지 중 하나다. diff --git a/docs/compatibility/grpc-advanced-support-matrix.md b/docs/compatibility/grpc-advanced-support-matrix.md index 9df35cbf..bb29f12c 100644 --- a/docs/compatibility/grpc-advanced-support-matrix.md +++ b/docs/compatibility/grpc-advanced-support-matrix.md @@ -1,60 +1,55 @@ -# gRPC advanced capability support matrix +# gRPC advanced capability 지원 매트릭스 -Every capability in `:grpc-advanced:*`, its grade, and what it would take to raise it. -`GrpcAdvancedSupportMatrix` is the machine-readable form; `GrpcAdvancedCapability.defaultGrade` -carries the same values. +`:grpc-advanced:*`의 모든 capability, 그 등급, 그리고 등급을 올리는 데 필요한 것이다. 기본 등급의 정본은 +`GrpcAdvancedCapability.defaultGrade`다. 근거가 있는 배포는 `GrpcAdvancedFeatureFlags.withGrade`로 바꾼다. -All capabilities are off by default. Flags are `app.grpc.advanced..enabled`. +capability는 모두 기본으로 꺼져 있다. 스위치는 `app.grpc.advanced..enabled`다. -## Grades +## 등급 -| Grade | May start | Production needs a separate approval | +| 등급 | 뜰 수 있나 | 운영에 별도 승인이 필요한가 | | --- | --- | --- | -| `ADVANCED_STABLE` | Yes | No | -| `EXPERIMENTAL` | Yes | Yes | -| `WATCH` | No | — | -| `DISABLED` | No | — | +| `ADVANCED_STABLE` | 예 | 아니요 | +| `EXPERIMENTAL` | 예 | 예 | +| `WATCH` | 아니요 | — | +| `DISABLED` | 아니요 | — | -## Capabilities +## capability -| Capability | Flag | Grade | Real infrastructure its evidence needs | +| capability | 스위치 | 등급 | 증거에 필요한 실제 인프라 | | --- | --- | --- | --- | | Protobuf Edition 2024 | `edition-2024` | `ADVANCED_STABLE` | — | | Protobuf Edition 2026 | `edition-2026` | `WATCH` | — | -| Client streaming | `client-streaming` | `ADVANCED_STABLE` | — | -| Bidirectional streaming | `bidi-streaming` | `ADVANCED_STABLE` | — | -| Manual flow control | `manual-flow-control` | `ADVANCED_STABLE` | — | -| Read-only unary hedging | `hedging` | `EXPERIMENTAL` | — | -| Custom name resolver | `custom-resolver` | `ADVANCED_STABLE` | — | -| Custom load balancer | `custom-load-balancer` | `EXPERIMENTAL` | — | -| Proxyless xDS | `xds` | `EXPERIMENTAL` | xDS control plane | +| client streaming | `client-streaming` | `ADVANCED_STABLE` | — | +| bidirectional streaming | `bidi-streaming` | `ADVANCED_STABLE` | — | +| 수동 flow control | `manual-flow-control` | `ADVANCED_STABLE` | — | +| 읽기 전용 unary hedging | `hedging` | `EXPERIMENTAL` | — | +| 사용자 정의 name resolver | `custom-resolver` | `ADVANCED_STABLE` | — | +| 사용자 정의 load balancer | `custom-load-balancer` | `EXPERIMENTAL` | — | +| proxyless xDS | `xds` | `EXPERIMENTAL` | xDS control plane | | gRPC-Web | `grpc-web` | `ADVANCED_STABLE` | gRPC-Web proxy | -| Servlet HTTP/2 | `servlet-compat` | `ADVANCED_STABLE` (flag only; no Servlet transport code since 2026-09-25) | Servlet container | +| Servlet HTTP/2 | `servlet-compat` | `ADVANCED_STABLE`(스위치만 있다. 2026-09-25부터 Servlet 전송 코드가 없다) | Servlet 컨테이너 | | Spring Integration bridge | `integration-bridge` | `ADVANCED_STABLE` | — | -| Reactor adapter | `reactor` | `ADVANCED_STABLE` | — | +| Reactor 어댑터 | `reactor` | `ADVANCED_STABLE` | — | | Kotlin coroutine / Flow | `kotlin` | `ADVANCED_STABLE` | Kotlin toolchain | -| Channelz / CSDS diagnostics | `channel-diagnostics` | `ADVANCED_STABLE` | — | +| Channelz / CSDS 진단 | `channel-diagnostics` | `ADVANCED_STABLE` | — | -## What the grades mean here, concretely +## 여기서 등급이 구체적으로 뜻하는 것 -**Grade is a statement about the contract, not about a deployment.** Every capability's contract is -implemented and tested in this repository. What no capability has is evidence from a real deployment: -`GrpcAdvancedPromotionEvidence` for each one is empty, and no promotion has been granted. +**등급은 배포가 아니라 계약에 대한 말이다.** 모든 capability의 계약은 이 저장소에서 구현되고 시험됐다. 실제 배포에서 나온 +증거는 어느 capability에도 없고, 승격된 것도 없다. -**Four capabilities cannot produce meaningful evidence here at all**, because the infrastructure they -need is absent (gRPC-Web proxy, Servlet container, xDS control plane, Kotlin toolchain), and a suite -that runs without its infrastructure passes and establishes nothing. +**capability 넷은 여기서 의미 있는 증거를 아예 낼 수 없다.** 필요한 인프라(gRPC-Web proxy, Servlet 컨테이너, xDS control +plane, Kotlin toolchain)가 없고, 인프라 없이 돈 suite는 통과해도 아무것도 세우지 않기 때문이다. -**Kotlin is the sharpest case.** This repository has no Kotlin toolchain, so Kotlin is not -supportable here until one exists. Only the Java-side coroutine cancellation bridge -(`GrpcCoroutineContextBridge`) is implemented and tested; there is no compile lane. +**Kotlin이 가장 날카로운 경우다.** 이 저장소에는 Kotlin toolchain이 없으므로 그것이 생기기 전까지 Kotlin은 여기서 지원할 수 +없다. Java 쪽 coroutine 취소 bridge(`GrpcCoroutineContextBridge`)만 구현되고 시험됐다. 컴파일 lane은 없다. -## Promotion thresholds +## 승격 기준 -| To | Soak | Also required | +| 목표 | soak | 그 밖에 필요한 것 | | --- | --- | --- | -| `ADVANCED_STABLE` | 7 days | compatibility evidence, security review, fault evidence, performance evidence, ADR, runbook, real-environment test | -| Stable default | 30 days | all of the above, plus a dependency, security and operational-cost review | +| `ADVANCED_STABLE` | 7일 | 호환성 증거, 보안 리뷰, 장애 증거, 성능 증거, ADR, runbook, 실제 환경 시험 | +| Stable 기본값 | 30일 | 위의 모두와 의존성·보안·운영 비용 리뷰 | -`WATCH` becomes `EXPERIMENTAL` before anything else. Promotions are independent: promoting one -capability changes no other's grade. +`WATCH`는 무엇보다 먼저 `EXPERIMENTAL`이 된다. 승격은 서로 독립이다. 한 capability를 올려도 다른 것의 등급은 바뀌지 않는다. diff --git a/docs/compatibility/grpc-support-matrix.md b/docs/compatibility/grpc-support-matrix.md index 525f33f7..67e9f739 100644 --- a/docs/compatibility/grpc-support-matrix.md +++ b/docs/compatibility/grpc-support-matrix.md @@ -1,77 +1,74 @@ -# gRPC platform support matrix +# gRPC 플랫폼 지원 매트릭스 -What the Stable gRPC platform (`:grpc:*`) is certified against, what it is only checked against, and -what is merely watched. The distinction is the point: "works with Spring Boot" is not a statement -anyone can act on. +Stable gRPC 플랫폼(`:grpc:*`)이 무엇에 대해 인증됐고, 무엇에 대해서는 확인만 하고, 무엇은 지켜보기만 하는지다. 그 구별이 +요점이다. 「Spring Boot와 동작한다」는 누구도 행동에 옮길 수 없는 말이다. -The release gate is the `grpc-stable-release-gate` job in `.github/workflows/release.yml`: each -certified lane is a strict test lane that fails when it runs nothing. The in-code -`GrpcCompatibilityMatrix`/`GrpcStableReleaseGate` pair was removed (review 2026-09-24 S5-lead-4): -no production or build code called it, so it gated nothing. +릴리스 gate는 `.github/workflows/release.yml`의 `grpc-stable-release-gate` job이다. 인증된 lane마다 아무것도 돌리지 않으면 +실패하는 strict test lane이다. -## Lanes +> 이력: 코드 안의 `GrpcCompatibilityMatrix`/`GrpcStableReleaseGate` 짝은 지웠다(리뷰 2026-09-24 S5-lead-4). 운영 코드도 빌드 +> 코드도 그것을 부르지 않아서 아무것도 막지 않았다. -| Lane | Grade | Failure blocks a release | +## lane + +| lane | 등급 | 실패하면 릴리스를 막나 | | --- | --- | --- | -| Boot-managed platform (Spring Boot 4.0.8 BOM) | Certified | Yes | -| proto3 with explicit `optional` | Certified | Yes | -| `grpc-netty-shaded` | Certified | Yes | -| `grpc-netty` (unshaded) | Compatibility | No | -| Upstream gRPC Java version override | Compatibility | No | -| Protobuf Edition 2024 | Watch | No | -| Protobuf Edition 2026 | Watch | No | +| Boot가 관리하는 플랫폼(저장소의 Spring Boot BOM) | Certified | 예 | +| 명시적 `optional`을 쓰는 proto3 | Certified | 예 | +| `grpc-netty-shaded` | Certified | 예 | +| `grpc-netty`(shade하지 않음) | Compatibility | 아니요 | +| upstream gRPC Java 버전 override | Compatibility | 아니요 | +| Protobuf Edition 2024 | Watch | 아니요 | +| Protobuf Edition 2026 | Watch | 아니요 | -## Runtime baseline +## 런타임 기준선 | | | | --- | --- | | Java | 21 | -| Spring Boot | 4.0.8 (the repository baseline; the plans assume 4.1) | -| io.grpc | `ext.grpcVersion` in `src/build.gradle` | -| Protobuf | `ext.protobufVersion` in `src/build.gradle` | -| Stable transport | Netty (shaded) | -| Stable RPC shapes | Unary, Server Streaming | -| Stable resolvers | Static, DNS, Unix domain socket | +| Spring Boot | 저장소 기준선, `src/gradle/libs.versions.toml`(계획은 4.1을 가정한다) | +| io.grpc | `src/gradle/libs.versions.toml`의 `grpc`. `GrpcPlatformModuleConventionPlugin`이 그 BOM을 모듈 범위로 import한다 | +| Protobuf | `src/gradle/libs.versions.toml`의 protobuf 항목(어느 leaf가 어느 것을 쓰는지는 그 파일의 주석이 적는다) | +| Stable 전송 | Netty(shaded) | +| Stable RPC 모양 | Unary, Server Streaming | +| Stable resolver | Static, DNS, Unix domain socket | | Stable load balancing | `pick_first`, `round_robin` | -## Evidence grades +## 증거 등급 -A capability may only be advertised on evidence of a grade that can establish it. -`GrpcEvidenceGrade.requireCertifies` enforces this, and `GrpcReleaseEvidence.supports` refuses a -claim backed by the wrong lane. +capability는 그것을 세울 수 있는 등급의 증거로만 광고한다. `GrpcEvidenceGrade.requireCertifies`가 이것을 강제하고, +`GrpcReleaseEvidence.supports`가 맞지 않는 lane이 뒷받침하는 주장을 거부한다. -| Grade | Lane | Establishes | +| 등급 | lane | 세우는 것 | | --- | --- | --- | -| `CONTRACT` | `grpcInProcessContractTest` | adapter, interceptor order, status mapping, validation, idempotency replay, context propagation | -| `TRANSPORT` | `grpcNettyContractTest` | HTTP/2, TLS, mTLS, metadata limit, message limit, GOAWAY, keepalive, graceful shutdown | -| `FAULT` | `grpcFaultTest` | connection loss, completion unknown, partial stream, evidence classifier | -| `PERFORMANCE` | `grpcPerformanceTest` | latency, stream saturation, executor saturation, drain budget | +| `CONTRACT` | `grpcInProcessContractTest` | 어댑터, interceptor 순서, 상태 매핑, 검증, 멱등 replay, context 전파 | +| `TRANSPORT` | `grpcNettyContractTest` | HTTP/2, TLS, mTLS, metadata 한도, 메시지 한도, GOAWAY, keepalive, graceful shutdown | +| `FAULT` | `grpcFaultTest` | 연결 끊김, 완료 모름, 부분 stream, 증거 분류기 | +| `PERFORMANCE` | `grpcPerformanceTest` | 지연, stream 포화, executor 포화, drain 예산 | -In-process results are never transport evidence. The in-process transport does not negotiate TLS, -does not frame HTTP/2 and does not enforce transport-level limits, so a suite that passes there has -tested the adapter and not the transport. +in-process 결과는 절대 전송 증거가 아니다. in-process 전송은 TLS를 협상하지 않고, HTTP/2 frame을 만들지 않고, 전송 수준 한도를 +강제하지 않는다. 그래서 거기서 통과한 suite는 전송이 아니라 어댑터를 시험한 것이다. -## What is not supported +## 지원하지 않는 것 -| | Where it lives | +| | 있는 곳 | | --- | --- | -| Client streaming, bidirectional streaming | `grpc-advanced` (`streaming`) | -| Manual flow control | `grpc-advanced` (`streaming`) | +| client streaming, bidirectional streaming | `grpc-advanced` (`streaming`) | +| 수동 flow control | `grpc-advanced` (`streaming`) | | Hedging | `grpc-advanced` (`resilience`) | -| Custom name resolver, custom load balancer | `grpc-advanced` (`resilience`) | +| 사용자 정의 name resolver, 사용자 정의 load balancer | `grpc-advanced` (`resilience`) | | xDS | `grpc-advanced` (`resilience`) | | gRPC-Web, Servlet HTTP/2, Spring Integration, Reactor, Kotlin | `grpc-advanced-compat` | -| Channelz / CSDS diagnostics | `grpc-advanced` (`diagnostics`) | +| Channelz / CSDS 진단 | `grpc-advanced` (`diagnostics`) | -## Current release status +## 지금 릴리스 상태 -Not released. Every `:grpc:*` leaf is `runtime_memberships: []` in the module registry, so the -platform is build-only: it compiles, its lanes run, and no deployed artifact carries it. +릴리스하지 않았다. registry에서 모든 `:grpc:*` leaf는 `"build": "optional-grpc"`라 주 빌드 밖에 있고 어느 조립에도 들어가지 +않는다. 플랫폼은 빌드만 된다. 컴파일되고 lane이 돌지만, 배포되는 산출물 어디에도 실리지 않는다. -Two release gate inputs are outstanding and are the work between here and a release: +릴리스 gate 입력 둘이 남아 있고, 그것이 지금부터 릴리스까지의 일이다. -- **Performance baseline.** The performance lane runs and asserts shape — ordered percentiles, a gate - that reads them — rather than absolute numbers. A recorded baseline on a known runner is what turns - it into a regression gate. -- **Schema codegen.** No `protoc` runs in this build (ADR-GRPC-002), so the descriptor artifact and - the consumer-compile fixture are governed as policy rather than produced from a compiled schema. +- **성능 기준선.** 성능 lane은 돌고, 절대 수치가 아니라 모양을 단언한다. 순서 있는 백분위수와 그것을 읽는 gate다. 알려진 + runner에서 기록한 기준선이 생겨야 회귀 gate가 된다. +- **schema codegen.** 이 빌드에서는 `protoc`가 돌지 않는다(ADR-GRPC-002). 그래서 descriptor 산출물과 consumer-compile fixture는 + 컴파일한 schema에서 만들어지지 않고 정책으로 다스린다. diff --git a/docs/fileserver/configuration.md b/docs/fileserver/configuration.md index 60af6511..70b14b68 100644 --- a/docs/fileserver/configuration.md +++ b/docs/fileserver/configuration.md @@ -1,209 +1,202 @@ -# Fileserver configuration +# Fileserver 설정 -Every key below lives under `app.fileserver-platform` (environment form -`APP_FILESERVER_PLATFORM_*`). +아래 key는 모두 `app.fileserver-platform` 아래에 있다(환경 변수 형태는 `APP_FILESERVER_PLATFORM_*`). -While `app.fileserver-platform.enabled` is false none of these keys is bound at all — the -auto-configuration that binds them is not processed — so a malformed value in a block nobody -enabled cannot fail a startup. Once enabled, binding is strict: an unknown key under the prefix is -refused rather than ignored. The defaults are the conservative ones: the -admin plane is off, background reclamation is on (leaving it off is what fills the volume), copies -and moves may only target the default namespace, and there is no permissive authorization fallback. Turning the capability on is a deliberate act, and so is every surface it -exposes. +`app.fileserver-platform.enabled`가 false인 동안에는 이 key들을 아예 바인딩하지 않는다. 바인딩하는 +auto-configuration이 처리되지 않기 때문이다. 그래서 아무도 켜지 않은 블록의 잘못된 값이 시작을 실패시키지 +않는다. 켜면 바인딩은 엄격하다. 접두사 아래의 모르는 key는 무시하지 않고 거부한다. 기본값은 보수적인 쪽이다. -## Minimum to start +- admin plane은 꺼져 있다. +- 백그라운드 회수는 켜져 있다(꺼 두면 volume이 찬다). +- copy와 move는 기본 namespace로만 쓸 수 있다. +- 권한을 느슨하게 풀어 주는 대체 경로는 없다. + +capability를 켜는 것은 의도한 행동이고, 그것이 여는 면 하나하나도 그렇다. + +## 시작에 필요한 최소 설정 ```yaml app: fileserver-platform: enabled: true - instance-id: ${HOSTNAME} # writer-lease owner; must be unique per node + instance-id: ${HOSTNAME} # writer lease 소유자. 노드마다 달라야 한다 storage: - root: /var/lib/backend/files # absolute, outside any webroot or config dir + root: /var/lib/backend/files # 절대 경로. webroot·설정 폴더 밖 security: - access-policy: role-based # or supply your own FileAccessPolicyPort bean + access-policy: role-based # 또는 직접 만든 FileAccessPolicyPort bean observability: fingerprint-key: ${FILESERVER_FINGERPRINT_KEY} ``` -Startup fails, rather than degrading, when any of these is missing or unsafe: +아래 중 하나라도 빠지거나 안전하지 않으면 기능을 줄여 돌지 않고 시작이 실패한다. -| Condition | Why it is fatal | +| 조건 | 왜 치명적인가 | | --- | --- | -| `security.access-policy` left at `required` with no `FileAccessPolicyPort` bean | a file capability that authorizes by default is worse than one that refuses to start | -| `observability.fingerprint-key` unset while metrics are on | an unkeyed digest of an enumerable identifier is reversible | -| the storage root fails a mandatory capability probe | a volume that cannot create atomically, keep staging and content on one FileStore, or refuse symlinks is unsafe, not degraded | -| `storage.publish-mode: atomic-move-required` on a volume where the probe could not prove an atomic move | the configured guarantee cannot be delivered | -| `security.access-policy: unenforced` under a `prod` profile | a value that was convenient in development must not survive promotion | +| `security.access-policy`가 `required`로 남았는데 `FileAccessPolicyPort` bean이 없다 | 기본으로 허락하는 파일 capability는 시작을 거부하는 것보다 나쁘다 | +| metric이 켜졌는데 `observability.fingerprint-key`가 없다 | 셀 수 있는 식별자를 key 없이 digest하면 되돌릴 수 있다 | +| 저장 루트가 필수 capability probe를 통과하지 못한다 | 원자적으로 만들지 못하거나, staging과 content를 한 FileStore에 두지 못하거나, symlink를 거부하지 못하는 volume은 기능이 줄어든 것이 아니라 안전하지 않은 것이다 | +| probe가 원자적 move를 증명하지 못한 volume에 `storage.publish-mode: atomic-move-required` | 설정한 보장을 지킬 수 없다 | +| `prod` profile에서 `security.access-policy: unenforced` | 개발 때 편했던 값이 승격까지 살아남으면 안 된다 | -## Authorization — `security` +## 권한 — `security` -| Key | Default | Meaning | +| Key | 기본값 | 뜻 | | --- | --- | --- | -| `access-policy` | `required` | `required` (supply your own bean), `role-based`, or `unenforced` | -| `read-roles` | `ROLE_FILE_READ` | grants metadata read and download | -| `write-roles` | `ROLE_FILE_WRITE` | grants create, append, finalize, delete, copy, move | -| `admin-roles` | `ROLE_FILE_ADMIN` | grants reverify and force-delete, and gates `/internal/fileserver/**` at the servlet chain | +| `access-policy` | `required` | `required`(bean을 직접 준다), `role-based`, `unenforced` | +| `read-roles` | `ROLE_FILE_READ` | metadata 읽기와 다운로드를 허락한다 | +| `write-roles` | `ROLE_FILE_WRITE` | create, append, finalize, delete, copy, move를 허락한다 | +| `admin-roles` | `ROLE_FILE_ADMIN` | reverify와 force-delete를 허락하고, servlet chain에서 `/internal/fileserver/**`를 막는다 | -These roles decide the tier inside each operation. In front of it, every operation's use case -carries a `file:*` permission that the web adapter's method security checks against -`app.authz.role-permissions`; `security.yml` grants `file:read` to `ROLE_FILE_READ`, -`file:upload`, `file:delete`, `file:copy` and `file:move` to `ROLE_FILE_WRITE`, and `file:admin` to -`ROLE_FILE_ADMIN`. Renaming a tier role here means mapping the new name there as well, or the -caller is refused before the tier is consulted (`docs/fileserver/design-deviations.md` §5). +이 role들은 각 연산 안에서 등급(tier)을 정한다. 그 앞에서는 연산마다 use case가 `file:*` 권한을 가지고, +web 어댑터의 method security가 그 권한을 `app.authz.role-permissions`와 대조한다. `security.yml`은 +`file:read`를 `ROLE_FILE_READ`에, `file:upload`·`file:delete`·`file:copy`·`file:move`를 `ROLE_FILE_WRITE`에, +`file:admin`을 `ROLE_FILE_ADMIN`에 준다. 여기서 등급 role의 이름을 바꾸면 거기서도 새 이름을 대응시켜야 +한다. 아니면 등급을 보기도 전에 호출자가 거부된다(`docs/fileserver/design-deviations.md` §5). -There is no anonymous-read switch. Every Fileserver route is authenticated by the servlet chain -before any application policy is consulted, so such a setting could only ever have described a -permission the transport had already refused — a configuration that reads as if it grants access -and does not. +익명 읽기 스위치는 없다. 모든 Fileserver 경로는 애플리케이션 정책을 보기 전에 servlet chain이 인증한다. +그래서 그런 설정은 transport가 이미 거부한 권한을 설명할 수밖에 없다. 접근을 허락하는 것처럼 읽히지만 +허락하지 않는 설정이 된다. -The three tiers do not inherit. An admin role cannot delete through the data plane, and a write role -cannot reach the management plane — a role model where "can delete" implied "can force-delete" would -make the audited plane reachable through the unaudited one. +세 등급은 서로 물려받지 않는다. admin role은 data plane으로 삭제할 수 없고, write role은 management plane에 +닿을 수 없다. 「삭제할 수 있으면 강제 삭제도 할 수 있다」는 role 모델이면 감사하지 않는 plane을 거쳐 감사하는 +plane에 닿게 된다. -`unenforced` authorizes everything and exists so a developer can exercise upload and download before -deciding on a role model. It is refused under a production profile. +`unenforced`는 모든 것을 허락한다. 개발자가 role 모델을 정하기 전에 업로드와 다운로드를 시험해 보라고 있는 +값이다. 운영 profile에서는 거부한다. -## Storage — `storage` +## 저장소 — `storage` -| Key | Default | Meaning | +| Key | 기본값 | 뜻 | | --- | --- | --- | -| `root` | `/var/lib/backend/files` | absolute path; the only place a path exists | +| `root` | `/var/lib/backend/files` | 절대 경로. 경로가 존재하는 유일한 곳 | | `publish-mode` | `atomic-move-preferred` | `atomic-move-required`, `atomic-move-preferred`, `metadata-pointer` | -| `buffer-size` | `128KB` | bounds every transfer allocation; memory never scales with file size | -| `forbidden-root-ancestors` | `/app,/etc,/usr/share/nginx/html` | roots the storage root must not live under (webroot, config dirs) | +| `buffer-size` | `128KB` | 모든 전송 할당의 상한. 메모리는 파일 크기에 따라 늘지 않는다 | +| `forbidden-root-ancestors` | `/app,/etc,/usr/share/nginx/html` | 저장 루트가 그 아래 있으면 안 되는 root(webroot, 설정 폴더) | -`root` must be absolute. A relative root resolves against the process working directory, which is -one path in a container and another in a test, so it is refused at binding time. +`root`는 절대 경로여야 한다. 상대 경로는 프로세스 작업 폴더를 기준으로 풀리고, 그 폴더는 container와 +테스트에서 다르다. 그래서 바인딩할 때 거부한다. -Three former keys are gone, pinned as constants instead: staging and content share one FileStore, -symbolic links are never followed, and the object and its directory are synced before READY. Each -is an invariant the atomic publish and the namespace boundary are built on — a deployment that -could switch one off would be running a different capability under the same name and the same -tests. +예전 key 셋은 없어지고 상수로 고정됐다: staging과 content는 FileStore 하나를 같이 쓴다, symbolic link는 +절대 따라가지 않는다, 객체와 그 폴더는 READY 전에 sync한다. 셋 다 원자적 게시와 namespace 경계가 기대는 +불변식이다. 그중 하나를 끌 수 있는 배포는 같은 이름과 같은 테스트로 다른 capability를 돌리는 셈이다. -The storage provider has no selector either. There is exactly one implementation, and a `type` key -with one legal value is a promise of pluggability that nothing keeps. +저장소 provider를 고르는 key도 없다. 구현이 정확히 하나이고, 허용 값이 하나뿐인 `type` key는 아무도 +지키지 않는 교체 가능성의 약속이다. -## Upload, download, transfer +## 업로드, 다운로드, 전송 -| Key | Default | Meaning | +| Key | 기본값 | 뜻 | | --- | --- | --- | -| `upload.max-file-size` | `100MB` | hard ceiling; also drives `spring.servlet.multipart.max-file-size` | -| `upload.max-request-size` | `110MB` | request envelope; must be at least `max-file-size` | -| `upload.initial-reservation` | `8MB` | quota reserved when the length is unknown | -| `upload.ttl` | `1h` | how long a resumable upload stays claimable | -| `upload.reservation-ttl` | `24h` | how long an unsettled quota reservation survives | -| `upload.lease-duration` | `30s` | writer lease; renewed at one third of this | -| `upload.max-parts` | `16` | multipart part ceiling | -| `upload.require-content-length` | `false` | refuse chunked raw uploads | -| `download.cache-control` | `private, no-store` | emitted on every content response | -| `download.inline-allowed` | `false` | scriptable content is always an attachment regardless | -| `download.max-ranges` | `1` | multi-range responses are opt-in | -| `download.max-range-bytes` | `100MB` | total bytes one ranged response may cover | -| `download.zero-copy-enabled` | `true` | hand large plaintext responses to the kernel | -| `download.zero-copy-minimum-bytes` | `16MB` | below this the syscall setup costs more than it saves | -| `transfer.core-size` / `max-size` / `queue-capacity` | `8` / `32` / `64` | blocking transfer pool bounds | -| `transfer.await-seconds` | `300` | how long a transfer may occupy a pool thread | +| `upload.max-file-size` | `100MB` | 넘을 수 없는 상한. `spring.servlet.multipart.max-file-size`도 이 값으로 정한다 | +| `upload.max-request-size` | `110MB` | 요청 전체 크기. `max-file-size` 이상이어야 한다 | +| `upload.initial-reservation` | `8MB` | 길이를 모를 때 예약하는 할당량 | +| `upload.ttl` | `1h` | 이어 올리기 업로드를 다시 잡을 수 있는 기간 | +| `upload.reservation-ttl` | `24h` | 정산하지 않은 할당량 예약이 남는 기간 | +| `upload.lease-duration` | `30s` | writer lease. 이 값의 1/3마다 갱신한다 | +| `upload.max-parts` | `16` | multipart part 개수 상한 | +| `upload.require-content-length` | `false` | chunked raw 업로드를 거부한다 | +| `download.cache-control` | `private, no-store` | 모든 content 응답에 붙인다 | +| `download.inline-allowed` | `false` | 스크립트가 될 수 있는 content는 이 값과 상관없이 늘 첨부 파일이다 | +| `download.max-ranges` | `1` | 여러 범위 응답은 켜야 생긴다 | +| `download.max-range-bytes` | `100MB` | 범위 응답 하나가 덮을 수 있는 총 바이트 | +| `download.zero-copy-enabled` | `true` | 큰 평문 응답을 kernel에 넘긴다 | +| `download.zero-copy-minimum-bytes` | `16MB` | 이보다 작으면 syscall 준비 비용이 아끼는 것보다 크다 | +| `transfer.core-size` / `max-size` / `queue-capacity` | `8` / `32` / `64` | blocking 전송 pool의 상한 | +| `transfer.await-seconds` | `300` | 전송 하나가 pool 스레드를 잡을 수 있는 시간 | -Zero copy changes no header and no status. When storage declines it — an unreadable region, an -unsupported backend — the response is streamed instead and is byte-identical. +zero copy는 헤더도 상태 코드도 바꾸지 않는다. 저장소가 거절하면(읽을 수 없는 영역, 지원하지 않는 backend) +응답을 스트리밍으로 보내고, 바이트는 똑같다. -## Verification — `verification` +## 검증 — `verification` -| Key | Default | Meaning | +| Key | 기본값 | 뜻 | | --- | --- | --- | -| `timeout` | `5s` | per-verifier ceiling | -| `require-media-type-verdict` | `false` | refuse a file whose type could not be determined | -| `inline-safe-profile` | `false` | accept scriptable content instead of quarantining it | +| `timeout` | `5s` | 검증기 하나의 상한 | +| `require-media-type-verdict` | `false` | 형식을 정하지 못한 파일을 거부한다 | +| `inline-safe-profile` | `false` | 스크립트가 될 수 있는 content를 격리하지 않고 받는다 | -Set `inline-safe-profile: true` only when downloads are never served inline from a trusted origin. +`inline-safe-profile: true`는 다운로드를 믿을 수 있는 origin에서 inline으로 절대 내보내지 않을 때만 쓴다. -## Quota and admission — `quota` +## 할당량과 허가 — `quota` -| Key | Default | Meaning | +| Key | 기본값 | 뜻 | | --- | --- | --- | -| `instance-upload-permits` | `16` | concurrent uploads this node admits | -| `scope-upload-permits` | `4` | concurrent uploads one caller (principal) admits; over it is a retryable `429` | -| `direct-download-permits` | `64` | concurrent non-delegated downloads | -| `soft-high-water` | `0.70` | storage fraction at which pressure is reported | -| `hard-high-water` | `0.85` | storage fraction at which uploads and copies are refused | -| `namespace-limit` | unset (unlimited) | most bytes one namespace may hold, live reservations plus committed usage; a create, copy or move that would pass it is refused with `QUOTA_EXCEEDED` (413) before any record, byte or namespace changes | +| `instance-upload-permits` | `16` | 이 노드가 받는 동시 업로드 수 | +| `scope-upload-permits` | `4` | 호출자(principal) 하나가 받는 동시 업로드 수. 넘으면 재시도할 수 있는 `429` | +| `direct-download-permits` | `64` | 위임하지 않은 동시 다운로드 수 | +| `soft-high-water` | `0.70` | 압박을 보고하기 시작하는 저장소 사용 비율 | +| `hard-high-water` | `0.85` | 업로드와 copy를 거부하는 저장소 사용 비율 | +| `namespace-limit` | 없음(제한 없음) | namespace 하나가 가질 수 있는 최대 바이트. 살아 있는 예약과 확정 사용량의 합이다. 이를 넘길 create, copy, move는 기록·바이트·namespace가 바뀌기 전에 `QUOTA_EXCEEDED`(413)로 거부한다 | -`namespace-limit` is checked against the usage the quota ledger reports and then reserved, in one -transaction but without a per-namespace lock: reservations admitted at the same moment can overshoot -the limit by at most their own size, and the next one is refused. A service that needs an exact cap -adds that lock in its persistence adapter. +`namespace-limit`은 할당량 ledger가 보고한 사용량과 비교한 뒤 예약한다. transaction 하나 안에서 하지만 +namespace별 lock은 없다. 그래서 같은 순간에 허가된 예약들은 자기 크기만큼까지 한도를 넘을 수 있고, 그다음 +예약은 거부된다. 정확한 상한이 필요한 서비스는 자기 persistence 어댑터에 그 lock을 더한다. -A move to another namespace carries the file's bytes in the ledger: in the transaction that relocates -the record it checks the target's limit, books the bytes as committed usage there and reclaims them -from the source. A refused move leaves the file, and both namespaces' usage, as they were. +다른 namespace로의 move는 ledger에서 파일의 바이트를 함께 옮긴다. 기록을 옮기는 transaction 안에서 대상의 +한도를 확인하고, 대상 쪽에 확정 사용량으로 올리고, 원래 쪽에서 회수한다. 거부된 move는 파일과 두 +namespace의 사용량을 그대로 둔다. -When the storage fraction cannot be read, admission treats it as unknown and does not apply the -high-water rule — a synthetic `0` would silently disable the guard, and a synthetic `1` would take -the capability down over a failed syscall. +저장소 사용 비율을 읽지 못하면 허가 단계는 그것을 모름으로 보고 high-water 규칙을 적용하지 않는다. 지어낸 +`0`은 보호 장치를 조용히 끄고, 지어낸 `1`은 syscall 하나 실패로 capability를 내린다. -## Background reclamation — `cleanup` +## 백그라운드 회수 — `cleanup` -| Key | Default | Meaning | +| Key | 기본값 | 뜻 | | --- | --- | --- | -| `enabled` | `true` | run the cleanup worker on this node; `false` logs a startup warning | -| `interval` | `60s` | fixed delay between batches, not fixed rate | -| `max-items` | `100` | items one batch may claim | -| `max-bytes` | `1GB` | bytes one batch may reclaim | -| `retry-backoff` | `5m` | how long a failed item waits before it is due again | +| `enabled` | `true` | 이 노드에서 cleanup worker를 돌린다. `false`면 시작할 때 경고를 남긴다 | +| `interval` | `60s` | batch 사이의 고정 지연. 고정 주기가 아니다 | +| `max-items` | `100` | batch 하나가 가져갈 수 있는 항목 수 | +| `max-bytes` | `1GB` | batch 하나가 회수할 수 있는 바이트 | +| `retry-backoff` | `5m` | 실패한 항목이 다시 차례가 될 때까지 기다리는 시간 | -The worker is on by default: it deletes only what the cleanup queue names, and without it cancelled -and expired staging, rejected and deleted content stay on the volume until the hard high-water mark -stops every upload. A node may turn it off — for instance when another node runs it — and startup -then logs a `WARN` naming `app.fileserver-platform.cleanup.enabled=false`. A node without it still -queues cleanup items; another node or an operator reclaims them. (A required "reason" key was -considered instead of the warning and rejected: it would be a setting whose only effect is to -silence startup, carried by every non-worker node.) An item that fails -eight times is abandoned rather than retried forever — it stays visible to an operator, parked -rather than discarded. +worker는 기본으로 켜져 있다. cleanup 큐가 이름 댄 것만 지운다. worker가 없으면 취소·만료된 staging, 거부· +삭제된 content가 hard high-water가 모든 업로드를 막을 때까지 volume에 남는다. 노드 하나가 worker를 끌 수 +있다(예: 다른 노드가 돌릴 때). 그러면 시작할 때 `app.fileserver-platform.cleanup.enabled=false`를 이름 댄 +`WARN`을 남긴다. worker가 없는 노드도 cleanup 항목을 큐에 넣는다. 다른 노드나 운영자가 회수한다. (경고 대신 +필수 「이유」 key를 두는 안도 검토했지만 버렸다. 시작 경고를 끄는 것 말고는 효과가 없는 설정을 worker 아닌 +모든 노드가 들고 다니게 된다.) 여덟 번 실패한 항목은 영원히 재시도하지 않고 내려놓는다. 버리지 않고 세워 +두므로 운영자에게는 계속 보인다. -Each pass also expires uploads whose `expiresAt` has passed (the record becomes `EXPIRED` and its -staged bytes are queued), purges orphans the admin plane retired to quarantine, and runs -reconciliation over stale `UPLOADED`/`VERIFYING`/`FAILED` records, so an ambiguous publish settles -without an operator. +매 회차는 이런 일도 한다. -## Copy and move targets +- `expiresAt`이 지난 업로드를 만료시킨다(기록은 `EXPIRED`가 되고 staging 바이트는 큐에 들어간다). +- admin plane이 격리로 내린 고아 객체를 지운다. +- 오래된 `UPLOADED`/`VERIFYING`/`FAILED` 기록에 대해 맞춰 보기를 돌린다. 그래서 결과를 모르는 게시가 운영자 + 없이 정리된다. -`app.fileserver-platform.target-namespaces` (`APP_FILESERVER_PLATFORM_TARGET_NAMESPACES`, a comma -list, empty by default) names the namespaces copy and move may write into besides -`default-namespace`, which is always allowed. The target namespace of a copy or a move comes from the request body, and a namespace is also the -quota grouping. Any other target is refused with `ACCESS_DENIED` before a byte moves or a -reservation is taken. +## Copy와 move 대상 + +`app.fileserver-platform.target-namespaces`(`APP_FILESERVER_PLATFORM_TARGET_NAMESPACES`, 쉼표 목록, 기본은 +비어 있음)는 늘 허용되는 `default-namespace` 말고 copy와 move가 쓸 수 있는 namespace를 적는다. copy나 move의 +대상 namespace는 요청 본문에서 오고, namespace는 할당량을 묶는 단위이기도 하다. 그 밖의 대상은 바이트가 +움직이거나 예약을 잡기 전에 `ACCESS_DENIED`로 거부한다. ## Management plane — `admin` -| Key | Default | Meaning | +| Key | 기본값 | 뜻 | | --- | --- | --- | -| `enabled` | `false` | expose `/internal/fileserver/**` | -| `orphan-minimum-age` | `1h` | how long an unreferenced object must exist before a scan may name it | +| `enabled` | `false` | `/internal/fileserver/**`를 연다 | +| `orphan-minimum-age` | `1h` | 참조 없는 객체가 scan에 이름이 오르기 전에 존재해야 하는 시간 | -Publishing content and committing its record are two steps. Anything younger than -`orphan-minimum-age` is assumed to be mid-commit rather than abandoned; shortening this makes -concurrent uploads look like orphans. +content를 게시하는 것과 그 기록을 확정하는 것은 두 단계다. `orphan-minimum-age`보다 어린 것은 버려진 것이 +아니라 확정 중인 것으로 본다. 이 값을 줄이면 동시 업로드가 고아처럼 보인다. -## Front-proxy delegation — `nginx` +## 프런트 프록시 위임 — `nginx` -| Key | Default | Meaning | +| Key | 기본값 | 뜻 | | --- | --- | --- | -| `enabled` | `false` | emit `X-Accel-Redirect` instead of a body | -| `internal-prefix` | `/__files/` | must be an `internal` location resolving to the content root | -| `object-suffix` | `.bin` | layout suffix the proxy appends | -| `minimum-size` | `16MB` | below this the application serves the transfer itself | +| `enabled` | `false` | 본문 대신 `X-Accel-Redirect`를 내보낸다 | +| `internal-prefix` | `/__files/` | content root로 풀리는 `internal` location이어야 한다 | +| `object-suffix` | `.bin` | 프록시가 붙이는 배치 접미사 | +| `minimum-size` | `16MB` | 이보다 작으면 애플리케이션이 직접 전송한다 | -Delegation is decided only after authorization and the READY gate, so an internal redirect can only -ever name content the caller was already allowed to read. +위임은 권한 확인과 READY 관문을 지난 뒤에만 정한다. 그래서 내부 redirect는 호출자가 이미 읽어도 되는 +content만 가리킬 수 있다. -## Protocols — `tus` +## 프로토콜 — `tus` -| Key | Default | Meaning | +| Key | 기본값 | 뜻 | | --- | --- | --- | -| `enabled` | `false` | expose the tus 1.0 endpoints | +| `enabled` | `false` | tus 1.0 endpoint를 연다 | -The HTTPbis resumable-upload draft-12 surface is experimental and documented in -[support-matrix.md](support-matrix.md). +HTTPbis resumable-upload draft-12 면은 실험 단계이고 [support-matrix.md](support-matrix.md)에 적었다. diff --git a/docs/fileserver/design-deviations.md b/docs/fileserver/design-deviations.md index 0273e4a9..6e9b23b9 100644 --- a/docs/fileserver/design-deviations.md +++ b/docs/fileserver/design-deviations.md @@ -1,216 +1,201 @@ -# Fileserver — deviations from the design +# Fileserver — 설계와 다른 곳 -The design specification and the implementation plan are frozen documents. Where implementation -found them under-specified or self-contradicting, the resolution is recorded here rather than by -editing the specification, and every entry names the test that pins the decision. +설계 명세와 구현 계획서는 고정된 문서다. 구현하다 보니 명세가 덜 정해졌거나 스스로 모순인 곳이 있었다. +그 해결은 명세를 고치지 않고 여기 적는다. 항목마다 그 결정을 고정하는 테스트를 적는다. -## Resolved inconsistencies in the state machine and contracts +## 상태 기계와 계약에서 해결한 모순 -### 1. `CREATED → FAILED` has no edge in the transition table +### 1. 전이 표에 `CREATED → FAILED` edge가 없다 -A create that fails after the record exists must end in `FAILED`, but the table has no direct edge. -The record therefore walks `CREATED → UPLOADING → FAILED`, which is also the honest reading: the -upload had been admitted before it failed. +기록이 생긴 뒤 실패한 create는 `FAILED`로 끝나야 하는데, 표에 바로 가는 edge가 없다. 그래서 기록은 +`CREATED → UPLOADING → FAILED`로 간다. 이것이 정직한 읽기이기도 하다. 업로드는 실패하기 전에 이미 허가됐다. -Pinned by `ResumableUploadUseCasesTest` (application-fileserver). +고정하는 테스트: `ResumableUploadUseCasesTest`(application-fileserver). -### 2. `ContentKey`'s alphabet admits a leading separator +### 2. `ContentKey`의 글자 집합이 맨 앞 구분자를 허락한다 -The design's key pattern `[a-z0-9/_-]{16,200}` matches `/etc/passwd/...`. Rejecting an absolute path -at the value type would change a design-fixed contract, so the stricter shape check lives in -`PhysicalPathResolver`, per §12.2 rule 1 — the only place that turns an identifier into a path. +설계의 key 패턴 `[a-z0-9/_-]{16,200}`은 `/etc/passwd/...`에 맞는다. 값 타입에서 절대 경로를 거부하면 설계가 +고정한 계약이 바뀐다. 그래서 더 엄격한 모양 검사는 §12.2 규칙 1에 따라 `PhysicalPathResolver`에 둔다. +식별자를 경로로 바꾸는 유일한 곳이다. -Pinned by `PhysicalPathResolverTest`. +고정하는 테스트: `PhysicalPathResolverTest`. -### 3. `VERIFYING → DELETING` has no edge +### 3. `VERIFYING → DELETING` edge가 없다 -Deleting a file that is mid-verification has no legal transition. The lifecycle service refuses it -with `409 FILE_NOT_READY` rather than inventing an edge, which matches the allowed-state list the -JPA `markDeleting` statement already enforced. +검증 중인 파일을 지우는 합법적 전이가 없다. lifecycle 서비스는 edge를 지어내지 않고 `409 FILE_NOT_READY`로 +거부한다. JPA `markDeleting` 문이 이미 강제하던 허용 상태 목록과 같다. -Pinned by `FileLifecycleUseCasesTest`. +고정하는 테스트: `FileLifecycleUseCasesTest`. -### 4. `If-Match` is specified as an ETag but the lifecycle was designed around the row version +### 4. `If-Match`는 ETag로 정해졌는데 lifecycle은 행 version을 기준으로 설계됐다 -The HTTP contract sends an entity tag; the metadata store guards on a numeric version. The service -takes `Optional expectedEtag` and compares against the record's strong validator, so the -precondition a client sends is the precondition that is checked. +HTTP 계약은 entity tag를 보내고, metadata 저장소는 숫자 version으로 막는다. 서비스는 +`Optional expectedEtag`를 받아 기록의 strong validator와 비교한다. 그래서 client가 보낸 선행 조건이 +곧 검사하는 선행 조건이다. -Pinned by `FileLifecycleUseCasesTest`. +고정하는 테스트: `FileLifecycleUseCasesTest`. -### 5. The filename policy left `:` intact +### 5. 파일 이름 정책이 `:`를 남겼다 -`C:\Windows\system.ini` sanitized to `C:Windowssystem.ini` — a drive-qualified name surviving into -display text and headers. `:` joined the structural strip set. +`C:\Windows\system.ini`가 `C:Windowssystem.ini`로 정리됐다. 드라이브가 붙은 이름이 표시 문자열과 헤더까지 +살아남았다. `:`를 구조 문자 제거 집합에 넣었다. -Pinned by `FileserverHardeningContractTest` and `AmbiguousFilesystemOperationDetectorTest`. +고정하는 테스트: `FileserverHardeningContractTest`, `AmbiguousFilesystemOperationDetectorTest`. -## Additions the design implies but does not specify +## 설계가 암시하지만 정하지 않은 추가 ### 6. `fs_recovery_item` -§10.2 lists five core tables and none of them can hold the recovery queue, yet §29.3 requires one: -reconciliation reports files whose bytes and metadata disagree, and holding that list in memory -would lose exactly the cases a restart interrupted. Added in -`V2__fileserver_recovery_and_staging_cleanup.sql` with one open item per file, so repeated sweeps -update a worklist rather than accumulating a log. +§10.2는 핵심 테이블 다섯을 나열하는데 그중 어느 것도 복구 큐를 담을 수 없다. 그런데 §29.3은 복구 큐를 +요구한다. 맞춰 보기는 바이트와 metadata가 어긋나는 파일을 보고하는데, 그 목록을 메모리에 두면 재시작이 끊은 +바로 그 경우를 잃는다. `V2__fileserver_recovery_and_staging_cleanup.sql`에서 더했다. 파일마다 열린 항목은 +하나다. 그래서 같은 정리를 반복해도 로그가 쌓이지 않고 작업 목록이 갱신된다. -Pinned by `PostgreSqlFileserverReclamationIntegrationTest`. +고정하는 테스트: `PostgreSqlFileserverReclamationIntegrationTest`. ### 7. `fs_cleanup_item.upload_id` -A staging object is addressed by upload, not by file. Without this column a queued staging cleanup -could name only already-published content, so a cancelled or expired upload left bytes nothing could -find. Added in the same migration, with a check constraint that an item names exactly one target. +staging 객체는 파일이 아니라 업로드로 가리킨다. 이 열이 없으면 큐에 넣은 staging 정리가 이미 게시된 +content만 가리킬 수 있어서, 취소·만료된 업로드는 아무도 찾지 못하는 바이트를 남겼다. 같은 마이그레이션에서 +더했고, 항목이 대상 정확히 하나를 가리키는지 check 제약을 둔다. -Pinned by `PostgreSqlFileserverReclamationIntegrationTest`. +고정하는 테스트: `PostgreSqlFileserverReclamationIntegrationTest`. -### 8. `ContentReferenceLedgerPort` and `StagingUploadLocatorPort` +### 8. `ContentReferenceLedgerPort`와 `StagingUploadLocatorPort` -The orphan scan must ask whether a record still claims a physical object, and reconciliation must -map a file back to the upload that last staged it. Neither question is answerable through the -design's `FileMetadataPort` or `UploadSessionPort` as written. Rather than widen those -design-fixed interfaces, both are narrow single-method ports. +고아 scan은 어떤 기록이 아직 물리 객체를 가리키는지 물어야 하고, 맞춰 보기는 파일을 마지막으로 staging한 +업로드로 되짚어야 한다. 설계에 적힌 그대로의 `FileMetadataPort`나 `UploadSessionPort`로는 어느 질문에도 +답할 수 없다. 설계가 고정한 interface를 넓히지 않고, 둘 다 메서드 하나짜리 좁은 port로 만들었다. -Pinned by `PostgreSqlFileserverReclamationIntegrationTest` and `LocalOrphanScanAdapterTest`. +고정하는 테스트: `PostgreSqlFileserverReclamationIntegrationTest`, `LocalOrphanScanTest`. -## Interpretations +## 해석 -### 9. Quota settlement is FIFO within a scope +### 9. 할당량 정산은 범위 안에서 FIFO다 -Nothing links a reservation row to the upload that took it, and the design deliberately reclaims -stragglers by TTL and the `STALE_QUOTA_RESERVATION` cleanup type rather than threading a reservation -id through the upload session. `QuotaCommitPort` therefore settles the oldest live reservation in -the file's namespace. +예약 행과 그것을 잡은 업로드를 잇는 것이 없다. 그리고 설계는 upload session에 예약 id를 끼워 넣지 않고 +TTL과 `STALE_QUOTA_RESERVATION` cleanup 유형으로 남은 것을 회수한다. 그래서 `QuotaCommitPort`는 그 파일의 +namespace에서 가장 오래된 살아 있는 예약을 정산한다. -Which row closes does not change any quota decision: enforcement sums reserved and committed bytes -per scope and never reads an individual row. Concurrent uploads of different sizes can leave the -reserved total transiently high or low, and it converges as each settles. Durable usage with no live -reservation behind it — an upload that outlived its TTL — is still recorded, because a ledger that -silently under-counts is worse than one that is briefly imprecise. +어느 행이 닫히는지는 할당량 판단을 바꾸지 않는다. 강제는 범위별로 예약·확정 바이트를 합하고 행 하나하나는 +읽지 않는다. 크기가 다른 동시 업로드는 예약 합계를 잠깐 높거나 낮게 남길 수 있고, 각각 정산되면서 맞춰진다. +뒤에 살아 있는 예약이 없는 확정 사용량(TTL보다 오래 걸린 업로드)도 기록한다. 조용히 덜 세는 ledger는 잠깐 +부정확한 ledger보다 나쁘다. -Pinned by `PostgreSqlFileserverReclamationIntegrationTest`. +고정하는 테스트: `PostgreSqlFileserverReclamationIntegrationTest`. -### 10. Zero copy is a channel transfer, not a file handoff +### 10. Zero copy는 파일 넘기기가 아니라 channel 전송이다 -Task 22 asks for zero copy on local files; §19 forbids a `Path` leaving the storage adapter, and §5 -of the plan forbids adding `Path` to the content store. WebFlux's zero-copy API takes a `Path`, so -that route is closed. +계획서 Task 22는 로컬 파일에 zero copy를 요구한다. 그런데 §19는 `Path`가 저장소 어댑터를 떠나는 것을 금하고, +계획서 §5는 content store에 `Path`를 더하는 것을 금한다. WebFlux의 zero-copy API는 `Path`를 받으므로 그 길은 +닫혀 있다. -The servlet path takes the other one: `ZeroCopyDownloadPort` receives a `WritableByteChannel` from -the transport and the storage adapter performs `FileChannel.transferTo` into it. That is a genuine -kernel-level transfer with no filesystem concept leaving storage. The reactive path continues to -stream with bounded demand. +servlet 경로는 다른 길을 쓴다. `ZeroCopyDownloadPort`는 transport에서 `WritableByteChannel`을 받고, 저장소 +어댑터가 그 안으로 `FileChannel.transferTo`를 한다. 파일 시스템 개념이 저장소를 떠나지 않는 진짜 kernel 수준 +전송이다. reactive transport는 2026-09-25에 지웠다([support-matrix.md](support-matrix.md)). -Zero copy is an optimization with no observable difference: when storage declines, the response is -streamed and is byte-identical. +zero copy는 관측 가능한 차이가 없는 최적화다. 저장소가 거절하면 응답은 스트리밍되고 바이트는 똑같다. -Pinned by `LocalStorageGatewayContractTest` and `ZeroCopyEligibilityTest`. +고정하는 테스트: `LocalStorageGatewayContractTest`, `ZeroCopyEligibilityTest`. -### 11. The Fileserver JPA stores are gated on the capability switch +### 11. Fileserver JPA 저장소는 capability 스위치 뒤에 있다 -The metadata store, session store, quota service, queues, ledger, and staging locator carry -`@ConditionalOnProperty(app.fileserver-platform.enabled)` even though the rest of -`adapter:outbound:persistence-jpa` is unconditional. +metadata 저장소, session 저장소, 할당량 서비스, 큐, ledger, staging locator는 `adapter:outbound:persistence-fileserver` +leaf에 있다. 그 leaf의 auto-configuration root `FileserverJpaPersistenceConfig`가 +`@ConditionalOnProperty(app.fileserver-platform.enabled)` 하나로 entity 스캔, Spring Data repository, 저장소 +bean을 모두 가린다. -게이트가 없으면 persistence 모듈을 포함한 조립 루트는 Fileserver를 쓰지 않아도 이 bean들을 만들고, 그 bean마다 -Fileserver 설정만 주는 협력 객체가 필요하다. That is the same rule the design states for the transport -surface, applied to persistence: no surface appears merely because the dependency is present. +이 관문이 없으면 persistence 모듈을 포함한 조립 루트는 Fileserver를 쓰지 않아도 이 bean들을 만들고, 그 +bean마다 Fileserver 설정만 주는 협력 객체가 필요하다. 설계가 transport 면에 대해 말한 규칙을 persistence에 +적용한 것이다: 의존성이 있다는 이유만으로 면이 나타나지 않는다. -`FileStateMachine` is bound alongside them, in `FileserverStorageConfiguration`. It had no -production binding at all before, which made the metadata store unconstructible in any -component-scanned context. +예전의 `FileStateMachine` bean은 지웠다. 상태 전이 검사는 `FileState.canTransitionTo`가 한다 +(`docs/capability-status.md` 「제거된 코드」). -Pinned by `SampleApplicationContextTest` (the capability off) and -`FileserverRuntimeAssemblyTest` (the capability on). +고정하는 테스트: `FileserverPersistenceActivationTest`(스캔이 스위치 뒤에 있음), +`FileserverRuntimeAssemblyTest`(capability를 켬), `FileStateTransitionTest`(전이 표). -### 12. Transaction boundaries are owned by the application services, and are deliberately narrow +### 12. Transaction 경계는 애플리케이션 서비스가 갖고, 일부러 좁다 -The design does not say where a transaction begins. The repository does: -`adapter:outbound:persistence-jpa` forbids a repository adapter from owning a `@Transactional` -boundary, and `application-core` owns them through `TransactionPort`. The Fileserver follows that -rule — every `Jpa*` store here declares no `@Transactional` of its own. +설계는 transaction이 어디서 시작하는지 말하지 않는다. 저장소가 말한다. `adapter:outbound:persistence-jpa`는 +repository 어댑터가 `@Transactional` 경계를 갖는 것을 금하고, `application-core`가 `TransactionPort`로 경계를 +가진다. Fileserver도 이 규칙을 따른다. 여기 있는 `Jpa*` 저장소는 자기 `@Transactional`을 선언하지 않는다. -What is specific to this capability is how narrow the boundaries are. A boundary covers a contiguous -run of metadata writes and **stops before every storage call**, because a filesystem operation -inside a database transaction would hold a connection for the length of a byte transfer. The upload -path therefore has three boundaries, not one: acquire the lease, transfer the bytes, commit the -offset. +이 capability에 특별한 것은 경계가 얼마나 좁은가다. 경계 하나는 이어진 metadata 쓰기를 덮고 **저장소 호출 +앞에서 늘 멈춘다**. DB transaction 안의 파일 시스템 작업은 바이트 전송 시간 내내 connection을 잡기 때문이다. +그래서 업로드 경로의 경계는 하나가 아니라 셋이다: lease 잡기, 바이트 전송, offset 확정. -Where several stores must agree, they share one boundary: +여러 저장소가 함께 맞아야 하는 곳은 경계 하나를 같이 쓴다. -| Unit | Why it is one boundary | +| 단위 | 경계 하나인 이유 | | --- | --- | -| reserve quota + insert record + create session | a reservation that outlived a failed insert holds capacity for a file that never existed | -| READY transition + quota commit | a finished file whose reservation was never converted holds capacity until the reservation expires | -| `markDeleting` + enqueue cleanup | a file that stopped being reachable with nothing queued to reclaim it is never collected | -| content delete settlement: reclaim + retire record + close queue item | half of it leaves the item to be retried against content that no longer exists | +| 할당량 예약 + 기록 insert + session 생성 | insert가 실패한 뒤 남은 예약은 존재한 적 없는 파일의 용량을 잡는다 | +| READY 전이 + 할당량 확정 | 예약이 확정으로 바뀌지 않은 완료 파일은 예약이 만료될 때까지 용량을 잡는다 | +| `markDeleting` + cleanup 큐 넣기 | 닿을 수 없게 됐는데 회수할 항목이 큐에 없는 파일은 영영 수거되지 않는다 | +| content 삭제 정산: 회수 + 기록 내리기 + 큐 항목 닫기 | 절반만 되면 이미 없는 content를 대상으로 항목이 재시도된다 | -What this cannot make atomic is the storage/metadata seam itself — no database boundary could. That -seam is exactly what the ambiguous-completion path and the reconciler exist for, and the one -hand-written compensation that remains (staging creation failing after the records committed) is -there for the same reason. +이렇게 해도 저장소/metadata 이음매 자체는 원자적으로 만들 수 없다. 어떤 DB 경계도 못 한다. 그 이음매 때문에 +결과를 모르는 완료 경로와 맞춰 보기가 있다. 남은 손으로 쓴 보상 하나(기록이 확정된 뒤 staging 생성이 실패한 +경우)도 같은 이유로 있다. -Pinned by `FileserverRoundTripContractTest` against real PostgreSQL; the application tests use -`DirectTransactions`, which runs a boundary inline and counts it. +고정하는 테스트: 애플리케이션 테스트는 경계를 그 자리에서 돌리며 세는 `DirectTransactions`를 쓴다. 실제 +PostgreSQL에서 조립 전체는 `FileserverCompositionIntegrationTest`(app-bootstrap `integrationTest`)가 돈다. +예전에 이 경계를 실제 PostgreSQL에서 고정하던 `FileserverRoundTripContractTest`는 지금 없다. -## Not implemented +## 구현하지 않은 것 ### `AsyncContentStore`, `CapacityAwareContentStore`, `CopyCapableContentStore`, `DelegatedDownloadStore` -Four optional content-store SPIs are declared in `application-core` with no implementation. Each is -an extension point for a backend this template does not ship: +`application-fileserver`에 구현 없이 선언돼 있던 선택 content-store SPI 넷이다. 구현도 호출도 없어서 지웠다 +(`docs/capability-status.md` 「제거된 코드」). 각각 이 템플릿이 내놓지 않는 backend를 위한 확장 지점이었다. -- `AsyncContentStore` — for a backend whose native client is non-blocking. The local platform is - blocking, and the reactive transport bridges to it on a dedicated I/O scheduler. -- `CapacityAwareContentStore` — capacity is reported through `StorageHealthPort` and - `StorageUsagePort`, which the local platform implements. -- `CopyCapableContentStore` — server-side copy is delivered by `CopyContentPort`; the local - platform has no cheaper primitive than a streamed copy. -- `DelegatedDownloadStore` — delegation is delivered at the transport boundary by the nginx - `X-Accel-Redirect` strategy, which needs no store participation. +- `AsyncContentStore` — native client가 non-blocking인 backend용. 로컬 플랫폼은 blocking이다. +- `CapacityAwareContentStore` — 용량은 로컬 플랫폼이 구현하는 `StorageHealthPort`와 `StorageUsagePort`로 + 보고한다. +- `CopyCapableContentStore` — 서버 쪽 copy는 `CopyContentPort`가 한다. 로컬 플랫폼에는 스트리밍 copy보다 싼 + 방법이 없다. +- `DelegatedDownloadStore` — 위임은 transport 경계에서 nginx `X-Accel-Redirect` 전략이 한다. 저장소가 끼어들 + 필요가 없다. -`ContentStoreCapabilities` reports what the running store actually supports, so no unimplemented SPI -is advertised as available. +`ContentStoreCapabilities`가 실행 중인 저장소가 실제로 지원하는 것을 보고한다. 그래서 구현하지 않은 것을 쓸 수 +있다고 광고하지 않는다. -## The repository's application-layer contract +## 저장소의 애플리케이션 계층 계약 -### 5. Fileserver operations are use cases (resolved, owner decision 32) +### 5. Fileserver 연산은 use case다 (해결됨, 소유자 결정 32) -Every operation the transport reaches is a `CommandUseCase` or `QueryUseCase` behind a one-method -port in `application.fileserver.port.in` — create, append, status, cancel, finalize and the -single-request upload; describe, prepare, open and transfer for downloads; delete, copy and move; -and the eight management-plane operations. Each implementation (`*ApplicationUseCase`) declares its -`@UseCaseCapability`, so the ArchUnit rules that check transaction mode, repository access and -outbound calls now see the Fileserver like every other feature. +transport가 닿는 모든 연산은 `application.fileserver.port.in`의 메서드 하나짜리 port 뒤에 있는 +`CommandUseCase`나 `QueryUseCase`다. -Two authorities guard a write, and both stay: +- 업로드: create, append, status, cancel, finalize, 요청 하나짜리 업로드 +- 다운로드: describe, prepare, open, transfer +- delete, copy, move +- management plane 연산 여덟 -| Check | Where | Decides | +구현(`*ApplicationUseCase`)마다 `@UseCaseCapability`를 선언한다. 그래서 transaction 방식, repository 접근, +외부 호출을 검사하는 ArchUnit 규칙이 이제 Fileserver를 다른 기능과 똑같이 본다. + +쓰기를 막는 권한은 둘이고, 둘 다 남는다. + +| 검사 | 위치 | 정하는 것 | | --- | --- | --- | -| `@RequiresPermission("file:…")` | the use case's proxy, enforced by the web adapter's method security | whether the caller's roles grant the operation at all | -| `FileAccessPolicyPort` | inside the use case, before any side effect | the tier (read/write/admin), and that the caller owns the file in its tenant | +| `@RequiresPermission("file:…")` | use case의 proxy. web 어댑터의 method security가 강제한다 | 호출자의 role이 그 연산을 아예 허락하는지 | +| `FileAccessPolicyPort` | use case 안, 부수 효과 전 | 등급(read/write/admin), 그리고 호출자가 자기 tenant에서 그 파일의 소유자인지 | -The permissions are `file:read` (describe, download, upload status), `file:upload` (create, -append, finalize, cancel, the single-request upload), `file:delete`, `file:copy`, `file:move` and -`file:admin` (every management-plane operation). `security.yml` grants them to `ROLE_FILE_READ`, -`ROLE_FILE_WRITE` and `ROLE_FILE_ADMIN` — the fileserver's own default tier roles — so a caller -holding a tier holds its permissions. A deployment that renames the tier roles, or supplies its own -`FileAccessPolicyPort` under other role names, maps those names in -`app.authz.role-permissions` too; `security.access-policy: unenforced` relaxes only the -tier and ownership check, never the permission gate. +권한은 `file:read`(describe, 다운로드, 업로드 상태), `file:upload`(create, append, finalize, cancel, 요청 +하나짜리 업로드), `file:delete`, `file:copy`, `file:move`, `file:admin`(모든 management plane 연산)이다. +`security.yml`은 이 권한을 fileserver 자신의 기본 등급 role인 `ROLE_FILE_READ`, `ROLE_FILE_WRITE`, +`ROLE_FILE_ADMIN`에 준다. 그래서 등급을 가진 호출자는 그 권한도 가진다. 등급 role 이름을 바꾸거나 다른 role +이름으로 자기 `FileAccessPolicyPort`를 주는 배포는 `app.authz.role-permissions`에도 그 이름을 대응시킨다. +`security.access-policy: unenforced`는 등급과 소유 검사만 풀고 권한 관문은 절대 풀지 않는다. -The resumable transfers run on the transfer pool, and method security reads the security context -of the calling thread, so `BlockingTransferExecutor` carries the request's context onto the worker -(`BlockingTransferExecutorSecurityContextTest`). Without it an authenticated append was refused as -anonymous. +이어 올리기 전송은 전송 pool에서 돌고, method security는 호출한 스레드의 security context를 읽는다. 그래서 +`BlockingTransferExecutor`가 요청의 context를 worker로 옮긴다(`BlockingTransferExecutorSecurityContextTest`). +이것이 없으면 인증한 append가 익명으로 거부됐다. -What is not a use case is what no transport calls: `CleanupService` and -`FileReconciliationService` are driven by background workers with no caller identity, and a -mutating use case must declare a permission a scheduler could not hold. -`FileserverUseCaseContractDeviationTest` freezes that list. - -The HTTP status vocabulary on `FileserverErrorCode` stays in the application layer, for the reason -this section used to give: the servlet transport and the Nginx delegation path must not answer the -same failure with different statuses. +use case가 아닌 것은 어떤 transport도 부르지 않는 것이다. `CleanupService`와 `FileReconciliationService`는 +호출자 신원이 없는 백그라운드 worker가 돌린다. 상태를 바꾸는 use case는 scheduler가 가질 수 없는 권한을 +선언해야 한다. `FileserverUseCaseContractDeviationTest`가 그 목록을 고정한다. +`FileserverErrorCode`의 HTTP 상태 어휘는 애플리케이션 계층에 남는다. 이 절이 예전에 든 이유 그대로다: +servlet transport와 Nginx 위임 경로가 같은 실패에 다른 상태로 답하면 안 된다. diff --git a/docs/fileserver/http-contract.md b/docs/fileserver/http-contract.md index 84034bfd..a5fb6aa6 100644 --- a/docs/fileserver/http-contract.md +++ b/docs/fileserver/http-contract.md @@ -1,35 +1,34 @@ -# Fileserver HTTP contract +# Fileserver HTTP 계약 -Every public endpoint is listed here. `FileserverDocumentationCoverageTest` scans the controllers -and fails if one is missing, so this file cannot silently fall behind the code. +모든 공개 endpoint를 여기 적는다. `FileserverDocumentationCoverageTest`가 controller를 훑어서 빠진 것이 있으면 +실패하므로, 이 파일은 코드보다 조용히 뒤처질 수 없다. -## Public endpoints +## 공개 endpoint -| Method | Path | Success | Notes | +| Method | Path | 성공 | 비고 | |---|---|---|---| -| POST | `/v1/files` | `201` READY, `202` VERIFYING | multipart single upload | -| POST | `/v1/files:raw` | `201`, `202` | the whole request body is the file | -| POST | `/v1/files:batch` | `200` | ordered per-part results; explicitly non-atomic | -| GET | `/v1/files/{fileId}` | `200` | public metadata; never a content key or path | -| GET | `/v1/files/{fileId}/content` | `200`, `206`, `304` | download | -| HEAD | `/v1/files/{fileId}/content` | `200`, `304` | identical headers, no body | -| DELETE | `/v1/files/{fileId}` | `202`, `204` | logical delete first | -| POST | `/v1/files/{fileId}:copy` | `202` | create-only target | -| POST | `/v1/files/{fileId}:move` | `200` | namespace change only, bytes stay; the file's quota moves with it, and a target namespace past its `namespace-limit` is `413` | -| OPTIONS | `/v1/uploads` | `204` | tus capability discovery | -| POST | `/v1/uploads` | `201` | tus creation | +| POST | `/v1/files` | `201` READY, `202` VERIFYING | multipart 단일 업로드 | +| POST | `/v1/files:raw` | `201`, `202` | 요청 본문 전체가 파일이다 | +| POST | `/v1/files:batch` | `200` | part별 결과를 순서대로 준다. 명시적으로 원자적이지 않다 | +| GET | `/v1/files/{fileId}` | `200` | 공개 metadata. content key나 경로는 절대 주지 않는다 | +| GET | `/v1/files/{fileId}/content` | `200`, `206`, `304` | 다운로드 | +| HEAD | `/v1/files/{fileId}/content` | `200`, `304` | 같은 헤더, 본문 없음 | +| DELETE | `/v1/files/{fileId}` | `202`, `204` | 먼저 논리 삭제 | +| POST | `/v1/files/{fileId}:copy` | `202` | 대상은 새로 만들기만 한다 | +| POST | `/v1/files/{fileId}:move` | `200` | namespace만 바뀌고 바이트는 그대로다. 파일의 할당량도 함께 옮긴다. 대상 namespace가 `namespace-limit`을 넘으면 `413` | +| OPTIONS | `/v1/uploads` | `204` | tus capability 조회 | +| POST | `/v1/uploads` | `201` | tus 생성 | | HEAD | `/v1/uploads/{uploadId}` | `204` | tus offset | -| PATCH | `/v1/uploads/{uploadId}` | `204` | tus append | -| DELETE | `/v1/uploads/{uploadId}` | `204` | tus termination | -| POST | `/v1/experimental/draft12/uploads` | `201` | Experimental; off by default | -| PATCH | `/v1/experimental/draft12/uploads/{uploadId}` | `204` | Experimental; off by default | +| PATCH | `/v1/uploads/{uploadId}` | `204` | tus 이어 쓰기 | +| DELETE | `/v1/uploads/{uploadId}` | `204` | tus 종료 | +| POST | `/v1/experimental/draft12/uploads` | `201` | Experimental. 기본으로 꺼져 있다 | +| PATCH | `/v1/experimental/draft12/uploads/{uploadId}` | `204` | Experimental. 기본으로 꺼져 있다 | -## Management endpoints +## 관리 endpoint -Reachable only where both `app.fileserver-platform.enabled=true` and -`app.fileserver-platform.admin.enabled=true`, gated at the servlet chain on -`app.fileserver-platform.security.admin-roles`, and intended for a management -port rather than the public one. +`app.fileserver-platform.enabled=true`와 `app.fileserver-platform.admin.enabled=true`가 둘 다 있을 때만 닿는다. +servlet chain에서 `app.fileserver-platform.security.admin-roles`로 막고, 공개 port가 아니라 관리 port에 두라고 +만든 것이다. | Method | Path | |---|---| @@ -42,38 +41,37 @@ port rather than the public one. | GET | `/internal/fileserver/uploads/incomplete` | | POST | `/internal/fileserver/uploads:cleanup` | -## Status codes +## 상태 코드 -| Status | Condition | +| 상태 | 조건 | |---:|---| -| `200` | metadata, full GET, batch result, move | -| `201` | file or upload created | -| `202` | verification or physical cleanup deferred | -| `204` | append, cancel, bodyless update | -| `206` | satisfiable Range | -| `304` | validator matched on GET or HEAD | -| `400` | malformed header or header combination | -| `401` | unauthenticated | -| `403` / `404` | denied, or hidden under the existence-hiding profile | -| `409` | state, offset, or lease conflict | -| `410` | expired or ended (cancelled, rejected, quarantined) upload resource | -| `411` | `require-content-length` profile with no length | -| `412` | precondition failed | -| `413` | size or quota policy violation | -| `415` | upload media type not accepted | -| `416` | unsatisfiable Range; carries the real length | -| `422` | digest, signature, or scanner rejection | -| `429` | transfer admission or rate limit | -| `460` | tus `Upload-Checksum` does not match that request's bytes; the chunk is discarded and the offset does not move | -| `503` | storage or scanner unavailable | -| `504` | downstream timeout | -| `507` | out of storage capacity | +| `200` | metadata, 전체 GET, batch 결과, move | +| `201` | 파일이나 업로드를 만들었다 | +| `202` | 검증이나 물리 정리를 미뤘다 | +| `204` | 이어 쓰기, 취소, 본문 없는 갱신 | +| `206` | 만족할 수 있는 Range | +| `304` | GET이나 HEAD에서 validator가 맞았다 | +| `400` | 헤더나 헤더 조합이 잘못됐다 | +| `401` | 인증하지 않았다 | +| `403` / `404` | 거부했거나, 존재를 숨기는 profile에서 숨겼다 | +| `409` | 상태, offset, lease 충돌 | +| `410` | 만료되거나 끝난(취소, 거부, 격리) 업로드 자원 | +| `411` | `require-content-length` profile인데 길이가 없다 | +| `412` | 선행 조건 실패 | +| `413` | 크기나 할당량 정책 위반 | +| `415` | 업로드 media type을 받지 않는다 | +| `416` | 만족할 수 없는 Range. 실제 길이를 담는다 | +| `422` | digest, 서명, 검사기 거부 | +| `429` | 전송 허가나 속도 제한 | +| `460` | tus `Upload-Checksum`이 그 요청의 바이트와 맞지 않는다. 그 chunk는 버리고 offset은 움직이지 않는다 | +| `503` | 저장소나 검사기를 쓸 수 없다 | +| `504` | 하류 시간 초과 | +| `507` | 저장 용량이 없다 | -## Failure body +## 실패 본문 -Every failure answers the application's one error shape, the `Envelope` (`application/json`), with -the stable code, its category, the shared Korean client message for that category and the -identifying values in `error.details`: +모든 실패는 애플리케이션의 오류 모양 하나인 `Envelope`(`application/json`)로 답한다. 안정된 code, 그 분류, +그 분류에 대한 공용 한국어 client 메시지, 그리고 `error.details`의 식별 값을 담는다. ```json { @@ -94,40 +92,37 @@ identifying values in `error.details`: } ``` -`details` carries only what the failure context holds: `fileId`, `uploadId`, `expectedOffset`, -`currentOffset`, `state`, and the flags `ambiguous` and `reconciliationRequired` when they are true. -The server-side exception message never appears. `ambiguous` is the field a client must read before -retrying: an ambiguous failure may already have taken effect. `retryable` is this occurrence's -decision and is never wider than the code allows. +`details`는 실패 context가 가진 것만 담는다: `fileId`, `uploadId`, `expectedOffset`, `currentOffset`, `state`, +그리고 참일 때만 `ambiguous`와 `reconciliationRequired` flag. 서버 쪽 예외 메시지는 절대 나오지 않는다. +`ambiguous`는 client가 재시도 전에 읽어야 하는 필드다. 결과를 모르는 실패는 이미 효과가 났을 수 있다. +`retryable`은 이번 발생에 대한 판단이고, 그 code가 허락하는 범위보다 넓어지지 않는다. -A batch upload part that is rejected carries the same `error` object (`code`, `category`, -`message`, `retryable`) in its `results[]` entry. +batch 업로드에서 거부된 part는 `results[]` 항목에 같은 `error` 객체(`code`, `category`, `message`, +`retryable`)를 담는다. -### Protocol exceptions to the Envelope rule +### Envelope 규칙의 프로토콜 예외 -Owner decision 2 keeps one HTTP error shape; the protocol pieces below are not error vocabulary and -stay as the protocol defines them (owner decision 12): +소유자 결정 2는 HTTP 오류 모양을 하나로 둔다. 아래 프로토콜 요소는 오류 어휘가 아니므로 프로토콜이 정한 +대로 둔다(소유자 결정 12). -- tus protocol headers (`Tus-Resumable`, `Upload-Offset`, `Upload-Length`, …) on every tus - response, success or failure. -- `Retry-After` and the unsatisfied-range `Content-Range` on a failure (see the header contract). -- The IETF resumable-upload draft's offset-mismatch response - (`Draft12UploadController#offsetMismatch`): `409 application/problem+json` with - `type = https://iana.org/assignments/http-problem-types#mismatching-upload-offset`, - `expectedOffset` and `providedOffset`. It is the only non-Envelope failure body. +- 성공이든 실패든 모든 tus 응답의 tus 프로토콜 헤더(`Tus-Resumable`, `Upload-Offset`, `Upload-Length`, …). +- 실패 응답의 `Retry-After`와 만족하지 못한 range의 `Content-Range`(헤더 계약을 본다). +- IETF resumable-upload draft의 offset 불일치 응답(`Draft12UploadController#offsetMismatch`): + `409 application/problem+json`, `type = https://iana.org/assignments/http-problem-types#mismatching-upload-offset`, + `expectedOffset`과 `providedOffset`. Envelope가 아닌 실패 본문은 이것 하나뿐이다. -## Header contract +## 헤더 계약 -| Header | Contract | +| 헤더 | 계약 | |---|---| -| `Content-Type` | client value is a claim; the verified type is stored separately | -| `Content-Disposition` | `attachment` by default; scriptable types are never inline | +| `Content-Type` | client 값은 주장일 뿐이다. 검증한 형식은 따로 저장한다 | +| `Content-Disposition` | 기본은 `attachment`. 스크립트가 될 수 있는 형식은 절대 inline이 아니다 | | `Accept-Ranges` | `bytes` | -| `Range` | single range by default; multi-range only under an explicit budget | -| `Content-Range` | actual range on `206`; the unsatisfied form on `416` | -| `ETag` | strong validator derived from the SHA-256 | -| `Last-Modified` | metadata publication instant, never a filesystem timestamp | -| `Cache-Control` | `private, no-store` by default | -| `X-Content-Type-Options` | always `nosniff` on a download | -| `Retry-After` | on retryable `409`, `429`, `503`, and `504` | -| `X-Accel-Redirect` | internal only; never forwarded to a client | +| `Range` | 기본은 범위 하나. 여러 범위는 명시적 예산이 있을 때만 | +| `Content-Range` | `206`에서는 실제 범위, `416`에서는 만족하지 못한 형태 | +| `ETag` | SHA-256에서 만든 strong validator | +| `Last-Modified` | metadata 게시 시각. 파일 시스템 timestamp가 아니다 | +| `Cache-Control` | 기본은 `private, no-store` | +| `X-Content-Type-Options` | 다운로드에는 늘 `nosniff` | +| `Retry-After` | 재시도할 수 있는 `409`, `429`, `503`, `504`에 붙인다 | +| `X-Accel-Redirect` | 내부 전용. client에게 넘기지 않는다 | diff --git a/docs/fileserver/operations.md b/docs/fileserver/operations.md index f3930451..a534d2bd 100644 --- a/docs/fileserver/operations.md +++ b/docs/fileserver/operations.md @@ -1,14 +1,14 @@ -# Fileserver runbooks +# Fileserver runbook -Each runbook names the exact metric that fires it and the exact command that resolves it. A runbook -whose trigger is "someone noticed" is not actionable, so every one below starts from a signal. +runbook마다 그것을 시작하게 하는 metric과 그것을 해결하는 명령을 정확히 적는다. 시작 조건이 「누가 알아챘다」인 +runbook은 대응할 수 없다. 그래서 아래 runbook은 모두 신호에서 시작한다. -## Storage full +## 저장소 가득 참 -**Signal** — `fileserver.quota{result="rejected"}` rising, or `507` responses appearing. +**신호** — `fileserver.quota{result="rejected"}`가 오르거나 `507` 응답이 나온다. -Storage capacity is exhausted or the high-water guard tripped. Uploads are rejected before any bytes -are written, so nothing is corrupt; the system is refusing work it cannot complete. +저장 용량이 바닥났거나 high-water 보호 장치가 걸렸다. 업로드는 바이트를 쓰기 전에 거부되므로 망가진 것은 +없다. 시스템이 끝낼 수 없는 일을 거절하고 있을 뿐이다. ```bash curl -s $ADMIN/internal/fileserver/storage-health | jq '.usedFraction, .usableBytes' @@ -16,71 +16,68 @@ curl -s -X POST "$ADMIN/internal/fileserver/uploads:cleanup?maxItems=500&maxByte curl -s "$ADMIN/internal/fileserver/orphans?limit=200" | jq '[.[].sizeBytes] | add' ``` -Drain the cleanup backlog first — it reclaims space the system already knows is dead. Only then -consider an orphan reconcile, and start with a dry run. +cleanup 적체부터 비운다. 시스템이 이미 죽은 것으로 아는 공간을 되찾는다. 그다음에야 고아 맞춰 보기를 +생각하고, dry run부터 한다. -## Orphan growth +## 고아 객체 증가 -**Signal** — `fileserver.cleanup{result="skipped"}` climbing, or the orphan scan returning more -objects each run. +**신호** — `fileserver.cleanup{result="skipped"}`가 오르거나, 고아 scan이 돌 때마다 더 많은 객체를 돌려준다. -Physical objects exist with no metadata record pointing at them. This is not immediately dangerous — -nothing serves them — but it consumes capacity indefinitely. +물리 객체는 있는데 그것을 가리키는 metadata 기록이 없다. 당장 위험하지는 않다. 아무것도 그것을 내보내지 +않는다. 하지만 용량을 끝없이 먹는다. ```bash -# Always look first. A reconcile without dryRun=false is a plan, not an action. +# 늘 먼저 본다. dryRun=false가 없는 reconcile은 실행이 아니라 계획이다. curl -s -X POST "$ADMIN/internal/fileserver/orphans:reconcile" \ -H 'content-type: application/json' -d '{"limit":100}' | jq '.candidates' -# Apply only the fingerprints you were just shown. +# 방금 본 fingerprint만 적용한다. curl -s -X POST "$ADMIN/internal/fileserver/orphans:reconcile" \ -H 'content-type: application/json' \ -d '{"dryRun":false,"limit":100,"maxBytes":1073741824, - "expectedFingerprints":[""],"reasonCode":"ORPHAN_GROWTH_RUNBOOK"}' + "expectedFingerprints":[""],"reasonCode":"ORPHAN_GROWTH_RUNBOOK"}' ``` -Echoing the fingerprints is the safety property: an object that changed between the scan and the -apply is skipped rather than deleted. +fingerprint를 되돌려 보내는 것이 안전 장치다. scan과 적용 사이에 바뀐 객체는 지우지 않고 건너뛴다. -## Verification backlog +## 검증 적체 -**Signal** — `fileserver.verification.queue{age_bucket="old"}` non-zero, or files sitting in -VERIFYING. +**신호** — `fileserver.verification.queue{age_bucket="old"}`가 0이 아니거나, 파일이 VERIFYING에 머문다. -A verifier is slow or unavailable. Files stay non-public, which is the correct failure direction: a -`RETRY` verdict never becomes an `ACCEPT`. +검증기가 느리거나 쓸 수 없다. 파일은 공개되지 않은 채 남는다. 맞는 실패 방향이다. `RETRY` 판정은 절대 +`ACCEPT`가 되지 않는다. ```bash curl -s $ADMIN/internal/fileserver/capabilities | jq '.storageType' -# Once the verifier is healthy, quarantined files can be re-examined individually. +# 검증기가 회복되면 격리된 파일을 하나씩 다시 검사할 수 있다. curl -s -X POST "$ADMIN/internal/fileserver/files/$FILE_ID:reverify" ``` -Do not clear the backlog by disabling verification. A file that reached READY without an accepting -verdict cannot be distinguished later from one that was verified. +검증을 꺼서 적체를 비우지 않는다. 받아들이는 판정 없이 READY가 된 파일은 나중에 검증받은 파일과 구분할 수 +없다. -## NFS ambiguity +## NFS 결과 모름 -**Signal** — problem documents carrying `"ambiguous": true`, or -`fileserver.transfer.interruption{reason="stale_handle"}`. +**신호** — 실패 Envelope의 `error.details`에 `"ambiguous": true`가 있거나, +`fileserver.transfer.interruption{reason="stale_handle"}`이 나온다. -An operation's outcome could not be determined: the response was lost after the write or rename may -have landed. These are never retried automatically. +연산의 결과를 알 수 없다. 쓰기나 rename이 적용됐을 수 있는데 응답이 사라졌다. 이런 연산은 절대 자동으로 +재시도하지 않는다. ```bash -# The recovery queue holds the files awaiting a decision. +# 복구 큐에 결정을 기다리는 파일이 있다. curl -s "$ADMIN/internal/fileserver/uploads/incomplete?limit=100" | jq ``` -Reconciliation compares the physical size and digest against the record and only confirms READY when -all four of key, size, digest, and version agree. Anything short of that is reported, never guessed. +맞춰 보기는 물리 크기와 digest를 기록과 비교하고, key·크기·digest· +version 넷이 모두 맞을 때만 READY를 확정한다. 그보다 못한 것은 짐작하지 않고 보고한다. -## PVC remount +## PVC 다시 마운트 -**Signal** — startup failure naming "atomic move", "same file store", or "not writable". +**신호** — "atomic move", "same file store", "not writable"을 담은 시작 실패. -The volume was remounted somewhere the probe can no longer prove a required capability. The -application refuses traffic rather than serving from storage it cannot publish to atomically. +volume이 다른 곳에 다시 마운트돼서 probe가 필수 capability를 더는 증명하지 못한다. 애플리케이션은 원자적으로 +게시할 수 없는 저장소로 내보내지 않고 요청을 거부한다. ```bash # staging과 content가 같은 파일 저장소(같은 장치 번호)인지 pod 안에서 본다 @@ -91,11 +88,11 @@ kubectl exec -- stat -c %d /var/lib/backend/files/staging /var/lib/backend 접근 모드, backend, mount 옵션)을 다시 적고, 인증한 묶음과 비교한다. 하나라도 다르면 그것이 원인이다. 인증은 그 차이를 넘어 옮겨지지 않는다. -## Nginx delegation failure +## Nginx 위임 실패 -**Signal** — `fileserver.download.delegation{delegated="true"}` with client-visible `404`s. +**신호** — `fileserver.download.delegation{delegated="true"}`인데 client에게 `404`가 보인다. -The internal location is misconfigured, so the proxy cannot resolve the redirect it was handed. +내부 location 설정이 잘못돼서 프록시가 넘겨받은 redirect를 풀지 못한다. 프록시 설정의 내부 location(기본 `/__files/`)이 아래 「운영 환경이 지켜야 할 조건」을 지키는지 본다. @@ -103,8 +100,7 @@ The internal location is misconfigured, so the proxy cannot resolve the redirect curl -s $ADMIN/internal/fileserver/capabilities | jq '.capabilities.delegatedDownload' ``` -Turning delegation off is a safe immediate mitigation: the application serves the transfer itself, -slower but correct. +위임을 끄는 것이 안전한 즉시 완화책이다. 애플리케이션이 직접 전송한다. 느리지만 맞다. ```bash app.fileserver-platform.nginx.enabled=false @@ -136,13 +132,12 @@ app.fileserver-platform.nginx.enabled=false 3. 그 volume이 `storage-certification.md`의 인증 항목(같은 파일 저장소, 원자적 rename, `O_EXCL` 생성)을 통과해야 한다. 기동 때 `FileserverStartupValidator`도 같은 probe를 다시 돌린다. -## Cleanup backlog +## 정리 적체 -**Signal** — `fileserver.cleanup{result="deferred"}` rising, or reclaimed bytes flat while deletes -continue. +**신호** — `fileserver.cleanup{result="deferred"}`가 오르거나, 삭제는 계속되는데 회수한 바이트가 평평하다. -Items are being deferred faster than they drain. The usual cause is an active writer lease still -holding staging objects, which is correct behaviour, not a fault. +항목이 비워지는 것보다 빠르게 미뤄진다. 흔한 원인은 아직 살아 있는 writer lease가 staging 객체를 잡고 있는 +것이다. 결함이 아니라 맞는 동작이다. ```bash curl -s "$ADMIN/internal/fileserver/uploads/incomplete?limit=100" \ @@ -150,23 +145,21 @@ curl -s "$ADMIN/internal/fileserver/uploads/incomplete?limit=100" \ curl -s -X POST "$ADMIN/internal/fileserver/uploads:cleanup?maxItems=500&maxBytes=10737418240" ``` -If the deferrals are all `ACTIVE_WRITER_LEASE`, the backlog resolves itself as those uploads expire. -Never delete staging content to clear a backlog: an upload that is mid-flight will corrupt. +미룬 이유가 모두 `ACTIVE_WRITER_LEASE`면 그 업로드들이 만료되면서 적체는 스스로 풀린다. 적체를 비우려고 +staging content를 지우지 않는다. 진행 중인 업로드가 망가진다. -## Namespace quota drift +## Namespace 할당량 어긋남 -**Signal** — a namespace's usage (`fileserver.quota` rejections, or the drift query below) disagrees -with the bytes its files actually hold. The known cause is history: before the 2026-11 maturity -review, `move` relocated a file without moving its quota. The bytes of every file moved before that -fix are still booked on the namespace it left, and deleting such a file reclaims from the namespace -it now lives in: the reclaim draws down the bookings of that namespace's other files, newest first, -or stops at zero, and the old booking stays behind either way. A derived -service that moved files across namespaces before taking the fix has this drift; one that never did -should see none. +**신호** — namespace의 사용량(`fileserver.quota` 거부, 또는 아래 drift query)이 그 파일들이 실제로 가진 바이트와 +다르다. 알려진 원인은 이력이다. 2026-11 성숙도 리뷰 전에는 `move`가 파일을 옮기면서 할당량은 옮기지 않았다. +그 수정 전에 옮긴 파일의 바이트는 아직 떠나온 namespace에 잡혀 있다. 그런 파일을 지우면 지금 있는 namespace에서 +회수한다. 그 회수는 그 namespace의 다른 파일 몫을 최신 것부터 깎거나 0에서 멈추고, 어느 쪽이든 옛 몫은 +남는다. 그 수정을 받기 전에 namespace를 넘어 파일을 옮긴 파생 서비스에는 이 어긋남이 있다. 그런 적이 없는 +서비스에는 없어야 한다. -What the ledger must equal: quota is committed when a file is published and reclaimed when cleanup -deletes its content, so a namespace's committed bytes are the sizes of its published files that are -not yet `DELETED`. The query compares the two and changes nothing. +ledger가 같아야 하는 값: 할당량은 파일을 게시할 때 확정하고 cleanup이 content를 지울 때 회수한다. 그래서 +namespace의 확정 바이트는 아직 `DELETED`가 아닌 게시된 파일 크기의 합이다. 아래 query가 둘을 비교한다. +아무것도 바꾸지 않는다. ```sql WITH booked AS ( @@ -188,18 +181,15 @@ SELECT coalesce(b.namespace, h.namespace) AS namespace, WHERE coalesce(b.booked_bytes, 0) <> coalesce(h.held_bytes, 0); ``` -A positive `drift_bytes` is booked capacity no file holds (the namespace a file left); a negative one -is held content nothing booked (the namespace it arrived in). While uploads, copies, moves or -cleanup run, a row can show a drift that only means work in flight, so judge drift with the -fileserver's writes stopped. +`drift_bytes`가 양수면 어떤 파일도 갖지 않은 잡힌 용량이다(파일이 떠나온 namespace). 음수면 아무도 잡지 않은 +content다(파일이 도착한 namespace). 업로드, copy, move, cleanup이 도는 동안에는 진행 중인 일 때문에 어긋남이 +보일 수 있다. 그러니 fileserver 쓰기를 멈춘 상태에서 판단한다. -To correct a namespace, stop every fileserver write to it first — uploads, copy, move, delete, and -the cleanup worker (`APP_FILESERVER_PLATFORM_CLEANUP_ENABLED=false`) — because the statement below -recomputes from `fs_file` and a publish or reclaim that lands between its two steps would be lost. -It zeroes the namespace's committed rows and books the recomputed total as one row, shaped the way a -publish leaves one (`COMMITTED`, `reserved_bytes` 0, the bytes in `committed_bytes`); the per-row -split has no meaning once reclaims have drawn rows down, and enforcement only ever reads the sum. -`RESERVED` rows (uploads in progress) are left alone. +namespace를 바로잡으려면 먼저 그 namespace로 가는 fileserver 쓰기를 모두 멈춘다. 업로드, copy, move, delete, +그리고 cleanup worker(`APP_FILESERVER_PLATFORM_CLEANUP_ENABLED=false`)다. 아래 문은 `fs_file`에서 다시 계산하므로, +두 단계 사이에 들어온 게시나 회수는 사라진다. 이 문은 그 namespace의 확정 행을 0으로 만들고, 다시 계산한 합계를 +게시가 남기는 모양의 행 하나로 잡는다(`COMMITTED`, `reserved_bytes` 0, 바이트는 `committed_bytes`). 회수가 행을 +깎은 뒤에는 행별 나눔에 의미가 없고, 강제는 합계만 읽는다. `RESERVED` 행(진행 중인 업로드)은 건드리지 않는다. ```sql BEGIN; @@ -221,5 +211,5 @@ SELECT gen_random_uuid(), 'namespace', :'namespace', 0, held, COMMIT; ``` -Run it with `psql -v namespace=`, then run the drift query again: the namespace must be gone -from its result before writes resume. +`psql -v namespace=`으로 돌리고 drift query를 다시 돌린다. 쓰기를 다시 열기 전에 그 namespace가 결과에서 +사라져야 한다. diff --git a/docs/fileserver/security.md b/docs/fileserver/security.md index cc27c308..54c39804 100644 --- a/docs/fileserver/security.md +++ b/docs/fileserver/security.md @@ -1,83 +1,78 @@ -# Fileserver security model +# Fileserver 보안 모델 -## The rule everything else follows +## 나머지가 모두 따르는 규칙 -Uploaded content is attacker-controlled. Every guard below exists because some part of the request -— the filename, the declared media type, the range, the offset — is a value the caller chose. +올라온 content는 공격자가 정한다. 아래 보호 장치는 모두 요청의 어떤 부분(파일 이름, 선언한 media type, +range, offset)이 호출자가 고른 값이기 때문에 있다. -## Path safety +## 경로 안전 -A client value never becomes a path. The physical key is server-generated, and `ContentKey`'s -character class excludes `.` entirely, so no traversal or extension-shaped segment survives -validation. `DefaultPhysicalPathResolver` is the only place an identifier becomes a `Path`, and it -normalizes and re-checks containment after construction rather than trusting the input. +client 값은 절대 경로가 되지 않는다. 물리 key는 서버가 만들고, `ContentKey`의 글자 집합에는 `.`이 아예 없다. +그래서 경로 거슬러 오르기나 확장자 모양의 조각은 검증을 통과하지 못한다. 식별자가 `Path`가 되는 곳은 +`DefaultPhysicalPathResolver` 하나다. 입력을 믿지 않고, 만든 뒤 정규화해서 root 안에 있는지 다시 확인한다. -Symlink refusal happens at open time, not only at construction. A parent directory can be replaced -between the two, so a check that ran only at path-building time would be a race, not a guard. +symlink 거부는 경로를 만들 때만이 아니라 열 때도 한다. 그 사이에 부모 폴더가 바뀔 수 있으므로, 경로를 만들 +때만 검사하면 보호 장치가 아니라 경쟁 조건이다. -## Filename handling +## 파일 이름 처리 -`OriginalFilenamePolicy` strips path separators, NUL, quoting characters, and the colon — the last -because on Windows it opens both a drive reference and an NTFS alternate data stream, so a name that -keeps it is still path-shaped after the slashes are gone. Control characters and bidirectional -overrides are removed, dot runs collapsed, reserved device names guarded, and the result is bounded -in UTF-8 bytes. +`OriginalFilenamePolicy`는 경로 구분자, NUL, 따옴표 문자, 콜론을 지운다. 콜론은 Windows에서 드라이브 참조와 +NTFS alternate data stream을 모두 열기 때문에, 슬래시를 지워도 콜론이 남으면 여전히 경로 모양이다. 제어 +문자와 양방향 override를 지우고, 이어진 점을 하나로 줄이고, 예약된 장치 이름을 막고, 결과를 UTF-8 바이트로 +제한한다. -The sanitized name is display data. It is never used to build a key, and it reaches a header only -through `ContentDispositionFactory`, which restricts the ASCII form and percent-encodes the UTF-8 -form. +정리한 이름은 표시용 데이터다. key를 만드는 데 절대 쓰지 않는다. 헤더에는 `HttpContentDispositionFactory`를 +거쳐서만 들어가고, 이것이 ASCII 형태를 제한하고 UTF-8 형태를 percent-encoding한다. -## Content type +## Content 형식 -The client's `Content-Type` is stored as a claim. The verified type comes from the verification -pipeline, and only the verified type is served. A claimed type that contradicts the content is -quarantined rather than corrected. +client의 `Content-Type`은 주장으로 저장한다. 검증한 형식은 검증 pipeline에서 오고, 검증한 형식만 내보낸다. +content와 어긋나는 주장 형식은 고치지 않고 격리한다. -Scriptable types are never served inline, whatever the caller asked for: serving stored HTML or SVG -inline from an upload origin is a stored cross-site scripting primitive. Every download also carries -`X-Content-Type-Options: nosniff`. +스크립트가 될 수 있는 형식은 호출자가 무엇을 요청했든 절대 inline으로 내보내지 않는다. 업로드 origin에서 +저장된 HTML이나 SVG를 inline으로 내보내면 stored cross-site scripting의 재료가 된다. 모든 다운로드는 +`X-Content-Type-Options: nosniff`도 붙인다. -## Verification precedence +## 검증 우선순위 -`REJECT > QUARANTINE > RETRY > ACCEPT`. A verifier that times out or throws is `RETRY`, never a -silent pass, and an empty verifier chain answers `RETRY` rather than accepting. A file becomes -publicly readable only after an `ACCEPT`. +`REJECT > QUARANTINE > RETRY > ACCEPT`. 시간 초과나 예외를 낸 검증기는 `RETRY`이고 조용한 통과가 아니다. +검증기가 하나도 없으면 받아들이지 않고 `RETRY`로 답한다. 파일은 `ACCEPT` 뒤에야 공개로 읽을 수 있다. -## Range safety +## Range 안전 -The range budget is enforced before content is opened, so a request naming many ranges is rejected -without amplifying into storage work. An unsatisfiable range answers `416` with the real length and -opens nothing. +range 예산은 content를 열기 전에 강제한다. 그래서 range를 많이 적은 요청은 저장소 작업을 불리지 않고 +거부된다. 만족할 수 없는 range는 실제 길이를 담은 `416`으로 답하고 아무것도 열지 않는다. -## Authorization +## 권한 -Every public operation calls the injected `FileAccessPolicyPort` before any quota reservation or storage -mutation, so a denial leaves no record, no reservation, and no staging object. Finalize is -authorized as `FINALIZE`, and management-plane reads as `ADMIN_READ`. Startup refuses to run a -production profile with an allow-all policy. +모든 공개 연산은 할당량 예약이나 저장소 변경 전에 주입한 `FileAccessPolicyPort`를 부른다. 그래서 거부하면 +기록도, 예약도, staging 객체도 남지 않는다. finalize는 `FINALIZE`로, management plane 읽기는 `ADMIN_READ`로 +권한을 본다. 시작 단계는 모두 허락하는 정책으로 운영 profile을 돌리는 것을 거부한다. -Each file records its owner: the principal that created it and, when the transport resolved one, -its tenant (the `tenant` subject attribute). The default role policy grants an operation on an -existing file only to its owner in the same tenant, so two callers holding the same role cannot -read, download, finalize, delete, copy or move each other's files. An admin role does not bypass -this — acting on another caller's file is what the audited management plane is for. A file created -before ownership was recorded (migration V5) has no owner and is reachable only through the -management plane. Anonymous read, when enabled, publishes every file and skips the owner check. +파일마다 소유자를 기록한다. 그 파일을 만든 principal, 그리고 transport가 하나를 풀었다면 그 tenant(`tenant` +subject 속성)다. 기본 role 정책은 이미 있는 파일에 대한 연산을 같은 tenant의 소유자에게만 허락한다. 그래서 +같은 role을 가진 두 호출자도 서로의 파일을 읽거나, 다운로드하거나, finalize하거나, 지우거나, copy하거나, +move할 수 없다. admin role도 이것을 건너뛰지 않는다. 다른 호출자의 파일을 다루라고 감사하는 management +plane이 있다. 소유자를 기록하기 전(마이그레이션 V5)에 만든 파일은 소유자가 없고 management plane으로만 닿는다. -## Delegation +익명 읽기는 설정으로 켤 수 없다([configuration.md](configuration.md) 「권한」). `role-based` 정책은 늘 끈 채로 +만든다. `RoleBasedFileAccessPolicy`를 직접 만들면서 익명 읽기를 켜면 모든 파일을 공개하고 소유자 검사를 +건너뛴다. -`X-Accel-Redirect` is emitted only after authorization and the READY gate, and only for a full, -unconditional response. The internal prefix must be an `internal` Nginx location; the front proxy -also strips any client-supplied delegation header so a caller cannot name an internal object. +## 위임 + +`X-Accel-Redirect`는 권한 확인과 READY 관문을 지난 뒤, 조건 없는 전체 응답에만 내보낸다. 내부 접두사는 +Nginx의 `internal` location이어야 한다. 프런트 프록시는 client가 보낸 위임 헤더도 지워서 호출자가 내부 객체를 +가리키지 못하게 한다. ## Telemetry -No metric label, span attribute, or audit record carries a file id, upload id, filename, path, or -user id. Where correlation is needed the value is a keyed HMAC fingerprint — keyed because the -identifier space is enumerable and an unkeyed digest of it is reversible by brute force. +metric label, span 속성, 감사 기록 어디에도 file id, upload id, 파일 이름, 경로, user id를 담지 않는다. +상관관계가 필요한 곳은 key를 쓴 HMAC fingerprint를 쓴다. 식별자 공간은 셀 수 있으므로 key 없는 digest는 +전수 대입으로 되돌릴 수 있다. 그래서 key가 필요하다. -## Ambiguous failures +## 결과를 모르는 실패 -A failure whose operation may already have taken effect is reported as ambiguous and is never -retryable. On a network filesystem a lost response is indistinguishable from a rejection at the -socket level, so anything not provably safe is treated as ambiguous and sent to reconciliation. +연산이 이미 효과를 냈을 수 있는 실패는 결과를 모르는 것(ambiguous)으로 보고하고 절대 재시도할 수 있다고 하지 +않는다. 네트워크 파일 시스템에서는 사라진 응답과 socket 수준의 거부를 구분할 수 없다. 그래서 안전하다고 +증명할 수 없는 것은 모두 결과를 모르는 것으로 보고 맞춰 보기로 보낸다. diff --git a/docs/fileserver/storage-certification.md b/docs/fileserver/storage-certification.md index 19117e1e..34638589 100644 --- a/docs/fileserver/storage-certification.md +++ b/docs/fileserver/storage-certification.md @@ -1,23 +1,22 @@ -# Storage certification +# 저장소 인증 -## Why a certification is per-volume +## 인증이 volume마다인 이유 -Atomic rename, same-file-store guarantees, and symlink refusal are properties of a specific -filesystem behind a specific mount — not of "Kubernetes" or "a PVC". Change the CSI driver, the -StorageClass, the access mode, the backend, or the mount options and any of them can differ. A -certification that does not name all five is not transferable. +원자적 rename, 같은 파일 저장소 보장, symlink 거부는 「Kubernetes」나 「PVC」의 성질이 아니라 특정 mount 뒤의 +특정 파일 시스템의 성질이다. CSI driver, StorageClass, 접근 모드, backend, mount 옵션 중 하나만 바꿔도 그중 +무엇이든 달라질 수 있다. 다섯을 모두 적지 않은 인증은 다른 곳으로 옮길 수 없다. -## What is certified +## 인증하는 것 -| Property | Why it matters | +| 성질 | 중요한 이유 | |---|---| -| Same file store for staging and content | A rename across stores is a copy, so publication stops being atomic. | -| Atomic rename | The publish path's default strategy. | -| Atomic create (`O_EXCL`) | Makes a publish create-only rather than a silent overwrite. | -| Symlink refusal | Stops a replaced parent from redirecting a write outside the root. | -| Ranged read | The download contract depends on it. | +| staging과 content가 같은 파일 저장소 | 저장소를 넘는 rename은 복사라서 게시가 원자적이지 않게 된다. | +| 원자적 rename | 게시 경로의 기본 전략이다. | +| 원자적 생성(`O_EXCL`) | 게시를 조용한 덮어쓰기가 아니라 새로 만들기만 하게 한다. | +| symlink 거부 | 바뀐 부모 폴더가 쓰기를 root 밖으로 돌리는 것을 막는다. | +| 범위 읽기 | 다운로드 계약이 기댄다. | -## Running the certification +## 인증 돌리기 이 repo는 인증 job 매니페스트를 두지 않는다(2026-11-07 소유자 결정). 배포하는 쪽이 대상 volume을 저장 루트(`/var/lib/backend/files`)에 마운트한 일회성 pod에서 아래를 차례로 확인한다. @@ -45,31 +44,30 @@ certification that does not name all five is not transferable. 2번이 실패하면 인증하지 않는다. staging과 content가 다른 저장소인 volume은 게시가 소리 없이 복사로 바뀐다. -## Network filesystems +## 네트워크 파일 시스템 ```bash docker compose -f src/adapter/outbound/fileserver/compose/nfs/compose.yml up -d FILESERVER_NFS_TESTS=true ./gradlew :adapter:outbound:fileserver:test ``` -The mount is `hard`, deliberately. A `soft` mount converts a slow server into a short write, which -is exactly the corruption this design refuses to accept. +mount는 일부러 `hard`다. `soft` mount는 느린 서버를 짧게 끝난 쓰기로 바꾼다. 이 설계가 받아들이지 않는 바로 +그 손상이다. -## Startup enforcement +## 시작 때 강제 -`FileserverStartupValidator` re-runs the probe at boot and refuses to accept traffic when a required -capability is missing — `ATOMIC_MOVE_REQUIRED` on a filesystem that cannot prove an atomic move -fails closed rather than degrading silently. +`FileserverStartupValidator`가 부팅 때 probe를 다시 돌리고, 필수 capability가 없으면 요청을 받지 않는다. +원자적 move를 증명하지 못하는 파일 시스템에 `ATOMIC_MOVE_REQUIRED`를 두면 조용히 기능을 줄이지 않고 닫힌 +쪽으로 실패한다. -## Adding a new store +## 새 저장소 더하기 -Pass two executable contracts. A prose claim of compatibility is not accepted. +실행되는 계약 둘을 통과해야 한다. 글로 쓴 호환 주장은 받지 않는다. -- `UploadStoragePortContract` — the application port's contract, in `application-fileserver` - testFixtures (`testImplementation testFixtures(project(':application-fileserver'))`). The - application's `FakeUploadStorageGateway` extends it too, so use case tests and the real store obey - the same offset, chunk-checksum and size-ceiling rules (a declared 0-byte upload refuses its first - byte). -- `ContentStoreContract` — the local adapter's internal `BlockingContentStore` SPI, in this - adapter's tests. That SPI stays in the adapter by design (review S1-#12: the application never - calls it), so its contract stays with it; a store that reuses the SPI extends it as well. +- `UploadStoragePortContract` — 애플리케이션 port의 계약이다. `application-fileserver` testFixtures에 있다 + (`testImplementation testFixtures(project(':application-fileserver'))`). 애플리케이션의 + `FakeUploadStorageGateway`도 이것을 상속한다. 그래서 use case 테스트와 실제 저장소가 같은 offset, chunk + checksum, 크기 상한 규칙을 지킨다(0바이트로 선언한 업로드는 첫 바이트를 거부한다). +- `ContentStoreContract` — 로컬 어댑터의 내부 `BlockingContentStore` SPI 계약이다. 이 어댑터의 테스트에 있다. + 그 SPI는 일부러 어댑터 안에 둔다(리뷰 S1-#12: 애플리케이션은 그것을 부르지 않는다). 그래서 계약도 어댑터에 + 있다. 그 SPI를 다시 쓰는 저장소도 이것을 상속한다. diff --git a/docs/fileserver/support-matrix.md b/docs/fileserver/support-matrix.md index 8e1c90ff..50b30b6a 100644 --- a/docs/fileserver/support-matrix.md +++ b/docs/fileserver/support-matrix.md @@ -1,71 +1,69 @@ -# Fileserver support matrix +# Fileserver 지원 매트릭스 -A support level here is a claim about evidence, not about intent. Every row names the CI job that -produces that evidence; `FileserverDocumentationCoverageTest` fails the build if a row names a job -that does not exist, so a level can never outlive the test that justified it. +여기의 지원 등급은 의도가 아니라 증거에 대한 주장이다. 행마다 그 증거를 만드는 CI job을 적는다. 행이 없는 +job을 적으면 `FileserverDocumentationCoverageTest`가 빌드를 실패시킨다. 그래서 등급은 그것을 정당화한 테스트보다 +오래 살 수 없다. -## Levels +## 등급 -| Level | What it means | +등급 이름은 원문 그대로 쓴다. 표와 테스트가 이 이름을 그대로 읽는다. + +| 등급 | 뜻 | |---|---| -| Stable | Certified on every pull request. Contract changes are breaking changes. | -| Beta | Certified nightly. The contract may still change with a deprecation notice. | -| Limited | Certified on the release gate only, under stated constraints. | -| Compatibility | Accepted but not optimized; known caveats are listed inline. | -| Experimental | Off by default, unratified upstream, may change without notice. | +| Stable | pull request마다 인증한다. 계약 변경은 깨지는 변경이다. | +| Beta | 매일 밤 인증한다. 폐기 예고와 함께 계약이 아직 바뀔 수 있다. | +| Limited | 밝힌 제약 아래에서 릴리스 게이트에서만 인증한다. | +| Compatibility | 받아들이지만 최적화하지 않는다. 알려진 주의점은 그 자리에 적는다. | +| Experimental | 기본으로 꺼져 있고, 상위 표준이 확정되지 않았으며, 예고 없이 바뀔 수 있다. | -## Runtime profiles +## 런타임 profile -| Profile | Level | CI job | +| Profile | 등급 | CI job | |---|---|---| -| Local filesystem (ext4) content store | Stable | `fileserver-local-ext4-contract` | -| Spring MVC transport (raw, multipart, batch, download) | Stable | `fileserver-http-contract` | -| Path, filename, range, and problem-detail hardening | Stable | `fileserver-security-suite` | -| Bounded-memory transfer | Stable | `fileserver-bounded-memory` | -| Application and architecture invariants | Stable | `fileserver-unit-and-architecture` | -| Runtime assembly (the capability starts with the flag on) | Stable | `fileserver-unit-and-architecture` | -| tus 1.0 resumable uploads | Stable | `fileserver-http-contract` | -| Crash-recovery matrix | Beta | `fileserver-process-kill-matrix` | -| NFSv4 ambiguity handling | Beta | `fileserver-nfs-ambiguity` | -| Large-file and slow-client performance | Beta | `fileserver-large-file-performance` | -| Multi-instance writer lease | Beta | `fileserver-multi-instance-lease` | -| Nginx `X-Accel-Redirect` delegation | Limited | `fileserver-http-contract` | -| Telemetry sensitive-data suppression | Stable | `fileserver-sensitive-telemetry-scan` | -| Documentation and support-claim coverage | Stable | `fileserver-documentation-gate` | -| Full release verification | Stable | `fileserver-full-verification` | +| 로컬 파일 시스템(ext4) content 저장소 | Stable | `fileserver-local-ext4-contract` | +| Spring MVC transport(raw, multipart, batch, 다운로드) | Stable | `fileserver-http-contract` | +| 경로, 파일 이름, range, problem-detail 강화 | Stable | `fileserver-security-suite` | +| 메모리 상한이 있는 전송 | Stable | `fileserver-bounded-memory` | +| 애플리케이션·아키텍처 불변식 | Stable | `fileserver-unit-and-architecture` | +| 런타임 조립(flag를 켜면 capability가 시작한다) | Stable | `fileserver-unit-and-architecture` | +| tus 1.0 이어 올리기 업로드 | Stable | `fileserver-http-contract` | +| 장애 복구 매트릭스 | Beta | `fileserver-process-kill-matrix` | +| NFSv4 결과 모름 처리 | Beta | `fileserver-nfs-ambiguity` | +| 큰 파일·느린 client 성능 | Beta | `fileserver-large-file-performance` | +| 여러 인스턴스 writer lease | Beta | `fileserver-multi-instance-lease` | +| Nginx `X-Accel-Redirect` 위임 | Limited | `fileserver-http-contract` | +| telemetry 민감 데이터 억제 | Stable | `fileserver-sensitive-telemetry-scan` | +| 문서와 지원 주장 범위 | Stable | `fileserver-documentation-gate` | +| 전체 릴리스 검증 | Stable | `fileserver-full-verification` | | HTTP resumable uploads draft-12 | Experimental | `fileserver-http-contract` | -### WebFlux transport removed +### WebFlux transport 제거 -The reactive router and handlers (`web.fileserver.reactive`) were removed on 2026-09-25 (D4: the -template is servlet on virtual threads). The shipped composition could never select them — the web -leaf puts `DispatcherServlet` on the classpath, so Boot resolves SERVLET. +reactive router와 handler(`web.fileserver.reactive`)는 2026-09-25에 지웠다(D4: 템플릿은 virtual thread 위의 +servlet이다). 내보낸 조립은 그것을 고를 수 없었다. web leaf가 `DispatcherServlet`을 classpath에 두므로 Boot는 +SERVLET으로 정한다. -## Explicitly not claimed +## 주장하지 않는 것 -These have no job, and therefore no claim: +아래는 job이 없고, 그래서 주장도 없다. - Kubernetes PVC(ReadWriteOnce 포함). 이 repo는 클러스터 매니페스트와 그것을 검사하던 release job을 2026-11-07에 지웠다. volume이 지켜야 할 조건은 [operations.md](operations.md) 「운영 환경이 지켜야 할 조건」, 인증 절차는 [storage-certification.md](storage-certification.md)다. 클러스터 결과는 배포하는 쪽이 만든다. +- Kubernetes ReadWriteMany PVC. 여러 노드의 동시 쓰기는 인증하지 않았다. +- 운영 저장 루트로서의 Windows NTFS. 파일 이름 정책이 NTFS가 예약한 문자를 지우지만, 그 위의 게시 경로를 + 인증하는 job은 없다. +- content 저장소로서의 object storage. 계약(`ContentStoreContract`)은 있지만 아직 구현한 어댑터가 없다. +- 서버 쪽 악성 코드 검사. 검증 pipeline에 port와 판정 우선순위는 있지만 내놓는 검사기는 없다. -- Kubernetes ReadWriteMany PVC. Concurrent writers across nodes are not certified. -- Windows NTFS as a production storage root. The filename policy strips the characters NTFS - reserves, but no job certifies the publish path there. -- Object storage as a content store. The contract exists (`ContentStoreContract`) but no adapter - implements it yet. -- Server-side malware scanning. The verification pipeline has the port and the verdict precedence; - no scanner is shipped. +## 나머지가 적힌 곳 -## Where the rest is written down - -- [configuration.md](configuration.md) — every `app.fileserver-platform.*` key, its default, and the - conditions that fail startup rather than degrade. -- [design-deviations.md](design-deviations.md) — where the implementation departs from the frozen - design, why, and the test that pins each decision. -- [http-contract.md](http-contract.md) — the wire contract. -- [security.md](security.md) — the threat model and what enforces each control. -- [operations.md](operations.md) — runbooks, each starting from a metric. -- [storage-certification.md](storage-certification.md) — how a volume is certified. -- [upgrade-guide.md](upgrade-guide.md) — what changes between versions. +- [configuration.md](configuration.md) — 모든 `app.fileserver-platform.*` key, 그 기본값, 기능을 줄이지 않고 + 시작을 실패시키는 조건. +- [design-deviations.md](design-deviations.md) — 구현이 고정된 설계와 다른 곳, 그 이유, 결정마다 고정하는 테스트. +- [http-contract.md](http-contract.md) — wire 계약. +- [security.md](security.md) — 위협 모델과 각 통제를 강제하는 것. +- [operations.md](operations.md) — 각각 metric에서 시작하는 runbook. +- [storage-certification.md](storage-certification.md) — volume을 인증하는 법. +- [upgrade-guide.md](upgrade-guide.md) — 버전 사이에 바뀌는 것. diff --git a/docs/fileserver/upgrade-guide.md b/docs/fileserver/upgrade-guide.md index e9bbf8bf..7e9dbf46 100644 --- a/docs/fileserver/upgrade-guide.md +++ b/docs/fileserver/upgrade-guide.md @@ -1,9 +1,9 @@ -# Fileserver upgrade guide +# Fileserver 업그레이드 안내 -## Enabling the capability +## Capability 켜기 -The Fileserver ships off. Nothing is registered — no endpoint, no thread pool, no metric — until it -is enabled explicitly. +Fileserver는 꺼진 채로 나온다. 명시적으로 켜기 전에는 아무것도 등록하지 않는다. endpoint도, 스레드 pool도, +metric도 없다. ```yaml app: @@ -15,68 +15,67 @@ app: fingerprint-key: ${FILESERVER_FINGERPRINT_KEY} ``` -`instance-id` must be unique per instance: it is the writer-lease owner, and two nodes sharing one -would both believe they hold the same lease. +`instance-id`는 인스턴스마다 달라야 한다. writer lease의 소유자이기 때문이다. 두 노드가 같은 값을 쓰면 둘 다 +같은 lease를 가졌다고 믿는다. -`fingerprint-key` is required and has no default. Startup fails without it rather than falling back -to an unkeyed digest, which would be reversible for an enumerable identifier space. +`fingerprint-key`는 필수이고 기본값이 없다. 없으면 key 없는 digest로 물러서지 않고 시작이 실패한다. 셀 수 +있는 식별자 공간에서 key 없는 digest는 되돌릴 수 있다. -## Optional surfaces +## 선택 면 -Each is a separate switch, and each defaults to off: +각각 따로 된 스위치이고, 모두 기본으로 꺼져 있다. ```yaml app: fileserver-platform: admin: - enabled: false # management plane; intended for a management port + enabled: false # management plane. 관리 port에 둔다 tus: - enabled: false # tus 1.0 Stable + enabled: false # tus 1.0, Stable httpbis-draft12: - enabled: false # Experimental; unratified, may change without notice + enabled: false # Experimental. 표준 미확정, 예고 없이 바뀔 수 있다 nginx: - enabled: false # front-proxy delegation; needs a validated internal location + enabled: false # 프런트 프록시 위임. 검증한 internal location이 필요하다 ``` -## Database schema +## DB schema -The metadata schema is installed as a capability migration and starts inactive: +metadata schema는 capability 마이그레이션으로 설치되고 비활성 상태로 시작한다. ``` V1__create_fileserver_metadata.sql → capability_schema_registry: jpa-fileserver-metadata-v1 ``` -Activate it deliberately. Enabling the capability without an activated schema fails at startup -rather than at the first upload. +의도해서 활성화한다. 활성화한 schema 없이 capability를 켜면 첫 업로드가 아니라 시작 때 실패한다. -## Choosing a publish mode +## 게시 방식 고르기 -| Mode | When | +| 방식 | 언제 | |---|---| -| `atomic-move-preferred` | Default. Uses an atomic rename when the probe proves one, else a metadata pointer. | -| `atomic-move-required` | Fail closed. Refuses to start on storage that cannot prove an atomic move. | -| `metadata-pointer` | For storage without atomic rename; publication is the metadata commit. | +| `atomic-move-preferred` | 기본값. probe가 증명하면 원자적 rename을, 아니면 metadata pointer를 쓴다. | +| `atomic-move-required` | 닫힌 쪽으로 실패한다. 원자적 move를 증명하지 못하는 저장소에서는 시작을 거부한다. | +| `metadata-pointer` | 원자적 rename이 없는 저장소용. 게시가 곧 metadata 확정이다. | -Pick `atomic-move-required` when the storage is certified and you want a misconfiguration to surface -at boot rather than at publish time. +저장소를 인증했고 잘못된 설정이 게시 때가 아니라 부팅 때 드러나기를 원하면 `atomic-move-required`를 고른다. -## Behaviour that will surprise you +## 놀랄 만한 동작 -- **A delete answers `202`, not `204`, when content still exists.** The file is already unreadable; - the physical reclaim is deferred. Treating `202` as a failure will produce spurious retries. -- **A batch upload answers `200` even when parts failed.** The batch is explicitly non-atomic, and a - single status could not report a partial outcome honestly. Read `results[].problem`. -- **An ambiguous failure must not be retried.** Check `"ambiguous": true` in the problem document. -- **`If-Match` takes the strong ETag, not a version number.** A client can only assert about the - representation it was actually served. -- **Inline rendering is refused for scriptable types** even when the caller asks for it. +- **content가 아직 있으면 삭제는 `204`가 아니라 `202`로 답한다.** 파일은 이미 읽을 수 없고, 물리 회수는 + 미뤘다. `202`를 실패로 다루면 쓸데없이 재시도한다. +- **batch 업로드는 part가 실패해도 `200`으로 답한다.** batch는 명시적으로 원자적이지 않고, 상태 코드 하나로는 + 부분 결과를 정직하게 알릴 수 없다. `results[].error`를 읽는다. +- **결과를 모르는 실패는 재시도하면 안 된다.** 실패 Envelope의 `error.details`에서 `"ambiguous": true`를 본다. +- **`If-Match`는 version 숫자가 아니라 strong ETag를 받는다.** client는 실제로 받은 표현에 대해서만 주장할 수 + 있다. +- **스크립트가 될 수 있는 형식은 호출자가 요청해도 inline으로 그리지 않는다.** -## Verifying an upgrade +## 업그레이드 확인 ```bash cd src ./gradlew verifyCleanArchitectureDependencies --console=plain -./gradlew :application-core:check :adapter:inbound:web:check \ - :adapter:outbound:fileserver:check --console=plain -./gradlew :app-bootstrap:test --tests '*Fileserver*' --console=plain +./gradlew :application-fileserver:check :adapter:inbound:web-fileserver:check \ + :adapter:outbound:fileserver:check :adapter:outbound:persistence-fileserver:check \ + :composition:fileserver-platform:check --console=plain +./gradlew :app-bootstrap:architectureTest --console=plain ``` diff --git a/docs/httpclient/configuration-reference.md b/docs/httpclient/configuration-reference.md index d23ff7c0..25691bed 100644 --- a/docs/httpclient/configuration-reference.md +++ b/docs/httpclient/configuration-reference.md @@ -1,37 +1,34 @@ -# HTTP Client Platform — Configuration Reference +# HTTP Client 플랫폼 — 설정 참조 -Every outbound call resolves exactly one **Named Client Profile**. The whole capability lives under -the `app.httpclient` prefix: profiles under `app.httpclient.clients[N]`, Dynamic Target policies -under `app.httpclient.dynamic-targets[N]`. +모든 외부 호출은 **Named Client Profile**(이름 붙은 client profile) 정확히 하나로 풀린다. capability 전체가 +`app.httpclient` 접두사 아래에 있다. profile은 `app.httpclient.clients[N]` 아래, Dynamic Target 정책은 +`app.httpclient.dynamic-targets[N]` 아래에 있다. -Design §30.1 forbids a production profile from inheriting large framework defaults. Anything a -production deployment must decide has either no default or an unusable one, and -`HttpClientStartupValidator` fails the context rather than guessing. +설계서 §30.1은 운영 profile이 framework의 큰 기본값을 물려받는 것을 금한다. 운영 배포가 정해야 하는 것은 +기본값이 없거나 쓸 수 없는 기본값을 가진다. `HttpClientStartupValidator`는 짐작하지 않고 context를 실패시킨다. -## The master switch +## 주 스위치 -| Property | Type | Default | Environment | +| 속성 | 타입 | 기본값 | 환경 변수 | |---|---|---|---| | `app.httpclient.enabled` | boolean | `true` | `APP_HTTPCLIENT_ENABLED` | -The module is on when present: a service adds `runtimeOnly project(':adapter:outbound:httpclient')` -to `app-bootstrap/build.gradle`, and the module's own `config/module-defaults/httpclient.yml` (loaded at the lowest -precedence by the support leaf's `ModuleDefaultsEnvironmentPostProcessor`) supplies `enabled: true`. Absent from the -build is the ordinary off state. `false` is the explicit off: `HttpClientPlatformAutoConfiguration` -is then never processed and neither is anything it imports — no property is bound, and no transport -provider, connection pool, TLS context, credential, thread, gateway or actuator endpoint exists. A -malformed HTTP client setting cannot fail the startup of a deployment that switched it off. +모듈은 있으면 켜진다. 서비스가 `app-bootstrap/build.gradle`에 `runtimeOnly project(':adapter:outbound:httpclient')`를 +더하면, 모듈 자신의 `config/module-defaults/httpclient.yml`(support leaf의 `ModuleDefaultsEnvironmentPostProcessor`가 +가장 낮은 우선순위로 읽는다)이 `enabled: true`를 준다. 빌드에 없는 것이 보통의 꺼진 상태다. `false`는 명시적으로 +끈 것이다. 그러면 `HttpClientPlatformAutoConfiguration`도, 그것이 import하는 것도 처리되지 않는다. 바인딩되는 +속성이 없고, transport provider, connection pool, TLS context, credential, 스레드, gateway, actuator endpoint도 +없다. 끈 배포에서는 잘못된 HTTP client 설정이 시작을 실패시키지 않는다. -Anything that is not exactly `true` — `yes`, `1`, blank — turns the platform off. On with no client -declared is a startup failure carrying `HTTPCLIENT_ACTIVE_WITHOUT_CLIENTS`: a platform with nothing -to call still holds transport providers and gateways no caller can reach. +정확히 `true`가 아닌 값(`yes`, `1`, 빈 값)은 플랫폼을 끈다. 켰는데 선언한 client가 없으면 +`HTTPCLIENT_ACTIVE_WITHOUT_CLIENTS`로 시작이 실패한다. 부를 대상이 없는 플랫폼도 아무 호출자도 닿을 수 없는 +transport provider와 gateway를 쥐고 있기 때문이다. -## Declaring clients from the environment +## 환경 변수로 client 선언하기 -Clients are an indexed list carrying their own `name`, not a map keyed by name. A map key becomes a -segment of the environment variable and the relaxed binder normalises it, so `payment-api` and -`payment_api` would arrive as one entry with nothing said about the one that was lost. Both a -duplicate name and a name that collides once normalised fail startup. +client는 이름을 key로 한 map이 아니라, 자기 `name`을 가진 index 목록이다. map key는 환경 변수 이름의 한 조각이 +되고 relaxed binder가 그것을 정규화한다. 그래서 `payment-api`와 `payment_api`가 한 항목으로 도착하고, 사라진 +쪽에 대해서는 아무 말도 없다. 이름이 겹치거나 정규화한 뒤 겹치면 둘 다 시작이 실패한다. ```dotenv APP_HTTPCLIENT_ENABLED=true @@ -47,200 +44,194 @@ APP_HTTPCLIENT_DYNAMIC_TARGETS_0_NAME=webhook APP_HTTPCLIENT_DYNAMIC_TARGETS_0_ALLOWED_SCHEMES_0=https ``` -`docs/httpclient/env-fields.yaml` is the registry of accepted variable names. It is -derived from the settings record and held to it in both directions, and the platform refuses to -start on an `APP_HTTPCLIENT_` variable that is not in it — so -`APP_HTTPCLIENT_CLIENTS_0_TIMEUOT_TOTAL_CALL` fails startup instead of silently leaving the client -on its default budget. Unknown keys supplied through a configuration file rather than the -environment are refused by strict binding for the same reason. +`docs/httpclient/env-fields.yaml`이 받아들이는 변수 이름의 registry다. settings record에서 만들어지고 양쪽 +방향으로 그 record와 대조된다. 플랫폼은 여기 없는 `APP_HTTPCLIENT_` 변수가 있으면 시작을 거부한다. 그래서 +`APP_HTTPCLIENT_CLIENTS_0_TIMEUOT_TOTAL_CALL`은 client를 조용히 기본 예산으로 두지 않고 시작을 실패시킨다. +환경 변수가 아니라 설정 파일로 준 모르는 key도 같은 이유로 엄격한 바인딩이 거부한다. -Only `APP_HTTPCLIENT_ENABLED` appears in `src/.env` and `docs/registries/env-keys.yaml`. It is the -one key with a deployment-independent value; templating an indexed client in `application.yml` would -materialise a nameless client in every deployment, which the aggregate validation refuses. +`src/.env`와 `docs/registries/env-keys.yaml`에는 `APP_HTTPCLIENT_ENABLED`만 있다. 배포와 상관없는 값을 가진 +유일한 key다. index를 단 client를 `application.yml`에 template로 두면 모든 배포에 이름 없는 client가 생기고, +그것은 묶음 검증이 거부한다. ## `app.httpclient.clients[N]` -| Property | Type | Default | Notes | +| 속성 | 타입 | 기본값 | 비고 | |---|---|---|---| -| `name` | string | — | Required, unique, and distinct from every other name once normalised for the environment | -| `mode` | `TRUSTED` \| `DYNAMIC` | `TRUSTED` | A dynamic profile may not carry a default credential | -| `base-url` | URI | — | Required for a trusted profile; no userinfo, no query | -| `allowed-hosts` | list | empty | Required in production | -| `allowed-ports` | list | empty | Compared against the effective port | -| `transport` | `APACHE` \| `JDK` \| `JETTY` \| `SIMPLE` | `APACHE` | `SIMPLE` is rejected in production; `JETTY` needs a deployment-registered provider | -| `protocols` | list | `HTTP_1_1` | The default transport is Apache, whose classic client is HTTP/1.1 only; a profile that wants HTTP/2 declares it together with a transport that can deliver it. `HTTP_3` requires the experimental acknowledgement | -| `experimental-acknowledgement` | string | — | Must equal `I_ACCEPT_HTTP3_EXPERIMENTAL_SEMANTICS` | +| `name` | string | — | 필수. 유일하고, 환경 변수용으로 정규화한 뒤에도 다른 모든 이름과 달라야 한다 | +| `mode` | `TRUSTED` \| `DYNAMIC` | `TRUSTED` | dynamic profile은 기본 credential을 가질 수 없다 | +| `base-url` | URI | — | trusted profile에 필수. userinfo와 query가 없어야 한다 | +| `allowed-hosts` | list | 비어 있음 | 운영에서 필수 | +| `allowed-ports` | list | 비어 있음 | 실제 port와 비교한다 | +| `transport` | `APACHE` \| `JDK` \| `JETTY` \| `SIMPLE` | `APACHE` | `SIMPLE`은 운영에서 거부한다. `JETTY`는 배포가 등록한 provider가 필요하다 | +| `protocols` | list | `HTTP_1_1` | 기본 transport는 Apache이고, 그 classic client는 HTTP/1.1만 한다. HTTP/2를 원하는 profile은 그것을 줄 수 있는 transport와 함께 선언한다. `HTTP_3`은 실험 동의가 필요하다 | +| `experimental-acknowledgement` | string | — | `I_ACCEPT_HTTP3_EXPERIMENTAL_SEMANTICS`와 같아야 한다 | ### `pool` -| Property | Default | Meaning | +| 속성 | 기본값 | 뜻 | |---|---|---| -| `max-total-connections` | `50` | Socket ceiling for the runtime | -| `max-connections-per-route` | `25` | Per-upstream ceiling | -| `max-pending-acquires` | `100` | Waiting-request memory ceiling | -| `pending-acquire-timeout` | `200ms` | Pool or stream wait ceiling | -| `max-idle-time` | `30s` | Idle eviction | -| `max-life-time` | `5m` | Picks up DNS, load-balancer, and certificate changes | -| `validate-after-inactivity` | `5s` | Stale and half-open detection | -| `requires-route-pool` | `false` | Set when route-scoped limits are mandatory; the JDK transport then refuses the profile | -| `requires-bounded-pending-queue` | `false` | Same, for a bounded pending queue | +| `max-total-connections` | `50` | 런타임의 socket 상한 | +| `max-connections-per-route` | `25` | upstream 하나의 상한 | +| `max-pending-acquires` | `100` | 기다리는 요청의 메모리 상한 | +| `pending-acquire-timeout` | `200ms` | pool이나 stream을 기다리는 상한 | +| `max-idle-time` | `30s` | 놀고 있는 connection 내보내기 | +| `max-life-time` | `5m` | DNS, load balancer, 인증서 변화를 받아들인다 | +| `validate-after-inactivity` | `5s` | 낡거나 반쯤 열린 connection 감지 | +| `requires-route-pool` | `false` | route 범위 상한이 필수일 때 켠다. 그러면 JDK transport가 그 profile을 거부한다 | +| `requires-bounded-pending-queue` | `false` | 같은 방식으로, 상한 있는 대기 큐가 필수일 때 | ### `timeout` -| Property | Default | Meaning | +| 속성 | 기본값 | 뜻 | |---|---|---| -| `dns` | `300ms` | Hostname resolution | -| `connect` | `500ms` | Socket connect | -| `tls-handshake` | `1s` | TLS and ALPN | -| `response-header` | `2s` | Until final response headers | -| `read-idle` | `3s` | Between response chunks | -| `total-call` | `4s` | The whole logical call, including retry backoff | +| `dns` | `300ms` | hostname 풀기 | +| `connect` | `500ms` | socket 연결 | +| `tls-handshake` | `1s` | TLS와 ALPN | +| `response-header` | `2s` | 최종 응답 헤더까지 | +| `read-idle` | `3s` | 응답 chunk 사이 | +| `total-call` | `4s` | 재시도 backoff를 포함한 논리 호출 전체 | -`total-call` must not be shorter than `connect` or `response-header`; the validator emits -`INVALID_TIMEOUT_BUDGET` otherwise. Every timeout above, and `pool.pending-acquire-timeout`, must be -greater than zero (`TIMEOUT_NOT_POSITIVE`): both engines read zero as "wait forever". +`total-call`은 `connect`나 `response-header`보다 짧으면 안 된다. 짧으면 validator가 `INVALID_TIMEOUT_BUDGET`을 +낸다. 위의 모든 timeout과 `pool.pending-acquire-timeout`은 0보다 커야 한다(`TIMEOUT_NOT_POSITIVE`). 두 엔진 모두 +0을 「영원히 기다림」으로 읽는다. -`total-call` also bounds the setup of a streaming download — connect, send, and the wait for -response headers. Once the stream is handed over, each gap of the body is bounded by `read-idle` -instead, so a long download is not cut at an arbitrary total (design §15.3). This holds on both -transports. The JDK transport keeps its exchange-wide timeout off a streamed body, and a per-stream -watchdog bounds each read's wait by `read-idle`, because the JDK client has no socket read timeout. -The watchdog wakes on one daemon thread of its own (`httpclient-jdk-read-idle`), not on the common -`ForkJoinPool`, so a service that fills that pool with blocking work does not delay it (re-review -2026-11-04 RR3-03-01). That thread ends 60 s after the last wake it had queued and the next stream -starts it again; it inherits no thread-locals from the request thread that starts it and uses the -module's class loader as its context loader, so an idle service keeps no thread and a redeployed -application's loader is not pinned (RR4-03-04). Before review 2026-11-03 RR-04-03 every JDK download longer than -`response-header` was cut mid-body. A body failure after hand-over is thrown from `read` as `HttpBodyReadException` — an `IOException`, as -`InputStream` promises, so `catch (IOException)` still sees it — whose `failure()` is -`HttpResponseTimeoutException` (a wait longer than `read-idle`) or `HttpResponseTruncatedException` -(the connection ended early), stage `RESPONSE_BODY`, evidence `PARTIAL_RESPONSE` (re-review -2026-11-04 RR-03-14). On the JDK transport `read-idle` bounds each read's wait, `skip` included, and -time the caller spends between reads does not count (RR-03-12). +`total-call`은 스트리밍 다운로드의 준비 단계(연결, 보내기, 응답 헤더 기다리기)도 제한한다. stream을 넘긴 뒤에는 +본문의 틈마다 `read-idle`이 제한한다. 그래서 긴 다운로드가 임의의 총 시간에 잘리지 않는다(설계서 §15.3). 두 +transport 모두 그렇다. -### Removed settings +- JDK transport는 스트리밍 본문에 exchange 전체 timeout을 걸지 않는다. JDK client에는 socket 읽기 timeout이 + 없으므로 stream마다 watchdog이 읽기 대기를 `read-idle`로 제한한다. +- watchdog은 공용 `ForkJoinPool`이 아니라 자기 daemon 스레드 하나(`httpclient-jdk-read-idle`)에서 깬다. 그래서 + 그 pool을 blocking 작업으로 채운 서비스도 watchdog을 늦추지 않는다(재리뷰 2026-11-04 RR3-03-01). +- 그 스레드는 마지막으로 예약한 깨우기 60초 뒤에 끝나고, 다음 stream이 다시 띄운다. 띄운 요청 스레드의 + thread-local을 물려받지 않고, 모듈의 class loader를 context loader로 쓴다. 그래서 노는 서비스는 스레드를 + 붙들지 않고, 다시 배포한 애플리케이션의 loader가 붙잡히지 않는다(RR4-03-04). +- 리뷰 2026-11-03 RR-04-03 전에는 `response-header`보다 긴 JDK 다운로드가 모두 본문 중간에 잘렸다. -Six keys were removed because they were bound and reached no transport (review 2026-11-01 05-15). -Setting one now fails startup with a bind error naming the key (`The elements -[app.httpclient.clients[0].timeout.request-write-idle] were left unbound.`), instead of being -accepted and ignored. +넘긴 뒤의 본문 실패는 `read`에서 `HttpBodyReadException`으로 던진다. `InputStream`이 약속한 대로 `IOException` +이므로 `catch (IOException)`도 그것을 잡는다. 그 `failure()`는 `HttpResponseTimeoutException`(`read-idle`보다 긴 +기다림)이나 `HttpResponseTruncatedException`(connection이 일찍 끝남)이고, 단계는 `RESPONSE_BODY`, 증거는 +`PARTIAL_RESPONSE`다(재리뷰 2026-11-04 RR-03-14). JDK transport에서 `read-idle`은 `skip`을 포함해 읽기마다의 +기다림을 제한하고, 호출자가 읽기 사이에 쓴 시간은 세지 않는다(RR-03-12). -| Removed key | Why | +### 지운 설정 + +어느 transport에도 닿지 않으면서 바인딩만 되던 key 여섯을 지웠다(리뷰 2026-11-01 05-15). 이제 그 key를 쓰면 +받아들이고 무시하는 대신 그 key를 이름 댄 바인딩 오류(`The elements +[app.httpclient.clients[0].timeout.request-write-idle] were left unbound.`)로 시작이 실패한다. + +| 지운 key | 이유 | |---|---| -| `timeout.request-write-idle` | Neither engine can bound a blocking socket write | -| `timeout.proxy-connect`, `proxy.connect-timeout` | The TCP connect to a proxy is governed by `timeout.connect` | -| `pool.eviction-interval` | Apache's idle evictor runs at `max-idle-time` | -| `pool.shutdown-timeout` | A retired runtime drains for `app.httpclient.rotation-drain-timeout` | -| `observability.operation-name-required` | An operation name is mandatory in the API; the switch could only be true | +| `timeout.request-write-idle` | 어느 엔진도 blocking socket 쓰기를 제한하지 못한다 | +| `timeout.proxy-connect`, `proxy.connect-timeout` | proxy로의 TCP 연결은 `timeout.connect`가 정한다 | +| `pool.eviction-interval` | Apache의 idle evictor는 `max-idle-time`마다 돈다 | +| `pool.shutdown-timeout` | 내린 런타임은 `app.httpclient.rotation-drain-timeout` 동안 비운다 | +| `observability.operation-name-required` | 연산 이름은 API에서 필수다. 이 스위치는 true일 수밖에 없었다 | ### `circuit-breaker` -What counts as a failure is fixed: a 5xx, 408 or 429 response — whether the call throws or returns -it as a result — and every transport failure. Every other 4xx is a healthy answer. These settings -only say how many failures, out of how many calls, open the circuit. Defaults are Resilience4j's own, -which every profile ran with before the keys existed. +무엇을 실패로 세는지는 고정이다. 5xx, 408, 429 응답(호출이 던지든 결과로 돌려주든)과 모든 transport 실패다. +그 밖의 4xx는 건강한 답이다. 이 설정은 몇 번 중 몇 번의 실패가 circuit을 여는지만 정한다. 기본값은 +Resilience4j 자체의 값이고, key가 생기기 전 모든 profile이 이 값으로 돌았다. -Two deadlines can end an attempt in flight, and they are counted differently (review 2026-11-03 -RR-04-01): +진행 중인 시도를 끝낼 수 있는 기한은 둘이고, 둘을 다르게 센다(리뷰 2026-11-03 RR-04-01). -| Ended by | Breaker | Why | +| 끝낸 것 | Breaker | 이유 | |---|---|---| -| The caller's own deadline (`HttpOperation.deadline()`, when earlier than `total-call`) | Not recorded; the permission is given back | The caller ran out of time. Counting it opened the circuit on a healthy upstream whenever callers passed short budgets | -| The profile's `timeout.total-call` | Recorded as a failure | `total-call` is the operator's statement of how long a healthy upstream may take; a slow-drip upstream that never trips a per-gap timeout is seen only through it | +| 호출자 자신의 기한(`HttpOperation.deadline()`, `total-call`보다 이를 때) | 기록하지 않고 허가를 돌려준다 | 호출자의 시간이 다 됐을 뿐이다. 이것을 세면 호출자가 짧은 예산을 줄 때마다 건강한 upstream의 circuit이 열렸다 | +| profile의 `timeout.total-call` | 실패로 기록한다 | `total-call`은 건강한 upstream이 걸려도 되는 시간에 대한 운영자의 말이다. 틈마다의 timeout에 걸리지 않고 조금씩 흘리는 upstream은 이것으로만 보인다 | -The first row has a blind spot (re-review 2026-11-04 RR-03-16). The attempt is let off whenever the -caller's deadline was the earlier one and had passed when the attempt failed — the code does not ask -whether the upstream was still answering within the profile's limits. If every caller of a profile -passes a budget shorter than `connect` or `response-header`, an upstream that hangs (drops packets, -never answers) ends every attempt at the caller's deadline first, so no attempt is recorded and the -circuit never opens; every call waits out its own budget. A failure that comes before the caller's -deadline — a refused connection — is still counted. For such a profile, set `connect` and -`response-header` shorter than the shortest caller budget. +첫 행에는 사각지대가 있다(재리뷰 2026-11-04 RR-03-16). 호출자의 기한이 더 이르고, 시도가 실패했을 때 그 기한이 +지났으면 그 시도는 세지 않는다. 코드는 upstream이 그때도 profile 한도 안에서 답하고 있었는지 묻지 않는다. +어떤 profile의 모든 호출자가 `connect`나 `response-header`보다 짧은 예산을 주면, 멈춘 upstream(패킷을 버리거나 +답하지 않음)은 모든 시도를 호출자의 기한에서 먼저 끝낸다. 그래서 아무 시도도 기록되지 않고 circuit은 열리지 +않으며, 모든 호출이 자기 예산을 다 기다린다. 호출자의 기한 전에 오는 실패(거부된 연결)는 여전히 센다. 그런 +profile에는 `connect`와 `response-header`를 가장 짧은 호출자 예산보다 짧게 둔다. -| Property | Default | Meaning | +| 속성 | 기본값 | 뜻 | |---|---|---| -| `failure-rate-threshold` | `50` | Percent of failed calls in the window that opens the circuit, 1–100 | -| `minimum-number-of-calls` | `100` | Calls recorded before the rate is evaluated; at most `sliding-window-size` | -| `sliding-window-size` | `100` | The last N calls the rate is computed over (count-based) | -| `wait-duration-in-open-state` | `60s` | How long an open circuit rejects before trial calls; positive | -| `permitted-calls-in-half-open-state` | `10` | Trial calls while half-open; at least 1 | +| `failure-rate-threshold` | `50` | circuit을 여는, 창 안 실패 호출의 백분율. 1–100 | +| `minimum-number-of-calls` | `100` | 비율을 계산하기 전에 기록할 호출 수. `sliding-window-size` 이하 | +| `sliding-window-size` | `100` | 비율을 계산하는 최근 N개 호출(개수 기준) | +| `wait-duration-in-open-state` | `60s` | 열린 circuit이 시험 호출 전까지 거부하는 시간. 양수 | +| `permitted-calls-in-half-open-state` | `10` | half-open 동안의 시험 호출. 1 이상 | -An out-of-range value fails startup with `CIRCUIT_BREAKER_SETTING_INVALID`. The breaker belongs to -the profile, not to a runtime generation, so a certificate rotation keeps its state. +범위 밖 값은 `CIRCUIT_BREAKER_SETTING_INVALID`로 시작이 실패한다. breaker는 런타임 세대가 아니라 profile에 +속한다. 그래서 인증서를 교체해도 상태가 남는다. ### `redirect`, `request`, `response` -| Property | Default | Meaning | +| 속성 | 기본값 | 뜻 | |---|---|---| -| `redirect.enabled` | `false` | Engine redirect handling is always off; the platform follows hops itself | -| `redirect.max-hops` | `0` | Enabling redirects with zero hops is a configuration error | -| `redirect.allow-cross-origin` | `false` | When enabled, credentials are stripped on the hop | -| `request.max-body-bytes` | `0` | Required in production | +| `redirect.enabled` | `false` | 엔진의 redirect 처리는 늘 꺼져 있다. 플랫폼이 hop을 직접 따라간다 | +| `redirect.max-hops` | `0` | redirect를 켜고 hop을 0으로 두면 설정 오류다 | +| `redirect.allow-cross-origin` | `false` | 켜면 hop에서 credential을 지운다 | +| `request.max-body-bytes` | `0` | 운영에서 필수 | | `request.compression` | `false` | | -| `response.max-wire-bytes` | `5242880` | Bytes on the wire | -| `response.max-decoded-bytes` | `10485760` | Bytes after decoding; hard maximum is 64 MiB | -| `response.allowed-content-types` | JSON + problem+json | Empty means "any" | +| `response.max-wire-bytes` | `5242880` | wire 위의 바이트 | +| `response.max-decoded-bytes` | `10485760` | 디코딩한 뒤의 바이트. 넘을 수 없는 최대는 64 MiB | +| `response.allowed-content-types` | JSON + problem+json | 비어 있으면 「아무것이나」 | ### `authentication` -| Property | Default | Meaning | +| 속성 | 기본값 | 뜻 | |---|---|---| -| `type` | `NONE` | One of the design §20.1 methods | -| `registration-id` | — | Required for OAuth2 | -| `scopes` | empty | Part of the token cache key | -| `audience` | — | Part of the token cache key | -| `header-name` | — | Required for `API_KEY_HEADER`; must be on the allowlist | -| `secret-reference` | — | Resolved by the deployment's secret loader, never a literal | +| `type` | `NONE` | 설계서 §20.1의 방식 중 하나 | +| `registration-id` | — | OAuth2에 필수 | +| `scopes` | 비어 있음 | token cache key의 일부 | +| `audience` | — | token cache key의 일부 | +| `header-name` | — | `API_KEY_HEADER`에 필수. 허용 목록에 있어야 한다 | +| `secret-reference` | — | 배포의 secret loader가 푼다. 값을 그대로 쓰지 않는다 | ### `retry` -| Property | Default | Meaning | +| 속성 | 기본값 | 뜻 | |---|---|---| -| `policy` | `none` | Named policy for reporting | -| `max-attempts` | `1` | Attempts, not retries; at most 5 (`RETRY_MAX_ATTEMPTS_EXCEEDED`) | +| `policy` | `none` | 보고용 정책 이름 | +| `max-attempts` | `1` | 재시도 수가 아니라 시도 수. 최대 5(`RETRY_MAX_ATTEMPTS_EXCEEDED`) | | `base-backoff` | `50ms` | | | `max-backoff` | `200ms` | | | `jitter` | `FULL` | `NONE` \| `FULL` \| `DECORRELATED` | | `retry-after` | `HONOR` | `HONOR` \| `IGNORE` \| `CAP` | -| `budget` | — | Shared token bucket name. A retrying profile that names none gets its own bucket, with the same pool-derived capacity (`max-total-connections / 10`, at least 1, refilled each minute) | +| `budget` | — | 공유 token bucket 이름. 재시도하는 profile이 이름을 주지 않으면 자기 bucket을 받는다. 용량 계산은 같다(`max-total-connections / 10`, 최소 1, 1분마다 채움) | ### `tls` -| Property | Default | Meaning | +| 속성 | 기본값 | 뜻 | |---|---|---| -| `profile-id` | — | Required in production; the only TLS identifier the actuator exposes | -| `protocols` | `TLSv1.3, TLSv1.2` | Anything else is rejected | -| `hostname-verification` | `true` | Setting it false fails startup | -| `trust-all` | `false` | Exists only so the unsafe intent is rejectable; nothing acts on `true` | -| `allow-plain-http` | `false` | Plaintext fallback fails startup in production | -| `trust-material-reference` | — | Custom CA, resolved by the secret loader | -| `key-material-reference` | — | Client certificate for mTLS | +| `profile-id` | — | 운영에서 필수. actuator가 보여 주는 유일한 TLS 식별자 | +| `protocols` | `TLSv1.3, TLSv1.2` | 그 밖의 값은 거부한다 | +| `hostname-verification` | `true` | false로 두면 시작이 실패한다 | +| `trust-all` | `false` | 위험한 의도를 거부할 수 있게 하려고만 있다. `true`에 반응하는 것은 없다 | +| `allow-plain-http` | `false` | 평문으로 물러서기는 운영에서 시작을 실패시킨다 | +| `trust-material-reference` | — | 사설 CA. secret loader가 푼다 | +| `key-material-reference` | — | mTLS용 client 인증서 | -### `proxy` and `observability` +### `proxy`와 `observability` -| Property | Default | Meaning | +| 속성 | 기본값 | 뜻 | |---|---|---| | `proxy.enabled` | `false` | | | `proxy.host` / `proxy.port` / `proxy.type` | — / `0` / `HTTP` | | -| `proxy.credential-provider` | — | Proxy authentication is separate from target authentication | -| `proxy.import-ambient-no-proxy` | `false` | Ambient `NO_PROXY` never widens a validated profile | +| `proxy.credential-provider` | — | proxy 인증은 대상 인증과 따로다 | +| `proxy.import-ambient-no-proxy` | `false` | 환경의 `NO_PROXY`는 검증한 profile을 넓히지 않는다 | | `observability.full-url-recording` | `false` | | | `observability.body-logging` | `false` | | ## `app.httpclient.dynamic-targets[N]` -| Property | Default | Meaning | +| 속성 | 기본값 | 뜻 | |---|---|---| -| `name` | — | Required, unique, and subject to the same normalisation rule as a client name | +| `name` | — | 필수, 유일, client 이름과 같은 정규화 규칙 | | `allowed-schemes` | `https` | | | `allowed-ports` | `443` | | -| `allowed-host-suffixes` | empty | | -| `allowed-hosts` | empty | Empty means "any host that survives address validation" | -| `max-redirect-hops` | `0` | Each hop repeats the full validation flow | -| `trace-propagation` | `false` | Off by default for dynamic targets | -| `blocked-cidrs` | empty | Organisation-defined internal ranges | +| `allowed-host-suffixes` | 비어 있음 | | +| `allowed-hosts` | 비어 있음 | 비어 있으면 「주소 검증을 통과한 아무 host」 | +| `max-redirect-hops` | `0` | hop마다 검증 흐름 전체를 다시 돈다 | +| `trace-propagation` | `false` | dynamic target은 기본으로 끈다 | +| `blocked-cidrs` | 비어 있음 | 조직이 정한 내부 범위 | -## Startup violation codes +## 시작 위반 코드 `TRUSTED_BASE_URL_REQUIRED`, `BASE_URL_USERINFO_FORBIDDEN`, `BASE_URL_QUERY_FORBIDDEN`, `PLAINTEXT_PRODUCTION_TARGET`, `ALLOWED_HOST_MISMATCH`, `ALLOWED_PORT_MISMATCH`, @@ -259,36 +250,33 @@ the profile, not to a runtime generation, so a certificate rotation keeps its st `DNS_TIMEOUT_UNSUPPORTED`, `PROXY_CREDENTIAL_UNSUPPORTED`, `PROXY_AMBIENT_NO_PROXY_UNSUPPORTED`, `TIMEOUT_NOT_POSITIVE`, `RETRY_MAX_ATTEMPTS_EXCEEDED`, `CIRCUIT_BREAKER_SETTING_INVALID`. -A key that names no setting is not a violation code: the shared strict binder -(`adapter:outbound:support` `StrictSettingsBinder`) refuses it while binding, at any depth. Spring's -own unbound-key check stops at the first level under a list element, so `clients[0].timeout.` -used to bind nothing and fail nothing; the binder now refuses a key under `clients[N]` or -`dynamic-targets[N]` that bound nothing, for every capability rather than for this platform alone -(review 2026-11-01 05-15). The platform's own guard for it, and its `HTTPCLIENT_UNKNOWN_SETTING` -code, were removed with that change. +어떤 설정도 가리키지 않는 key는 위반 코드가 아니다. 공용 엄격 binder(`adapter:outbound:support` +`StrictSettingsBinder`)가 바인딩하면서 깊이와 상관없이 거부한다. Spring 자체의 바인딩 안 된 key 검사는 list 원소 +아래 첫 단계에서 멈춘다. 그래서 `clients[0].timeout.`는 아무것도 바인딩하지 않고 아무것도 실패시키지 +않았다. 이제 binder는 `clients[N]`이나 `dynamic-targets[N]` 아래에서 아무것도 바인딩하지 않은 key를 이 +플랫폼만이 아니라 모든 capability에서 거부한다(리뷰 2026-11-01 05-15). 그 변경과 함께 플랫폼 자체의 보호 장치와 +그 `HTTPCLIENT_UNKNOWN_SETTING` 코드는 지웠다. -`DNS_TIMEOUT_UNSUPPORTED`, `PROXY_CREDENTIAL_UNSUPPORTED` and `PROXY_AMBIENT_NO_PROXY_UNSUPPORTED` name settings the platform binds but cannot yet honour. Neither the Apache classic -client nor the JDK client exposes a DNS-resolution timeout, and no proxy-credential path exists, so -a non-default value is refused rather than accepted and ignored. Leaving the defaults alone is -unaffected — only a deliberate, unmet request fails. +`DNS_TIMEOUT_UNSUPPORTED`, `PROXY_CREDENTIAL_UNSUPPORTED`, `PROXY_AMBIENT_NO_PROXY_UNSUPPORTED`는 플랫폼이 +바인딩은 하지만 아직 지키지 못하는 설정을 가리킨다. Apache classic client도 JDK client도 DNS 풀기 timeout을 +내놓지 않고, proxy credential 경로도 없다. 그래서 기본값이 아닌 값은 받아들이고 무시하지 않고 거부한다. +기본값을 그대로 두면 영향이 없다. 의도했지만 지킬 수 없는 요청만 실패한다. -Three of these are about a guarantee that used to be silently unmet rather than refused: +아래 코드들은 예전에 거부하지 않고 조용히 지키지 못하던 보장에 관한 것이다. -- `HTTP2_REQUIRED_TRANSPORT_UNSUPPORTED` — declaring `protocols: [HTTP_2]` alone states that HTTP/2 - is required. No transport can be configured to offer H2 and nothing else; the JDK client treats it - as a preference and negotiates HTTP/1.1, and Apache's classic client is HTTP/1.1 only. -- `POOL_ROUTE_EXCEEDS_TOTAL` — a per-route ceiling above the total is incoherent. -- `TLS_PROTOCOL_SET_REQUIRED` — an empty `tls.protocols` used to pass and then let the JVM choose, - so emptying the list to "tighten" a profile loosened it. -- `RETRY_POLICY_CONTRADICTS_ATTEMPTS` — `retry.policy` was read by nothing on the execution path, so - the actuator could report `none` for a profile retrying three times. The two settings must now - agree: `policy: none` requires `max-attempts: 1`, and any other policy requires more than one. -- `FULL_URL_RECORDING_FORBIDDEN` / `BODY_LOGGING_FORBIDDEN` — both settings were bindable and inert. - Recording an expanded URL puts path identifiers and query strings into unbounded metric tags; - recording bodies puts someone else's data into logs. Representable so the intent is rejectable, - refused under a production profile. +- `HTTP2_REQUIRED_TRANSPORT_UNSUPPORTED` — `protocols: [HTTP_2]`만 선언하면 HTTP/2가 필수라는 뜻이다. H2만 + 제공하도록 설정할 수 있는 transport는 없다. JDK client는 그것을 선호로 다루고 HTTP/1.1로 협상하고, Apache의 + classic client는 HTTP/1.1만 한다. +- `POOL_ROUTE_EXCEEDS_TOTAL` — route별 상한이 전체보다 크면 앞뒤가 맞지 않는다. +- `TLS_PROTOCOL_SET_REQUIRED` — 빈 `tls.protocols`가 예전에는 통과해서 JVM이 고르게 두었다. 그래서 profile을 + 「조이려고」 목록을 비우면 오히려 풀렸다. +- `RETRY_POLICY_CONTRADICTS_ATTEMPTS` — 실행 경로의 어느 것도 `retry.policy`를 읽지 않았다. 그래서 세 번 + 재시도하는 profile에 대해 actuator가 `none`을 보고할 수 있었다. 이제 두 설정이 맞아야 한다. `policy: none`은 + `max-attempts: 1`을 요구하고, 다른 정책은 1보다 큰 값을 요구한다. +- `FULL_URL_RECORDING_FORBIDDEN` / `BODY_LOGGING_FORBIDDEN` — 두 설정은 바인딩은 됐지만 아무 효과가 없었다. + 펼친 URL을 기록하면 경로 식별자와 query string이 상한 없는 metric tag에 들어가고, 본문을 기록하면 남의 데이터가 + 로그에 들어간다. 의도를 거부할 수 있게 표현만 해 두고, 운영 profile에서는 거부한다. -`DYNAMIC_TARGET_PROXY_UNSUPPORTED` is worth spelling out: a forward proxy resolves the hostname on -its own side, so the addresses this platform validated and pinned are not the addresses the -connection reaches. The SSRF defence would be present, correct, and bypassed — so the combination is -refused rather than served with a guarantee it cannot keep. +`DYNAMIC_TARGET_PROXY_UNSUPPORTED`는 따로 설명할 만하다. forward proxy는 hostname을 자기 쪽에서 푼다. 그래서 +이 플랫폼이 검증하고 고정한 주소가 연결이 실제로 닿는 주소가 아니다. SSRF 방어는 있고 맞지만 우회된다. 그래서 +이 조합은 지킬 수 없는 보장을 단 채 내주지 않고 거부한다. diff --git a/docs/httpclient/env-fields.yaml b/docs/httpclient/env-fields.yaml index b8ecbf59..f10d483e 100644 --- a/docs/httpclient/env-fields.yaml +++ b/docs/httpclient/env-fields.yaml @@ -1,29 +1,27 @@ -# HTTP Client platform — Java field path to environment variable template. +# HTTP Client 플랫폼 — Java 필드 경로에서 환경 변수 template로의 대응. # -# The SSOT is HttpClientPlatformSettings. HttpClientPlatformEnvManifestTest derives this list from -# the record tree and fails when the two disagree in either direction, and the shared strict binder -# refuses to start on an APP_HTTPCLIENT_ variable that names no field. So a -# field added with no entry, an entry whose field was renamed, and a misspelled variable in a -# deployment are all failures rather than silence. +# 정본은 HttpClientPlatformSettings다. HttpClientPlatformEnvManifestTest가 record 트리에서 이 목록을 만들어 +# 양쪽 방향으로 어긋나면 실패하고, 공용 엄격 binder는 어떤 필드도 가리키지 않는 APP_HTTPCLIENT_ 변수가 +# 있으면 시작을 거부한다. 그래서 항목 없이 더한 필드, 필드 이름이 바뀐 항목, 배포의 오타 변수가 모두 +# 조용히 넘어가지 않고 실패한다. # -# `N` and `M` are list indices, not literals: `N` for the outermost list, `M` for a list inside it. -# `app.httpclient.clients[N].base-url` is set as APP_HTTPCLIENT_CLIENTS_0_BASE_URL for the first -# client, and `clients[N].allowed-hosts[M]` as APP_HTTPCLIENT_CLIENTS_0_ALLOWED_HOSTS_0. +# `N`과 `M`은 글자 그대로가 아니라 list index다. `N`은 바깥 list, `M`은 그 안의 list다. +# 첫 client의 `app.httpclient.clients[N].base-url`은 APP_HTTPCLIENT_CLIENTS_0_BASE_URL로, +# `clients[N].allowed-hosts[M]`은 APP_HTTPCLIENT_CLIENTS_0_ALLOWED_HOSTS_0으로 준다. # -# Only APP_HTTPCLIENT_ENABLED is registered in docs/registries/env-keys.yaml and shipped in -# src/.env: it is the only key with a deployment-independent value, and it is the only one the -# three-way :app-bootstrap:verifyEnvKeys gate can express. Everything below is per deployment and is set directly -# in the environment — templating an indexed client in application.yml would materialise a nameless -# client in every deployment, which the settings' aggregate validation refuses. +# docs/registries/env-keys.yaml에 등록하고 src/.env에 담는 것은 APP_HTTPCLIENT_ENABLED뿐이다. 배포와 +# 상관없는 값을 가진 유일한 key이고, 세 방향을 대조하는 :app-bootstrap:verifyEnvKeys 게이트가 표현할 수 +# 있는 유일한 key다. 아래 나머지는 모두 배포마다 다르고 환경에 직접 준다. index를 단 client를 +# application.yml에 template로 두면 모든 배포에 이름 없는 client가 생기고, settings의 묶음 검증이 그것을 +# 거부한다. # -# This file lives beside the HTTP Client documentation rather than in docs/registries, which is a -# fail-closed catalog of exactly eight contract registries with a fixed row schema -# (owner_branch/compatibility_impact/required_test per row). A field-to-variable mapping does not -# have that shape, and admitting it would have meant loosening a gate rather than satisfying one. +# 이 파일은 docs/registries가 아니라 HTTP Client 문서 옆에 있다. docs/registries는 행 schema +# (행마다 owner_branch/compatibility_impact/required_test)가 고정된 계약 registry만 받는, 닫힌 쪽으로 +# 실패하는 목록이다. 필드-변수 대응은 그 모양이 아니고, 받아들이려면 게이트를 맞추는 대신 풀어야 했다. # -# Secrets are referenced, never carried: authentication.secret-reference, tls.*-material-reference -# and proxy.credential-provider name material that a secret backend resolves. Putting the material -# itself in one of these variables defeats the indirection they exist for. +# secret은 값이 아니라 참조로 준다. authentication.secret-reference, tls.*-material-reference, +# proxy.credential-provider는 secret backend가 푸는 재료의 이름이다. 재료 자체를 이 변수에 넣으면 +# 이 변수들이 있는 이유인 간접화가 무너진다. fields: - field: enabled env: APP_HTTPCLIENT_ENABLED diff --git a/docs/httpclient/operations.md b/docs/httpclient/operations.md index bf95cfae..f19f8754 100644 --- a/docs/httpclient/operations.md +++ b/docs/httpclient/operations.md @@ -1,129 +1,123 @@ -# HTTP Client Platform — Operations Runbook +# HTTP Client 플랫폼 — 운영 runbook -## Metrics +## Metric -| Metric | Meaning | +| Metric | 뜻 | |---|---| -| `http.client.requests` | Physical attempt timer (Spring standard name, kept deliberately) | -| `http.client.logical.calls` | User-visible logical call timer | -| `http.client.attempts` | Attempt counter | -| `http.client.retry.count` | Retries by reason | -| `http.client.retry.exhausted` | Retry budget exhausted | -| `http.client.ambiguous` | Ambiguous outcomes | -| `http.client.timeout` | Timeouts by stage | -| `http.client.request.bytes` | Request wire bytes | -| `http.client.response.bytes` | Response bytes | -| `http.client.active` | In-flight attempts | -| `http.client.pool.connections` | Leased and available connections | -| `http.client.pool.pending` | Pool waiters | -| `http.client.pool.acquire.duration` | Pool wait time | -| `http.client.dns.duration` | DNS time | -| `http.client.connect.duration` | Connect time | -| `http.client.tls.duration` | TLS time | -| `http.client.circuit.state` | Circuit state | -| `http.client.bulkhead.rejected` | Bulkhead rejections | -| `http.client.rate_limit.rejected` | Local rate-limit rejections | -| `http.client.oauth.refresh` | Token refresh outcomes | -| `http.client.ssrf.rejected` | Dynamic target rejections | +| `http.client.requests` | 물리 시도 timer(Spring 표준 이름. 일부러 그대로 둔다) | +| `http.client.logical.calls` | 사용자에게 보이는 논리 호출 timer | +| `http.client.attempts` | 시도 counter | +| `http.client.retry.count` | 이유별 재시도 | +| `http.client.retry.exhausted` | 재시도 예산 소진 | +| `http.client.ambiguous` | 결과를 모르는 경우 | +| `http.client.timeout` | 단계별 시간 초과 | +| `http.client.request.bytes` | 요청 wire 바이트 | +| `http.client.response.bytes` | 응답 바이트 | +| `http.client.active` | 진행 중인 시도 | +| `http.client.pool.connections` | 빌려 간 connection과 남은 connection | +| `http.client.pool.pending` | pool 대기자 | +| `http.client.pool.acquire.duration` | pool 대기 시간 | +| `http.client.dns.duration` | DNS 시간 | +| `http.client.connect.duration` | 연결 시간 | +| `http.client.tls.duration` | TLS 시간 | +| `http.client.circuit.state` | circuit 상태 | +| `http.client.bulkhead.rejected` | bulkhead 거부 | +| `http.client.rate_limit.rejected` | 로컬 속도 제한 거부 | +| `http.client.oauth.refresh` | token 갱신 결과 | +| `http.client.ssrf.rejected` | dynamic target 거부 | -`http.client.requests` counts attempts and `http.client.logical.calls` counts user calls. When they -diverge, retries are absorbing failures — which is the first thing to look at during an incident. +`http.client.requests`는 시도를 세고 `http.client.logical.calls`는 사용자 호출을 센다. 둘이 벌어지면 재시도가 +실패를 흡수하고 있다는 뜻이다. 장애 때 가장 먼저 볼 곳이다. -## Reading an incident +## 장애 읽기 -| Symptom | Likely cause | Where to look | +| 증상 | 그럴듯한 원인 | 볼 곳 | |---|---|---| -| logical calls fine, attempts spiking | upstream degraded, retries absorbing it | `http.client.retry.count` by reason | -| `http.client.ambiguous` non-zero | non-idempotent writes reaching `SENT_NO_RESPONSE` | reconcile with the upstream; consider an idempotency key | -| pool pending climbing | pool too small or upstream slow | `http.client.pool.acquire.duration`, `pool.connections` | -| circuit open | sustained upstream failure: transport errors, 5xx, 408, 429 | `http.client.circuit.state`; local rejections and other 4xx do not open it | -| `http.client.ssrf.rejected` non-zero | a caller is submitting internal URLs | Dynamic Target policy and audit trail | +| 논리 호출은 괜찮은데 시도가 치솟는다 | upstream이 나빠졌고 재시도가 흡수하고 있다 | 이유별 `http.client.retry.count` | +| `http.client.ambiguous`가 0이 아니다 | 멱등이 아닌 쓰기가 `SENT_NO_RESPONSE`에 닿는다 | upstream과 맞춰 본다. 멱등 key를 검토한다 | +| pool 대기가 오른다 | pool이 작거나 upstream이 느리다 | `http.client.pool.acquire.duration`, `pool.connections` | +| circuit이 열렸다 | 계속된 upstream 실패: transport 오류, 5xx, 408, 429 | `http.client.circuit.state`. 로컬 거부와 그 밖의 4xx는 circuit을 열지 않는다 | +| `http.client.ssrf.rejected`가 0이 아니다 | 호출자가 내부 URL을 넣고 있다 | Dynamic Target 정책과 감사 기록 | ## Actuator -`GET /actuator/httpclients` reports profile name, runtime generation, state, transport, API, -protocols, active leases, pool ceiling, credential type, TLS profile id, redirect flag, retry policy, -and capability warnings. Base URL, credentials, trust store paths, and resolved IPs are deliberately -absent: an actuator endpoint is reachable by more people than a secret store is. +`GET /actuator/httpclients`는 profile 이름, 런타임 세대, 상태, transport, API, protocol, 진행 중인 lease, pool +상한, credential 유형, TLS profile id, redirect flag, 재시도 정책, capability 경고를 보고한다. Base URL, credential, +trust store 경로, 푼 IP는 일부러 뺐다. actuator endpoint에는 secret 저장소보다 많은 사람이 닿는다. -## Rotation +## 교체 -Certificates and secrets rotate by building a new runtime generation and swapping the registry -pointer, never by mutating a live client. A connection pool holds sockets established under the -previous identity, so replacing material without replacing the pool leaves live connections -authenticated by a certificate that is meant to be gone. +인증서와 secret은 살아 있는 client를 바꾸지 않고, 새 런타임 세대를 만들어 registry pointer를 바꿔 끼우는 식으로 +교체한다. connection pool은 앞 신원으로 맺은 socket을 쥐고 있다. 그래서 pool은 그대로 두고 재료만 바꾸면, 없어져야 +할 인증서로 인증한 connection이 살아 있다. ```text -build new generation → validate → atomic swap → new calls use it -old generation → DRAINING → in-flight calls finish → no new retries → forced close at the drain deadline +새 세대 만들기 → 검증 → 원자적 교체 → 새 호출이 그것을 쓴다 +옛 세대 → DRAINING → 진행 중인 호출이 끝난다 → 새 재시도 없음 → drain 기한에 강제로 닫는다 ``` -## Shutdown +## 종료 ```text RUNNING → DRAINING -new logical calls refused or routed to the new generation -in-flight attempts complete -new retries refused -shutdown timeout -remaining calls cancelled -pool closed +새 논리 호출을 거부하거나 새 세대로 보낸다 +진행 중인 시도가 끝난다 +새 재시도를 거부한다 +종료 시간 초과 +남은 호출을 취소한다 +pool을 닫는다 ``` -## Retry ownership +## 재시도 소유 -Exactly one of the application client, an external SDK, or the service mesh may own retries. -Two owners multiply traffic during an incident. Record the owner per upstream and check it whenever -a mesh retry policy changes. +애플리케이션 client, 외부 SDK, service mesh 중 정확히 하나만 재시도를 가진다. 소유자가 둘이면 장애 중에 트래픽이 +곱절로 는다. upstream마다 소유자를 적고, mesh 재시도 정책이 바뀔 때마다 확인한다. -## Error model +## 오류 모델 -Every outbound failure is one of these stable types. The type is derived from the classified failure -category, not from whatever the engine happened to throw, so it means the same thing on Apache and -JDK. Each carries `HttpFailureMetadata`: client, operation, method, URI **template**, -evidence, replayability, stage, retryability, attempt, elapsed, remaining deadline, status, trace id -— and nothing else. +모든 외부 호출 실패는 아래 안정된 타입 중 하나다. 타입은 엔진이 마침 던진 것이 아니라 분류한 실패 범주에서 +정한다. 그래서 Apache와 JDK에서 같은 뜻이다. 모두 `HttpFailureMetadata`를 가진다: client, 연산, method, URI +**template**, 증거, 재전송 가능성, 단계, 재시도 가능 여부, 시도 번호, 흐른 시간, 남은 기한, 상태, trace id. +그 밖의 것은 없다. -| Exception | Raised when | Retryable | +| 예외 | 던지는 때 | 재시도 | |---|---|---| -| `HttpConfigurationException` | profile, operation, or capability configuration is invalid | never | -| `HttpTargetRejectedException` | target URI, host, port, header, or address policy refused the request | never | -| `HttpDnsException` | hostname resolution failed or timed out | yes, inside budget | -| `HttpPoolAcquireTimeoutException` | no connection or stream within the pending-acquire budget | yes, inside budget | -| `HttpConnectException` | socket connect failed | yes, inside budget | -| `HttpProxyException` | proxy connect, CONNECT tunnel, or proxy auth failed | yes, inside budget | -| `HttpTlsException` | TLS handshake failed | only a transient handshake timeout | -| `HttpRequestWriteException` | request headers or body could not be fully written | only when safely idempotent | -| `HttpResponseTimeoutException` | final headers or a body chunk did not arrive in time | only when safely idempotent | -| `HttpResponseTruncatedException` | the response ended before the body was complete | only when safely idempotent and undelivered | -| `HttpRemoteErrorException` | non-success status without a problem document | per the status rules | -| `HttpProblemDetailException` | non-success status with a bounded RFC 9457 document | per the status rules | -| `HttpRedirectRejectedException` | a hop violated hop count, origin, method, or replay policy | never | -| `HttpAuthenticationException` | credential materialization or refresh failed | never | -| `HttpSerializationException` | request encoding or response decoding failed | never | -| `HttpResponseTooLargeException` | wire or decoded bytes exceeded the profile limit | never | -| `HttpDeadlineExceededException` | the effective deadline was reached | never | -| `HttpCircuitOpenException` | the upstream circuit is open | never | -| `HttpBulkheadRejectedException` | no attempt or logical admission permit was available | never | -| `HttpRateLimitRejectedException` | the local attempt rate limiter rejected the attempt | never | -| `HttpRetryBudgetExhaustedException` | the per-upstream retry budget refused a further attempt | never | -| `HttpRuntimeDrainingException` | the profile's runtime was retired (certificate rotation) before a granted retry started | never — a new call runs on the replacement | -| `HttpUnknownTransportException` | the engine failed in a way no category above describes; the metadata evidence, not the type, says whether it was sent | never | -| `HttpAmbiguousExecutionException` | a non-idempotent request was sent and the outcome is unknown | never — reconcile instead | +| `HttpConfigurationException` | profile, 연산, capability 설정이 잘못됐다 | 안 함 | +| `HttpTargetRejectedException` | 대상 URI, host, port, 헤더, 주소 정책이 요청을 거부했다 | 안 함 | +| `HttpDnsException` | hostname 풀기가 실패하거나 시간이 넘었다 | 예산 안에서 함 | +| `HttpPoolAcquireTimeoutException` | 대기 예산 안에 connection이나 stream을 얻지 못했다 | 예산 안에서 함 | +| `HttpConnectException` | socket 연결이 실패했다 | 예산 안에서 함 | +| `HttpProxyException` | proxy 연결, CONNECT tunnel, proxy 인증이 실패했다 | 예산 안에서 함 | +| `HttpTlsException` | TLS handshake가 실패했다 | 일시적인 handshake 시간 초과만 | +| `HttpRequestWriteException` | 요청 헤더나 본문을 다 쓰지 못했다 | 안전하게 멱등일 때만 | +| `HttpResponseTimeoutException` | 최종 헤더나 본문 chunk가 제때 오지 않았다 | 안전하게 멱등일 때만 | +| `HttpResponseTruncatedException` | 본문이 끝나기 전에 응답이 끝났다 | 안전하게 멱등이고 아직 넘기지 않았을 때만 | +| `HttpRemoteErrorException` | problem document 없는 실패 상태 | 상태 규칙대로 | +| `HttpProblemDetailException` | 크기가 제한된 RFC 9457 document가 있는 실패 상태 | 상태 규칙대로 | +| `HttpRedirectRejectedException` | hop이 hop 수, origin, method, 재전송 정책을 어겼다 | 안 함 | +| `HttpAuthenticationException` | credential 만들기나 갱신이 실패했다 | 안 함 | +| `HttpSerializationException` | 요청 인코딩이나 응답 디코딩이 실패했다 | 안 함 | +| `HttpResponseTooLargeException` | wire나 디코딩한 바이트가 profile 한도를 넘었다 | 안 함 | +| `HttpDeadlineExceededException` | 실제 기한에 닿았다 | 안 함 | +| `HttpCircuitOpenException` | upstream circuit이 열렸다 | 안 함 | +| `HttpBulkheadRejectedException` | 시도나 논리 허가를 얻지 못했다 | 안 함 | +| `HttpRateLimitRejectedException` | 로컬 시도 속도 제한이 시도를 거부했다 | 안 함 | +| `HttpRetryBudgetExhaustedException` | upstream별 재시도 예산이 다음 시도를 거부했다 | 안 함 | +| `HttpRuntimeDrainingException` | 허락한 재시도가 시작되기 전에 profile 런타임이 내려갔다(인증서 교체) | 안 함 — 새 호출은 바뀐 런타임에서 돈다 | +| `HttpUnknownTransportException` | 위 범주 어느 것도 설명하지 못하는 방식으로 엔진이 실패했다. 보냈는지는 타입이 아니라 metadata의 증거가 말한다 | 안 함 | +| `HttpAmbiguousExecutionException` | 멱등이 아닌 요청을 보냈고 결과를 모른다 | 안 함 — 대신 맞춰 본다 | -A streamed body that fails after hand-over is the one place these arrive wrapped: `read` throws -`HttpBodyReadException`, an `IOException` as `InputStream` promises, and its `failure()` is the -`HttpResponseTimeoutException` or `HttpResponseTruncatedException` above (re-review 2026-11-04 -RR-03-14). +이 예외들이 감싸져서 오는 곳은 하나다. 넘긴 뒤 실패한 스트리밍 본문이다. `read`가 `HttpBodyReadException`을 +던진다. `InputStream`이 약속한 대로 `IOException`이고, 그 `failure()`가 위의 `HttpResponseTimeoutException`이나 +`HttpResponseTruncatedException`이다(재리뷰 2026-11-04 RR-03-14). -## Traces +## Trace ```text -http.client.operation logical internal span -└─ http.client.request attempt 1 CLIENT span -└─ http.client.request attempt 2 CLIENT span +http.client.operation 논리 호출의 내부 span +└─ http.client.request 시도 1의 CLIENT span +└─ http.client.request 시도 2의 CLIENT span ``` -W3C Trace Context is propagated with a Baggage allowlist. Dynamic Targets do not propagate trace -context by default. Retry reason and evidence are recorded as span events; credentials and remote -error bodies are never recorded as attributes. +W3C Trace Context를 Baggage 허용 목록과 함께 전파한다. Dynamic Target은 기본으로 trace context를 전파하지 +않는다. 재시도 이유와 증거는 span event로 기록한다. credential과 원격 오류 본문은 절대 속성으로 기록하지 않는다. diff --git a/docs/httpclient/performance-baseline.md b/docs/httpclient/performance-baseline.md index 0a1ee87e..ea6a387b 100644 --- a/docs/httpclient/performance-baseline.md +++ b/docs/httpclient/performance-baseline.md @@ -1,55 +1,51 @@ -# HTTP Client Platform — Performance Baseline +# HTTP Client 플랫폼 — 성능 기준선 -The certification lane asserts **resource bounds**, not throughput targets. Its purpose is to prove -that a failing upstream, a large body, or a rotation cannot consume unbounded memory, connections, -threads, or upstream traffic. Nothing here becomes a runtime adaptive default: every bound comes -from an explicit profile setting. +인증 lane은 처리량 목표가 아니라 **자원 상한**을 단언한다. 실패하는 upstream, 큰 본문, 교체가 메모리, connection, +스레드, upstream 트래픽을 끝없이 먹지 못함을 증명하려는 것이다. 여기 있는 어떤 것도 실행 중 적응형 기본값이 되지 +않는다. 모든 상한은 profile에 명시한 설정에서 온다. -## How to run +## 돌리는 법 ```bash -# every bound, structural and machine-dependent +# 모든 상한: 구조적 상한과 기계에 따른 상한 ./gradlew :adapter:outbound:httpclient:httpClientPerformanceTest --console=plain -# JMH benchmarks: numbers only, never a gate +# JMH benchmark: 숫자만 낸다. 게이트가 아니다 ./gradlew :adapter:outbound:httpclient:jmh --console=plain ``` -The lane asserts every bound in every run. There is no switch that turns the machine-dependent one -off: the strict-lane convention fails a performance lane before it runs when the build sets -`performance.assertions.enabled` to anything but `true`, and fails it when one of its tests is -skipped. The same command is what `integration-main.yml` (`:performanceCheck`) and `release.yml` -run. Every run prints the measured heap increase (`[httpclient-performance] streaming download heap -increase … bytes, bound … bytes`) to the test output and report, and a bound that fails repeats the -value in its assertion message; for numbers without a verdict, use JMH. +lane은 매번 모든 상한을 단언한다. 기계에 따라 다른 상한을 끄는 스위치는 없다. 빌드가 +`performance.assertions.enabled`에 `true` 아닌 값을 넣으면 strict lane convention이 성능 lane을 돌기 전에 실패시키고, +테스트 하나라도 건너뛰면 실패시킨다. `integration-main.yml`(`:performanceCheck`)과 `release.yml`이 도는 것도 같은 +명령이다. 매번 잰 heap 증가량(`[httpclient-performance] streaming download heap increase … bytes, bound … bytes`)을 +테스트 출력과 보고서에 찍고, 실패한 상한은 단언 메시지에 그 값을 다시 적는다. 판정 없는 숫자가 필요하면 JMH를 쓴다. -## Certified bounds +## 인증한 상한 -| Test | Bound | Kind | +| 테스트 | 상한 | 종류 | |---|---|---| -| `RetryStormBudgetTest` | 10 000 logical calls against a failing upstream produce at most 11 000 physical attempts at a 10 % budget | structural | -| `LargeBodyResourceTest` | a 32 MiB streaming download consumes every byte without buffering the payload on the heap | structural + machine-dependent heap bound | -| `PoolSaturationPerformanceTest` | 24 concurrent calls against a 4-connection pool all reach a terminal outcome; none hang | structural | -| `OAuthRefreshContentionTest` | 100 genuinely concurrent callers produce exactly one token request | structural | -| `RuntimeRotationDrainTest` | 50 rotations close all 50 retired generations and leave no drain thread | structural | +| `RetryStormBudgetTest` | 실패하는 upstream에 대한 논리 호출 10 000개가 10 % 예산에서 물리 시도를 최대 11 000개 만든다 | 구조적 | +| `LargeBodyResourceTest` | 32 MiB 스트리밍 다운로드가 payload를 heap에 버퍼링하지 않고 모든 바이트를 읽는다 | 구조적 + 기계에 따른 heap 상한 | +| `PoolSaturationPerformanceTest` | connection 4개짜리 pool에 대한 동시 호출 24개가 모두 끝 상태에 닿는다. 멈춘 것이 없다 | 구조적 | +| `OAuthRefreshContentionTest` | 정말 동시에 부르는 호출자 100개가 token 요청을 정확히 하나 만든다 | 구조적 | +| `RuntimeRotationDrainTest` | 교체 50번이 내린 세대 50개를 모두 닫고 drain 스레드를 남기지 않는다 | 구조적 | -## Recording a baseline +## 기준선 기록하기 -When certifying a deployment, record alongside the numbers: the exact command, the commit, hardware, -JVM flags, the profile YAML under test, p50/p95/p99/max, peak heap, peak direct memory, thread count, -connection count, physical attempt count, and error count. A latency figure without its profile and -hardware is not a baseline; it is an anecdote. +배포를 인증할 때는 숫자와 함께 이것을 적는다: 정확한 명령, commit, 하드웨어, JVM flag, 시험한 profile YAML, +p50/p95/p99/max, 최대 heap, 최대 direct memory, 스레드 수, connection 수, 물리 시도 수, 오류 수. profile과 +하드웨어 없는 지연 숫자는 기준선이 아니라 일화다. -| Field | Value | +| 항목 | 값 | |---|---| -| Command | _fill in at certification time_ | -| Commit | _fill in_ | -| Hardware / JVM | _fill in_ | -| Profile under test | _fill in_ | -| p50 / p95 / p99 / max | _fill in_ | -| Peak heap / direct memory | _fill in_ | -| Threads / connections | _fill in_ | -| Physical attempts / errors | _fill in_ | +| 명령 | _인증할 때 채운다_ | +| Commit | _채운다_ | +| 하드웨어 / JVM | _채운다_ | +| 시험한 profile | _채운다_ | +| p50 / p95 / p99 / max | _채운다_ | +| 최대 heap / direct memory | _채운다_ | +| 스레드 / connection | _채운다_ | +| 물리 시도 / 오류 | _채운다_ | -The table is intentionally left unfilled in the repository: publishing numbers measured on a build -agent as if they were a certified baseline would be worse than having none. +이 표는 저장소에서 일부러 비워 둔다. 빌드 agent에서 잰 숫자를 인증한 기준선처럼 내놓는 것은 기준선이 없는 +것보다 나쁘다. diff --git a/docs/httpclient/release-checklist.md b/docs/httpclient/release-checklist.md index a11e0f7f..f4de1284 100644 --- a/docs/httpclient/release-checklist.md +++ b/docs/httpclient/release-checklist.md @@ -1,8 +1,8 @@ -# HTTP Client Platform — Release Checklist +# HTTP Client 플랫폼 — 릴리스 점검표 -A release is complete when each item below is demonstrated by a command, not by review. +아래 항목마다 검토가 아니라 명령으로 보여 줬을 때 릴리스가 끝난다. -## Gates +## 게이트 ```bash cd src @@ -11,34 +11,33 @@ cd src ./gradlew :adapter:outbound:httpclient:httpClientSecurityTest --console=plain ./gradlew :adapter:outbound:httpclient:spring62ApiSurfaceScan --console=plain ./gradlew :adapter:outbound:httpclient:spring70CompatibilityTest --console=plain -./gradlew :adapter:outbound:httpclient:httpClientFailureInjectionTest --console=plain # needs Docker -./gradlew :adapter:outbound:httpclient:httpClientPerformanceTest --console=plain # every bound asserted +./gradlew :adapter:outbound:httpclient:httpClientFailureInjectionTest --console=plain # Docker 필요 +./gradlew :adapter:outbound:httpclient:httpClientPerformanceTest --console=plain # 모든 상한을 단언 ./gradlew verifyCleanArchitectureDependencies --console=plain ./gradlew :app-bootstrap:architectureTest --console=plain python3 ../scripts/verify-httpclient-docs.py ``` -## Completion criteria (design §33) +## 완료 기준 (설계서 §33) -- [ ] Typed clients are the default entry point; H2 and H3 are separately authorised. -- [ ] H1–H4 cannot bypass timeout, host, TLS, auth, size, or observation policy. -- [ ] Apache and JDK produce identical result and exception metadata. -- [ ] Pool, DNS, connect, TLS, and retry backoff all fit inside the effective deadline. -- [ ] Every extra attempt is explained by idempotency, replayability, evidence, deadline, and budget. -- [ ] Non-idempotent `SENT_NO_RESPONSE` surfaces as `HttpAmbiguousExecutionException`. -- [ ] Pool and buffers are reclaimed after unread bodies, decode errors, cancels, and size rejections. -- [ ] OAuth2 refresh is single-flight and 401 replay happens at most once. -- [ ] Trust-all and hostname-verification bypass fail at startup. -- [ ] Canonicalisation, DNS/IP validation, redirect revalidation, and egress control all pass. -- [ ] No transparent retry occurs after the first delivered byte. -- [ ] The negotiated wire protocol matches what the support matrix claims per transport. -- [ ] Logical calls and attempts are separate metrics with no forbidden label. -- [ ] DNS, pool, TLS, reset, partial response, and HTTP/2 GOAWAY are reproducible. -- [ ] Thread, heap, direct memory, pool, and retry budget bounds hold. -- [ ] The support matrix, configuration reference, security guide and runbook match the code. +- [ ] 타입 있는 client가 기본 진입점이다. H2와 H3은 따로 허가한다. +- [ ] H1–H4는 timeout, host, TLS, 인증, 크기, 관측 정책을 우회할 수 없다. +- [ ] Apache와 JDK가 같은 결과와 예외 metadata를 낸다. +- [ ] pool, DNS, 연결, TLS, 재시도 backoff가 모두 실제 기한 안에 들어간다. +- [ ] 추가 시도마다 멱등성, 재전송 가능성, 증거, 기한, 예산으로 설명된다. +- [ ] 멱등이 아닌 `SENT_NO_RESPONSE`는 `HttpAmbiguousExecutionException`으로 드러난다. +- [ ] 읽지 않은 본문, 디코딩 오류, 취소, 크기 거부 뒤에 pool과 buffer를 되찾는다. +- [ ] OAuth2 갱신은 한 번만 날아가고, 401 재전송은 많아야 한 번이다. +- [ ] trust-all과 hostname 검증 우회는 시작 때 실패한다. +- [ ] 정규화, DNS/IP 검증, redirect 재검증, egress 통제가 모두 통과한다. +- [ ] 첫 바이트를 넘긴 뒤에는 투명한 재시도가 일어나지 않는다. +- [ ] 협상한 wire protocol이 support matrix가 transport마다 주장하는 것과 맞는다. +- [ ] 논리 호출과 시도는 따로 된 metric이고 금지 label이 없다. +- [ ] DNS, pool, TLS, reset, 부분 응답, HTTP/2 GOAWAY를 재현할 수 있다. +- [ ] 스레드, heap, direct memory, pool, 재시도 예산 상한이 지켜진다. +- [ ] support matrix, 설정 참조, 보안 안내, runbook이 코드와 맞는다. ## Experimental -Jetty HTTP/3 stays Experimental until `Http3CapabilityReport` reports QUIC and TLS 1.3 and the -contract subset it declares passes in a dedicated environment. It is never auto-configured by the -Stable starter. +Jetty HTTP/3은 `Http3CapabilityReport`가 QUIC와 TLS 1.3을 보고하고, 그것이 선언한 계약 부분집합이 전용 환경에서 +통과할 때까지 Experimental로 남는다. Stable starter가 자동 구성하는 일은 없다. diff --git a/docs/httpclient/repository-adaptation.md b/docs/httpclient/repository-adaptation.md index 4b7c9476..fbd7d5b9 100644 --- a/docs/httpclient/repository-adaptation.md +++ b/docs/httpclient/repository-adaptation.md @@ -1,44 +1,43 @@ -# HTTP Client Platform — Repository Adaptation Contract +# HTTP Client 플랫폼 — 저장소 적응 계약 -**Design source:** `docs/design/2026-08-08-httpclient-platform-design.md` -**Plan source:** `docs/history/plans/2026-08-08-httpclient-platform-implementation-plan.md` +**설계서:** `docs/design/2026-08-08-httpclient-platform-design.md` +**계획서:** `docs/history/plans/2026-08-08-httpclient-platform-implementation-plan.md` -The design package states its own adaptation rule: +설계 패키지는 자기 적응 규칙을 스스로 밝힌다. > 실제 Backend Skeleton 저장소가 제공되지 않았으므로 package 경로와 Gradle 구조는 설계서의 명시적 > 구현 가정이다. 구현 전 저장소의 기존 convention과 root package에 맞춰 경로만 조정하고 공개 계약과 > 정책 의미론은 유지한다. -This file is the single record of *how* the design's assumed layout was mapped onto this repository. -Only paths, build DSL, and composition-root ownership changed. Public contracts, policy order, and -error semantics are implemented exactly as specified. +이 파일은 설계가 가정한 배치를 이 저장소에 *어떻게* 옮겼는지 적은 유일한 기록이다. 바뀐 것은 경로, 빌드 DSL, +조립 루트의 소유뿐이다. 공개 계약, 정책 순서, 오류 의미는 명세대로 구현했다. -## 1. Why the module layout differs +## 1. 모듈 배치가 다른 이유 -The design assumes a greenfield library with 19 Gradle projects under `modules/httpclient/`. -This repository is a Clean Architecture template whose **fail-closed registry** -(`src/config/architecture/modules.json`, enforced by `src/settings.gradle` and -`verifyCleanArchitectureDependencies`) declares **exactly 19 leaf identities**. Creating 19 more -Gradle projects would violate HARD-STOP #5 in `AGENTS.md`. +설계는 `modules/httpclient/` 아래에 Gradle 프로젝트 19개를 둔 새 라이브러리를 가정한다. 이 저장소는 Clean +Architecture 템플릿이고, **닫힌 쪽으로 실패하는 registry**(`src/config/architecture/modules.json`)가 Gradle 프로젝트 +목록을 정한다. `src/settings.gradle`이 registry에 있는 프로젝트만 포함하고, `verifyCleanArchitectureDependencies`가 +허용하지 않은 의존을 막는다. leaf 목록은 registry가 정본이다. 설계의 모듈마다 Gradle 프로젝트를 만들면 +`AGENTS.md`의 HARD-STOP 5번(registry·Gradle 의존성 검증 위반)에 걸린다. -Therefore the design's 19 library modules become **package boundaries inside the registered leaf** -`:adapter:outbound:httpclient`, with two exceptions driven by this repository's own rules: +그래서 설계의 라이브러리 모듈은 등록된 leaf `:adapter:outbound:httpclient` **안의 package 경계**가 된다. 이 저장소 +자신의 규칙 때문에 예외가 둘 있다. -| Design module | Repository home | Reason | +| 설계 모듈 | 저장소 위치 | 이유 | |---|---|---| -| `httpclient-spring-boot-starter` | `:adapter:outbound:httpclient` (`dev.caskeleton.adapter.outbound.httpclient.autoconfigure`) | Capability-specific Spring composition is owned with the reusable HTTP client platform; `app-bootstrap` only selects/includes the capability and runtime activation remains `app.httpclient.enabled`. | -| `httpclient-testkit` | `:adapter:outbound:httpclient` `src/testFixtures/java/**/testkit` | The design forbids production modules depending on the testkit. Gradle `testFixtures` publishes the reusable test support only to test consumers; ordinary tests, integration/performance lanes, and JMH opt into that surface explicitly without exposing it to production. `PlatformClasses` excludes test-fixture output so the boundary rules keep meaning production classes. | +| `httpclient-spring-boot-starter` | `:adapter:outbound:httpclient`(`dev.caskeleton.adapter.outbound.httpclient.autoconfigure`) | capability 전용 Spring 조립은 재사용하는 HTTP client 플랫폼과 함께 둔다. `app-bootstrap`은 capability를 고르고 포함할 뿐이고, 런타임 활성화는 `app.httpclient.enabled`로 남는다. | +| `httpclient-testkit` | `:adapter:outbound:httpclient` `src/testFixtures/java/**/testkit` | 설계는 production 모듈이 testkit에 의존하는 것을 금한다. Gradle `testFixtures`는 재사용 테스트 지원을 테스트 소비자에게만 내놓는다. 보통 테스트, integration/performance lane, JMH는 그 면을 명시적으로 골라 쓰고 production에는 드러나지 않는다. `PlatformClasses`는 test-fixture 출력을 빼서 경계 규칙이 계속 production 클래스만 뜻하게 한다. | -The package boundary is enforced by ArchUnit rules (`PublicApiArchitectureTest`, -`HttpClientModuleBoundaryTest`) that reproduce the design's module dependency table. +package 경계는 설계의 모듈 의존 표를 재현한 ArchUnit 규칙(`PublicApiArchitectureTest`, +`HttpClientModuleBoundaryTest`)이 강제한다. -## 2. Package mapping +## 2. Package 대응 Root package: `io.backend.skeleton.httpclient` → `dev.caskeleton.adapter.outbound.httpclient`. -| Design module | Design package | Repository package | +| 설계 모듈 | 설계 package | 저장소 package | |---|---|---| -| `httpclient-core-api` | `…httpclient.api` (+ `.body`, `.error`, `.operation`, `.result`) | `dev.caskeleton.adapter.outbound.httpclient.api` (+ same subpackages) | +| `httpclient-core-api` | `…httpclient.api` (+ `.body`, `.error`, `.operation`, `.result`) | `dev.caskeleton.adapter.outbound.httpclient.api` (+ 같은 하위 package) | | `httpclient-profile` | `…httpclient.profile` | `…outbound.httpclient.profile` | | `httpclient-transport-spi` | `…httpclient.transport` | `…outbound.httpclient.transport` | | `httpclient-transport-apache` | `…httpclient.apache` | `…outbound.httpclient.apache` | @@ -48,38 +47,38 @@ Root package: `io.backend.skeleton.httpclient` → `dev.caskeleton.adapter.outbo | `httpclient-auth` | `…httpclient.auth` | `…outbound.httpclient.auth` | | `httpclient-security` | `…httpclient.security` | `…outbound.httpclient.security` | | `httpclient-observability` | `…httpclient.observation` | `…outbound.httpclient.observation` | -| `httpclient-transport-reactor-netty` | `…httpclient.reactor` | removed (decision 9, 2026-09-25: blocking only) | -| `httpclient-webclient` | `…httpclient.webclient` | removed (decision 9, 2026-09-25: blocking only) | +| `httpclient-transport-reactor-netty` | `…httpclient.reactor` | 지움(결정 9, 2026-09-25: blocking만) | +| `httpclient-webclient` | `…httpclient.webclient` | 지움(결정 9, 2026-09-25: blocking만) | | `httpclient-service-client` | `…httpclient.service` | `…outbound.httpclient.service` | | `httpclient-dynamic-target` | `…httpclient.dynamic` | `…outbound.httpclient.dynamic` | | `httpclient-jetty-http3-experimental` | `…httpclient.http3` | `…outbound.httpclient.http3` | | `httpclient-spring-boot-starter` | `…httpclient.autoconfigure` | `dev.caskeleton.adapter.outbound.httpclient.autoconfigure` | -| `httpclient-testkit` | `…httpclient.testkit` | `…outbound.httpclient.testkit` (`testkit` source set) | +| `httpclient-testkit` | `…httpclient.testkit` | `…outbound.httpclient.testkit` (`testFixtures` source set) | -## 3. Other deliberate substitutions +## 3. 그 밖에 일부러 바꾼 것 -| Design assumption | Repository reality | Adaptation | +| 설계 가정 | 저장소 현실 | 적응 | |---|---|---| -| Gradle Kotlin DSL, `build-logic` convention plugin | Groovy DSL, root `build.gradle` conventions, `LockMode.STRICT` dependency locking | Dependencies declared in `src/adapter/outbound/httpclient/build.gradle`; `gradle.lockfile` regenerated. | -| Spring Framework 6.2 baseline with 7.0 compatibility | Spring Boot 4.0.8 / Spring Framework 7.0 is the repository baseline | Common code targets the Spring 6.2 **API surface** (no 6.2-only or 7.0-only classes in common packages). The Spring 7 HTTP Service Group integration and the `RestTemplate` migration package were removed. | -| `settings.gradle.kts` module registration | Fail-closed registry | No registry change; leaf identity, gradle path, allowed dependencies unchanged. | -| Design §6.2 grades Apache HttpClient 5 as HTTP/2-capable | Spring's blocking factory drives Apache's **classic** client, which is HTTP/1.1 only; HTTP/2 lives in Apache's async client | `ApacheBlockingTransportProvider` declares HTTP/1.1 and rejects an HTTP/2 profile at startup. Blocking HTTP/2 is served by the JDK transport, measured by `NegotiatedProtocolContractTest`. | -| Design §28.1 names WireMock for stateful fixtures | WireMock's Jetty modules bind a different Jetty 12 ABI than the Boot-managed one this module already needs for HTTP/3, and fail at server start | `StatefulUpstream` provides path-keyed stateful responses on the existing fixture server; the WireMock dependency was removed rather than worked around with a shaded jar | -| Per-task `git commit` | `AGENTS.md`: commit policy is `human-only` | Implementation is delivered unstaged; commits are the human's action. This is the only plan step intentionally not executed, and it is recorded here. | -| `docs/httpclient/**`, `.github/workflows/httpclient-*.yml`, `scripts/verify-httpclient-docs.py` | Repository already owns `docs/` and `.github/workflows/` | Created at the same repository-relative paths. | +| Gradle Kotlin DSL, `build-logic` convention plugin | Groovy DSL, root `build.gradle` convention, `LockMode.STRICT` 의존성 잠금 | 의존성은 `src/adapter/outbound/httpclient/build.gradle`에 선언하고 `gradle.lockfile`을 다시 만들었다. | +| Spring Framework 6.2 기준, 7.0 호환 | 저장소 기준은 Spring Boot 4.0 계열 / Spring Framework 7.0이다. 정확한 버전은 `src/gradle/libs.versions.toml`의 `springBoot`다 | 공통 코드는 Spring 6.2 **API 면**을 대상으로 한다(공통 package에 6.2 전용이나 7.0 전용 클래스가 없다). Spring 7 HTTP Service Group 통합과 `RestTemplate` 이전 package는 지웠다. | +| `settings.gradle.kts` 모듈 등록 | 닫힌 쪽으로 실패하는 registry | registry는 바꾸지 않았다. leaf 식별자, gradle path, 허용 의존은 그대로다. | +| 설계 §6.2는 Apache HttpClient 5를 HTTP/2 가능으로 등급 매긴다 | Spring의 blocking factory는 Apache의 **classic** client를 쓰고, 그것은 HTTP/1.1만 한다. HTTP/2는 Apache의 async client에 있다 | `ApacheBlockingTransportProvider`는 HTTP/1.1을 선언하고 HTTP/2 profile을 시작 때 거부한다. blocking HTTP/2는 JDK transport가 맡고, `NegotiatedProtocolContractTest`가 잰다. | +| 설계 §28.1은 상태 있는 fixture로 WireMock을 든다 | WireMock의 Jetty 모듈은 이 모듈이 HTTP/3 때문에 이미 쓰는 Boot 관리 Jetty 12와 ABI가 달라 서버 시작에서 실패한다 | `StatefulUpstream`이 기존 fixture 서버 위에서 경로별 상태 있는 응답을 준다. shaded jar로 돌아가지 않고 WireMock 의존성을 지웠다 | +| 작업마다 `git commit` | `AGENTS.md`: 커밋 정책은 `human-only` | 구현은 stage하지 않은 채 넘겼고, 커밋은 사람이 했다. 계획 중 일부러 실행하지 않은 단계는 이것 하나이고, 여기 적어 둔다. | +| `docs/httpclient/**`, `.github/workflows/httpclient-*.yml`, `scripts/verify-httpclient-docs.py` | 저장소가 이미 `docs/`와 `.github/workflows/`를 가진다 | 같은 저장소 상대 경로에 만들었다. | -## 4. What is unchanged from the design +## 4. 설계에서 바뀌지 않은 것 -- H1 / H2 / H3 / H4 exposure rules and the forbidden native-engine signatures. +- H1 / H2 / H3 / H4 노출 규칙과 금지한 native 엔진 시그니처. - `ExecutionEvidence`, `BodyReplayability`, `OperationIdempotency`, `AttemptStage`, `FailureCategory`. - `HttpOperation`, `HttpCallResult`, `BodySource`, `ResponseType`, `BlockingStreamingResponse`. -- The complete stable exception hierarchy and `HttpFailureMetadata` redaction rules. -- Named Client Profile schema, startup validation codes, and operation override direction. -- Effective deadline formula, attempt budget, and streaming setup/idle split. -- Retry eligibility inputs, the ordered decision table, retry budget, and backoff rules. -- Circuit → Rate Limiter → Bulkhead attempt order and logical admission placement. -- OAuth2 cache key, single-flight refresh, and the 401 replay-at-most-once rule. -- TLS allow/forbid lists and permanent-failure classification. -- Dynamic Target canonicalization → all-answer DNS validation → pinning → redirect revalidation. -- Low-cardinality tag allowlist, forbidden labels, trace and logging rules. -- Runtime generation swap and drain semantics. +- 안정된 예외 계층 전체와 `HttpFailureMetadata` 가리기 규칙. +- Named Client Profile schema, 시작 검증 코드, 연산 덮어쓰기 방향. +- 실제 기한 공식, 시도 예산, 스트리밍의 준비/idle 분리. +- 재시도 자격 입력, 순서 있는 판정 표, 재시도 예산, backoff 규칙. +- Circuit → Rate Limiter → Bulkhead 시도 순서와 논리 허가 위치. +- OAuth2 cache key, 한 번만 날아가는 갱신, 401 재전송은 많아야 한 번이라는 규칙. +- TLS 허용/금지 목록과 영구 실패 분류. +- Dynamic Target 정규화 → 모든 DNS 답 검증 → 고정 → redirect 재검증. +- 가짓수가 적은 tag 허용 목록, 금지 label, trace와 로그 규칙. +- 런타임 세대 교체와 drain 의미. diff --git a/docs/httpclient/retry-and-ambiguity.md b/docs/httpclient/retry-and-ambiguity.md index 0f7e5b4c..8aa43fe1 100644 --- a/docs/httpclient/retry-and-ambiguity.md +++ b/docs/httpclient/retry-and-ambiguity.md @@ -1,87 +1,80 @@ -# Retry and Ambiguity +# 재시도와 결과 모름 -The platform never decides a retry from the HTTP method alone (design D-09). A second attempt -happens only when idempotency, body replayability, execution evidence, deadline, and retry budget -all permit it. +플랫폼은 HTTP method만 보고 재시도를 정하지 않는다(설계 D-09). 두 번째 시도는 멱등성, 본문 재전송 가능성, 실행 +증거, 기한, 재시도 예산이 모두 허락할 때만 일어난다. -## Execution evidence +## 실행 증거 -| Evidence | Meaning | Typical cause | +| 증거 | 뜻 | 흔한 원인 | |---|---|---| -| `NOT_SENT` | Proven that the server never received the request | profile rejection, pool timeout, DNS failure, connect failure, pre-request TLS failure, HTTP/2 `REFUSED_STREAM` | -| `SENT_NO_RESPONSE` | Some or all of the request was written, no final header arrived | partial write, response-header timeout, connection reset | -| `RESPONSE_RECEIVED` | Final headers arrived, whatever the status | 2xx, 4xx, 5xx, redirect | -| `PARTIAL_RESPONSE` | Headers and part of the body arrived | reset during decode, interrupted stream | +| `NOT_SENT` | 서버가 요청을 받지 않았음이 증명됐다 | profile 거부, pool 시간 초과, DNS 실패, 연결 실패, 요청 전 TLS 실패, HTTP/2 `REFUSED_STREAM` | +| `SENT_NO_RESPONSE` | 요청 일부나 전부를 썼고, 최종 헤더가 오지 않았다 | 부분 쓰기, 응답 헤더 시간 초과, connection reset | +| `RESPONSE_RECEIVED` | 상태와 상관없이 최종 헤더가 왔다 | 2xx, 4xx, 5xx, redirect | +| `PARTIAL_RESPONSE` | 헤더와 본문 일부가 왔다 | 디코딩 중 reset, 끊긴 stream | -`NOT_SENT` is only produced by a stage failure that proves it. A generic engine I/O error is never -upgraded to `NOT_SENT`, because that is exactly how a timeout becomes a duplicate payment. +`NOT_SENT`는 그것을 증명하는 단계 실패만 만든다. 일반 엔진 I/O 오류는 절대 `NOT_SENT`로 올리지 않는다. 시간 +초과가 이중 결제가 되는 길이 바로 그것이기 때문이다. -## Body replayability +## 본문 재전송 가능성 -| Body | Replayability | +| 본문 | 재전송 가능성 | |---|---| -| immutable `byte[]` | `REPLAYABLE` | -| DTO plus a deterministic codec | `REPLAYABLE` | -| reopenable file or resource supplier | `REOPENABLE` | -| a single `InputStream` instance | `ONE_SHOT` | -| publisher factory | as declared | -| publisher instance | `ONE_SHOT` | -| multipart | the weakest part | +| 바뀌지 않는 `byte[]` | `REPLAYABLE` | +| DTO와 결정적 codec | `REPLAYABLE` | +| 다시 열 수 있는 파일이나 resource supplier | `REOPENABLE` | +| `InputStream` 인스턴스 하나 | `ONE_SHOT` | +| publisher factory | 선언한 대로 | +| publisher 인스턴스 | `ONE_SHOT` | +| multipart | 가장 약한 part를 따른다 | -## Decision order +## 판정 순서 -`DefaultRetryEligibilityEngine` evaluates in this order, and a later rule can never re-enable -something an earlier one forbade: +`DefaultRetryEligibilityEngine`은 이 순서로 판정한다. 뒤 규칙은 앞 규칙이 금지한 것을 절대 다시 허락하지 못한다. -1. `SENT_NO_RESPONSE` on an operation that is not safely idempotent → `AmbiguousFailure` -2. attempts exhausted → `RetryDenied.maxAttempts()` -3. retry budget empty → `RetryDenied.budgetExhausted()` -4. body not replayable → `RetryDenied.bodyNotReplayable()` -5. first byte already delivered → `RetryDenied.responseAlreadyDelivered()` -6. runtime draining → `RetryDenied.runtimeDraining()` -7. remaining deadline below the minimum attempt budget → `RetryDenied.deadline()` -8. permanent failure category → `RetryDenied.permanentFailure(...)` -9. `PARTIAL_RESPONSE` on an operation that is not safely idempotent → `AmbiguousFailure` -10. status- and failure-specific rules +1. 안전하게 멱등이 아닌 연산의 `SENT_NO_RESPONSE` → `AmbiguousFailure` +2. 시도를 다 썼다 → `RetryDenied.maxAttempts()` +3. 재시도 예산이 비었다 → `RetryDenied.budgetExhausted()` +4. 본문을 재전송할 수 없다 → `RetryDenied.bodyNotReplayable()` +5. 첫 바이트를 이미 넘겼다 → `RetryDenied.responseAlreadyDelivered()` +6. 런타임이 비우는 중이다 → `RetryDenied.runtimeDraining()` +7. 남은 기한이 최소 시도 예산보다 작다 → `RetryDenied.deadline()` +8. 영구 실패 범주 → `RetryDenied.permanentFailure(...)` +9. 안전하게 멱등이 아닌 연산의 `PARTIAL_RESPONSE` → `AmbiguousFailure` +10. 상태별·실패별 규칙 -Ambiguity comes first because it describes the outcome, not whether another attempt is allowed. It -used to sit below the attempt check, so with the default `max-attempts: 1` a POST that timed out -after it was sent reached the caller as an ordinary timeout (review 2026-11-01 05-14). +결과 모름이 맨 앞인 것은 그것이 다른 시도가 허락되는지가 아니라 결과를 설명하기 때문이다. 예전에는 시도 검사 +아래에 있었다. 그래서 기본값 `max-attempts: 1`에서는 보낸 뒤 시간이 넘은 POST가 호출자에게 보통의 시간 초과로 +도착했다(리뷰 2026-11-01 05-14). -## Status rules +## 상태 규칙 -| Status | Decision | +| 상태 | 판정 | |---|---| -| 408 | retry inside deadline and budget | -| 425 | at most one retry, first attempt only | -| 429 | retry inside `Retry-After`, deadline, and budget | -| 401 | one refresh-and-replay, safe replayable operations only. The credential is refreshed only once the retry is granted; a 401 that will not be replayed (one attempt, no budget, no deadline) leaves the token cache alone | -| 500 | denied unless the upstream registered it as transient **and** the operation is safely idempotent | -| 502, 503, 504 | retry for safely idempotent operations; ambiguous otherwise | -| other 4xx | denied | +| 408 | 기한과 예산 안에서 재시도 | +| 425 | 첫 시도에서만, 많아야 한 번 재시도 | +| 429 | `Retry-After`, 기한, 예산 안에서 재시도 | +| 401 | 안전하고 재전송 가능한 연산에서만 갱신 후 재전송 한 번. credential은 재시도를 허락받은 뒤에만 갱신한다. 재전송하지 않을 401(시도 한 번, 예산 없음, 기한 없음)은 token cache를 건드리지 않는다 | +| 500 | upstream이 일시적이라고 등록했고 **그리고** 연산이 안전하게 멱등일 때만 허락. 아니면 거부 | +| 502, 503, 504 | 안전하게 멱등인 연산은 재시도. 아니면 결과 모름 | +| 그 밖의 4xx | 거부 | -## Ambiguity +## 결과 모름 -A non-idempotent request that reached `SENT_NO_RESPONSE` raises -`HttpAmbiguousExecutionException`. It is a third answer on purpose: retrying may duplicate a side -effect, and reporting a plain failure would tell the caller the request did not happen, which may -be false. The caller reconciles, usually by querying the upstream or replaying with an idempotency -key. +멱등이 아닌 요청이 `SENT_NO_RESPONSE`에 닿으면 `HttpAmbiguousExecutionException`을 던진다. 일부러 만든 세 번째 +답이다. 재시도하면 부수 효과가 두 번 날 수 있고, 보통의 실패로 알리면 요청이 일어나지 않았다고 호출자에게 말하는 +셈인데 그것이 거짓일 수 있다. 호출자는 맞춰 본다. 보통 upstream에 조회하거나 멱등 key로 다시 보낸다. -### Where the evidence comes from +### 증거는 어디서 오나 -Whether a failed request was sent is read from the stage the attempt reached and the engine's -exception type. Apache reports the moment it starts writing the request onto an established -connection (`RequestWriteSignal`), so a failure while leasing, resolving, connecting or completing -the TLS handshake is `NOT_SENT` even when the engine throws a generic exception. Transports that -cannot report that moment (JDK, Jetty) are treated as writing from the moment the engine is called, -because guessing "not sent" is what turns a timeout into a duplicate payment. An HTTP/2 -`REFUSED_STREAM` frame is proof the peer processed nothing and is kept as `NOT_SENT` through -exception mapping. +실패한 요청을 보냈는지는 시도가 닿은 단계와 엔진의 예외 타입에서 읽는다. Apache는 맺은 connection에 요청을 쓰기 +시작하는 순간을 알려 준다(`RequestWriteSignal`). 그래서 빌리기, 풀기, 연결, TLS handshake 중의 실패는 엔진이 일반 +예외를 던져도 `NOT_SENT`다. 그 순간을 알려 주지 못하는 transport(JDK, Jetty)는 엔진을 부른 순간부터 쓰는 중으로 +본다. 「안 보냈다」고 짐작하는 것이 시간 초과를 이중 결제로 바꾸기 때문이다. HTTP/2 `REFUSED_STREAM` frame은 +상대가 아무것도 처리하지 않았다는 증거이고, 예외 변환을 거쳐도 `NOT_SENT`로 남는다. -## Budget and backoff +## 예산과 backoff -Retry tokens come from a per-upstream token bucket sized as a fraction of real traffic, so a failing -upstream cannot be flooded by retries from a healthy fleet. Backoff is exponential with full or -decorrelated jitter, bounded by `max-backoff`, by `Retry-After`, and by the remaining deadline. No -connection and no bulkhead permit is held while a backoff is waiting. +재시도 token은 실제 트래픽의 일정 비율로 크기를 정한 upstream별 token bucket에서 나온다. 그래서 건강한 인스턴스 +무리가 실패하는 upstream을 재시도로 덮치지 못한다. backoff는 full이나 decorrelated jitter를 쓰는 지수 backoff이고, +`max-backoff`, `Retry-After`, 남은 기한으로 제한한다. backoff를 기다리는 동안에는 connection도 bulkhead 허가도 +잡지 않는다. diff --git a/docs/httpclient/security.md b/docs/httpclient/security.md index e15f28c4..15d716fc 100644 --- a/docs/httpclient/security.md +++ b/docs/httpclient/security.md @@ -1,75 +1,68 @@ -# HTTP Client Platform — Security Guide +# HTTP Client 플랫폼 — 보안 안내 -## What the platform owns +## 플랫폼이 소유하는 것 -`Authorization`, `Proxy-Authorization`, `Host`, `Content-Length`, `Transfer-Encoding`, -`Traceparent`, `Tracestate`, `Baggage`, and (unless a profile opts in) `Cookie` are platform-owned. -A caller cannot set them. `Idempotency-Key` is accepted only when the operation declares it. Any -header name or value containing CR or LF is rejected before the request is built. +`Authorization`, `Proxy-Authorization`, `Host`, `Content-Length`, `Transfer-Encoding`, `Traceparent`, +`Tracestate`, `Baggage`, 그리고 (profile이 고르지 않는 한) `Cookie`는 플랫폼이 소유한다. 호출자는 이것들을 정할 수 +없다. `Idempotency-Key`는 연산이 선언했을 때만 받는다. 이름이나 값에 CR이나 LF가 있는 헤더는 요청을 만들기 전에 +거부한다. -## Target policy +## 대상 정책 -A trusted profile accepts only a profile-relative URI template. An absolute URI is rejected rather -than sanitised: varying the destination is what H3 is for, and H3 has its own policy, credentials, -and address validation. Template variables are encoded per component, so a value containing `/`, -`?`, or `#` cannot change the shape of the request. +trusted profile은 profile 기준 상대 URI template만 받는다. 절대 URI는 정리하지 않고 거부한다. 목적지를 바꾸는 것은 +H3가 하는 일이고, H3에는 자기 정책, credential, 주소 검증이 있다. template 변수는 구성 요소마다 인코딩한다. 그래서 +`/`, `?`, `#`이 든 값도 요청의 모양을 바꾸지 못한다. ## TLS -Allowed: TLS 1.2 and 1.3, hostname verification, the JVM trust store, a per-profile custom CA, a -per-profile client certificate, mTLS, SNI and ALPN, and certificate rotation through a new runtime -generation. +허락: TLS 1.2와 1.3, hostname 검증, JVM trust store, profile별 사설 CA, profile별 client 인증서, mTLS, SNI와 +ALPN, 새 런타임 세대를 통한 인증서 교체. -Forbidden and unrepresentable: a trust-all trust manager, disabled hostname verification, ignoring -certificate errors, automatically trusting a production self-signed certificate, falling back to -plaintext after an HTTPS failure, and writing key material into configuration or logs. +금지하고 표현할 수도 없음: 모두 믿는 trust manager, hostname 검증 끄기, 인증서 오류 무시, 운영의 자체 서명 인증서를 +자동으로 믿기, HTTPS 실패 뒤 평문으로 물러서기, key 재료를 설정이나 로그에 쓰기. -Unknown CA, hostname mismatch, expired certificate, revoked certificate, protocol mismatch, and a -missing client certificate are permanent. Only a transient handshake timeout may be retried, inside -the deadline. +모르는 CA, hostname 불일치, 만료한 인증서, 폐기된 인증서, protocol 불일치, 빠진 client 인증서는 영구 실패다. +일시적인 handshake 시간 초과만 기한 안에서 재시도할 수 있다. ## Dynamic Target (SSRF) -Every hop — the first one included — runs the whole flow: +첫 hop을 포함해 모든 hop이 흐름 전체를 돈다. -1. strict URI parse -2. scheme allowlist -3. reject userinfo and invalid ports -4. IDNA-canonicalise the host -5. host allowlist or suffix policy -6. resolve **every** A and AAAA answer -7. normalise each address, including IPv4-mapped IPv6 -8. reject loopback, link-local, RFC1918, ULA, carrier-grade NAT, unspecified, multicast, cloud - metadata, and organisation-defined ranges -9. pin the connection to the approved addresses through the same validated resolver -10. apply response size and content policy -11. repeat for each redirect +1. 엄격한 URI 파싱 +2. scheme 허용 목록 +3. userinfo와 잘못된 port 거부 +4. host를 IDNA로 정규화 +5. host 허용 목록이나 접미사 정책 +6. A와 AAAA 답을 **모두** 푼다 +7. IPv4-mapped IPv6를 포함해 주소마다 정규화 +8. loopback, link-local, RFC1918, ULA, carrier-grade NAT, 미지정, multicast, cloud metadata, 조직이 정한 범위를 + 거부 +9. 같은 검증 resolver로 connection을 승인한 주소에 고정 +10. 응답 크기와 content 정책 적용 +11. redirect마다 반복 -Any forbidden address in the answer set rejects the whole target. Validating only the first answer -would let a host that resolves to one public and one private address through. +답 묶음에 금지 주소가 하나라도 있으면 대상 전체를 거부한다. 첫 답만 검증하면 공개 주소 하나와 사설 주소 하나로 +풀리는 host가 통과한다. -Dynamic profiles inherit no API key, OAuth token, Cookie, or default header, and no Cookie jar is -created. A specific host may be granted a credential only through an explicitly registered -`DynamicCredentialBinding`. +dynamic profile은 API key, OAuth token, Cookie, 기본 헤더를 물려받지 않고, Cookie jar도 만들지 않는다. 특정 host에 +credential을 주려면 명시적으로 등록한 `DynamicCredentialBinding`을 거쳐야만 한다. -Application-level validation is not sufficient on its own. A network control — Kubernetes -NetworkPolicy, service-mesh egress policy, firewall, or proxy ACL — is an operational completion -requirement. +애플리케이션 수준 검증만으로는 충분하지 않다. 네트워크 통제(Kubernetes NetworkPolicy, service mesh egress 정책, +방화벽, proxy ACL)가 운영 완료 요건이다. -## Redirects +## Redirect -Disabled by default. Engine redirect handling is off in every transport so the platform can -re-validate each hop. 307 and 308 preserve method and body and are therefore allowed only for a -replayable body. Cross-origin hops are refused unless the profile opts in, and when they are -allowed `Authorization`, `Proxy-Authorization`, `Cookie`, and API-key headers are stripped. +기본으로 꺼져 있다. 플랫폼이 hop마다 다시 검증할 수 있게 모든 transport에서 엔진의 redirect 처리를 끈다. 307과 +308은 method와 본문을 유지하므로 재전송 가능한 본문일 때만 허락한다. origin을 넘는 hop은 profile이 고르지 않으면 +거부하고, 허락하면 `Authorization`, `Proxy-Authorization`, `Cookie`, API key 헤더를 지운다. -## Observability +## 관측 -Allowed tags: `clientName`, `operationName`, `method`, `uriTemplate`, `status`, `outcome`, -`transport`, `protocol`, `timeoutType`, `retryReason`, `evidence`, `circuitState`. +허락한 tag: `clientName`, `operationName`, `method`, `uriTemplate`, `status`, `outcome`, `transport`, +`protocol`, `timeoutType`, `retryReason`, `evidence`, `circuitState`. -Rejected outright: full URL, query parameters, path variable values, user ID, raw tenant ID, -resolved IP, API key, token, Cookie, idempotency key, request or response body, exception message. +바로 거부: 전체 URL, query parameter, 경로 변수 값, user ID, 날것의 tenant ID, 푼 IP, API key, token, Cookie, 멱등 +key, 요청이나 응답 본문, 예외 메시지. -Failures are logged once, structured, at the end of a logical call. Retry attempts are DEBUG or span -events. URLs appear only as templates. +실패는 논리 호출 끝에 구조화해서 한 번 로그를 남긴다. 재시도 시도는 DEBUG이거나 span event다. URL은 template로만 +나온다. diff --git a/docs/httpclient/streaming.md b/docs/httpclient/streaming.md index a68136d2..fd5e0686 100644 --- a/docs/httpclient/streaming.md +++ b/docs/httpclient/streaming.md @@ -1,36 +1,34 @@ -# Streaming and Large Bodies +# 스트리밍과 큰 본문 -## Response lifecycle +## 응답 수명 -A streaming download returns `BlockingStreamingResponse`, never a bare `InputStream`. Closing is -idempotent and always releases the connection — after a full read, a partial read, a decode failure, -or a size rejection. The status is validated before any body byte is delivered, so a failed download -never becomes a half-consumed stream the caller has to reason about. +스트리밍 다운로드는 맨 `InputStream`이 아니라 `BlockingStreamingResponse`를 돌려준다. 닫기는 멱등이고, 다 읽은 +뒤든, 일부만 읽은 뒤든, 디코딩 실패나 크기 거부 뒤든 늘 connection을 돌려준다. 상태는 본문 바이트를 넘기기 전에 +검증한다. 그래서 실패한 다운로드가 호출자가 따져야 하는 반쯤 읽힌 stream이 되지 않는다. -Wire bytes and decoded bytes are bounded independently, because a compressed payload passes a wire -check and then expands. Limits are enforced while reading, not after buffering. +wire 바이트와 디코딩한 바이트는 따로 제한한다. 압축한 payload는 wire 검사를 통과한 뒤 늘어나기 때문이다. 한도는 +버퍼링한 뒤가 아니라 읽는 동안 강제한다. -## The first-byte boundary +## 첫 바이트 경계 ```text -response headers received - → nothing delivered yet - → a read-only operation may still be retried - → the response is handed to the caller - → transparent retry is no longer possible +응답 헤더를 받았다 + → 아직 아무것도 넘기지 않았다 + → 읽기 전용 연산은 아직 재시도할 수 있다 + → 응답을 호출자에게 넘겼다 + → 투명한 재시도는 더는 할 수 없다 ``` -Retrying after delivery would replay a stream the caller has already partly consumed, producing -duplicated or reordered data that no downstream code can detect. The streaming gateway hands out -the response only after the attempt has finished, so there is no retry left to run once the caller -reads. +넘긴 뒤에 재시도하면 호출자가 이미 일부 읽은 stream을 다시 보내게 된다. 그러면 아래쪽 어느 코드도 알아챌 수 없는 +중복되거나 순서가 바뀐 데이터가 생긴다. 스트리밍 gateway는 시도가 끝난 뒤에만 응답을 넘긴다. 그래서 호출자가 +읽기 시작하면 돌릴 재시도가 남아 있지 않다. -## Request bodies +## 요청 본문 -A reopenable body is opened once per attempt, which is what makes it replayable; reusing the -previous stream would silently send an empty body on the retry. A one-shot stream is never retried. +다시 열 수 있는 본문은 시도마다 한 번 연다. 그래서 재전송할 수 있다. 앞 stream을 다시 쓰면 재시도에서 빈 본문을 +조용히 보낸다. 한 번만 쓰는 stream은 절대 재시도하지 않는다. ## Server-sent events -The platform has no server-sent-event client. It was part of the reactive stack, which was removed -(decision 9, 2026-09-25): the platform runs blocking calls on the caller's thread only. +플랫폼에는 server-sent event client가 없다. 그것은 지운 reactive stack의 일부였다(결정 9, 2026-09-25). 플랫폼은 +호출자의 스레드에서 blocking 호출만 돌린다. diff --git a/docs/httpclient/support-matrix.md b/docs/httpclient/support-matrix.md index a253cfd9..24bc5509 100644 --- a/docs/httpclient/support-matrix.md +++ b/docs/httpclient/support-matrix.md @@ -1,87 +1,82 @@ -# HTTP Client Platform — Support Matrix +# HTTP Client 플랫폼 — 지원 매트릭스 -Grades follow design §6 and §29. A row is **Stable** only when the cross-transport contract suite -proves it; anything the suite cannot prove is **Experimental** and says so. +등급은 설계서 §6과 §29를 따른다. 행이 **Stable**이려면 transport를 넘는 계약 suite가 그것을 증명해야 한다. suite가 +증명하지 못하는 것은 **Experimental**이고 그렇다고 밝힌다. 등급 이름(Stable, Default, Restricted, Internal, +Experimental)은 원문 그대로 쓴다. ## Spring API -| API | Grade | Role | Constraint | +| API | 등급 | 역할 | 제약 | |---|---|---|---| -| `RestClient` | Stable | Blocking execution (the only execution model) | Bounded concurrency and an effective deadline are mandatory | -| HTTP Service Client (`@HttpExchange`) | Default | Declarative typed client | Operation metadata is mandatory | -| Generic Exchange (H2) | Restricted | Dynamic method, path, body | Base URL and policy are immutable | -| Dynamic Target (H3) | Restricted | User-supplied URL | Separate SSRF policy; inherits no credential | -| Native engine | Internal | Engine-specific configuration | Never an application-facing API | +| `RestClient` | Stable | blocking 실행(유일한 실행 모델) | 동시성 상한과 실제 기한이 필수다 | +| HTTP Service Client(`@HttpExchange`) | Default | 선언형 타입 있는 client | 연산 metadata가 필수다 | +| Generic Exchange (H2) | Restricted | 동적 method, 경로, 본문 | Base URL과 정책은 바꿀 수 없다 | +| Dynamic Target (H3) | Restricted | 사용자가 준 URL | 따로 된 SSRF 정책. credential을 물려받지 않는다 | +| Native 엔진 | Internal | 엔진별 설정 | 애플리케이션이 쓰는 API가 절대 아니다 | -## Transports +## Transport -The platform is blocking only (decision 9, 2026-09-25): every call runs on the caller's thread — -a virtual thread in this template — through `RestClient`. There is no reactive execution path, no -`WebClient`, and no Reactor Netty transport. +플랫폼은 blocking만 한다(결정 9, 2026-09-25). 모든 호출은 호출자의 스레드(이 템플릿에서는 virtual thread)에서 +`RestClient`를 거쳐 돈다. reactive 실행 경로도, `WebClient`도, Reactor Netty transport도 없다. -| Transport | HTTP/1.1 | HTTP/2 | HTTP/3 | Grade | Verified by | +| Transport | HTTP/1.1 | HTTP/2 | HTTP/3 | 등급 | 확인하는 것 | |---|---:|---:|---:|---|---| -| Apache HttpClient 5 (classic) | yes | **no** | no | Stable (default) | `httpClientStableContractTest`, `NegotiatedProtocolContractTest` | -| JDK HttpClient | yes | yes (TLS/ALPN) | no | Stable (lightweight, HTTP/2) | `NegotiatedProtocolContractTest` | -| Jetty | yes | yes | yes | **Experimental** | `Http3OptInTest` only | -| Simple request factory | limited | no | no | Local test only | rejected in production by `ClientProfileValidator` | +| Apache HttpClient 5 (classic) | 된다 | **안 된다** | 안 된다 | Stable(기본) | `httpClientStableContractTest`, `NegotiatedProtocolContractTest` | +| JDK HttpClient | 된다 | 된다(TLS/ALPN) | 안 된다 | Stable(가벼움, HTTP/2) | `NegotiatedProtocolContractTest` | +| Jetty | 된다 | 된다 | 된다 | **Experimental** | `Http3OptInTest`뿐 | +| Simple request factory | 제한적 | 안 된다 | 안 된다 | 로컬 테스트 전용 | 운영에서는 `ClientProfileValidator`가 거부한다 | -### Apache is HTTP/1.1 here, and why +### 여기서 Apache가 HTTP/1.1인 이유 -Design §6.2 grades Apache HttpClient 5 as HTTP/2-capable, and the library is — in its **async** -client. Spring's `HttpComponentsClientHttpRequestFactory` drives the **classic** client, which -speaks HTTP/1.1 only. `NegotiatedProtocolContractTest` measures this rather than assuming it: the -classic client fails outright against a prior-knowledge h2c server. +설계서 §6.2는 Apache HttpClient 5를 HTTP/2 가능으로 등급 매긴다. 라이브러리는 그렇다. 다만 **async** client에서다. +Spring의 `HttpComponentsClientHttpRequestFactory`는 **classic** client를 쓰고, 그것은 HTTP/1.1만 한다. +`NegotiatedProtocolContractTest`는 이것을 가정하지 않고 잰다. classic client는 prior-knowledge h2c 서버에 대해 +바로 실패한다. -So `ApacheBlockingTransportProvider.capabilities()` declares HTTP/1.1, and a profile that pairs -Apache with `HTTP_2` is rejected at startup instead of quietly running HTTP/1.1 while this table -claims otherwise. **HTTP/2 is served by the JDK transport**, measured from the client after a real -TLS handshake, not read from configuration. No transport can be restricted to HTTP/2 alone, so a -profile that declares only `HTTP_2` is refused (`HTTP2_REQUIRED_TRANSPORT_UNSUPPORTED`). +그래서 `ApacheBlockingTransportProvider.capabilities()`는 HTTP/1.1을 선언한다. Apache와 `HTTP_2`를 짝지은 +profile은 이 표가 다르게 주장하는 동안 조용히 HTTP/1.1로 도는 대신 시작 때 거부된다. **HTTP/2는 JDK transport가 +맡는다.** 설정에서 읽지 않고, 실제 TLS handshake 뒤 client 쪽에서 잰다. HTTP/2만으로 제한할 수 있는 transport는 +없으므로 `HTTP_2`만 선언한 profile은 거부한다(`HTTP2_REQUIRED_TRANSPORT_UNSUPPORTED`). -The JDK transport declares `routeScopedPool=false`, `boundedPendingAcquireQueue=false`, and -`dynamicTargetStable=false`. A profile that needs any of those is rejected at startup rather than -served with weaker guarantees. Choosing between Apache and JDK is therefore a real trade: Apache -gives route-scoped pooling and Dynamic Target pinning, JDK gives HTTP/2. +JDK transport는 `routeScopedPool=false`, `boundedPendingAcquireQueue=false`, `dynamicTargetStable=false`를 +선언한다. 그중 하나라도 필요한 profile은 약한 보장으로 돌지 않고 시작 때 거부된다. 그래서 Apache와 JDK 사이의 +선택은 진짜 맞바꿈이다. Apache는 route 범위 pool과 Dynamic Target 고정을 주고, JDK는 HTTP/2를 준다. -## Capability gates +## Capability 관문 -| Capability | Gate | +| Capability | 관문 | |---|---| -| Dynamic Target (H3) | Apache only; JDK and Jetty are rejected | -| HTTP/3 | `experimentalAcknowledgement` must equal `I_ACCEPT_HTTP3_EXPERIMENTAL_SEMANTICS` | -| Cross-origin redirect | opt-in per profile; credentials are stripped on the hop | -| Retry | evidence-based; never enabled by HTTP method alone | +| Dynamic Target (H3) | Apache만. JDK와 Jetty는 거부한다 | +| HTTP/3 | `experimentalAcknowledgement`가 `I_ACCEPT_HTTP3_EXPERIMENTAL_SEMANTICS`와 같아야 한다 | +| origin을 넘는 redirect | profile마다 골라 켠다. hop에서 credential을 지운다 | +| 재시도 | 증거 기반. HTTP method만으로 켜지지 않는다 | -## CI matrix +## CI 매트릭스 -| Profile | Frequency | Release gate | Task | +| Profile | 빈도 | 릴리스 게이트 | Task | |---|---|---|---| -| Spring Framework 7.0 (repository baseline) | PR touching this leaf, main push, release | required | `spring70CompatibilityTest` | -| Spring Framework 6.2 API surface | every PR (`check`), release | required | `spring62ApiSurfaceScan` | -| Apache HC5 + RestClient | PR touching this leaf (both transports together on every PR through `check`), release | required | `httpClientStableContractTest -Phttpclient.contract.transports=apache` | -| JDK HttpClient + RestClient | PR touching this leaf (both transports together on every PR through `check`), release | required | `httpClientStableContractTest -Phttpclient.contract.transports=jdk` | -| SSRF / cardinality suite | every PR (`check`), release | required | `httpClientSecurityTest` | -| Toxiproxy fault suite | main push, nightly (`integrationCheck`), release | required | `httpClientFailureInjectionTest` | -| Performance certification | main push, nightly (`performanceCheck`), release | required | `httpClientPerformanceTest` (every bound asserted; no switch turns them off) | -| Jetty HTTP/3 | main push, nightly | Experimental, non-blocking | `test -Phttp3.tests.enabled=true` | +| Spring Framework 7.0(저장소 기준) | 이 leaf를 건드린 PR, main push, 릴리스 | 필수 | `spring70CompatibilityTest` | +| Spring Framework 6.2 API 면 | 모든 PR(`check`), 릴리스 | 필수 | `spring62ApiSurfaceScan` | +| Apache HC5 + RestClient | 이 leaf를 건드린 PR(두 transport는 `check`로 모든 PR에서 함께 돈다), 릴리스 | 필수 | `httpClientStableContractTest -Phttpclient.contract.transports=apache` | +| JDK HttpClient + RestClient | 이 leaf를 건드린 PR(두 transport는 `check`로 모든 PR에서 함께 돈다), 릴리스 | 필수 | `httpClientStableContractTest -Phttpclient.contract.transports=jdk` | +| SSRF / 가짓수 suite | 모든 PR(`check`), 릴리스 | 필수 | `httpClientSecurityTest` | +| Toxiproxy 장애 suite | main push, nightly(`integrationCheck`), 릴리스 | 필수 | `httpClientFailureInjectionTest` | +| 성능 인증 | main push, nightly(`performanceCheck`), 릴리스 | 필수 | `httpClientPerformanceTest`(모든 상한을 단언. 끄는 스위치가 없다) | +| Jetty HTTP/3 | main push, nightly | Experimental, 막지 않음 | `test -Phttp3.tests.enabled=true` | -### Known limitation of the Spring 6.2 lane +### Spring 6.2 lane의 알려진 한계 -This repository's Spring Boot 4.0 baseline pins Spring Framework 7, so a real 6.2 runtime cannot be -resolved here. `spring62ApiSurfaceScan` therefore verifies the **API surface**: the common -packages must not reference any Spring 7-only type, and no class uses -`org.springframework.web.service.registry`. Executing the suite against an actual 6.2 distribution -requires a host project on that line. This limitation is stated rather than hidden behind a passing -check. +이 저장소의 Spring Boot 4.0 기준은 Spring Framework 7을 고정한다. 그래서 여기서는 실제 6.2 런타임을 풀 수 없다. +`spring62ApiSurfaceScan`은 대신 **API 면**을 확인한다. 공통 package가 Spring 7 전용 타입을 참조하지 않아야 하고, +어떤 클래스도 `org.springframework.web.service.registry`를 쓰지 않아야 한다. 실제 6.2 배포판에 대해 suite를 +돌리려면 그 계열의 host 프로젝트가 필요하다. 이 한계는 통과하는 검사 뒤에 숨기지 않고 밝혀 둔다. +## Suite가 증명하지 않는 것 -## What the suites do not prove +매트릭스를 바람이 아니라 측정으로 읽게 하려고 적는다. -Stated so the matrix is read as a measurement rather than an aspiration. - -| Gap | Why | What is proven instead | +| 빈곳 | 이유 | 대신 증명하는 것 | |---|---|---| -| HTTP/2 frame injection (`REFUSED_STREAM`, arbitrary `GOAWAY`) | The fixture server exposes no frame-level control, and a purpose-built h2 server is a larger dependency than the guarantee is worth here | `Http2EvidenceMapperTest` proves the frame → evidence mapping, and `NegotiatedProtocolContractTest` proves h2 is really negotiated | -| Spring 6.2 runtime | This repository's Boot 4.0 baseline pins Spring 7 | `spring62ApiSurfaceScan` confines the common packages to the 6.2 API surface | -| Performance latency baseline | Numbers measured on a build agent are not a certification | `httpClientPerformanceTest` asserts its structural bounds and the streaming heap bound in every run; it asserts no latency figure | +| HTTP/2 frame 주입(`REFUSED_STREAM`, 임의 `GOAWAY`) | fixture 서버에 frame 수준 제어가 없고, 전용 h2 서버는 여기서 얻는 보장보다 큰 의존성이다 | `Http2EvidenceMapperTest`가 frame → 증거 대응을, `NegotiatedProtocolContractTest`가 h2가 정말 협상되는지를 증명한다 | +| Spring 6.2 런타임 | 이 저장소의 Boot 4.0 기준이 Spring 7을 고정한다 | `spring62ApiSurfaceScan`이 공통 package를 6.2 API 면 안에 가둔다 | +| 성능 지연 기준선 | 빌드 agent에서 잰 숫자는 인증이 아니다 | `httpClientPerformanceTest`가 매번 구조적 상한과 스트리밍 heap 상한을 단언한다. 지연 숫자는 단언하지 않는다 | diff --git a/docs/jpa/batch-write-guide.md b/docs/jpa/batch-write-guide.md index 2cf65e28..eed38d1d 100644 --- a/docs/jpa/batch-write-guide.md +++ b/docs/jpa/batch-write-guide.md @@ -1,22 +1,19 @@ -# JPA batch write configuration +# JPA batch 쓰기 설정 -`HibernateJpaBatchExecutor` is an advanced opt-in. The template does not enable Hibernate batch -write settings globally because statistics and statement reordering add runtime cost even in -applications that never perform bulk writes. +`HibernateJpaBatchExecutor`는 고급 opt-in이다. 템플릿은 Hibernate batch 쓰기 설정을 전역으로 켜지 않는다. 통계와 문장 +재정렬은 bulk 쓰기를 한 번도 하지 않는 애플리케이션에도 런타임 비용을 더하기 때문이다. -## What the executor owns +## executor가 가지는 것 -A `JpaBatchProfile` owns the JDBC batch size for one batch run. Before the first item is written, -the executor applies `profile.jdbcBatchSize()` to the current Hibernate `Session`. The previous -Session value is restored in `finally`, including failed runs. +`JpaBatchProfile`이 batch 실행 한 번의 JDBC batch 크기를 가진다. executor는 첫 항목을 쓰기 전에 +`profile.jdbcBatchSize()`를 지금 Hibernate `Session`에 적용한다. 앞 Session 값은 실패한 실행을 포함해 `finally`에서 +되돌린다. -The executor does **not** open a transaction. The application service must enter a -`TransactionPort.inWrite(...)` boundary first. +executor는 트랜잭션을 열지 **않는다**. 애플리케이션 서비스가 먼저 `TransactionPort.inWrite(...)` 경계에 들어가야 한다. -## What the application must configure +## 애플리케이션이 설정할 것 -If a profile requests insert or update ordering, the matching Hibernate setting must already be -enabled on the SessionFactory: +profile이 insert나 update 정렬을 요구하면, 맞는 Hibernate 설정이 SessionFactory에 이미 켜져 있어야 한다. ```yaml spring: @@ -28,37 +25,31 @@ spring: generate_statistics: true ``` -`hibernate.generate_statistics=true` is required because `BatchExecutionResult` reports measured -flush and prepared-statement deltas. A disabled statistics registry would turn those values into -convincing zeros. +`BatchExecutionResult`가 잰 flush와 prepared statement의 차이를 보고하므로 `hibernate.generate_statistics=true`가 필요하다. +통계 registry가 꺼져 있으면 그 값이 그럴듯한 0이 된다. -The `HibernateStatisticsCollector` must also receive an instrumented `JdbcBatchCounter`. -`HibernateStatisticsCollector.of(sessionFactory)` is intentionally insufficient for this executor: -Hibernate statistics do not expose actual JDBC batch executions. +`HibernateStatisticsCollector`는 계측된 `JdbcBatchCounter`도 받아야 한다. 이 executor에는 +`HibernateStatisticsCollector.of(sessionFactory)`가 일부러 모자라다. Hibernate 통계는 실제 JDBC batch 실행을 드러내지 않는다. -`hibernate.default_batch_fetch_size` is unrelated to this write executor. It affects association -fetching and belongs to query/fetch tuning instead. +`hibernate.default_batch_fetch_size`는 이 쓰기 executor와 상관없다. 연관 fetch에 영향을 주고, 쿼리·fetch 조정에 속한다. -## Entity identifier constraint +## 엔티티 식별자 제약 -When `JpaBatchProfile.batchingRequired()` is true, an entity using -`GenerationType.IDENTITY` is rejected by `HibernateBatchConfigurationGuard`. Hibernate must issue -each INSERT immediately to obtain the generated identifier, so JDBC insert batching cannot satisfy -that profile. +`JpaBatchProfile.batchingRequired()`가 참이면 `GenerationType.IDENTITY`를 쓰는 엔티티는 `HibernateBatchConfigurationGuard`가 +거부한다. Hibernate는 생성된 식별자를 얻으려고 INSERT마다 바로 실행해야 하므로, JDBC insert batching으로는 그 profile을 +채울 수 없다. -Prefer a sequence-based identifier when a workload requires insert batching. Keep the sequence -allocation size aligned with the database migration. +insert batching이 필요한 작업에는 sequence 기반 식별자를 쓴다. sequence의 allocation size는 DB 마이그레이션과 맞춰 둔다. -## Failure behavior +## 실패 동작 -Configuration is checked before the persister receives the first item: +설정은 persister가 첫 항목을 받기 전에 확인한다. -- missing `hibernate.order_inserts=true` when the profile requests insert ordering: fail; -- missing `hibernate.order_updates=true` when the profile requests update ordering: fail; -- disabled Hibernate statistics: fail; -- missing JDBC batch instrumentation: fail; -- no caller-owned transaction: fail. +- profile이 insert 정렬을 요구하는데 `hibernate.order_inserts=true`가 없다: 실패. +- profile이 update 정렬을 요구하는데 `hibernate.order_updates=true`가 없다: 실패. +- Hibernate 통계가 꺼져 있다: 실패. +- JDBC batch 계측이 없다: 실패. +- 호출자가 가진 트랜잭션이 없다: 실패. -These failures are deliberate. A batch API that silently degrades to one statement per row produces -correct data but false performance evidence, which is harder to detect than a startup or invocation -failure. +이 실패는 일부러다. 행마다 문장 하나로 조용히 떨어지는 batch API는 데이터는 맞지만 성능 증거는 거짓이고, 그것은 기동이나 +호출 실패보다 알아채기 어렵다. diff --git a/docs/jpa/entity-mapping-guide.md b/docs/jpa/entity-mapping-guide.md index aae8772c..c8c57686 100644 --- a/docs/jpa/entity-mapping-guide.md +++ b/docs/jpa/entity-mapping-guide.md @@ -1,117 +1,92 @@ -# Entity Mapping Guide +# 엔티티 매핑 가이드 -Design §10-§13. The rules here exist because each one has a failure mode that is invisible in review -and expensive in production. +설계서 §10-§13. 여기 있는 규칙마다, 리뷰에서는 보이지 않고 운영에서는 비싼 실패 꼴이 있다. -## The domain owns the model +## 모델은 도메인이 가진다 -The platform defines no business entity. Table names, column semantics, keys, unique and check -requirements, associations, cascade rules, lock policy, and soft-delete policy all belong to the -domain module. There is no `GenericRepository` and no platform base repository, because a -single generic API forces every aggregate through the same operations — and one aggregate's later -requirement then changes behaviour for all of them. +플랫폼은 업무 엔티티를 정의하지 않는다. 테이블 이름, 열의 뜻, 키, unique·check 요구, 연관, cascade 규칙, lock 정책, +soft-delete 정책은 모두 도메인 모듈의 것이다. `GenericRepository`도 플랫폼 base repository도 없다. generic API +하나는 모든 aggregate를 같은 연산으로 몰아넣고, 그러면 한 aggregate의 나중 요구가 모두의 동작을 바꾼다. -## Entities must be proxyable +## 엔티티는 proxy가 될 수 있어야 한다 -- Not `final`. Hibernate creates a lazy proxy by generating a subclass; a final entity cannot be - subclassed, so *every* association to it loads eagerly whatever the mapping says. Nothing errors. -- A non-private no-arg constructor. The provider instantiates entities reflectively before - populating fields. +- `final`이 아니다. Hibernate는 subclass를 만들어 lazy proxy를 만든다. final 엔티티는 subclass를 만들 수 없으므로 그것으로의 + 연관은 매핑이 뭐라고 하든 *모두* eager로 읽힌다. 아무 오류도 나지 않는다. +- private이 아닌 인자 없는 생성자. provider는 칸을 채우기 전에 reflection으로 엔티티를 만든다. -`EntityMappingCondition` in the testkit enforces both. +testkit의 `EntityMappingCondition`이 둘을 강제한다. -## Identifiers +## 식별자 -Default to a sequence with an `allocationSize` that matches the migration's `INCREMENT BY`. When -they disagree, the provider hands out identifiers the sequence has not reserved and the collision -surfaces later as a primary-key violation under load. +기본은 sequence이고, `allocationSize`는 마이그레이션의 `INCREMENT BY`와 맞춘다. 둘이 다르면 provider가 sequence가 예약하지 +않은 식별자를 내주고, 충돌은 나중에 부하에서 primary key 위반으로 드러난다. -`GenerationType.IDENTITY` is supported and limited: the key is assigned on insert, so the provider -must execute each insert immediately to learn it, which disables JDBC insert batching entirely. -`HibernateBatchConfigurationGuard` fails a batch profile that targets an IDENTITY entity rather than -letting the import silently run an order of magnitude slower. +`GenerationType.IDENTITY`는 지원하지만 제한이 있다. 키가 insert 때 정해지므로 provider는 키를 알려고 insert마다 바로 +실행해야 하고, 그러면 JDBC insert batching이 아예 꺼진다. `HibernateBatchConfigurationGuard`는 IDENTITY 엔티티를 대상으로 +하는 batch profile을, import가 조용히 열 배 느리게 돌게 두는 대신 실패시킨다. -UUIDv7 (`UuidV7Generator`) is the application-side option. It is preferred over UUIDv4 for a primary -key because v4 is uniformly random: every insert lands on a random leaf of the B-tree, so the index -never stays in cache and write amplification grows with the table. +UUIDv7(`UuidV7Generator`)은 애플리케이션 쪽 선택지다. primary key로는 UUIDv4보다 낫다. v4는 고르게 무작위라서 insert마다 +B-tree의 무작위 leaf에 떨어지고, 인덱스가 캐시에 머물지 못하며, 쓰기 증폭이 테이블과 함께 커진다. -## Values +## 값 -- Enums are `EnumType.STRING` or an explicit converter. **Never** `ORDINAL` — it stores the - constant's position, so inserting a new constant anywhere but the end silently reinterprets every - existing row. -- Money is `BigDecimal` with explicit precision and scale. `double` cannot represent `0.1`, so sums - drift and reconciliation disagrees with the ledger. -- `Duration` goes through a converter that stores milliseconds. The ISO-8601 text form sorts and - compares wrongly in SQL. -- `Instant` and `OffsetDateTime` map differently; a column typed for one cannot faithfully store the - other. +- enum은 `EnumType.STRING`이나 명시적 converter다. `ORDINAL`은 **절대** 쓰지 않는다. 상수의 위치를 저장하므로, 끝이 아닌 + 곳에 새 상수를 넣으면 기존 행이 모두 조용히 다른 뜻이 된다. +- 금액은 정밀도와 scale을 명시한 `BigDecimal`이다. `double`은 `0.1`을 나타내지 못해서 합계가 어긋나고 맞추기가 장부와 + 다른 말을 한다. +- `Duration`은 밀리초를 저장하는 converter를 거친다. ISO-8601 문자열 꼴은 SQL에서 정렬과 비교가 틀린다. +- `Instant`와 `OffsetDateTime`은 다르게 매핑된다. 한쪽에 맞춘 열은 다른 쪽을 그대로 저장하지 못한다. -## Associations +## 연관 (Associations) -Map each association from **one side only**. A JPA association between two entities is one foreign -key column. A bidirectional pair (`@ManyToOne` on the child plus `@OneToMany(mappedBy = ...)` on -the parent) stores that one column in two Java fields, and JPA writes only the owning one. The pair -stays consistent only while every caller remembers to update both fields, and nothing fails when -someone forgets. +연관은 **한쪽에서만** 매핑한다. 두 엔티티 사이의 JPA 연관은 foreign key 열 하나다. 양방향 짝(자식의 `@ManyToOne`과 부모의 +`@OneToMany(mappedBy = ...)`)은 그 열 하나를 Java 칸 둘에 저장하고, JPA는 소유하는 쪽만 쓴다. 짝은 모든 호출자가 두 칸을 +함께 고치는 것을 기억할 때만 맞고, 누가 잊어도 아무것도 실패하지 않는다. -What to use, in order of preference: +쓸 것, 고르는 순서대로: -1. **An ID reference between aggregates.** Hold the other aggregate's identifier as a plain column - (`UUID ownerId`). This is what every production entity in the template does today. Loading the - other aggregate is an explicit repository call, so a cross-aggregate load is visible in the code. -2. **A unidirectional `@ManyToOne` inside one aggregate**, always `fetch = FetchType.LAZY`. JPA's - default for a to-one association is `EAGER`, so every query that loads a child also queries for - its parent — the most common accidental N+1 in a JPA application. -3. **A collection is a query, not a field.** "The children of X" is a repository method - (`findByParentId`, or a fetch-join or projection query that pages in SQL). The query states its - own fetch plan and page, where a mapped collection hides both. -4. **Values the aggregate owns** — a list of tags, a set of codes — are `@ElementCollection` - (`LAZY`), not entities. +1. **aggregate 사이에는 ID 참조.** 다른 aggregate의 식별자를 평범한 열로 든다(`UUID ownerId`). 지금 템플릿의 모든 운영 엔티티가 + 이렇게 한다. 다른 aggregate를 읽는 것은 명시적인 repository 호출이라, aggregate를 넘는 읽기가 코드에 보인다. +2. **한 aggregate 안에서는 단방향 `@ManyToOne`**, 늘 `fetch = FetchType.LAZY`. JPA의 to-one 기본값은 `EAGER`라서, 자식을 + 읽는 모든 쿼리가 부모도 조회한다. JPA 애플리케이션에서 가장 흔한 실수 N+1이다. +3. **collection은 칸이 아니라 쿼리다.** 「X의 자식들」은 repository 메서드다(`findByParentId`, 또는 SQL에서 페이지를 나누는 + fetch join이나 projection 쿼리). 쿼리는 자기 fetch 계획과 페이지를 말하고, 매핑한 collection은 둘 다 숨긴다. +4. **aggregate가 가진 값**(태그 목록, 코드 집합)은 엔티티가 아니라 `@ElementCollection`(`LAZY`)이다. -A unidirectional `@OneToMany` with its own `@JoinColumn` is the exception, not the default. Use it -only for child entities the root genuinely owns and changes only through itself (the testkit's -`LifecycleParent` and `PagedParent` are this shape). It still costs an `UPDATE` per child when the -join column is nullable, and the collection still loads as a unit. The child then has no -association back to the root — not even a read-only `@ManyToOne` on the same join column -(`insertable = false, updatable = false`): that is the bidirectional pair again, without the -`mappedBy` that names it. If the child needs the root, it holds the root's ID. +자기 `@JoinColumn`이 있는 단방향 `@OneToMany`는 기본이 아니라 예외다. root가 정말 가지고 root를 통해서만 바꾸는 자식 +엔티티에만 쓴다(testkit의 `LifecycleParent`와 `PagedParent`가 이 모양이다). join 열이 nullable이면 자식마다 `UPDATE` 한 +번이 들고, collection은 여전히 한 덩어리로 읽힌다. 그러면 자식에는 root로 돌아가는 연관이 없다. 같은 join 열에 읽기 전용 +`@ManyToOne`(`insertable = false, updatable = false`)도 두지 않는다. 그것은 이름을 붙이는 `mappedBy`만 없을 뿐 다시 양방향 +짝이다. 자식이 root가 필요하면 root의 ID를 든다. -`CascadeType.ALL` with `orphanRemoval` is correct only for a child the aggregate genuinely owns. -Between independent aggregates it deletes rows another part of the system still owns — another -reason those are ID references. +`orphanRemoval`과 함께 쓰는 `CascadeType.ALL`은 aggregate가 정말 가진 자식에만 맞다. 독립된 aggregate 사이에서는 시스템의 +다른 부분이 아직 가진 행을 지운다. 그것들이 ID 참조인 또 하나의 이유다. -`JpaArchitectureRules.associationsAreMappedFromOneSideOnly()` (testkit) fails the build on every -bidirectional pair, on `@Entity`, `@MappedSuperclass` and `@Embeddable` types: an association that -declares `mappedBy` (only that inverse half is reported), and two entities whose associations point -at each other without `mappedBy` (both halves are reported — the `@JoinColumn` form above, review -RR-03-04). The message says how the pair keeps the link: one join column mapped from both ends, or -the link stored twice — a `@OneToMany` without `@JoinColumn` in a join table beside the child's own -`@ManyToOne` column (what a forgotten `mappedBy` produces), or two `@ManyToMany` each owning a join -table (re-review round 3, RR3-02-05). That last check also refuses two entities that each hold their own foreign key to the -other (`Order.@OneToOne latestInvoice` with `Invoice.@ManyToOne order`). It is not one link mapped -twice, and the message says so; it is refused on purpose, because the two tables then reference each -other: neither row can be inserted or deleted first, one key has to be nullable and written by a -second `UPDATE`, and the entity graph is a cycle. Keep the association on one side and give the other -an ID or a query (re-review round 2, RR-02-15). A class that links to itself is a pair only when a -second member points back the other way (`@ManyToOne parent` with `@OneToMany children`); two -`@ManyToOne` links of a class to itself (a manager and a mentor) pass, because both keys point into -the one table and there are no two tables to order. 이 규칙은 `JpaProductionArchitectureTest`(app-bootstrap -`architectureTest`)가 운영 그래프 전체에 건다. -The failure message names the fields and these alternatives. +`JpaArchitectureRules.associationsAreMappedFromOneSideOnly()`(testkit)는 `@Entity`, `@MappedSuperclass`, `@Embeddable` 타입의 +모든 양방향 짝에서 빌드를 실패시킨다. `mappedBy`를 선언한 연관(그 반대쪽 반만 보고한다), 그리고 `mappedBy` 없이 서로를 +가리키는 두 엔티티(두 반을 다 보고한다. 위의 `@JoinColumn` 꼴, review RR-03-04)다. 메시지는 짝이 링크를 어떻게 가지는지 +말한다. 양 끝에서 매핑한 join 열 하나이거나, 링크를 두 번 저장한 것이다. 두 번 저장한 것은 자식 자신의 `@ManyToOne` 열 옆 +join 테이블의, `@JoinColumn` 없는 `@OneToMany`(`mappedBy`를 잊으면 생긴다)이거나, 저마다 join 테이블을 가진 `@ManyToMany` +둘이다(재확인 리뷰 round 3, RR3-02-05). 그 마지막 검사는 서로에게 저마다 foreign key를 든 두 엔티티도 거부한다 +(`Order.@OneToOne latestInvoice`와 `Invoice.@ManyToOne order`). 링크 하나를 두 번 매핑한 것은 아니고, 메시지도 그렇게 +말한다. 일부러 거부한다. 그러면 두 테이블이 서로를 참조해서, 어느 행도 먼저 넣거나 지울 수 없고, 키 하나는 nullable이어야 +하고 두 번째 `UPDATE`로 써야 하며, 엔티티 그래프가 cycle이 된다. 연관은 한쪽에 두고 다른 쪽에는 ID나 쿼리를 준다(재확인 +리뷰 round 2, RR-02-15). 자기 자신에 링크하는 클래스는, 두 번째 멤버가 반대로 가리킬 때만 짝이다(`@ManyToOne parent`와 +`@OneToMany children`). 자기 자신으로의 `@ManyToOne` 링크 둘(manager와 mentor)은 통과한다. 두 키가 모두 한 테이블을 가리켜서 +순서를 정할 두 테이블이 없기 때문이다. 이 규칙은 `JpaProductionArchitectureTest`(app-bootstrap `architectureTest`)가 운영 +그래프 전체에 건다. 실패 메시지가 칸 이름과 이 대안들을 알려 준다. -Chosen and rejected: +고른 것과 버린 것: -| Option | Decision | Why | +| 선택지 | 결정 | 이유 | | --- | --- | --- | -| One side only (ID reference, unidirectional `@ManyToOne`, collection by query), enforced by ArchUnit | Chosen | The link lives in one field, so there is nothing to keep in step. The rule turns a developer-memory convention into a build failure | -| Bidirectional with `mappedBy` and an `addChild`/`removeChild` helper that sets both sides | Rejected | The helper is the only thing keeping the two fields in step, and it must be remembered by every caller, every serializer (cycles in `toString`/JSON) and every cascade decision. A missed update leaves a row unlinked or a graph that disagrees with the database, with no error | -| Ban `@OneToMany` entirely | Rejected for now | It also bans a root-owned child collection, which has no second field to forget. Revisit if a real need for child entities that are read or changed on their own appears — that need is a sign they are a separate aggregate | -| Document only | Rejected | A convention the build does not check is invisible where the mapping is written, and the next copy of the template inherits whatever the examples show | +| 한쪽만(ID 참조, 단방향 `@ManyToOne`, 쿼리로 읽는 collection), ArchUnit으로 강제 | 고름 | 링크가 칸 하나에 있어서 맞춰 둘 것이 없다. 규칙이 개발자의 기억에 맡긴 관례를 빌드 실패로 바꾼다 | +| `mappedBy`와 양쪽을 다 설정하는 `addChild`/`removeChild` helper를 둔 양방향 | 버림 | 두 칸을 맞춰 두는 것은 helper뿐이고, 모든 호출자, 모든 serializer(`toString`·JSON의 cycle), 모든 cascade 결정이 그것을 기억해야 한다. 고치기를 하나 놓치면 링크 없는 행이나 DB와 다른 그래프가 남고, 오류는 없다 | +| `@OneToMany`를 아예 금지 | 지금은 버림 | root가 가진 자식 collection도 막는데, 그것에는 잊을 두 번째 칸이 없다. 자식 엔티티를 따로 읽거나 바꿀 실제 필요가 생기면 다시 본다. 그 필요는 그것이 별도 aggregate라는 신호다 | +| 문서만 | 버림 | 빌드가 확인하지 않는 관례는 매핑을 쓰는 자리에서 보이지 않고, 템플릿의 다음 사본은 예시가 보여 주는 것을 그대로 물려받는다 | -## Entities never leave the transaction +## 엔티티는 트랜잭션 밖으로 나가지 않는다 -A controller must not return an entity, or a collection or `Optional` of one. Response serialisation -happens after the transaction closes, so a lazy association touched by the serialiser either throws -or — with OSIV on, which this platform forbids — issues a query from the view layer, one per element. -`EntityExposureCondition` checks generic type arguments, not just the erased return type. +controller는 엔티티를, 또는 엔티티의 collection이나 `Optional`을 돌려주지 않는다. 응답 직렬화는 트랜잭션이 닫힌 뒤에 일어나므로, +serializer가 건드린 lazy 연관은 예외를 던지거나, OSIV가 켜져 있으면(이 플랫폼은 금지한다) view 계층에서 원소마다 쿼리를 낸다. +`EntityExposureCondition`은 지워진 반환 타입만이 아니라 generic 타입 인자까지 확인한다. diff --git a/docs/jpa/experimental-promotion-checklist.md b/docs/jpa/experimental-promotion-checklist.md index c6906018..7ab055c5 100644 --- a/docs/jpa/experimental-promotion-checklist.md +++ b/docs/jpa/experimental-promotion-checklist.md @@ -1,45 +1,43 @@ -# Experimental Promotion Checklist +# Experimental 승격 점검 목록 -A reviewer evaluates this checklist. Every technical item, then the ADR. (The -`ExperimentalPromotionGate` class that encoded it in main code was removed on 2026-09-25; nothing -called it.) +리뷰어가 이 목록을 판정한다. 기술 항목을 모두 본 뒤 ADR을 본다. (이것을 main 코드로 담았던 `ExperimentalPromotionGate` +클래스는 부르는 곳이 없어 2026-09-25에 지웠다.) -## Technical evidence +## 기술 증거 -- [ ] **Compatibility** — the Stable contract suite passes on the experimental target, twice, on two - supported patch releases. One passing run is a coincidence. -- [ ] **Security** — for tenancy features, cross-tenant read *and* write are both proven impossible, - including through native SQL, bulk DML, `getReference`, and the second-level cache. A filter - that covers only entity queries covers none of those. -- [ ] **Failure** — connection reuse does not leak tenant context; a failover does not silently route - a read-after-write to a stale replica; the commit-ambiguity scenarios still behave. -- [ ] **Migration** — per-tenant migration is resumable after a partial failure, and rate-limited. - With one schema per tenant, a run is N independent migrations and "it failed" is not an answer. -- [ ] **Performance** — pool capacity, replica lag under load, and per-tenant memory are measured, - not estimated. Database-per-tenant fails as a sum, not as an individual pool. +- [ ] **호환성** — Stable 계약 suite가 experimental 대상에서, 지원하는 patch 릴리스 둘에서, 두 번 통과한다. 한 번의 통과는 + 우연이다. +- [ ] **보안** — tenancy 기능이면 다른 테넌트의 읽기 *와* 쓰기가 둘 다 불가능함을 증명한다. native SQL, bulk DML, + `getReference`, second-level cache를 통한 것도 포함한다. 엔티티 쿼리만 덮는 필터는 그중 어느 것도 덮지 않는다. +- [ ] **장애** — 연결 재사용이 테넌트 context를 흘리지 않는다. failover가 쓰기 뒤 읽기를 조용히 낡은 replica로 보내지 않는다. + 커밋 모호함 시나리오가 여전히 맞게 동작한다. +- [ ] **마이그레이션** — 테넌트별 마이그레이션은 부분 실패 뒤 이어서 할 수 있고, 속도가 제한된다. 테넌트마다 schema가 하나면 + 실행 한 번은 독립 마이그레이션 N개이고, 「실패했다」는 답이 아니다. +- [ ] **성능** — 풀 용량, 부하에서의 replica 지연, 테넌트별 메모리를 어림하지 않고 잰다. 테넌트마다 DB를 두는 방식은 풀 + 하나가 아니라 합으로 실패한다. -## Decision +## 결정 -- [ ] **Reviewed ADR** — recording what is being promised, the operational burden it carries, and - what would cause it to be withdrawn. +- [ ] **검토한 ADR** — 무엇을 약속하는지, 그것이 지우는 운영 부담, 무엇이 생기면 거두는지를 기록한다. -The ADR is not a formality. The technical suites establish that something works; the ADR records -that the platform should promise it, which is a different question with a different cost. +ADR은 형식이 아니다. 기술 suite는 무언가가 동작함을 세우고, ADR은 플랫폼이 그것을 약속해야 함을 기록한다. 다른 질문이고 +비용도 다르다. -## What does not count as evidence +## 증거로 치지 않는 것 -- The version being generally available. -- The feature working in one environment. -- A passing suite that skipped because Docker was unavailable. -- A green lane whose assertions were relaxed to make it pass. +- 그 버전이 GA라는 사실. +- 그 기능이 한 환경에서 동작한다는 사실. +- Docker가 없어서 건너뛰고 통과한 suite. +- 통과시키려고 단언을 느슨하게 한 초록 lane. -## Outcomes +## 결과 -| Decision | Meaning | +결과 이름은 지운 `ExperimentalPromotionGate`가 쓰던 것이고, 지금은 리뷰어가 판정을 적는 말이다. + +| 결정 | 뜻 | |---|---| -| `BLOCKED_TECHNICAL` | at least one suite has not passed | -| `BLOCKED_MISSING_ADR` | evidence is complete; no reviewed decision exists | -| `ELIGIBLE_FOR_STABLE_REVIEW` | both; Stable review may begin | +| `BLOCKED_TECHNICAL` | 통과하지 않은 suite가 하나 이상 있다 | +| `BLOCKED_MISSING_ADR` | 증거는 다 있고, 검토한 결정이 없다 | +| `ELIGIBLE_FOR_STABLE_REVIEW` | 둘 다 있다. Stable 리뷰를 시작해도 된다 | -The two blocked states are distinct because they need different work: one needs evidence, the other -needs a decision. +막힌 상태 둘을 나누는 이유는 필요한 일이 달라서다. 하나는 증거가, 다른 하나는 결정이 필요하다. diff --git a/docs/jpa/experimental-support-matrix.md b/docs/jpa/experimental-support-matrix.md index 99e4e862..15bee87f 100644 --- a/docs/jpa/experimental-support-matrix.md +++ b/docs/jpa/experimental-support-matrix.md @@ -1,43 +1,35 @@ -# Experimental Support Matrix +# Experimental 지원 매트릭스 -Experimental code is library code in `dev.caskeleton.adapter.outbound.persistence.experimental`. -Nothing composes it and no setting turns it on: a deployment that wants one of these creates the -entry point in its own adapter code, and that call is the opt-in. None of it is part of the Stable -composition, and `JpaModuleBoundaryTest` keeps Stable packages from depending on it. +Experimental 코드는 `dev.caskeleton.adapter.outbound.persistence.experimental`의 라이브러리 코드다. 그것을 조립하는 것도, 켜는 +설정도 없다. 이 중 하나를 원하는 배포는 자기 어댑터 코드에서 진입점을 만들고, 그 호출이 opt-in이다. 어느 것도 Stable 조립에 +들어가지 않고, `JpaModuleBoundaryTest`가 Stable 패키지가 그것에 의존하지 못하게 막는다. -| Feature | Entry point | Evidence (PostgreSQL lane unless noted) | State | +| 기능 | 진입점 | 증거(따로 적지 않으면 PostgreSQL lane) | 상태 | |---|---|---|---| -| Shared-schema multi-tenancy (column) | `tenant.TenantContext`, `tenant.TenantAwareRepositoryGuard` | `TenantColumnIsolationTest` | Experimental | +| 공유 schema multi-tenancy(열) | `tenant.TenantContext`, `tenant.TenantAwareRepositoryGuard` | `TenantColumnIsolationTest` | Experimental | | PostgreSQL RLS multi-tenancy | `rls.RlsTenantSessionBinder`, `rls.RlsPolicyVerifier` | `RlsIsolationFailureTest` | Experimental | -| Schema-per-tenant | `schema.SchemaMultiTenantConnectionProvider`, `schema.SchemaTenantMigrationOrchestrator` | `SchemaTenantMigrationContractTest` | Experimental | -| Database-per-tenant pool budget | `database.TenantDataSourceRegistry`, `database.TenantPoolBudget` | `TenantPoolCapacityContractTest` | Experimental | -| Consistency-aware read replica | `replica.ConsistencyAwareDataSourceRouter` (you implement `ReplicaLagMonitor`) | `ReadAfterWriteRoutingContractTest` | Experimental | -| Jakarta Persistence 4.0, Hibernate ORM 8, PostgreSQL 19 | none — probes in `.github/workflows/jpa-next.yml` record `NOT_EXECUTABLE` | `Jpa4CompatibilityTest`, `Hibernate8CompatibilityTest`, `PostgreSql19CompatibilityTest` (unit-lane version canaries) | Not executable | +| 테넌트마다 schema | `schema.SchemaMultiTenantConnectionProvider`, `schema.SchemaTenantMigrationOrchestrator` | `SchemaTenantMigrationContractTest` | Experimental | +| 테넌트마다 DB의 풀 예산 | `database.TenantDataSourceRegistry`, `database.TenantPoolBudget` | `TenantPoolCapacityContractTest` | Experimental | +| 일관성을 아는 read replica | `replica.ConsistencyAwareDataSourceRouter`(`ReplicaLagMonitor`는 직접 구현) | `ReadAfterWriteRoutingContractTest` | Experimental | +| Jakarta Persistence 4.0, Hibernate ORM 8, PostgreSQL 19 | 없음 — `.github/workflows/jpa-next.yml`의 probe가 `NOT_EXECUTABLE`을 기록 | `Jpa4CompatibilityTest`, `Hibernate8CompatibilityTest`, `PostgreSql19CompatibilityTest`(unit lane의 버전 canary) | 실행 불가 | -The `backend.jpa.experimental.*` flags and `ExperimentalFeatureGate` that used to front these were -removed on 2026-09-25: no code read the flags from configuration, so setting one did nothing, and -the gate only checked a map the caller built itself. +> 이력: 이것들 앞에 있던 `backend.jpa.experimental.*` 스위치와 `ExperimentalFeatureGate`는 2026-09-25에 지웠다. 어떤 코드도 +> 설정에서 스위치를 읽지 않아서 켜도 아무 일이 없었고, gate는 호출자가 스스로 만든 map만 확인했다. -## Known constraints +## 알려진 제약 -- Tenant context is fail-closed. An unbound tenant in a shared-schema deployment means a query with - no tenant predicate, which returns every tenant's rows. -- A Hibernate filter is not the security boundary. It does not apply to native SQL, bulk DML, - `getReference`, or the second-level cache. -- RLS requires all three of: `ENABLE ROW LEVEL SECURITY`, `FORCE ROW LEVEL SECURITY` (the owner is - otherwise exempt from its own policies), and a runtime role without `BYPASSRLS`. -- Tenant bindings are transaction-local. A session-local setting survives the connection's return to - the pool. -- `readOnly=true` never routes to a replica on its own. Read-after-write uses a consistency token or - the primary. -- Unavailable replica lag evidence means the primary. Absence of evidence is not evidence of - freshness. -- Per-tenant pools are bounded globally. Fifty tenants with a modest pool each is five hundred - connections against a server that permits a hundred. -- Tenant ids never become metric tags. Tenant cardinality is unbounded by definition. +- 테넌트 context는 닫힌 채 실패한다. 공유 schema 배포에서 테넌트가 묶이지 않으면 테넌트 조건 없는 쿼리가 되고, 모든 테넌트의 + 행을 돌려준다. +- Hibernate filter는 보안 경계가 아니다. native SQL, bulk DML, `getReference`, second-level cache에 적용되지 않는다. +- RLS에는 셋이 모두 필요하다. `ENABLE ROW LEVEL SECURITY`, `FORCE ROW LEVEL SECURITY`(그렇지 않으면 소유자는 자기 정책에서 + 빠진다), `BYPASSRLS` 없는 런타임 역할. +- 테넌트 묶기는 트랜잭션 로컬이다. 세션 로컬 설정은 연결이 풀로 돌아간 뒤에도 남는다. +- `readOnly=true`만으로는 replica로 보내지 않는다. 쓰기 뒤 읽기는 일관성 token이나 primary를 쓴다. +- replica 지연 증거를 얻을 수 없으면 primary다. 증거가 없다는 것은 최신이라는 증거가 아니다. +- 테넌트별 풀은 전역으로 제한한다. 적당한 풀을 가진 테넌트 50개는 연결 100개를 허용하는 서버에 대한 연결 500개다. +- 테넌트 id는 메트릭 태그가 되지 않는다. 테넌트 수는 정의상 상한이 없다. -## Lanes never change Stable +## lane은 Stable을 바꾸지 않는다 -A compatibility lane publishes nothing and changes no Stable contract. If Hibernate 8 generates -different SQL for the fetch-pagination gate, that is a finding about Hibernate 8 — the 7.x gate keeps -asserting what 7.x must do, because that is what deployments run. +호환성 lane은 아무것도 게시하지 않고 어떤 Stable 계약도 바꾸지 않는다. Hibernate 8이 fetch-pagination gate에 다른 SQL을 +만들면 그것은 Hibernate 8에 대한 발견이다. 7.x gate는 7.x가 해야 할 것을 계속 단언한다. 배포가 돌리는 것이 그것이기 때문이다. diff --git a/docs/jpa/migration-guide.md b/docs/jpa/migration-guide.md index 0a6b3e61..3d00664d 100644 --- a/docs/jpa/migration-guide.md +++ b/docs/jpa/migration-guide.md @@ -1,198 +1,165 @@ -# Migration Guide +# 마이그레이션 가이드 -Design §31-§32. Flyway owns the schema; Hibernate only validates. +설계서 §31-§32. 스키마는 Flyway가 가지고, Hibernate는 검증만 한다. -## Who may change the schema +이 문서의 절 셋은 코드와 다른 문서가 영어 제목으로 가리킨다. 그래서 그 절 제목에는 영어 이름을 괄호로 함께 둔다: +「누가 스키마를 바꾸나 (Who may change the schema)」, 「잠금 대기에 상한을 둔다 (Bound the lock wait)」, +「동시 인덱스 빌드 (Concurrent index builds)」. -| Environment | Mode | +## 누가 스키마를 바꾸나 (Who may change the schema) + +| 환경 | 방식 | |---|---| -| local, test, dev | migrate at startup with the migration credential | -| staging, prod | deployment-owned migration; the application validates only | +| local, test, dev | 마이그레이션 자격 증명으로 기동할 때 migrate한다 | +| staging, prod | 배포가 가진 마이그레이션. 애플리케이션은 검증만 한다 | -Migrating from inside the application in production means every instance of a rolling deploy races -to apply the same script, and the loser's failure is indistinguishable from a real one. +운영에서 애플리케이션 안에서 migrate하면 rolling deploy의 모든 인스턴스가 같은 스크립트를 적용하려고 경주하고, 진 쪽의 +실패는 진짜 실패와 구별되지 않는다. -Whoever runs the migration holds Flyway's PostgreSQL migration lock for the session, not in a -transaction: `flyway.postgresql.transactional.lock=false`. Flyway's default (`true`) keeps a -transaction open until the whole run ends, and a concurrent index build waits for every transaction -older than itself, Flyway's own included — the deploy stops with no error and no time limit -("Concurrent index builds" below). The template sets it for every Flyway it runs: the module -defaults (`config/module-defaults/persistence-jpa.yml`, `spring.flyway.postgresql.transactional-lock: -false`) for the one Spring Boot builds at startup, and `FlywaySchemaPolicy.configure()` for every -stream it builds itself — a service's own stream starts from it too, and `JpaProductionArchitectureTest` -refuses production code that builds a Flyway any other way: calling `Flyway.configure()`, or -constructing a configuration itself (`new FluentConfiguration()`, `new ClassicConfiguration()`, a -subclass of either, or `FluentConfiguration::new`). `new Flyway(...)` over the policy's configuration -is allowed. The deployment-owned migration of -staging and prod is outside this repository: give its tool the same value -(`FLYWAY_POSTGRESQL_TRANSACTIONAL_LOCK=false`, or the key above in its configuration file). +마이그레이션을 돌리는 쪽은 Flyway의 PostgreSQL 마이그레이션 잠금을 트랜잭션이 아니라 세션에 둔다: +`flyway.postgresql.transactional.lock=false`. Flyway의 기본값(`true`)은 실행 전체가 끝날 때까지 트랜잭션을 열어 두고, +동시 인덱스 빌드는 Flyway 자신의 것을 포함해 자기보다 오래된 모든 트랜잭션을 기다린다. 그러면 배포가 오류도 시간 상한도 +없이 멈춘다(아래 「동시 인덱스 빌드」). 템플릿은 자기가 돌리는 모든 Flyway에 이 값을 둔다. Spring Boot가 기동할 때 만드는 +Flyway에는 module defaults(`config/module-defaults/persistence-jpa.yml`, `spring.flyway.postgresql.transactional-lock: +false`)가, 스스로 만드는 stream에는 `FlywaySchemaPolicy.configure()`가 그렇게 한다. 서비스 자신의 stream도 거기서 +시작하고, `JpaProductionArchitectureTest`는 다른 방법으로 Flyway를 만드는 운영 코드를 거부한다. `Flyway.configure()`를 +부르거나, 설정을 직접 만드는 것(`new FluentConfiguration()`, `new ClassicConfiguration()`, 그 둘의 subclass, +`FluentConfiguration::new`)이다. 정책의 설정 위에 `new Flyway(...)`를 하는 것은 허용한다. staging과 prod의 배포 쪽 +마이그레이션은 이 저장소 밖에 있다. 그 도구에도 같은 값을 준다(`FLYWAY_POSTGRESQL_TRANSACTIONAL_LOCK=false`, 또는 그 도구 +설정 파일의 위 키). -A session lock assumes the connection Flyway takes stays its own for the whole run, which the -template's direct Hikari connection gives. Behind a pooler in transaction mode (PgBouncer -`pool_mode = transaction`) the unlock can reach another server connection and release nothing, and -the next migration waits for a lock that a pooled connection still holds. Run migrations over a -direct connection or a session-mode pool. +세션 잠금은 Flyway가 잡은 연결이 실행 내내 Flyway의 것으로 남는다고 가정한다. 템플릿의 직접 Hikari 연결이 그것을 준다. +트랜잭션 모드 pooler(PgBouncer `pool_mode = transaction`) 뒤에서는 unlock이 다른 서버 연결로 가서 아무것도 풀지 못하고, +다음 마이그레이션은 풀의 연결이 아직 쥔 잠금을 기다린다. 마이그레이션은 직접 연결이나 세션 모드 풀로 돌린다. -`ddl-auto` is `validate` or `none`. Never `update`: it never drops or narrows anything, so it -produces a schema that is neither the old one nor the one the migrations describe — silently, on -whichever instance started first. +`ddl-auto`는 `validate`나 `none`이다. `update`는 절대 쓰지 않는다. 그것은 아무것도 지우거나 좁히지 않으므로, 옛 스키마도 +아니고 마이그레이션이 설명하는 스키마도 아닌 스키마를 만든다. 조용히, 먼저 뜬 인스턴스에서. -## Validation fails closed and never repairs +## 검증은 닫힌 채 실패하고, repair하지 않는다 -At startup Flyway's own validation (and Hibernate `ddl-auto=validate`) refuses a checksum mismatch, -a missing migration, or a schema Hibernate disagrees with. Nothing in the application calls -`repair`. In tests, the testkit's `FlywayValidationGate` turns a failed `ValidateResult` into -`SchemaMismatchException`; the migration contract tests use it. +기동할 때 Flyway 자신의 검증(과 Hibernate `ddl-auto=validate`)이 checksum 불일치, 빠진 마이그레이션, Hibernate가 동의하지 +않는 스키마를 거부한다. 애플리케이션의 어떤 것도 `repair`를 부르지 않는다. 테스트에서는 testkit의 `FlywayValidationGate`가 +실패한 `ValidateResult`를 `SchemaMismatchException`으로 바꾸고, 마이그레이션 계약 테스트가 그것을 쓴다. -Repair rewrites the schema history table to match whatever scripts are on disk. That resolves the -symptom by deleting the evidence: a checksum mismatch means the deployed script differs from the -applied one, and the interesting question is which change is missing from this database. Repair -makes that question unaskable. It exists only as an explicit admin operation with an operator, a -reason, and an approval (design §8.4). +repair는 schema history 테이블을 디스크에 있는 스크립트에 맞춰 다시 쓴다. 그것은 증거를 지워서 증상을 없앤다. checksum +불일치는 배포한 스크립트가 적용된 것과 다르다는 뜻이고, 물어야 할 것은 이 DB에 어느 변경이 빠졌느냐다. repair는 그 질문을 +물을 수 없게 만든다. repair는 운영자, 이유, 승인이 있는 명시적 관리 작업으로만 있다(설계서 §8.4). -The one change to the history an operator makes is narrower than repair: after a concurrent index -migration fails, the failed row of that one version is deleted so that the version can run again -("Concurrent index builds" below). Every applied row, and its checksum, stays as it was. +운영자가 이력에 하는 변경은 repair보다 좁은 것 하나다. 동시 인덱스 마이그레이션이 실패한 뒤, 그 버전을 다시 돌릴 수 있게 +그 한 버전의 실패 행을 지운다(아래 「동시 인덱스 빌드」). 적용된 행과 그 checksum은 모두 그대로다. -Only Flyway's structured error codes reach the exception. Its messages embed the script path and -part of the failing statement. +예외에는 Flyway의 구조화된 오류 코드만 닿는다. Flyway의 메시지는 스크립트 경로와 실패한 문장 일부를 담는다. -## Bound the lock wait +## 잠금 대기에 상한을 둔다 (Bound the lock wait) -A migration that locks a table already in use starts with `SET LOCAL lock_timeout = '5s';`, before -the first statement that takes the lock. `ALTER TABLE` takes the strongest lock there is, which -conflicts even with a plain read; a non-concurrent `CREATE INDEX` takes one that stops every write; -`UPDATE` and `DELETE` wait on the rows other transactions hold. Unbounded, the migration waits for -the oldest open transaction that touched the table — an operator's forgotten `BEGIN` in psql has no -deadline — and every read and write that arrives meanwhile queues behind the migration, holding a -pool connection while it waits. With the bound, the migration fails after five seconds, Flyway -rolls it back whole, the database stays on the version before it and the new release does not -start: a failed deploy instead of an outage. Deploy again when the transaction has ended. +이미 쓰는 테이블을 잠그는 마이그레이션은, 잠금을 잡는 첫 문장 전에 `SET LOCAL lock_timeout = '5s';`로 시작한다. +`ALTER TABLE`은 가장 강한 잠금을 잡아 평범한 읽기와도 부딪친다. 동시가 아닌 `CREATE INDEX`는 모든 쓰기를 멈추는 잠금을 +잡는다. `UPDATE`와 `DELETE`는 다른 트랜잭션이 쥔 행을 기다린다. 상한이 없으면 마이그레이션은 그 테이블을 건드린 가장 오래된 +열린 트랜잭션을 기다린다. psql에서 운영자가 잊은 `BEGIN`에는 마감이 없다. 그사이 도착하는 모든 읽기와 쓰기가 마이그레이션 +뒤에 줄을 서고, 기다리는 동안 풀 연결을 쥔다. 상한이 있으면 마이그레이션은 5초 뒤 실패하고, Flyway가 통째로 롤백하고, DB는 +그 앞 버전에 남고, 새 릴리스는 뜨지 않는다. 장애 대신 실패한 배포다. 그 트랜잭션이 끝난 뒤 다시 배포한다. -`LOCAL`, because a plain `SET` outlives the migration on the pooled connection Flyway borrowed and -changes every statement that later runs on it. The value is not zero: `lock_timeout = 0` (or -`DEFAULT`, or a later `RESET`) is no bound at all. A migration with `executeInTransaction=false` -cannot use it — `SET LOCAL` outside a transaction only warns — so a statement that locks a table -goes into a migration that runs in one. A statement on a table the same migration created a moment -earlier waits for nothing and needs no bound; `CREATE TABLE IF NOT EXISTS` does not count, because -the table may already be there. +`LOCAL`인 이유: 평범한 `SET`은 Flyway가 빌린 풀 연결에서 마이그레이션보다 오래 남아, 나중에 그 연결에서 도는 모든 문장을 +바꾼다. 값은 0이 아니다. `lock_timeout = 0`(또는 `DEFAULT`, 뒤의 `RESET`)은 상한이 아니다. `executeInTransaction=false`인 +마이그레이션은 그것을 쓸 수 없다. 트랜잭션 밖의 `SET LOCAL`은 경고만 하기 때문이다. 그래서 테이블을 잠그는 문장은 +트랜잭션 안에서 도는 마이그레이션에 넣는다. 같은 마이그레이션이 방금 만든 테이블에 대한 문장은 기다릴 것이 없어 상한이 +필요 없다. `CREATE TABLE IF NOT EXISTS`는 해당하지 않는다. 테이블이 이미 있을 수 있기 때문이다. -Flyway also takes a migration out of its transaction on its own, without a `.sql.conf`: on -PostgreSQL 12 and later, any statement that starts with `VACUUM`, `CREATE [UNIQUE] INDEX -CONCURRENTLY`, `DROP INDEX CONCURRENTLY`, `REINDEX [VERBOSE] SCHEMA|DATABASE|SYSTEM`, `CREATE` or -`DROP DATABASE|TABLESPACE|SUBSCRIPTION`, `ALTER SYSTEM` or `DISCARD ALL` (Flyway 11, -`PostgreSQLParser`; words inside parentheses are skipped, so `VACUUM (FULL)` and `REINDEX (VERBOSE) -SCHEMA` count). One such statement puts the whole script outside a transaction. Next to any other -statement — a `SET LOCAL lock_timeout` included — Flyway refuses the migration at deploy under its -default `mixed=false`; a service that sets `mixed=true` gets it run, with the bound silently gone. -Put such a statement in a migration of its own. `REINDEX TABLE|INDEX CONCURRENTLY` is not on -Flyway's list: Flyway runs it in the transaction, PostgreSQL refuses it there, and it needs -`executeInTransaction=false` (below). A locking statement that cannot run in a transaction at all — -`VACUUM FULL`, a non-concurrent `REINDEX SCHEMA|DATABASE|SYSTEM` — can never be bounded this way and -does not belong in a migration: run it by hand as an operations step, outside a deploy, in a psql -session that sets `SET lock_timeout = '5s';` first (the session ends with the step, so the plain -`SET` is the bound there). A `.sql.conf` with `executeInTransaction=true` does not change that: it -keeps the statement and its `SET LOCAL` in the transaction only for PostgreSQL to refuse it at -deploy, and the inspector below refuses it as well. +Flyway는 `.sql.conf` 없이도 스스로 마이그레이션을 트랜잭션 밖으로 뺀다. PostgreSQL 12 이상에서 `VACUUM`, `CREATE [UNIQUE] +INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY`, `REINDEX [VERBOSE] SCHEMA|DATABASE|SYSTEM`, `CREATE`나 +`DROP DATABASE|TABLESPACE|SUBSCRIPTION`, `ALTER SYSTEM`, `DISCARD ALL`로 시작하는 문장이 있으면 그렇다(Flyway 11, +`PostgreSQLParser`. 괄호 안의 낱말은 건너뛰므로 `VACUUM (FULL)`과 `REINDEX (VERBOSE) SCHEMA`도 센다). 그런 문장 하나가 +스크립트 전체를 트랜잭션 밖에 둔다. 다른 문장(`SET LOCAL lock_timeout` 포함) 옆에 두면 Flyway는 기본값 `mixed=false`에서 +배포 때 그 마이그레이션을 거부한다. `mixed=true`로 둔 서비스는 그것을 돌리지만 상한이 조용히 사라진다. 그런 문장은 따로 +마이그레이션 하나에 넣는다. `REINDEX TABLE|INDEX CONCURRENTLY`는 Flyway의 목록에 없다. Flyway는 그것을 트랜잭션 안에서 +돌리고 PostgreSQL이 거기서 거부하므로 `executeInTransaction=false`가 필요하다(아래). 트랜잭션 안에서 아예 돌 수 없는 잠그는 +문장(`VACUUM FULL`, 동시가 아닌 `REINDEX SCHEMA|DATABASE|SYSTEM`)은 이 방법으로 상한을 둘 수 없고 마이그레이션에 넣지 않는다. +배포 밖에서 운영 단계로 손으로 돌린다. 먼저 `SET lock_timeout = '5s';`를 거는 psql 세션에서 한다(세션이 그 단계와 함께 +끝나므로 거기서는 평범한 `SET`이 상한이다). `executeInTransaction=true`인 `.sql.conf`도 이것을 바꾸지 못한다. 그 문장과 +`SET LOCAL`을 트랜잭션 안에 둘 뿐이고, 배포 때 PostgreSQL이 거부하며, 아래의 inspector도 거부한다. -Enforced, not remembered: `LockWaitMigrationInspector` (persistence-jpa testkit) reads a script — -and the `.sql.conf` beside it, as Flyway reads it (a properties file, `false` in any case), and -otherwise the statements Flyway takes out of the transaction on its own — and names the statements -from its list that lock an existing table with no bound in force: `ALTER TABLE`, `LOCK TABLE`, `TRUNCATE`, `DROP TABLE`; `CREATE INDEX`, -`DROP INDEX`, `REINDEX` and `REFRESH MATERIALIZED VIEW` without `CONCURRENTLY`, `CLUSTER`, `VACUUM -FULL`; `REFERENCES` on the table it references, in a new table as much as in an `ALTER TABLE` (a -foreign key locks its parent against writes while it is added); `CREATE TRIGGER` and `DROP TRIGGER` -on their table; `UPDATE` and `DELETE`. It reads text, so a statement outside the list is not -checked. `MigrationLockWaitTest`는 이 leaf의 데이터베이스가 돌리는 모든 트리에 이 검사를 건다. 서비스 -스트림은 이 테스트를 복사해 자기 폴더를 넣는다. 이 테스트는 Flyway와 같은 방식으로 마이그레이션을 찾고, 소수 -버전(`V22_1__`)도 포함한다(`VersionedMigrationFiles`, testkit). The migrations released before the rule wait unbounded and -stay that way (they are applied, and applied files are never edited); the test lists them and -refuses any new one. `PostgreSqlMigrationLockWaitIntegrationTest` -(`postgresqlMigrationLockWaitIntegrationTest`) shows on real PostgreSQL that a bounded migration -gives up within the bound while another transaction holds the table, and leaves the version below -it; it also compares the inspector's copy of Flyway's list with Flyway itself for the statements it -lists (each is named by the inspector exactly when Flyway refuses it next to a `SET LOCAL`), and -shows a `VACUUM FULL` run under `mixed=true` waiting out a reader despite its `SET LOCAL`. A -statement a Flyway upgrade adds to the list is outside that comparison; `LockWaitMigrationInspectorTest` -pins Flyway's own patterns (`PostgreSQLParser`), so such an upgrade fails the pull request's `ci` -until the copy follows. The gRPC ledger's tree lives in the -optional build, which cannot depend on the testkit: its `GrpcOperationLedgerMigrationLockWaitIT` -runs every ledger migration after V001, read from the tree, against a held ledger instead, so its -next migration is checked on real PostgreSQL. It finds and orders that tree with the testkit's own -`VersionedMigrationFiles`, which the ledger's `build.gradle` copies into its integration-test sources -at build time (`sharedMigrationFileSources`), so both builds read one definition. A concurrent index -build in that tree runs outside a transaction and is no case for a held ledger: it goes in the -test's `RUN_OUTSIDE_A_TRANSACTION` with its reason, and the same test holds each file listed there to -`ConcurrentIndexMigrationInspector`, copied the same way ("Concurrent index builds"). Every ledger -lane applies the tree one file at a time, as Flyway does, so such a file is not refused inside the -implicit transaction of one string holding many. The rule came -from V21 having the bound and V22, in the same commit, not having it (re-review 2026-11-03 round 2, -RR-02-09; round 3, RR3-02-01, RR3-02-03, RR3-02-04; round 4, RR4-02-01; round 6, RR6-03-02, -RR6-03-03; round 7, RR7-03-01). +기억에 맡기지 않고 강제한다. `LockWaitMigrationInspector`(persistence-jpa testkit)가 스크립트를 읽는다. 옆의 `.sql.conf`도 +Flyway처럼 읽고(properties 파일, 대소문자 상관없이 `false`), 그 밖에는 Flyway가 스스로 트랜잭션 밖으로 빼는 문장을 본다. +그리고 상한 없이 이미 있는 테이블을 잠그는, 자기 목록의 문장을 이름 댄다: `ALTER TABLE`, `LOCK TABLE`, `TRUNCATE`, +`DROP TABLE`; `CONCURRENTLY` 없는 `CREATE INDEX`, `DROP INDEX`, `REINDEX`, `REFRESH MATERIALIZED VIEW`, `CLUSTER`, +`VACUUM FULL`; 참조하는 테이블에 대한 `REFERENCES`(새 테이블에서도 `ALTER TABLE`에서도. foreign key는 추가되는 동안 부모 +테이블의 쓰기를 막는다); 그 테이블의 `CREATE TRIGGER`와 `DROP TRIGGER`; `UPDATE`와 `DELETE`. 텍스트를 읽으므로 목록 밖의 +문장은 확인하지 않는다. `MigrationLockWaitTest`는 이 leaf의 데이터베이스가 돌리는 모든 트리에 이 검사를 건다. 서비스 +스트림은 이 테스트를 복사해 자기 폴더를 넣는다. 이 테스트는 Flyway와 같은 방식으로 마이그레이션을 찾고, 소수 버전 +(`V22_1__`)도 포함한다(`VersionedMigrationFiles`, testkit). 규칙 전에 나간 마이그레이션은 상한 없이 기다리고 그대로 둔다 +(이미 적용됐고, 적용된 파일은 고치지 않는다). 테스트가 그것을 나열하고 새것은 거부한다. -## Concurrent index builds +`PostgreSqlMigrationLockWaitIntegrationTest`(`postgresqlMigrationLockWaitIntegrationTest`)가 실제 PostgreSQL에서 보인다. +다른 트랜잭션이 테이블을 쥔 동안 상한 있는 마이그레이션은 상한 안에 포기하고 그 아래 버전을 남긴다. 또 inspector가 가진 +Flyway 목록 사본을 그것이 나열한 문장에 대해 Flyway 자신과 비교하고(inspector는 Flyway가 `SET LOCAL` 옆에서 거부하는 바로 +그때 그 문장을 이름 댄다), `mixed=true`에서 돈 `VACUUM FULL`이 `SET LOCAL`에도 불구하고 읽는 쪽을 기다리는 것도 보인다. +Flyway 업그레이드가 목록에 더한 문장은 그 비교 밖이다. `LockWaitMigrationInspectorTest`가 Flyway 자신의 패턴 +(`PostgreSQLParser`)을 고정하므로, 그런 업그레이드는 사본이 따라올 때까지 pull request의 `ci`를 실패시킨다. -`CREATE INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY` and `REINDEX … CONCURRENTLY` cannot run -inside a transaction block. Flyway runs a script outside a transaction on its own when it holds -`CREATE`/`DROP INDEX CONCURRENTLY` or `REINDEX SCHEMA|DATABASE`, with or without `CONCURRENTLY` -(above). It runs `REINDEX INDEX|TABLE … CONCURRENTLY` — `REINDEX (CONCURRENTLY) TABLE` included — in -the transaction, where PostgreSQL refuses it. `PostgreSqlMigrationLockWaitIntegrationTest` shows the -five forms on real PostgreSQL. Write the companion configuration for every concurrent statement -anyway, so the file says what it needs and no reader has to know Flyway's list: +gRPC ledger의 트리는 optional 빌드에 있어서 testkit에 의존할 수 없다. 그래서 그 `GrpcOperationLedgerMigrationLockWaitIT`가 +트리에서 읽은 V001 뒤의 모든 ledger 마이그레이션을 대신 쥔 ledger에 대고 돌리므로, 다음 마이그레이션도 실제 PostgreSQL에서 +확인된다. 그 트리를 찾고 순서를 매기는 것은 testkit 자신의 `VersionedMigrationFiles`다. ledger의 `build.gradle`이 빌드 때 +그것을 통합 테스트 소스로 복사하므로(`sharedMigrationFileSources`) 두 빌드가 한 정의를 읽는다. 그 트리의 동시 인덱스 빌드는 +트랜잭션 밖에서 돌므로 쥔 ledger로 시험할 경우가 아니다. 그런 파일은 이유와 함께 테스트의 `RUN_OUTSIDE_A_TRANSACTION`에 +넣고, 같은 테스트가 거기 나열한 파일마다 같은 방식으로 복사한 `ConcurrentIndexMigrationInspector`를 건다(「동시 인덱스 +빌드」). 모든 ledger lane은 Flyway처럼 트리를 파일 하나씩 적용하므로, 그런 파일이 여러 문장을 담은 문자열 하나의 암묵적 +트랜잭션 안에서 거부되지 않는다. + +이 규칙은 같은 커밋에서 V21에는 상한이 있고 V22에는 없었던 데서 나왔다(재확인 리뷰 2026-11-03 round 2, RR-02-09; round 3, +RR3-02-01, RR3-02-03, RR3-02-04; round 4, RR4-02-01; round 6, RR6-03-02, RR6-03-03; round 7, RR7-03-01). + +## 동시 인덱스 빌드 (Concurrent index builds) + +`CREATE INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY`, `REINDEX … CONCURRENTLY`는 트랜잭션 블록 안에서 돌 수 없다. Flyway는 +스크립트가 `CREATE`/`DROP INDEX CONCURRENTLY`나 `REINDEX SCHEMA|DATABASE`(`CONCURRENTLY`가 있든 없든)를 담으면 스스로 +트랜잭션 밖에서 돌린다(위). `REINDEX INDEX|TABLE … CONCURRENTLY`(`REINDEX (CONCURRENTLY) TABLE` 포함)는 트랜잭션 안에서 +돌리고, PostgreSQL이 거기서 거부한다. `PostgreSqlMigrationLockWaitIntegrationTest`가 다섯 꼴을 실제 PostgreSQL에서 보인다. +그래도 모든 동시 문장에 짝 설정을 쓴다. 파일이 자기에게 필요한 것을 말하고, 읽는 사람이 Flyway의 목록을 알 필요가 없다. ```conf # V42__order_index.sql.conf executeInTransaction=false ``` -Outside a transaction, `CREATE INDEX CONCURRENTLY` and `REINDEX … CONCURRENTLY` still wait until -every transaction older than them has ended. Under Flyway's default lock that includes the -transaction Flyway itself keeps open, and Flyway waits for the build in turn: the deploy never ends, -and the table's other DDL and autovacuum queue behind the build meanwhile. The template's Flyway -holds its lock for the session instead ("Who may change the schema"), so the build waits only for -other transactions; a deployment tool left on Flyway's default stops on the first such migration. -`DROP INDEX CONCURRENTLY` does not wait that way: it waits only for the transactions that hold a -lock on its table. `PostgreSqlConcurrentIndexMigrationIntegrationTest` -(`postgresqlConcurrentIndexMigrationIntegrationTest`) applies both builds as a second deploy, with -the Flyway Spring Boot builds from the module defaults and with `FlywaySchemaPolicy.configure()`, -on real PostgreSQL. The other transactions still count: a long one an operator or a report keeps -open holds the build, and the drop too once it has touched the table, and a file run outside a -transaction cannot bound that wait with `SET LOCAL`. Look for old transactions -(`pg_stat_activity.xact_start`) before deploying one. +트랜잭션 밖에서도 `CREATE INDEX CONCURRENTLY`와 `REINDEX … CONCURRENTLY`는 자기보다 오래된 모든 트랜잭션이 끝날 때까지 +기다린다. Flyway 기본 잠금에서는 Flyway 자신이 열어 둔 트랜잭션도 거기 들고, Flyway는 다시 빌드를 기다린다. 배포가 끝나지 +않고, 그동안 그 테이블의 다른 DDL과 autovacuum이 빌드 뒤에 줄을 선다. 템플릿의 Flyway는 대신 세션에 잠금을 둔다(「누가 +스키마를 바꾸나」). 그래서 빌드는 다른 트랜잭션만 기다린다. Flyway 기본값에 둔 배포 도구는 그런 첫 마이그레이션에서 멈춘다. +`DROP INDEX CONCURRENTLY`는 그렇게 기다리지 않는다. 그 테이블에 잠금을 쥔 트랜잭션만 기다린다. +`PostgreSqlConcurrentIndexMigrationIntegrationTest`(`postgresqlConcurrentIndexMigrationIntegrationTest`)가 두 빌드를 두 번째 +배포로, module defaults로 Spring Boot가 만드는 Flyway와 `FlywaySchemaPolicy.configure()`로, 실제 PostgreSQL에 적용한다. +다른 트랜잭션은 여전히 센다. 운영자나 리포트가 열어 둔 긴 트랜잭션은 빌드를 붙잡고, 테이블을 건드린 뒤라면 삭제도 붙잡는다. +트랜잭션 밖에서 도는 파일은 그 대기에 `SET LOCAL`로 상한을 둘 수 없다. 그런 마이그레이션을 배포하기 전에 오래된 트랜잭션 +(`pg_stat_activity.xact_start`)을 찾는다. -The testkit's `ConcurrentIndexMigrationInspector` checks a script for this in a migration test -(nothing checks it at startup), and additionally requires the migration to contain nothing else. -Next to another statement, a concurrent one makes Flyway refuse the file before any of it runs when -nothing configures it; with `executeInTransaction=false` Flyway commits each statement on its own, -and a failed build leaves the statements before it applied — state to reconstruct by hand. +testkit의 `ConcurrentIndexMigrationInspector`가 마이그레이션 테스트에서 스크립트를 이 관점으로 확인하고(기동 때 확인하는 +것은 없다), 그 마이그레이션에 다른 것이 없기를 더 요구한다. 다른 문장 옆에 두면, 아무것도 설정하지 않았을 때 동시 문장은 +Flyway가 파일을 하나도 돌리기 전에 거부하게 만든다. `executeInTransaction=false`면 Flyway는 문장마다 따로 커밋하고, 실패한 +빌드는 그 앞 문장을 적용된 채 남긴다. 손으로 다시 맞춰야 하는 상태다. -Alone, a failed statement leaves an invalid index and a history row with `success = false` for its -version, and Flyway refuses every later deploy ("Detected failed migration to version …") until that -row is gone: dropping the index is not enough. The recovery is -[migration-failed.md](../runbooks/migration-failed.md) "Recover a failed concurrent index migration": -confirm no build is running, remove the cause, drop the invalid index a failed build or rebuild -left, delete that version's failed row and nothing else, deploy again. A failed `DROP INDEX -CONCURRENTLY` leaves invalid the index it was dropping; the runbook leaves that one for the deploy -again to drop, since dropped by hand it makes the same statement fail. It is not `flyway repair`, -which would also rewrite the remaining rows' checksums. `PostgreSqlConcurrentIndexMigrationIntegrationTest` -(`postgresqlConcurrentIndexMigrationIntegrationTest`) runs the runbook's SQL, read from the runbook, -after a unique build that failed on a duplicate and after a rebuild and a drop cancelled while they -waited for an open transaction, and shows both mixed files above. +혼자 있는 문장이 실패하면 무효 인덱스와 그 버전의 `success = false` 이력 행을 남기고, 그 행이 사라질 때까지 Flyway는 뒤의 +모든 배포를 거부한다("Detected failed migration to version …"). 인덱스를 지우는 것만으로는 안 된다. 복구는 +[migration-failed.md](../runbooks/migration-failed.md) 「실패한 동시 인덱스 마이그레이션 복구 (Recover a failed concurrent +index migration)」다. 도는 빌드가 없는지 확인하고, 원인을 없애고, 실패한 빌드나 재빌드가 남긴 무효 인덱스를 지우고, 그 +버전의 실패 행만 지우고, 다시 배포한다. 실패한 `DROP INDEX CONCURRENTLY`는 지우던 인덱스를 무효로 남긴다. runbook은 그것을 +다시 배포가 지우도록 남긴다. 손으로 지우면 같은 문장이 실패하기 때문이다. 이것은 `flyway repair`가 아니다. repair는 남은 행의 +checksum도 다시 쓴다. `PostgreSqlConcurrentIndexMigrationIntegrationTest`(`postgresqlConcurrentIndexMigrationIntegrationTest`)가 +runbook에서 읽은 runbook의 SQL을, 중복으로 실패한 unique 빌드 뒤와, 열린 트랜잭션을 기다리다 취소된 재빌드와 삭제 뒤에 돌리고, +위의 섞인 파일 둘도 보인다. -An invalid index is not merely useless — the planner ignores it while every write still maintains -it. [runbooks.md](runbooks.md) has the query that finds them. Nothing drops them automatically: an -invalid index can also mean a build is still running, and the two are indistinguishable from the -catalog alone. +무효 인덱스는 쓸모없기만 한 게 아니다. planner는 그것을 무시하는데 모든 쓰기는 여전히 그것을 유지한다. 찾는 쿼리는 +[runbooks.md](runbooks.md)에 있다. 아무것도 그것을 자동으로 지우지 않는다. 무효 인덱스는 아직 도는 빌드를 뜻할 수도 있고, +카탈로그만으로는 둘을 구별할 수 없다. -## Upgrade scenarios +## 업그레이드 시나리오 -Three, each catching something the others do not: +셋이고, 저마다 다른 것이 못 잡는 것을 잡는다. -| Scenario | Catches | +| 시나리오 | 잡는 것 | |---|---| -| `empty` | an early migration edited to match a later one, no longer applying to a fresh database | -| `previous-release` | the actual deployment path; the only one exercising this release's migrations | -| `oldest-supported` | a migration that silently assumes state only recent databases have | +| `empty` | 뒤 마이그레이션에 맞추려고 고친 앞 마이그레이션이 새 DB에 더는 적용되지 않음 | +| `previous-release` | 실제 배포 경로. 이 릴리스의 마이그레이션을 돌리는 유일한 시나리오 | +| `oldest-supported` | 최근 DB에만 있는 상태를 몰래 가정하는 마이그레이션 | -Each asserts a data invariant, not just the schema version. A migration that renames a column and -loses its contents leaves the version correct and the data gone. +시나리오마다 스키마 버전만이 아니라 데이터 불변식을 단언한다. 열 이름을 바꾸면서 내용을 잃은 마이그레이션은 버전은 맞고 +데이터는 사라진 채로 남는다. diff --git a/docs/jpa/observability.md b/docs/jpa/observability.md index ad05f819..24d74828 100644 --- a/docs/jpa/observability.md +++ b/docs/jpa/observability.md @@ -1,58 +1,49 @@ -# Observability +# 관측 -Design §37. What is measured, and what must never appear in a measurement. +설계서 §37. 무엇을 재고, 측정에 무엇이 절대 나타나면 안 되나. -## What is emitted by default +## 기본으로 내는 것 -Nothing JPA-specific. No composition constructs a `MeterRegistry`-backed observation for the -platform, and `SpringTransaction` records no transaction metric. The `jpa.transaction.*` meters -this page used to list (`duration`, `rollback`, `timeout`, `completion.unknown`) were produced by -`JpaTransactionObservation`, which nothing constructed; it was removed on 2026-09-25 -(`docs/capability-status.md`). Transaction outcomes are visible through the shared persistence error -codes and the application's own metrics, not through a JPA meter. +JPA 고유의 것은 없다. 어떤 조립도 플랫폼에 `MeterRegistry` 기반 observation을 만들지 않고, `SpringTransaction`은 트랜잭션 +메트릭을 기록하지 않는다. 트랜잭션 결과는 JPA meter가 아니라 공유 영속성 오류 코드와 애플리케이션 자신의 메트릭으로 보인다. -## Query metrics — only when the caller asks +> 이력: 이 문서가 전에 적던 `jpa.transaction.*` meter(`duration`, `rollback`, `timeout`, `completion.unknown`)는 +> `JpaTransactionObservation`이 만들었는데, 그것을 만드는 곳이 없어서 2026-09-25에 지웠다(`docs/capability-status.md`). -`jpa.query.duration` and `jpa.query.rows` are recorded by `MicrometerQueryObservation`, and only -when a service passes it to a library executor that accepts a `QueryObservation` -(`JpaStreamExecutor`, `HibernateBulkDmlExecutor`). The default is `NoopQueryObservation`. Rows are -measured as well as duration because a query that issues one statement and hydrates twenty thousand -rows is fast per statement and catastrophic per request — a duration metric alone reports it as -merely slow. +## 쿼리 메트릭 — 호출자가 요청할 때만 -## Bounded tags, always +`jpa.query.duration`과 `jpa.query.rows`는 `MicrometerQueryObservation`이 기록한다. 서비스가 `QueryObservation`을 받는 라이브러리 +executor(`JpaStreamExecutor`, `HibernateBulkDmlExecutor`)에 그것을 넘길 때만이다. 기본값은 `NoopQueryObservation`이다. 걸린 +시간뿐 아니라 행도 재는 이유가 있다. 문장 하나를 내고 행 2만 개를 채우는 쿼리는 문장으로는 빠르고 요청으로는 재앙이다. 걸린 +시간 메트릭만으로는 그저 느리다고 보고된다. -Every meter `MicrometerQueryObservation` records carries exactly five tags: persistence unit, -operation, query, outcome, failure category (`JpaMetricTags`). All five are registered identifiers, -validated by `LowCardinality` at construction rather than at the registry — so an unbounded value -fails where it was introduced instead of surviving until a dashboard stops loading. +## 태그는 늘 상한이 있다 -Never a tag: entity id, tenant id, SQL parameter, exception message, JDBC URL. Each is unbounded, so -each creates a time series per row or per failure; several are also the data the platform keeps out -of logs, which a metrics backend would store just as durably and export just as widely. +`MicrometerQueryObservation`이 기록하는 meter는 모두 태그를 정확히 다섯 가진다. persistence unit, operation, query, outcome, +failure category(`JpaMetricTags`)다. 다섯 다 등록된 식별자이고, registry가 아니라 만들 때 `LowCardinality`가 검증한다. 그래서 +상한 없는 값은 대시보드가 안 열릴 때까지 살아남지 않고, 들어온 자리에서 실패한다. -## Query names in SQL +절대 태그가 아닌 것: entity id, tenant id, SQL 파라미터, 예외 메시지, JDBC URL. 하나하나가 상한이 없어서 행마다나 실패마다 +시계열을 만든다. 몇은 플랫폼이 로그에서도 빼는 데이터이고, 메트릭 backend는 그것을 로그만큼 오래 저장하고 넓게 내보낸다. -`JpaRepositoryFragmentSupport` sets the registered query name as the `org.hibernate.comment` hint; -Hibernate writes it into the SQL only when `hibernate.use_sql_comments=true`. The alternative is -`NamedStatementInspector`, which prefixes a statement with the query name bound by -`JpaStreamExecutor`, `JpaKeysetQuerySupport` or `JpaRepositoryFragmentSupport.observing(..)`. -Neither is on by default: a deployment enables the inspector with -`spring.jpa.properties.hibernate.session_factory.statement_inspector=dev.caskeleton.adapter.outbound.persistence.hibernate.NamedStatementInspector`. -The comment then travels into `pg_stat_activity`, `auto_explain`, and the slow-query log. Without it, -"which endpoint issues this query" is answered by grepping the codebase for fragments of SQL. +## SQL 안의 쿼리 이름 -## Diagnostics +`JpaRepositoryFragmentSupport`는 등록한 쿼리 이름을 `org.hibernate.comment` hint로 둔다. Hibernate는 +`hibernate.use_sql_comments=true`일 때만 그것을 SQL에 쓴다. 다른 길은 `NamedStatementInspector`다. `JpaStreamExecutor`, +`JpaKeysetQuerySupport`, `JpaRepositoryFragmentSupport.observing(..)`이 묶은 쿼리 이름을 문장 앞에 붙인다. 둘 다 기본으로 꺼져 +있다. 배포는 +`spring.jpa.properties.hibernate.session_factory.statement_inspector=dev.caskeleton.adapter.outbound.persistence.hibernate.NamedStatementInspector`로 +inspector를 켠다. 그러면 주석이 `pg_stat_activity`, `auto_explain`, slow query 로그로 간다. 그것이 없으면 「어느 엔드포인트가 이 +쿼리를 내나」는 코드에서 SQL 조각을 grep해서 답한다. -`SqlDiagnosticRedactor.redact(sql)` removes string literals, numbers, and anything email-shaped. It is -a utility for code that is about to log SQL; nothing in the platform logs SQL through it. Redaction -is blunt on purpose: preserving "harmless" values would require knowing which columns hold personal -data. +## 진단 -## The actuator endpoint +`SqlDiagnosticRedactor.redact(sql)`은 문자열 literal, 숫자, 이메일 모양의 모든 것을 지운다. SQL을 곧 로그에 쓸 코드를 위한 +도구다. 플랫폼 안의 어떤 것도 그것을 거쳐 SQL을 로그에 쓰지 않는다. 지우기는 일부러 거칠다. 「해롭지 않은」 값을 남기려면 +어느 열이 개인정보를 담는지 알아야 한다. -`jpaplatform` reports database major version, provider version, schema version, OSIV state, runtime -role verification, and capability levels. It reports no JDBC URL, no username, no SQL, and no entity -catalog — an actuator endpoint is reachable by anyone who reaches the management port, and each of -those would be a free reconnaissance answer. It is read-only: an endpoint that could trigger a -migration or a repair would be an admin capability exposed over HTTP. +## actuator 엔드포인트 + +`jpaplatform`은 DB major 버전, provider 버전, 스키마 버전, OSIV 상태, 런타임 역할 검증, capability 수준을 보고한다. JDBC URL, +사용자 이름, SQL, 엔티티 목록은 보고하지 않는다. actuator 엔드포인트는 management 포트에 닿는 누구나 닿을 수 있고, 그 하나하나가 +공짜 정찰 답이 된다. 읽기 전용이다. 마이그레이션이나 repair를 일으킬 수 있는 엔드포인트는 HTTP로 드러난 관리 capability가 된다. diff --git a/docs/jpa/postgresql-extensions.md b/docs/jpa/postgresql-extensions.md index 2124e0e8..e13d0b67 100644 --- a/docs/jpa/postgresql-extensions.md +++ b/docs/jpa/postgresql-extensions.md @@ -1,50 +1,43 @@ -# PostgreSQL Extensions +# PostgreSQL 확장 기능 -Design §8.3, §21, §30. What the platform uses beyond portable JPA, and what each is guarded by. +설계서 §8.3, §21, §30. 플랫폼이 이식 가능한 JPA 너머에서 무엇을 쓰고, 각각을 무엇이 지키나. -Everything here is core PostgreSQL. No server extension is required. +여기 있는 것은 모두 PostgreSQL core다. 서버 extension은 필요 없다. -## Locking +## 잠금 -`SELECT ... FOR UPDATE` with a finite bound, always. `PostgreSqlLockOptions` refuses an unbounded -lock request because it waits as long as the holder holds it, turning one slow transaction into a -pile-up of blocked connections. +`SELECT ... FOR UPDATE`에는 늘 유한한 상한을 둔다. `PostgreSqlLockOptions`는 상한 없는 잠금 요청을 거부한다. 쥔 쪽이 쥐는 만큼 +기다리므로, 느린 트랜잭션 하나가 막힌 연결 더미가 된다. -`NOWAIT` and a wait timeout are separate requests, not two spellings of one — modelling them as a -single field with a magic zero is how "no wait" becomes "wait forever". +`NOWAIT`와 대기 시간 상한은 같은 것의 두 표기가 아니라 다른 요청이다. 둘을 마법의 0을 가진 칸 하나로 모델링하면 「기다리지 +않음」이 「영원히 기다림」이 된다. -`55P03` (lock not available) and `40P01` (deadlock) drive opposite recovery and are never collapsed: -the first leaves the transaction alive and the caller in control; the second has already been rolled -back by the server. +`55P03`(잠금을 얻을 수 없음)과 `40P01`(교착)은 반대 복구로 이어지므로 합치지 않는다. 앞의 것은 트랜잭션을 살려 두고 호출자에게 +통제를 남긴다. 뒤의 것은 서버가 이미 롤백했다. ## JSONB -`JsonDocument` carries a schema name and version alongside the payload. A JSONB column is schemaless -at the database level, so without an envelope the only record of what a stored document means is the -code that wrote it — and a document written two releases ago is indistinguishable from a current one. +`JsonDocument`는 payload와 함께 schema 이름과 버전을 싣는다. JSONB 열은 DB 수준에서 schema가 없으므로, envelope가 없으면 저장된 +문서가 무엇을 뜻하는지 기록한 것은 그것을 쓴 코드뿐이다. 두 릴리스 전에 쓴 문서와 지금 문서를 구별할 수 없다. -The payload never carries a Java class name. Type metadata in a JSONB column is a deserialization -gadget: whoever can write a row chooses the class the reader instantiates. +payload에는 Java 클래스 이름을 절대 싣지 않는다. JSONB 열의 타입 메타데이터는 deserialization gadget이다. 행을 쓸 수 있는 누구나 +읽는 쪽이 만들 클래스를 고른다. -Query paths are registered. A JSON path is part of the SQL text and cannot be bound, so forwarding a -request field into one is concatenating untrusted input into a statement. Values are always bound. +쿼리 경로는 등록한다. JSON 경로는 SQL 문장의 일부라 묶을 수 없으므로, 요청 칸을 그것에 넘기면 믿을 수 없는 입력을 문장에 이어 +붙이는 것이다. 값은 늘 묶는다. -## Arrays and ranges +## 배열과 범위 -Arrays are built with `Connection.createArrayOf`, never by formatting a literal — hand-formatting is -where quoting bugs live, and a tag containing a comma changes the array's shape rather than its -content. +배열은 literal을 꾸미지 않고 `Connection.createArrayOf`로 만든다. 손으로 꾸미면 quoting 버그가 생기고, 쉼표가 든 태그는 배열의 +내용이 아니라 모양을 바꾼다. -`PgRange` models both endpoints as independently optional and independently inclusive, because that -is what a PostgreSQL range is. Whether `[09:00, 10:00)` and `[10:00, 11:00)` overlap depends on the -bracket, not the values, and a pair of `timestamptz` columns cannot express it. +`PgRange`는 두 끝을 저마다 선택적으로, 저마다 포함 여부를 따로 모델링한다. PostgreSQL range가 그렇기 때문이다. +`[09:00, 10:00)`과 `[10:00, 11:00)`이 겹치는지는 값이 아니라 괄호가 정하고, `timestamptz` 열 한 쌍으로는 그것을 나타낼 수 없다. ## COPY (J4 admin) -`COPY` bypasses the Persistence Context, entity callbacks, version checks, and Envers entirely. That -is why it is fast and why it is an admin capability with a registered statement, a bounded stream, a -row and byte cap, a finite server-side `statement_timeout`, and a named operator. +`COPY`는 Persistence Context, 엔티티 callback, 버전 확인, Envers를 모두 건너뛴다. 그래서 빠르고, 그래서 관리 capability다. 등록한 +문장, 상한 있는 stream, 행·바이트 상한, 유한한 서버 쪽 `statement_timeout`, 이름 있는 운영자가 필요하다. -The registry accepts only `COPY ... FROM STDIN`. `COPY ... FROM '/path'` reads a file on the -*database server* as the server's OS user; it is superuser-only for exactly that reason and does not -belong behind an application API. +registry는 `COPY ... FROM STDIN`만 받는다. `COPY ... FROM '/path'`는 *DB 서버*의 파일을 서버 OS 사용자로 읽는다. 바로 그 +이유로 superuser 전용이고, 애플리케이션 API 뒤에 둘 것이 아니다. diff --git a/docs/jpa/query-fetch-guide.md b/docs/jpa/query-fetch-guide.md index 75b023ad..a3e5dbd2 100644 --- a/docs/jpa/query-fetch-guide.md +++ b/docs/jpa/query-fetch-guide.md @@ -1,75 +1,63 @@ -# Query and Fetch Guide +# 쿼리와 fetch 가이드 -Design §23-§28. How queries are chosen, bounded, and proven. +설계서 §23-§28. 쿼리를 어떻게 고르고, 제한하고, 증명하나. -## Named queries +## 이름 있는 쿼리 -Every registered query carries a `QueryName`. It is the tag `MicrometerQueryObservation` records -under and the SQL comment that appears in `pg_stat_activity` and the slow-query log — which is the -only thing that connects a statement on the server back to the use case that issued it. Neither is on -by default; [observability.md](observability.md) says how a deployment turns each on. The format rejects raw -SQL for a reason: a metric tag built from a query string is unbounded by construction, and one built -from a parameterised value leaks row data into telemetry. +등록한 쿼리는 모두 `QueryName`을 가진다. 그것은 `MicrometerQueryObservation`이 기록하는 태그이고, `pg_stat_activity`와 +slow query 로그에 나타나는 SQL 주석이다. 서버의 문장을 그것을 낸 use case와 잇는 것은 그것뿐이다. 둘 다 기본으로 꺼져 +있다. 배포가 각각을 켜는 법은 [observability.md](observability.md)에 있다. 형식이 원본 SQL을 거부하는 데는 이유가 있다. 쿼리 +문자열로 만든 메트릭 태그는 처음부터 상한이 없고, 파라미터 값으로 만든 것은 행 데이터를 원격 측정으로 흘린다. -## Fetch plans, not eager mappings +## eager 매핑이 아니라 fetch 계획 -N+1 is solved per use case with a registered entity graph, not by making an association `EAGER` in -the mapping. The eager fix repairs the one query that needed it and imposes the extra join on every -other query against that entity, including the ones that only wanted the id. +N+1은 매핑에서 연관을 `EAGER`로 만들어서가 아니라 use case마다 등록한 entity graph로 푼다. eager 고침은 그것이 필요했던 쿼리 +하나를 고치고, 그 엔티티에 대한 다른 모든 쿼리에 추가 join을 지운다. id만 원했던 쿼리까지. -`fetchgraph` and `loadgraph` are different: a fetch graph is exhaustive (attributes outside it are -lazy whatever the mapping says), a load graph is additive. Choosing the wrong one produces either -missing data or the amplification the graph was meant to avoid. +`fetchgraph`와 `loadgraph`는 다르다. fetch graph는 빠짐없는 목록이고(그 밖의 속성은 매핑이 뭐라고 하든 lazy다), load graph는 +더하는 것이다. 잘못 고르면 데이터가 빠지거나, graph가 피하려던 증폭이 생긴다. -## Measuring, not guessing +## 짐작하지 말고 잰다 -`QueryMeasurement` records statements, hydrated entities, rows, fetches, and elapsed time. Statement -count alone cannot distinguish the two failures that matter: +`QueryMeasurement`는 문장, 채운 엔티티, 행, fetch, 걸린 시간을 기록한다. 문장 수만으로는 중요한 두 실패를 가릴 수 없다. -- **N+1** — many statements, few rows. -- **Cartesian fetch** — one statement, an enormous number of rows. +- **N+1** — 문장은 많고 행은 적다. +- **Cartesian fetch** — 문장은 하나이고 행은 엄청나게 많다. -A suite asserting only on statement count passes the second one every time. +문장 수만 단언하는 suite는 두 번째를 늘 통과시킨다. -## Pagination +## 페이지 나누기 -Offset pagination makes the database walk and discard `n` rows before returning any. Keyset -pagination replaces it: +offset 페이지 나누기는 DB가 무엇이든 돌려주기 전에 `n`행을 지나가며 버리게 한다. keyset 페이지 나누기가 그것을 대신한다. -- The predicate is lexicographic. For an ordering of `(createdAt, id)`, "after `(t, x)`" is - `createdAt < t OR (createdAt = t AND id < x)` — **not** `createdAt <= t AND id < x`, which reads - plausibly and silently drops rows from the middle of the result set. -- The ordering must end in a unique column. Without one, a page boundary inside a run of equal - values duplicates and skips rows. -- `size + 1` rows are fetched and `size` returned. That extra row answers `hasNext` without a count - query, which would be a second full scan whose answer is stale on arrival. +- 조건은 사전순이다. `(createdAt, id)` 정렬에서 「`(t, x)` 다음」은 `createdAt < t OR (createdAt = t AND id < x)`다. + `createdAt <= t AND id < x`가 **아니다.** 그것은 그럴듯해 보이지만 결과 중간의 행을 조용히 빠뜨린다. +- 정렬은 unique 열로 끝나야 한다. 그렇지 않으면 같은 값이 이어지는 구간 안의 페이지 경계가 행을 중복하고 건너뛴다. +- `size + 1`행을 읽고 `size`를 돌려준다. 그 한 행이 count 쿼리 없이 `hasNext`에 답한다. count 쿼리는 두 번째 전체 scan이고, + 답이 도착할 때 이미 낡았다. -Cursors are signed. An unsigned cursor is client-controlled ordering state: rewriting it lets a -caller seek to arbitrary keys. +cursor에는 서명한다. 서명 없는 cursor는 클라이언트가 다루는 정렬 상태다. 그것을 고치면 호출자가 아무 키로나 건너뛸 수 있다. -## Sorting +## 정렬 -Client sort parameters are mapped through `SafeSortRegistry`, never passed through. A sort field -reaches the query as part of the ORDER BY clause rather than as a bound value, so forwarding the -client's string means the client writes part of the statement. `JpaSort.unsafe` has no call site in -this platform. +클라이언트의 정렬 파라미터는 그대로 넘기지 않고 `SafeSortRegistry`로 매핑한다. 정렬 칸은 묶은 값이 아니라 ORDER BY 절의 +일부로 쿼리에 닿으므로, 클라이언트의 문자열을 넘기면 클라이언트가 문장의 일부를 쓰게 된다. `JpaSort.unsafe`는 이 플랫폼에서 +부르는 곳이 없다. -The registry's tie-breaker is always appended, because a sort that does not end in a unique column -has no total order and paging over a non-total order duplicates and skips rows. +registry의 tie-breaker는 늘 덧붙인다. unique 열로 끝나지 않는 정렬은 전체 순서가 없고, 전체 순서가 아닌 것으로 페이지를 +나누면 행이 중복되고 건너뛰어진다. -## Streaming +## streaming -A JPA `Stream` is a live cursor holding a `ResultSet`, a statement, and a connection. `JpaStreamExecutor` -consumes it inside a try-with-resources and never returns it, because a stream returned past the -transaction boundary is a connection leak that presents as unrelated timeouts elsewhere. A read-only -transaction is required: streaming inside a write transaction pins a write connection for the whole -traversal. +JPA `Stream`은 `ResultSet`, 문장, 연결을 쥔 살아 있는 cursor다. `JpaStreamExecutor`는 그것을 try-with-resources 안에서 다 쓰고 +절대 돌려주지 않는다. 트랜잭션 경계 밖으로 돌려준 stream은 연결 누수이고, 다른 곳의 상관없어 보이는 시간 초과로 나타난다. +읽기 전용 트랜잭션이 필요하다. 쓰기 트랜잭션 안의 streaming은 순회 내내 쓰기 연결을 붙잡는다. -## Batching +## batching -Configuring `hibernate.jdbc.batch_size` proves nothing. `BatchExecutionResult.jdbcBatches` comes from -counting real `executeBatch()` calls at the JDBC layer, because an IDENTITY generator, an interleaved -select, or a mid-loop flush disables batching while the configuration still says it is on. +`hibernate.jdbc.batch_size`를 설정한 것은 아무것도 증명하지 않는다. `BatchExecutionResult.jdbcBatches`는 JDBC 층에서 실제 +`executeBatch()` 호출을 세서 나온다. IDENTITY generator, 끼어든 select, 반복 중간의 flush는 설정이 켜져 있다고 말하는 동안 +batching을 꺼 버리기 때문이다. -Flush and clear are separate boundaries. Flushing alone sends the statements and keeps every entity -in the Persistence Context — the classic bulk-import out-of-memory. +flush와 clear는 다른 경계다. flush만 하면 문장은 보내지만 모든 엔티티를 Persistence Context에 남긴다. 대량 import의 전형적인 +메모리 부족이다. diff --git a/docs/jpa/repository-adaptation.md b/docs/jpa/repository-adaptation.md index c0b3a490..2bb8bcf2 100644 --- a/docs/jpa/repository-adaptation.md +++ b/docs/jpa/repository-adaptation.md @@ -1,165 +1,147 @@ -# JPA Relational Persistence Platform — Repository Adaptation Contract +# JPA 관계형 영속성 플랫폼 — 저장소 대응 계약 -**Design source:** `docs/design/2026-08-11-jpa-persistence-platform-design.md` -**Stable plan source:** `docs/history/plans/2026-08-11-jpa-persistence-platform-implementation-plan.md` -**Experimental plan source:** `docs/history/plans/2026-08-11-jpa-persistence-experimental-expansion-plan.md` +**설계 출처:** `docs/design/2026-08-11-jpa-persistence-platform-design.md` +**Stable 계획 출처:** `docs/history/plans/2026-08-11-jpa-persistence-platform-implementation-plan.md` +**Experimental 계획 출처:** `docs/history/plans/2026-08-11-jpa-persistence-experimental-expansion-plan.md` -The design package states its own adaptation rule (§3.2): the assumed package paths and Gradle -structure are explicit implementation *assumptions* made because the real Backend Skeleton -repository was not supplied. Before implementing, paths are adjusted to the repository's existing -conventions and root package while the public contracts and policy semantics are preserved. +설계 패키지는 자기 대응 규칙을 스스로 밝힌다(§3.2). 가정한 패키지 경로와 Gradle 구조는 실제 Backend Skeleton 저장소를 +받지 못해서 둔 명시적 구현 *가정*이다. 구현 전에 공개 계약과 정책 의미는 지키면서 경로를 저장소의 기존 관례와 root 패키지에 +맞춘다. -This file is the single record of *how* that mapping was performed. Only paths, build DSL, and -composition-root ownership changed. Public contracts, policy order, retry semantics, and error -semantics are implemented as specified. +이 파일은 그 대응을 *어떻게* 했는지 적는 유일한 기록이다. 바뀐 것은 경로, 빌드 DSL, 조립 루트 소유뿐이다. 공개 계약, 정책 +순서, 재시도 의미, 오류 의미는 명세대로 구현했다. -## 1. Why the module layout differs +## 1. 모듈 배치가 다른 이유 -The plan assumes a greenfield library with 18 Stable Gradle projects under `modules/jpa/` plus 7 -Experimental projects under `modules/jpa-experimental/`. This repository is a Clean Architecture -template whose **fail-closed registry** (`src/config/architecture/modules.json`, enforced by -`src/settings.gradle` and `verifyCleanArchitectureDependencies`) declares **exactly 19 leaf -identities**, and `src/settings.gradle` throws when the registry does not contain exactly 19 -modules. Creating 25 more Gradle projects would violate HARD-STOP #5 in `AGENTS.md`. +계획은 `modules/jpa/` 아래 Stable Gradle 프로젝트 18개와 `modules/jpa-experimental/` 아래 Experimental 프로젝트 7개를 둔 +새 라이브러리를 가정한다. 이 저장소는 **fail-closed registry**(`src/config/architecture/modules.json`)를 가진 Clean +Architecture 템플릿이다. `src/settings.gradle`은 registry를 읽고 검증한 뒤 등록된 프로젝트만 들이고, +`verifyCleanArchitectureDependencies`가 그 밖의 edge를 막는다. leaf 목록은 registry가 정한다. 계획의 Gradle 프로젝트를 +새로 만들면 `AGENTS.md`의 HARD-STOP #5를 어긴다. -Therefore the plan's library modules become **package boundaries inside the registered leaf** -`:adapter:outbound:persistence-jpa`, with two exceptions driven by this repository's own rules. -This is the same adaptation already applied to the HTTP client platform -(`docs/httpclient/repository-adaptation.md`). +그래서 계획의 라이브러리 모듈은 등록 leaf `:adapter:outbound:persistence-jpa` **안의 패키지 경계**가 된다. 예외는 이 저장소 +자신의 규칙에서 나온 둘이다. HTTP 클라이언트 플랫폼에 이미 한 것과 같은 대응이다(`docs/httpclient/repository-adaptation.md`). -| Plan module | Repository home | Reason | +| 계획 모듈 | 저장소 위치 | 이유 | |---|---|---| -| `jpa-spring-boot-starter` | `:adapter:outbound:persistence-jpa` (`…persistence.autoconfigure`, `…persistence.startup`) | Relational persistence is a capability module selected by one build line (`AGENTS.md` capability rules): the leaf registers its own auto-configuration, startup validation, actuator view and shipped settings, and the default composition does not carry it. Use-case assembly over its ports (the outbox relay) stays in `app-bootstrap`. | -| `jpa-testkit`, `jpa-testkit-postgresql`, `jpa-testkit-migration`, `jpa-testkit-queryplan` | `:adapter:outbound:persistence-jpa` `src/testkit/java/**/testkit` | The plan forbids production modules depending on the testkit. A source set whose dependencies are declared only on test configurations gives the same guarantee without a new Gradle project, and more than one lane consumes it. | +| `jpa-spring-boot-starter` | `:adapter:outbound:persistence-jpa` (`…persistence.autoconfigure`, `…persistence.startup`) | 관계형 영속성은 빌드 한 줄로 고르는 capability 모듈이다(`AGENTS.md` capability 규칙). leaf가 자기 auto-configuration, 기동 검증, actuator view, 내보내는 설정을 등록하고, 기본 조립은 그것을 싣지 않는다. 그 port 위의 use case 조립(outbox relay)은 `composition:outbox-relay`에 있다. | +| `jpa-testkit`, `jpa-testkit-postgresql`, `jpa-testkit-migration`, `jpa-testkit-queryplan` | `:adapter:outbound:persistence-jpa` `src/testFixtures/java/**/testkit` | 계획은 운영 모듈이 testkit에 의존하는 것을 막는다. 의존을 test 설정에만 선언한 source set이 새 Gradle 프로젝트 없이 같은 보장을 주고, 여러 lane이 그것을 쓴다. | -The package boundary is enforced by `JpaModuleBoundaryTest`. It holds a closed catalog of the -production root's direct child packages, compares that catalog against the tree for exact equality, -checks every observed top-level edge against the declared ones, and rejects cycles. +패키지 경계는 `JpaModuleBoundaryTest`가 강제한다. 운영 root의 바로 아래 자식 패키지를 닫힌 목록으로 들고, 그 목록을 +트리와 정확히 같은지 비교하고, 관찰한 최상위 edge를 모두 선언한 것과 대조하고, cycle을 거부한다. -This used to be a stronger claim than the test. The catalog listed thirteen packages while the tree -held twenty-two, so nine — `audit`, `config`, `failure`, `fileserver`, `h2`, `idempotency`, `lock`, -`notification`, `outbox` — were governed by nothing, and a `transaction → postgresql` / -`postgresql → transaction` cycle passed. Both are closed now, and the catalog's exact-equality check -is what keeps a new package from being green by omission. +> 이력: 전에는 문서의 주장이 테스트보다 강했다. 목록은 패키지 13개였는데 트리에는 22개가 있어서, 아홉 개(`audit`, +> `config`, `failure`, `fileserver`, `h2`, `idempotency`, `lock`, `notification`, `outbox`)를 아무것도 다스리지 않았고 +> `transaction → postgresql` / `postgresql → transaction` cycle이 통과했다. 둘 다 닫았다. 새 패키지가 빠져서 초록이 되지 +> 않게 막는 것은 목록의 정확히-같음 검사다. -**Known gap.** The catalog governs top-level packages. Sub-package edges inside one top-level -package are not checked, and the target tree in the review's JPA-023 (a `capability/*` layout) is -not implemented — the notification configuration facade is the first step toward it. +**알려진 빈틈.** 목록은 최상위 패키지를 다스린다. 한 최상위 패키지 안의 하위 패키지 edge는 확인하지 않는다. 리뷰 +JPA-023의 목표 트리(`capability/*` 배치)는 구현하지 않았다. 알림 설정 facade가 그쪽으로 가는 첫걸음이다. -## 2. Package mapping +## 2. 패키지 대응 -Root package: `io.backend.skeleton.jpa` → `dev.caskeleton.adapter.outbound.persistence`. +root 패키지: `io.backend.skeleton.jpa` → `dev.caskeleton.adapter.outbound.persistence`. -| Plan module | Plan package | Repository package | +| 계획 모듈 | 계획 패키지 | 저장소 패키지 | |---|---|---| -| `jpa-core-api` | `…jpa.api` (+ `.capability`, `.error`, `.query`, `.transaction`) | `dev.caskeleton.adapter.outbound.persistence.api` (+ same subpackages) | +| `jpa-core-api` | `…jpa.api` (+ `.capability`, `.error`, `.query`, `.transaction`) | `dev.caskeleton.adapter.outbound.persistence.api` (+ 같은 하위 패키지) | | `jpa-transaction` | `…jpa.transaction` | `…persistence.transaction` | | `jpa-spring-data` | `…jpa.springdata` | `…persistence.springdata` | | `jpa-querydsl` | `…jpa.querydsl` | `…persistence.querydsl` | -| `jpa-hibernate` | `…jpa.hibernate` (+ `.batch`, `.bulk`, `.stateless`) | `…persistence.hibernate` (+ same subpackages) | -| `jpa-postgresql` | `…jpa.postgresql` (+ `.error`, `.lock`, `.constraint`, `.json`, `.array`, `.range`, `.write`) | `…persistence.postgresql` (+ same subpackages except `.write`, removed 2026-09-25) | +| `jpa-hibernate` | `…jpa.hibernate` (+ `.batch`, `.bulk`, `.stateless`) | `…persistence.hibernate` (+ 같은 하위 패키지) | +| `jpa-postgresql` | `…jpa.postgresql` (+ `.error`, `.lock`, `.constraint`, `.json`, `.array`, `.range`, `.write`) | `…persistence.postgresql` (+ `.write`를 뺀 같은 하위 패키지. `.write`는 2026-09-25에 지움) | | `jpa-postgresql-copy` | `…jpa.postgresql.copy` | `…persistence.postgresql.copy` | | `jpa-migration-flyway` | `…jpa.migration` | `…persistence.migration` | -| `jpa-auditing` | `…jpa.auditing` | none — removed; `…persistence.audit.AuditableEntity` is the one audit mechanism | +| `jpa-auditing` | `…jpa.auditing` | 없음 — 지웠다. `…persistence.audit.AuditableEntity`가 유일한 감사 방식이다 | | `jpa-envers` | `…jpa.envers` | `…persistence.envers` | | `jpa-cache-hibernate` | `…jpa.cache` | `…persistence.cache` | | `jpa-observability` | `…jpa.observation` | `…persistence.observation` | | `jpa-security` | `…jpa.security` | `…persistence.security` | | `jpa-spring-boot-starter` | `…jpa.autoconfigure` | `…persistence.autoconfigure`, `…persistence.startup` | -| `jpa-testkit*` | `…jpa.testkit` (+ `.id`, `.mapping`, `.lifecycle`, `.query`, `.fetch`, `.postgresql`, `.migration`, `.queryplan`, `.failure`, `.pool`, `.release`) | `…persistence.testkit` (+ same subpackages), `testkit` source set | -| `jpa-experimental/*` | `…jpa.experimental` (+ `.tenant`, `.rls`, `.schema`, `.database`, `.replica`, `.next`) | `…persistence.experimental` (+ same subpackages except `.next`, removed 2026-09-25) | +| `jpa-testkit*` | `…jpa.testkit` (+ `.id`, `.mapping`, `.lifecycle`, `.query`, `.fetch`, `.postgresql`, `.migration`, `.queryplan`, `.failure`, `.pool`, `.release`) | `…persistence.testkit` (+ 같은 하위 패키지), `testFixtures` source set | +| `jpa-experimental/*` | `…jpa.experimental` (+ `.tenant`, `.rls`, `.schema`, `.database`, `.replica`, `.next`) | `…persistence.experimental` (+ `.next`를 뺀 같은 하위 패키지. `.next`는 2026-09-25에 지움) | -The existing `…persistence.transaction` and `…persistence.postgresql` packages already hold this -leaf's `TransactionPort` implementation and PostgreSQL vendor composition. The platform types are -**additive**: no existing type was renamed, moved, or replaced, and no plan type collides with an -existing name. +이미 있던 `…persistence.transaction`과 `…persistence.postgresql` 패키지는 이 leaf의 `TransactionPort` 구현과 PostgreSQL +vendor 조립을 이미 가지고 있다. 플랫폼 타입은 **더하기만** 했다. 이름을 바꾸거나 옮기거나 대신한 기존 타입은 없고, 기존 +이름과 부딪치는 계획 타입도 없다. -## 3. Test-suite mapping +## 3. 테스트 suite 대응 -The plan declares seven JVM test suites (`test`, `integrationTest`, `contractTest`, -`migrationTest`, `failureTest`, `performanceTest`, `compatibilityTest`). This leaf already owns a -Docker-backed `postgresqlIntegrationTest` source set and its readiness Gradle tasks are registered -as strict lanes in this leaf's `build.gradle`; `JpaReadinessRegistryTest` holds the readiness cards -to those lanes (it replaced the build-tools `verifyJpaReadinessRegistry`). +계획은 JVM 테스트 suite 일곱을 선언한다(`test`, `integrationTest`, `contractTest`, `migrationTest`, `failureTest`, +`performanceTest`, `compatibilityTest`). 이 leaf는 이미 Docker를 쓰는 `postgresqlIntegrationTest` source set을 가지고, +그 readiness Gradle 태스크는 이 leaf의 `build.gradle`에 strict lane으로 등록돼 있다. `JpaReadinessRegistryTest`가 readiness +card를 그 lane과 대조한다(build-tools의 `verifyJpaReadinessRegistry`를 대신했다). -| Plan suite | Repository lane | +| 계획 suite | 저장소 lane | |---|---| -| `test` | `src/test` — hermetic unit lane, `./gradlew :adapter:outbound:persistence-jpa:test` | -| `contractTest`, `integrationTest`, `migrationTest`, `failureTest`, `compatibilityTest` | `src/postgresqlIntegrationTest` — real PostgreSQL containers; selected by the `jpaPlatform*` Gradle tasks | -| `performanceTest` | `src/jpaPlatformPerformanceTest` — pool and `REQUIRES_NEW` connection behaviour, run by `jpaPlatformPoolContractTest`; never part of `check`. The source set keeps the plan's name; the lane asserts behaviour rather than measuring, and no numeric performance bound is claimed anywhere from it. | +| `test` | `src/test` — 밀폐된 unit lane, `./gradlew :adapter:outbound:persistence-jpa:test` | +| `contractTest`, `integrationTest`, `migrationTest`, `failureTest`, `compatibilityTest` | `src/postgresqlIntegrationTest` — 실제 PostgreSQL 컨테이너. `jpaPlatform*` Gradle 태스크가 고른다 | +| `performanceTest` | `src/jpaPlatformPerformanceTest` — 풀과 `REQUIRES_NEW` 연결 동작. `jpaPlatformPoolContractTest`가 돌리고, `check`에는 절대 들어가지 않는다. source set은 계획의 이름을 그대로 쓴다. 이 lane은 측정하지 않고 동작을 단언하며, 그로부터 어떤 성능 수치도 주장하지 않는다. | -Docker-dependent lanes fail closed rather than skipping, matching the existing -`PostgreSqlReadinessSupport.assertDockerAvailable()` convention in this leaf. +Docker가 필요한 lane은 건너뛰지 않고 닫힌 채 실패한다. 이 leaf의 기존 관례 `PostgreSqlReadinessSupport.assertDockerAvailable()`과 +같다. -## 4. Other deliberate substitutions +## 4. 그 밖에 일부러 바꾼 것 -| Plan assumption | Repository reality | Adaptation | +| 계획의 가정 | 저장소의 실제 | 대응 | |---|---|---| -| Gradle Kotlin DSL, `build-logic` convention plugin, `jpa-library-conventions.gradle.kts` | Groovy DSL, root `src/build.gradle` conventions (spotless google-java-format, checkstyle, SpotBugs + FindSecBugs, ErrorProne, `-Werror`, one-type-per-file), `LockMode.STRICT` dependency locking | Source sets and dependencies declared in `src/adapter/outbound/persistence-jpa/build.gradle`; `gradle.lockfile` regenerated with `resolveAndLockAll --write-locks`. | -| Spring Boot 4.1 dependency management, Spring Data JPA 4.1 | Repository baseline is Spring Boot 4.0.8 | Versions are inherited from the repository BOM and never pinned per module, exactly as the plan requires ("do not override Hibernate/Flyway/Hikari versions outside the Boot BOM"). | -| Hibernate ORM 7.4 is the Stable provider | Boot 4.0.0 resolves `org.hibernate.orm:hibernate-core:7.1.8.Final` | The *declared* Stable provider baseline of the design stays 7.4 in `HibernateProviderPolicy`; the runtime provider version is read from Hibernate itself and reported. The collection-fetch-pagination gate runs against whatever provider the BOM resolves, and `HibernateProviderPolicy.driftsFromDeclaredBaseline()` makes the difference visible instead of hiding it behind a green check. | -| PostgreSQL 16·17·18 Stable matrix | This leaf's existing evidence image is `postgres:16-alpine` | `PostgreSqlVersion` declares exactly PG 16, 17, 18. The default lane runs the repository's existing 16 image; 17 and 18 are selected by `-Pjpa.matrix.versions=16,17,18`, and an unknown or empty selection is an error rather than a skip. | -| `settings.gradle.kts` module registration | Fail-closed 19-leaf registry | No registry change: leaf identity, Gradle path, allowed dependencies, and runtime memberships are unchanged. | +| Gradle Kotlin DSL, `build-logic` convention plugin, `jpa-library-conventions.gradle.kts` | Groovy DSL, `src/build-logic`의 convention plugin(Java로 씀: spotless google-java-format, checkstyle, SpotBugs + FindSecBugs, ErrorProne, `-Werror`, 파일 하나에 타입 하나), `LockMode.STRICT` 의존성 잠금 | source set과 의존성은 `src/adapter/outbound/persistence-jpa/build.gradle`에 선언했다. `gradle.lockfile`은 `resolveAndLockAll --write-locks`로 다시 만들었다. | +| Spring Boot 4.1 의존성 관리, Spring Data JPA 4.1 | 저장소 기준선은 `src/gradle/libs.versions.toml`의 Spring Boot 버전이다 | 버전은 저장소 BOM에서 물려받고 모듈마다 고정하지 않는다. 계획이 요구하는 그대로다("do not override Hibernate/Flyway/Hikari versions outside the Boot BOM"). | +| Hibernate ORM 7.4가 Stable provider | 저장소 BOM이 `org.hibernate.orm:hibernate-core:7.1.8.Final`을 푼다(release registry의 `stable-tested-baseline`) | 설계의 *선언* Stable provider 기준선은 `HibernateProviderPolicy`에서 7.4로 남는다. 런타임 provider 버전은 Hibernate 자신에게서 읽어 보고한다. collection-fetch-pagination gate는 BOM이 푸는 provider에서 돌고, `HibernateProviderPolicy.driftsFromDeclaredBaseline()`이 차이를 초록 검사 뒤에 숨기지 않고 드러낸다. | +| PostgreSQL 16·17·18 Stable matrix | 컨테이너 이미지는 `src/config/testing/container-images.properties`에 digest로 고정한다 | `PostgreSqlVersion`이 PG 16, 17, 18을 정확히 선언한다. 기본 lane은 16이고, 다른 major는 `-Pjpa.matrix.versions=`로 고른다. 계약 suite(`JpaPlatformContractSupport.start()`)는 JVM 하나에 major 하나만 받는다. 여러 major를 한 번에 받는 것은 `StablePostgreSqlMatrixContractTest`뿐이다. 모르는 값이나 빈 선택은 건너뛰지 않고 오류다. | +| `settings.gradle.kts` 모듈 등록 | fail-closed registry | registry는 바꾸지 않았다. leaf 신원, Gradle path, 허용 의존은 그대로다. | | `infra/jpa/{postgres,roles,toxiproxy}` | 이 repo는 운영 인프라 파일을 두지 않는다(2026-11-07 소유자 결정) | 2026-11-07에 지웠다(쓰는 곳이 없거나 운영 인프라 파일). 운영 DB 조건은 `docs/jpa/security.md`로 옮겼다. | -| `docs/jpa/**`, `docs/adr/ADR-JPA-*`, `.github/workflows/jpa-*.yml` | Repository already owns `docs/` and `.github/workflows/` | Created at the same repository-relative paths. | -| release blocking aggregate | `jpaReleaseQualification` (persistence-jpa `build.gradle`) over `persistence-jpa/release/release-registry.json`, run per PostgreSQL major by the `jpa-release-gate` job in `.github/workflows/release.yml` | The registry names the blocking lanes; Gradle defines how each lane runs; CI only schedules the matrix. | | -| Per-task `git add` + `git commit` | `AGENTS.md`: commit policy is `human-only`; agents do not stage, commit, amend, or push | Implementation is delivered unstaged. This is the only plan step intentionally not executed, and it is recorded here. | -| Querydsl as an optional module dependency | Querydsl is not part of this repository's dependency set | `querydsl` is implemented against the plan's contracts with the Querydsl types kept behind `compileOnly`, so the Stable runtime classpath never carries Querydsl and a deployment opting in adds the artifact itself. | -| Hibernate Envers as a module dependency | Envers is not part of this repository's dependency set | Same treatment as Querydsl: `compileOnly` + explicit opt-in, matching the plan's "Envers is opt-in and never enabled by a global base class". | -| `build-logic/src/test/kotlin/JpaModuleBoundaryTest.kt` | There is no `build-logic` project and no Kotlin source set; module boundaries are enforced by the registry itself | `verifyCleanArchitectureDependencies` plus `:app-bootstrap:architectureTest` assert the same property against `src/config/architecture/modules.json`, which is the authority the plan's test would have had to duplicate. | -| `PostgreSqlRuntimeRoleVerifierIntegrationTest` (Task 45) | The security lane is one suite in this leaf rather than a per-module `integrationTest` | `PostgreSqlSecurityContractTest` (tag `jpa-security`) exercises `PostgreSqlRuntimeRoleVerifier.verify` and `.requireSafe` against a real restricted role on a real server. | -| `JpaSafetyProperties`, `JpaDataSourceProperties` | `NamingConventionTest` requires every `@ConfigurationProperties` type to end in `Settings` or `Policy` | Renamed to `JpaSafetySettings` and `JpaDataSourceSettings`. The bound property prefixes and every field are unchanged; only the class names move to this repository's convention. | +| `docs/jpa/**`, `docs/adr/ADR-JPA-*`, `.github/workflows/jpa-*.yml` | 저장소가 이미 `docs/`와 `.github/workflows/`를 가진다 | 같은 저장소 상대 경로에 만들었다. | +| 릴리스를 막는 집계 | `persistence-jpa/release/release-registry.json` 위의 `jpaReleaseQualification`(persistence-jpa `build.gradle`). `.github/workflows/release.yml`의 `jpa-release-gate` job이 PostgreSQL major마다 돌린다 | registry가 막는 lane을 이름 대고, Gradle이 lane마다 도는 법을 정하고, CI는 matrix 일정만 잡는다. | | +| task마다 `git add` + `git commit` | `AGENTS.md`: 커밋 정책은 `human-only`다. 에이전트는 stage, commit, amend, push를 하지 않는다 | 구현은 stage하지 않은 채로 넘겼다. 일부러 하지 않은 계획 단계는 이것 하나이고, 여기에 기록한다. | +| Querydsl을 선택 모듈 의존성으로 | Querydsl은 이 저장소의 의존성 묶음에 없다 | `querydsl`은 계획의 계약대로 구현하되 Querydsl 타입을 `compileOnly` 뒤에 둔다. 그래서 Stable 런타임 classpath에는 Querydsl이 없고, 쓰기로 한 배포가 artifact를 직접 더한다. | +| Hibernate Envers를 모듈 의존성으로 | Envers는 이 저장소의 의존성 묶음에 없다 | Querydsl과 같다. `compileOnly` + 명시적 opt-in. 계획의 "Envers is opt-in and never enabled by a global base class"와 맞는다. | +| `build-logic/src/test/kotlin/JpaModuleBoundaryTest.kt` | `src/build-logic`은 있지만 Kotlin source set은 없다 | 패키지 경계는 이 leaf의 `JpaModuleBoundaryTest`(§1)가, leaf 경계는 `verifyCleanArchitectureDependencies`와 `:app-bootstrap:architectureTest`가 `src/config/architecture/modules.json`을 정본으로 강제한다. | +| `PostgreSqlRuntimeRoleVerifierIntegrationTest` (Task 45) | 보안 lane은 모듈마다의 `integrationTest`가 아니라 이 leaf의 suite 하나다 | `PostgreSqlSecurityContractTest`(tag `jpa-security`)가 실제 서버의 실제 제한 역할에 대고 `PostgreSqlRuntimeRoleVerifier.verify`와 `.requireSafe`를 돌린다. | +| `JpaSafetyProperties`, `JpaDataSourceProperties` | `NamingConventionTest`는 모든 `@ConfigurationProperties` 타입 이름이 `Settings`나 `Policy`로 끝나기를 요구한다 | `JpaSafetySettings`로 이름을 바꿨다. 묶는 속성 prefix와 모든 칸은 그대로이고 클래스 이름만 이 저장소 관례로 옮겼다. `JpaDataSourceProperties`에 해당하는 설정 클래스는 지금 없다. datasource 검사는 `JpaDataSourceProfileValidator`가 한다. | -### Types relocated to keep the dependency direction legal +### 의존 방향을 지키려고 옮긴 타입 -The plan's module map forbids `jpa-core-api` from depending on any other platform module. Three -value-only types the design places in a downstream module are consumed by a core contract, so they -live in the core here instead. Each is a pure value with no framework dependency, so the relocation -costs nothing and the alternative — a core contract importing an adapter package — would break the -boundary the module map exists to hold. +계획의 모듈 지도는 `jpa-core-api`가 다른 플랫폼 모듈에 의존하는 것을 막는다. 설계가 하위 모듈에 둔 값 타입 셋을 core 계약이 +쓰므로, 여기서는 core에 둔다. 셋 다 framework 의존이 없는 순수 값이라 옮기는 비용이 없다. 대안인, core 계약이 어댑터 패키지를 +import하는 것은 모듈 지도가 지키려는 경계를 깬다. -| Type | Plan module | Repository package | Consumed by | +| 타입 | 계획 모듈 | 저장소 패키지 | 쓰는 곳 | |---|---|---|---| -| `TransactionCompletionEvidence` | `jpa-transaction` | `…persistence.api.transaction` | `TransactionCompletionUnknownException` (design §17.3 types the field) | -| `ConstraintCode` | `jpa-postgresql` | `…persistence.api.error` | `ConstraintViolationDetails` (design §22.4) | -| `SqlExceptionSqlStateResolver` | `jpa-transaction` | `…persistence.api.error` | the PostgreSQL translators | +| `TransactionCompletionEvidence` | `jpa-transaction` | `…persistence.api.transaction` | `TransactionCompletionUnknownException`(설계서 §17.3이 칸의 타입을 정한다) | +| `ConstraintCode` | `jpa-postgresql` | `…persistence.api.error` | `ConstraintViolationDetails`(설계서 §22.4) | +| `SqlExceptionSqlStateResolver` | `jpa-transaction` | `…persistence.api.error` | PostgreSQL translator들 | -The ArchUnit rule pack (`JpaArchitectureRules`, `EntityMappingCondition`, `EntityExposureCondition`) -is placed in the `testkit` source set rather than in `…persistence.security` production code. ArchUnit -is a test library; putting the rule pack in `main` would drag it onto every deployment's runtime -classpath to serve code that only ever runs in a test. +ArchUnit 규칙 묶음(`JpaArchitectureRules`, `EntityMappingCondition`, `EntityExposureCondition`)은 `…persistence.security` 운영 +코드가 아니라 `testFixtures` source set에 둔다. ArchUnit은 테스트 라이브러리다. 규칙 묶음을 `main`에 두면 테스트에서만 도는 +코드를 위해 모든 배포의 런타임 classpath에 그것을 끌고 간다. +### 실제 서버에서 계약이 찾은 것 -### Findings the contracts produced against a real server +설계의 규칙 둘이 조금 틀리게 적혀 있었고, 그것을 보여 준 것은 컨테이너 lane이다. 설계서 본문은 여전히 옛 내용이라 여기에 +기록한다. -Two of the design's rules turned out to be stated slightly wrong, and the container lanes are what -showed it. Both are recorded here because the design text still reads the old way. +- **§17.2 커밋 모호함은 SQLSTATE class `08`만이 아니다.** 커밋이 진행 중인 backend에 `pg_terminate_backend`를 하면 연결 + class 상태가 아니라 `57P01`(`admin_shutdown`)을 보고하고, 그것이 도착할 때 커밋 기록은 이미 WAL에 있을 수 있다. 이것을 + 담았던 classifier(`CommitFailureClassifier`)는 2026-09-25에 두 번째 트랜잭션 엔진과 함께 지웠다. + `PostgreSqlConcurrencyFailureContractTest`가 여전히 주입 지점을 고정한다. +- **schema-per-tenant 상태는 실행 결과로 짐작하지 말고 다시 읽어야 한다.** `MigrateResult`의 대상 버전은 이미 최신이던 + tenant에서 비어 있어서, 그것을 기록하면 부분 rollout 중 마이그레이션한 tenant를 안 한 것으로 보고했다. + `SchemaTenantMigrationOrchestrator`가 이제 tenant의 schema history에서 적용된 버전을 읽는다. -- **§17.2 commit ambiguity is not only SQLSTATE class `08`.** `pg_terminate_backend` on a backend - with a commit in flight reports `57P01` (`admin_shutdown`), not a connection-class state — and the - commit record may already be in the WAL when it arrives. The classifier that encoded this - (`CommitFailureClassifier`) was removed with the second transaction engine on 2026-09-25; - `PostgreSqlConcurrencyFailureContractTest` still pins the injection points. -- **Schema-per-tenant status must be read back, not inferred from the run.** `MigrateResult`'s - target version is empty for a tenant that was already current, so recording it reported migrated - tenants as unmigrated during a partial rollout. `SchemaTenantMigrationOrchestrator` now reads the - applied version from the tenant's schema history. +## 5. 설계에서 바뀌지 않은 것 -## 5. What is unchanged from the design - -- Domain owns Entity, Embeddable, Repository, Query, index requirements, lock/soft-delete/audit - policy. No `GenericRepository` and no Spring Data CRUD re-implementation exists. -- Application Service owns the transaction boundary; OSIV is false in every runtime profile. -- `TransactionCompletionUnknownException` always reports `completionUnknown=true`, - `retryable=false`, and is never automatically retried — reconciliation handles it. -- Retry re-executes the whole use case in a new transaction and a new Persistence Context. -- SQLSTATE classification is structural (`40001`, `40003`, `40P01`, `23505`, `23503`, `23514`, - `55P03`) and never parses localized message text. -- Flyway is the source of truth for production schema change; Hibernate only validates; - `ddl-auto` never mutates a deployed schema. -- `CREATE INDEX CONCURRENTLY` requires an explicit non-transactional migration marker. -- Metric labels and ordinary logs never carry SQL parameters, entity IDs, tenant IDs, or PII. -- Experimental features (multi-tenancy, RLS, schema/database tenancy, read replica) are library code - a deployment constructs itself and never enter the Stable composition. JPA 4, Hibernate 8 and - PostgreSQL 19 are `NOT_EXECUTABLE` probes, not features. The `backend.jpa.experimental.*` flags - were removed on 2026-09-25: nothing read them. +- 도메인이 Entity, Embeddable, Repository, Query, 인덱스 요구, lock·soft-delete·감사 정책을 가진다. `GenericRepository`도, + Spring Data CRUD를 다시 구현한 것도 없다. +- Application Service가 트랜잭션 경계를 가진다. OSIV는 모든 런타임 profile에서 false다. +- `TransactionCompletionUnknownException`은 늘 `completionUnknown=true`, `retryable=false`를 보고하고, 자동으로 다시 시도하지 + 않는다. 맞추기가 처리한다. +- 재시도는 use case 전체를 새 트랜잭션과 새 Persistence Context에서 다시 돌린다. +- SQLSTATE 분류는 구조적이다(`40001`, `40003`, `40P01`, `23505`, `23503`, `23514`, `55P03`). 지역화된 메시지 문장을 파싱하지 + 않는다. +- 운영 스키마 변경의 정본은 Flyway다. Hibernate는 검증만 하고, `ddl-auto`는 배포된 스키마를 바꾸지 않는다. +- `CREATE INDEX CONCURRENTLY`에는 명시적인 비트랜잭션 마이그레이션 표시가 필요하다. +- 메트릭 label과 보통 로그에는 SQL 파라미터, entity ID, tenant ID, PII를 싣지 않는다. +- Experimental 기능(multi-tenancy, RLS, schema·database tenancy, read replica)은 배포가 직접 만드는 라이브러리 코드이고 Stable + 조립에 들어가지 않는다. JPA 4, Hibernate 8, PostgreSQL 19는 기능이 아니라 `NOT_EXECUTABLE` probe다. + `backend.jpa.experimental.*` 스위치는 아무것도 읽지 않아서 2026-09-25에 지웠다. diff --git a/docs/jpa/runbooks.md b/docs/jpa/runbooks.md index 6e954dc7..1f95e3fd 100644 --- a/docs/jpa/runbooks.md +++ b/docs/jpa/runbooks.md @@ -1,65 +1,56 @@ -# JPA Platform Runbooks +# JPA 플랫폼 runbook -Operator procedures for the failures this platform is designed to surface rather than hide. +이 플랫폼이 숨기지 않고 드러내도록 설계한 실패에 대한 운영자 절차다. -## A transaction reported completion unknown +## 트랜잭션이 완료를 모른다고 보고했다 -**Signal:** a write use case failed with a commit-phase error (connection lost, `57P01`, class -`08`) from `TransactionPort`. +**신호:** 쓰기 use case가 `TransactionPort`에서 커밋 단계 오류(연결 끊김, `57P01`, class `08`)로 실패했다. -**What it means:** the commit may or may not have happened. It is not a rollback. +**뜻:** 커밋이 됐을 수도 안 됐을 수도 있다. 롤백이 아니다. -**Do not** re-run the use case. That is what the platform refused to do automatically, for the same -reason. +use case를 다시 돌리지 **않는다**. 플랫폼이 같은 이유로 자동으로 하기를 거부한 일이다. -**Procedure:** +**절차:** -1. Take the idempotency key or operation id of the failed request. -2. Check the idempotency record for that key. -3. Check the business row the use case would have written. -4. Check the outbox for a corresponding event. -5. If all three agree the write happened, stop — the request succeeded. -6. If all three agree it did not, the use case may be re-run. -7. If they disagree or are inconclusive, escalate. An inconclusive answer is a legitimate outcome; - guessing is not. +1. 실패한 요청의 멱등 키나 operation id를 꺼낸다. +2. 그 키의 멱등성 기록을 확인한다. +3. use case가 썼을 업무 행을 확인한다. +4. outbox에 그에 맞는 이벤트가 있는지 확인한다. +5. 셋이 모두 쓰기가 일어났다고 하면 멈춘다. 요청은 성공했다. +6. 셋이 모두 일어나지 않았다고 하면 use case를 다시 돌려도 된다. +7. 서로 다르거나 결론이 나지 않으면 넘긴다. 결론 없음은 정당한 결과다. 짐작은 아니다. -## Deadlock or serialization rate rising +## 교착이나 직렬화 실패 비율이 오른다 -**Signal:** `DB_DEADLOCK` / serialization failures rising in the persistence error codes. +**신호:** 영속성 오류 코드에서 `DB_DEADLOCK`·직렬화 실패가 오른다. -`SpringTransaction` does not retry, so each one reaches the caller. +`SpringTransaction`은 다시 시도하지 않으므로 하나하나가 호출자에게 닿는다. -1. Group the failures by operation. A single operation dominating means a hot row or an - inconsistent lock order. -2. For deadlocks, check whether two operations take the same rows in opposite orders — that is a - code fix, not a tuning one. -3. For serialization failures under `SERIALIZABLE`, confirm the isolation is actually required. +1. 실패를 operation별로 묶는다. operation 하나가 압도하면 hot row나 어긋난 잠금 순서다. +2. 교착이면 두 operation이 같은 행을 반대 순서로 잡는지 확인한다. 그것은 조정이 아니라 코드를 고칠 일이다. +3. `SERIALIZABLE`에서의 직렬화 실패면 그 격리 수준이 정말 필요한지 확인한다. -## Pool exhaustion +## 풀 고갈 -**Signal:** connection acquisition timeouts; `PoolMeasurement.pending` non-zero. +**신호:** 연결 획득 시간 초과. `PoolMeasurement.pending`이 0이 아니다. -1. Check `REQUIRES_NEW` usage. It takes a second connection while pinning the first, so the pool - must satisfy `(threads x (1 + depth)) + 1`. -2. Check for streaming outside a bounded scope — a `Stream` returned past the transaction holds its - connection until the pool notices. -3. Check for external calls inside a DB transaction. The design forbids them precisely because an - HTTP timeout then holds a connection for its whole duration. +1. `REQUIRES_NEW` 사용을 확인한다. 첫 연결을 쥔 채 두 번째 연결을 잡으므로, 풀은 `(threads x (1 + depth)) + 1`을 채워야 한다. +2. 상한 있는 범위 밖의 streaming을 확인한다. 트랜잭션 밖으로 돌려준 `Stream`은 풀이 알아챌 때까지 연결을 쥔다. +3. DB 트랜잭션 안의 외부 호출을 확인한다. 설계가 그것을 금지하는 이유가 바로 그것이다. 그러면 HTTP 시간 초과가 그 시간 + 내내 연결을 쥔다. -## Flyway validation failed at startup +## 기동할 때 Flyway 검증이 실패했다 -The deployment is running against a schema it was not built for. It failed closed, which is correct. +배포가 맞지 않는 스키마에서 돌고 있다. 닫힌 채 실패했고, 그것이 맞다. -1. Read the reported error codes (the messages are deliberately not propagated). -2. `CHECKSUM_MISMATCH` — an applied migration was edited afterwards. Find which change is missing - from this database. **Do not run `repair`**: it rewrites history to match the scripts, which - resolves the symptom by deleting the evidence. -3. `MISSING_SCRIPT` — a migration applied here is not in this build. Usually a rollback to an older - artifact. +1. 보고된 오류 코드를 읽는다(메시지는 일부러 전달하지 않는다). +2. `CHECKSUM_MISMATCH` — 적용된 마이그레이션을 나중에 고쳤다. 이 DB에 어느 변경이 빠졌는지 찾는다. **`repair`를 돌리지 + 않는다.** repair는 이력을 스크립트에 맞춰 다시 써서, 증거를 지워 증상을 없앤다. +3. `MISSING_SCRIPT` — 여기 적용된 마이그레이션이 이 빌드에 없다. 보통 옛 산출물로 되돌린 것이다. -## An invalid index exists +## 무효 인덱스가 있다 (An invalid index exists) -**Signal:** this query returns rows. +**신호:** 이 쿼리가 행을 돌려준다. ```sql select n.nspname || '.' || i.relname as invalid_index @@ -69,28 +60,24 @@ join pg_namespace n on n.oid = i.relnamespace where not x.indisvalid; ``` -A concurrent build, rebuild or drop failed. The index is ignored by the planner and maintained by -every write. +동시 빌드, 재빌드, 삭제가 실패했다. planner는 그 인덱스를 무시하고, 모든 쓰기는 그것을 유지한다. -1. Confirm no build is currently running. An in-progress build looks identical in the catalog. -2. If a migration was building, rebuilding or dropping it, Flyway recorded that version as failed - (`success = false`) and refuses every later deploy until that row is gone: dropping the index - does not clear it. Follow [migration-failed.md](../runbooks/migration-failed.md) "Recover a - failed concurrent index migration" instead of the next step. It removes the cause, drops the - index a failed build or rebuild left, and deletes that one row. It leaves the index a failed - `DROP INDEX CONCURRENTLY` left, for the deploy again to drop: dropped by hand, that statement - finds no index and fails again. -3. Otherwise run `DROP INDEX CONCURRENTLY IF EXISTS ;` outside a migration, and - re-apply the index migration. +1. 지금 도는 빌드가 없는지 확인한다. 진행 중인 빌드도 카탈로그에서는 똑같이 보인다. +2. 마이그레이션이 그것을 빌드, 재빌드, 삭제하던 중이었으면, Flyway는 그 버전을 실패(`success = false`)로 기록했고 그 행이 + 사라질 때까지 뒤의 모든 배포를 거부한다. 인덱스를 지워도 풀리지 않는다. 다음 단계 대신 + [migration-failed.md](../runbooks/migration-failed.md) 「실패한 동시 인덱스 마이그레이션 복구 (Recover a failed + concurrent index migration)」를 따른다. 그 절차는 원인을 없애고, 실패한 빌드나 재빌드가 남긴 인덱스를 지우고, 그 한 행을 + 지운다. 실패한 `DROP INDEX CONCURRENTLY`가 남긴 인덱스는 다시 배포가 지우도록 남긴다. 손으로 지우면 그 문장이 인덱스를 + 찾지 못해 다시 실패한다. +3. 그렇지 않으면 마이그레이션 밖에서 `DROP INDEX CONCURRENTLY IF EXISTS ;`를 돌리고, 인덱스 마이그레이션을 + 다시 적용한다. -The platform does not drop these automatically: on a rolling deploy every instance would race to -drop an index another instance was about to finish building. +플랫폼은 이것을 자동으로 지우지 않는다. rolling deploy에서는 모든 인스턴스가, 다른 인스턴스가 곧 빌드를 끝낼 인덱스를 +지우려고 경주한다. -## The runtime role failed verification +## 런타임 역할이 검증에 실패했다 -Startup refused because the runtime credential holds `CREATE`, or `search_path` contains an -unapproved schema. +런타임 자격 증명이 `CREATE`를 가지거나 `search_path`에 승인하지 않은 schema가 있어서 기동이 거부됐다. -This is not a false positive to be worked around. `docs/jpa/security.md` 「역할과 권한 — 운영 DB가 -갖춰야 할 것」대로 권한을 다시 맞춘다. 애플리케이션 자격 증명이 DDL을 가지면 다른 schema 보장을 하나도 -지킬 수 없다. +돌아갈 오탐이 아니다. `docs/jpa/security.md` 「역할과 권한 — 운영 DB가 갖춰야 할 것」대로 권한을 다시 맞춘다. 애플리케이션 +자격 증명이 DDL을 가지면 다른 schema 보장을 하나도 지킬 수 없다. diff --git a/docs/jpa/security.md b/docs/jpa/security.md index dbf5fa92..818990eb 100644 --- a/docs/jpa/security.md +++ b/docs/jpa/security.md @@ -1,18 +1,18 @@ -# Security +# 보안 -Design §36. Credential separation, privilege verification, and what never leaves the process. +설계서 §36. 자격 증명 분리, 권한 검증, 프로세스 밖으로 절대 나가지 않는 것. -## Three credentials +## 자격 증명 셋 -| Role | May | +| 역할 | 할 수 있는 것 | |---|---| -| `app_migration` | own the schema, apply migrations (DDL) | -| `app_runtime` | select, insert, update, delete (DML only) | -| `app_admin` | J4 operations — COPY, backfill, maintenance | +| `app_migration` | schema 소유, 마이그레이션 적용(DDL) | +| `app_runtime` | select, insert, update, delete(DML만) | +| `app_admin` | J4 작업 — COPY, backfill, 정비 | -The separation is what makes "Flyway owns schema change" enforceable rather than aspirational. If -the application's own credential cannot execute DDL, then no code path, no library, and no injected -statement can alter the schema at runtime, regardless of what the application intended. +이 분리가 「schema 변경은 Flyway가 가진다」를 바람이 아니라 강제할 수 있는 규칙으로 만든다. 애플리케이션 자신의 자격 증명이 +DDL을 실행할 수 없으면, 애플리케이션이 무엇을 의도했든 어떤 코드 경로도, 라이브러리도, 주입된 문장도 실행 중에 schema를 바꿀 +수 없다. ### 역할과 권한 — 운영 DB가 갖춰야 할 것 @@ -50,9 +50,9 @@ statement can alter the schema at runtime, regardless of what the application in 확장(extension)은 필요 없다. JSONB, 배열, 범위, `SKIP LOCKED`, `ON CONFLICT`는 모두 PostgreSQL 본체 기능이다. -## Startup verification +## 기동 검증 -`PostgreSqlRuntimeRoleVerifier` asks the *server* what the connection can do: +`PostgreSqlRuntimeRoleVerifier`가 연결이 무엇을 할 수 있는지 *서버*에 묻는다. ```sql select current_user, @@ -61,38 +61,35 @@ select current_user, has_database_privilege(current_user, current_database(), 'CREATE') ``` -Configuration cannot answer this. Effective privileges come from direct grants, inherited role -memberships, `PUBLIC` grants, and schema ownership, and no reading of a deployment manifest -reconstructs that combination reliably. +설정으로는 이것에 답할 수 없다. 실제 권한은 직접 grant, 물려받은 역할 membership, `PUBLIC` grant, schema 소유에서 오고, 배포 +manifest를 읽어서는 그 조합을 믿을 만하게 되살릴 수 없다. -Startup fails when the runtime role is not on the allowlist, or holds `CREATE` on the schema or the -database. +런타임 역할이 허용 목록에 없거나, schema나 데이터베이스에 `CREATE`를 가지면 기동이 실패한다. ## search_path -`SearchPathPolicy` is an allowlist. `search_path` decides which schema an unqualified name resolves -to, so a writable untrusted schema on it — classically `public`, where `CREATE` was granted broadly -before PostgreSQL 15 — lets a planted table, function, or operator shadow the real one, and the -application executes it without noticing. `$user` is exempt: only the connected role owns it. +`SearchPathPolicy`는 허용 목록이다. `search_path`는 이름만 쓴 객체가 어느 schema로 풀리는지 정한다. 그래서 그 위에 쓸 수 있는 +믿지 못할 schema가 있으면(전형적으로 `public`. PostgreSQL 15 전에는 `CREATE`가 넓게 주어졌다) 심어 둔 테이블, 함수, 연산자가 +진짜 것을 가리고, 애플리케이션은 알아채지 못한 채 그것을 실행한다. `$user`는 예외다. 연결한 역할만 그것을 소유한다. -Refusing the runtime role `CREATE` closes the same route from the other side. +런타임 역할에게 `CREATE`를 주지 않는 것이 같은 길을 반대쪽에서 막는다. -## What never leaves the process +## 프로세스 밖으로 절대 나가지 않는 것 -- SQL parameter values, entity ids, tenant ids, and PII: not in exception messages, not in metric - tags, not in logs. `JpaFailureContext` composes messages from bounded values only. -- Constraint names reach the application as registered `ConstraintCode`s; an unregistered physical - name maps to a bounded unknown code rather than being passed through. -- Cursors are HMAC-signed. An unsigned cursor is client-controlled ordering state. -- The actuator report carries no JDBC URL, username, or SQL. +- SQL 파라미터 값, entity id, tenant id, PII. 예외 메시지에도, 메트릭 태그에도, 로그에도 없다. `JpaFailureContext`는 상한 있는 + 값으로만 메시지를 만든다. +- 제약 이름은 등록된 `ConstraintCode`로 애플리케이션에 닿는다. 등록되지 않은 물리 이름은 그대로 넘기지 않고 상한 있는 unknown + 코드로 매핑한다. +- cursor는 HMAC으로 서명한다. 서명 없는 cursor는 클라이언트가 다루는 정렬 상태다. +- actuator 보고에는 JDBC URL, 사용자 이름, SQL이 없다. -## Injection surfaces, and how each is closed +## 주입 표면과 각각을 막는 법 -| Surface | Why it cannot be a parameter | Closed by | +| 표면 | 파라미터가 될 수 없는 이유 | 막는 것 | |---|---|---| -| sort field | part of ORDER BY | `SafeSortRegistry` allowlist | -| JSON path | part of the statement | registered `JsonPathName` | -| schema name | an identifier | registered `SchemaTenantRegistry` | -| COPY table | an identifier | registered `RegisteredCopyStatement` | +| 정렬 칸 | ORDER BY의 일부 | `SafeSortRegistry` 허용 목록 | +| JSON 경로 | 문장의 일부 | 등록한 `JsonPathName` | +| schema 이름 | 식별자 | 등록한 `SchemaTenantRegistry` | +| COPY 테이블 | 식별자 | 등록한 `RegisteredCopyStatement` | -Values are always bound. Identifiers are always registered. +값은 늘 묶는다. 식별자는 늘 등록한다. diff --git a/docs/jpa/support-matrix.md b/docs/jpa/support-matrix.md index 258fa1fa..50a1965d 100644 --- a/docs/jpa/support-matrix.md +++ b/docs/jpa/support-matrix.md @@ -1,89 +1,79 @@ -# JPA Persistence Platform — Support Matrix +# JPA 영속성 플랫폼 — 지원 매트릭스 -**This document is a rendering. The machine-readable source is -[`src/adapter/outbound/persistence-jpa/release/release-registry.json`](../../src/adapter/outbound/persistence-jpa/release/release-registry.json).** +**이 문서는 렌더링이다. 기계가 읽는 정본은 +[`src/adapter/outbound/persistence-jpa/release/release-registry.json`](../../src/adapter/outbound/persistence-jpa/release/release-registry.json)이다.** -`JpaReleaseManifest` used to parse this file with regular expressions: every `PostgreSQL NN` it -mentioned became a supported version, whatever table or sentence produced the match. An Experimental -major joined the Stable list, a version named once in prose counted as supported, and demoting a -major changed nothing so long as the string survived somewhere in the document. Now the registry -declares a support level per major as a field, each gate names the Gradle task that produces its -evidence, and this document describes what the registry says. +registry는 major마다 지원 수준을 칸으로 선언하고, gate마다 그 증거를 만드는 Gradle 태스크를 이름 댄다. 이 문서는 +registry가 말하는 것을 설명한다. 표를 고치지 말고 registry를 고친다. 표가 따라오지 않으면 빌드가 실패한다. -Being a rendering used to be a claim rather than a mechanism: the tables below were still typed by -hand, so a major demoted in the registry stayed Stable here and kept its full release job. -`JpaReleaseRenderingTest` now compares the database table, the gate table and `release.yml`'s JPA -matrix and promotion lists to the registry, and the `jpaReleaseQualification` aggregate depends on -every blocking gate's task, so a gate naming a task that does not exist fails when the task graph is -built. Edit the registry; these tables follow, or the build fails. +- `JpaReleaseRenderingTest`가 DB 표, gate 표, `release.yml`의 JPA matrix와 승격 목록을 registry와 비교한다. +- `jpaReleaseQualification` 집계 태스크는 막는 gate마다 그 태스크에 의존한다. 그래서 없는 태스크를 이름 댄 gate는 태스크 + 그래프를 만들 때 실패한다. +- `jpa-nightly.yml`의 matrix도 같은 비교를 받는다. Experimental major는 `.github/workflows`의 어떤 lane이 그것을 대상으로 + 기록해야 하고, Stable lane은 그것을 돌리면 안 된다. -Two renderings stayed outside that comparison until they were added to it. `jpa-nightly.yml` runs -its own matrix and nothing checked it, so a demotion corrected the release lane and left the nightly -lane certifying the major. And an Experimental major's "compatibility lane only" named no file: the -lane existed, but the registry, this document and the release workflow could each be read end to end -without establishing that, so a reader looking for it concluded there was none. An Experimental major -now has to be recorded as the target of a lane in `.github/workflows`, and a Stable lane may not run -it. +> 이력: 전에는 `JpaReleaseManifest`가 이 파일을 정규식으로 읽었다. 어느 표나 문장에서 나왔든 `PostgreSQL NN`이 지원 +> 버전이 됐다. Experimental major가 Stable 목록에 들어갔고, 본문에 한 번 나온 버전이 지원으로 셌고, 문자열이 문서 +> 어딘가에 남아 있는 한 major를 내려도 아무것도 바뀌지 않았다. registry로 옮긴 뒤에도 한동안 아래 표는 손으로 썼다. +> 그래서 registry에서 내린 major가 여기서는 Stable로 남고 자기 전체 릴리스 job을 계속 가졌다. `jpa-nightly.yml`은 자기 +> matrix를 아무도 확인하지 않아서, 내리기가 릴리스 lane만 고치고 nightly lane은 그 major를 계속 인증했다. Experimental +> major의 「compatibility lane only」는 어떤 파일도 가리키지 않았다. lane은 있었지만 registry, 이 문서, 릴리스 workflow를 +> 끝까지 읽어도 그것을 알 수 없어서, 찾던 사람은 없다고 결론 냈다. -## Database +## 데이터베이스 | Database | Support | Evidence | |---|---|---| -| PostgreSQL 16 | Stable | full contract suite, release lane (own matrix job) | -| PostgreSQL 17 | Stable | full contract suite, release lane (own matrix job) | -| PostgreSQL 18 | Stable | full contract suite, release lane (own matrix job) | -| PostgreSQL 19 | Experimental | [`jpa-next.yml`](../../.github/workflows/jpa-next.yml) — `NOT_EXECUTABLE`: no `postgres:19-alpine` is published, so no container of that major has been started; promotion requires an ADR | -| H2 | Local convenience | **never** evidence of PostgreSQL behaviour | +| PostgreSQL 16 | Stable | 전체 계약 suite, 릴리스 lane(자기 matrix job) | +| PostgreSQL 17 | Stable | 전체 계약 suite, 릴리스 lane(자기 matrix job) | +| PostgreSQL 18 | Stable | 전체 계약 suite, 릴리스 lane(자기 matrix job) | +| PostgreSQL 19 | Experimental | [`jpa-next.yml`](../../.github/workflows/jpa-next.yml) — `NOT_EXECUTABLE`: `postgres:19-alpine`이 게시되지 않아 그 major의 컨테이너를 띄운 적이 없다. 승격에는 ADR이 필요하다 | +| H2 | Local convenience | PostgreSQL 동작의 증거가 **절대** 아니다 | -Each major gets its **own release job**, because for a while it did not. The release lane passed -`-Pjpa.matrix.versions=16,17,18` to a `JpaPlatformContractSupport.start()` that used -`selectedVersions().get(0)`, so the whole integration suite ran against PostgreSQL 16 and this table -recorded 17 and 18 as fully covered on the strength of a three-assertion smoke test. `start()` now -refuses a multi-version selection outright, the `jpa-release-gate` job in `release.yml` fans out to one job per major, and a -promotion job requires all three majors' evidence to carry the same commit SHA — so a removed major -removes the release, not the evidence for it. +major마다 **자기 릴리스 job**이 있다. `release.yml`의 `jpa-release-gate` job이 major마다 job 하나로 펼치고, 승격 job은 세 +major의 증거가 모두 같은 커밋 SHA를 지니기를 요구한다. 그래서 major 하나가 빠지면 그 증거가 아니라 릴리스가 빠진다. +`JpaPlatformContractSupport.start()`는 여러 버전 선택을 아예 거부한다. -**Provider baseline.** The gates run against the Hibernate version the Spring Boot BOM resolves — -**7.1.8.Final** — which the registry records as `stable-tested-baseline`. This document previously -called 7.4 the Stable baseline and the pagination gate was named `hibernate-7.4-fetch-pagination`, -so every run of that gate produced evidence labelled with a provider it had never executed against. -7.4 is recorded as `compatibility-target`; it becomes the baseline when a full lane has actually run -on it. +> 이력: 한동안 그렇지 않았다. 릴리스 lane이 `-Pjpa.matrix.versions=16,17,18`을 `selectedVersions().get(0)`을 쓰는 +> `JpaPlatformContractSupport.start()`에 넘겼으므로, 통합 suite 전체가 PostgreSQL 16에만 돌았다. 이 표는 단언 셋짜리 +> smoke test를 근거로 17과 18을 전부 덮었다고 적었다. -H2 is not a second production target. It reports different SQLSTATEs for the same violation, no JSONB -operators, no range types, and no concurrent index builds. A green H2 run is evidence that the code -compiles and runs, and nothing more. +**provider 기준선.** gate는 Spring Boot BOM이 푸는 Hibernate 버전 **7.1.8.Final**에서 돈다. registry는 그것을 +`stable-tested-baseline`으로 기록한다. 7.4는 `compatibility-target`으로 기록하고, 전체 lane이 실제로 그 버전에서 돈 뒤에 +기준선이 된다. -`SKIP LOCKED` needs its own sentence, because two documents said different things about it. The -module's `CLAUDE.md` records a measurement: H2 2.4.240 accepts `FOR UPDATE SKIP LOCKED` and does -genuinely skip locked rows, which is why the outbox claim SQL is identical on both vendors. This -document previously said H2 has no such guarantee. Both are right about different questions, and -the distinction is the point: **observed behaviour in the version we measured is not a production -guarantee, and it is never PostgreSQL contract evidence.** The measurement is why the claim SQL -needs no vendor branch; the absence of a guarantee is why every concurrency contract still runs -against a real PostgreSQL. +> 이력: 이 문서는 전에 7.4를 Stable 기준선이라 불렀고 페이지네이션 gate 이름도 `hibernate-7.4-fetch-pagination`이었다. +> 그래서 그 gate를 돌릴 때마다 한 번도 돌려 보지 않은 provider 이름이 붙은 증거가 나왔다. -## Specification and provider +H2는 두 번째 운영 대상이 아니다. 같은 위반에 다른 SQLSTATE를 보고하고, JSONB 연산자도, range 타입도, 동시 인덱스 +빌드도 없다. H2에서 통과한 실행은 코드가 컴파일되고 돈다는 증거일 뿐이다. -| Component | Stable | Experimental | +`SKIP LOCKED`는 따로 한 문장이 필요하다. 두 문서가 다른 말을 했기 때문이다. 모듈의 `CLAUDE.md`는 측정을 기록한다. +H2 2.4.240은 `FOR UPDATE SKIP LOCKED`를 받고 잠긴 행을 정말로 건너뛴다. 그래서 outbox claim SQL이 두 vendor에서 같다. 이 +문서는 전에 H2에 그런 보장이 없다고 했다. 둘은 서로 다른 질문에 각각 맞았고, 그 구별이 요점이다. **측정한 버전에서 관찰한 +동작은 운영 보장이 아니고, PostgreSQL 계약 증거는 더욱 아니다.** 측정 덕분에 claim SQL에 vendor 분기가 필요 없고, 보장이 +없으므로 모든 동시성 계약은 여전히 실제 PostgreSQL에서 돈다. + +## 명세와 provider + +| 구성 요소 | Stable | Experimental | |---|---|---| | Jakarta Persistence | 3.2 | 4.0 (lane) | -| Hibernate ORM | 7.4 declared baseline | 8 (lane) | -| Spring Boot | repository BOM | — | +| Hibernate ORM | 7.4 선언 기준선 | 8 (lane) | +| Spring Boot | 저장소 BOM | — | -The Hibernate row needs a note. The design declares 7.4 as the Stable provider; this repository's -Spring Boot BOM resolves 7.1.x. `HibernateProviderPolicy` holds both — the declared baseline as a -constant, the resolved version read from Hibernate itself — and `driftsFromDeclaredBaseline()` makes -the difference visible instead of asserting a constant against itself. See -[repository-adaptation.md](repository-adaptation.md) §4. +Hibernate 줄에는 설명이 필요하다. 설계서는 7.4를 Stable provider로 선언하고, 이 저장소의 Spring Boot BOM은 7.1.x를 푼다. +`HibernateProviderPolicy`가 둘을 다 가진다. 선언 기준선은 상수로, 풀린 버전은 Hibernate 자신에게서 읽는다. +`driftsFromDeclaredBaseline()`이 상수를 상수와 비교하는 대신 그 차이를 드러낸다. +[repository-adaptation.md](repository-adaptation.md) §4를 본다. -## Capability support levels +## capability 지원 수준 -The levels are the ones `JpaPlatformAutoConfiguration.capabilities()` reports through the -`jpaplatform` actuator endpoint. Advanced and Experimental rows are library code a service calls -itself (`src/adapter/outbound/persistence-jpa/README.md` "라이브러리 API"). +수준은 `jpaplatform` actuator 엔드포인트가 `JpaPlatformReport.platformCapabilities()`로 보고하는 값이다. 마지막 세 +줄(기술 감사, multi-tenancy, read replica)은 그 보고에 없고 이 문서가 정한다. Advanced와 Experimental 줄은 서비스가 직접 +부르는 라이브러리 코드다(`src/adapter/outbound/persistence-jpa/README.md` 「라이브러리 API」). -| Capability | Level | +| capability | 수준 | |---|---| | Keyset pagination | Stable | | Flyway schema gate | Stable | @@ -95,44 +85,40 @@ itself (`src/adapter/outbound/persistence-jpa/README.md` "라이브러리 API"). | PostgreSQL array and range | Advanced | | Bulk DML | Advanced | | Hibernate `StatelessSession` | Advanced | -| PostgreSQL `COPY` | Admin (J4) | +| PostgreSQL `COPY` | Advanced (admin 자격 증명 필요) | | Hibernate second-level cache | Advanced | | Hibernate Envers | Advanced | -| Technical auditing — `audit/AuditableEntity` | Stable (canonical) | +| 기술 감사 — `audit/AuditableEntity` | Stable (canonical) | | Multi-tenancy (column, RLS, schema, database) | Experimental | -| Consistency-aware read replica | Experimental | +| 일관성을 아는 read replica | Experimental | -## Release gates +## 릴리스 gate -Each row is a way the platform could pass its tests and still be wrong in production. +줄마다, 플랫폼이 테스트를 통과하고도 운영에서 틀릴 수 있는 길 하나다. -| Gate | Kind | What it prevents | +| Gate | Kind | 막는 것 | |---|---|---| -| `postgresql-contract` | gate | a release whose only database evidence came from H2 | -| `completion-unknown-no-retry` | gate | automatically re-running a write that may already have committed | -| `osiv-disabled` | gate | lazy loading from the view layer, one query per rendered row | -| `flyway-validate` | gate | Hibernate mutating a deployed schema, or running against one it was not built for | -| `runtime-role-no-ddl` | gate | the application's own credential being able to alter or drop schema objects | -| `collection-fetch-pagination` | gate | a paged collection fetch silently reading the whole table and paginating in memory | +| `postgresql-contract` | gate | DB 증거가 H2에서만 나온 릴리스 | +| `completion-unknown-no-retry` | gate | 이미 커밋됐을 수 있는 쓰기를 자동으로 다시 돌림 | +| `osiv-disabled` | gate | view 계층에서의 lazy loading, 렌더링한 행마다 쿼리 하나 | +| `flyway-validate` | gate | Hibernate가 배포된 스키마를 바꾸거나, 맞지 않는 스키마에서 돎 | +| `runtime-role-no-ddl` | gate | 애플리케이션 자신의 자격 증명으로 스키마 객체를 바꾸거나 지울 수 있음 | +| `collection-fetch-pagination` | gate | 페이지 단위 collection fetch가 몰래 테이블 전체를 읽고 메모리에서 페이지를 나눔 | -### The audit mechanism +### 감사 방식 -`audit/AuditableEntity` is the only one: `created_*`/`updated_*`, a 256-character actor, stamped -explicitly by the repository adapter. 서비스의 엔티티는 이것을 상속하고, 마이그레이션도 이 열에 -맞춰 썼다. A second, Spring Data listener-based mechanism (`auditing/AuditMetadata`) was never -composed and has been removed; `JpaAuditMechanismRule.entitiesUseExactlyOneAuditMechanism` keeps it -from coming back on an entity. +감사 방식은 `audit/AuditableEntity` 하나다. `created_*`/`updated_*`, 256자 actor이고, repository 어댑터가 명시적으로 +찍는다. 서비스의 엔티티는 이것을 상속하고, 마이그레이션도 이 열에 맞춰 썼다. 두 번째 방식인 Spring Data listener 기반 +(`auditing/AuditMetadata`)은 한 번도 조립되지 않아서 지웠다. `JpaAuditMechanismRule.entitiesUseExactlyOneAuditMechanism`이 +그것이 엔티티에 돌아오지 못하게 막는다. -The mechanism does not reach a bulk or native update. It stamps on an ordinary save in the adapter, -so a statement that goes straight to the database leaves the audit columns showing the previous save. -A bulk update of an audited entity must therefore set the audit column in the statement, which -`JpaAuditMechanismRule.bulkUpdatesOfAuditedEntitiesStampAudit` checks over the production graph. +이 방식은 bulk·native update에 닿지 않는다. 어댑터의 보통 save에서 찍으므로, DB로 바로 가는 문장은 감사 열을 앞 save의 +값으로 남긴다. 그래서 감사 대상 엔티티의 bulk update는 문장 안에서 감사 열을 설정해야 하고, +`JpaAuditMechanismRule.bulkUpdatesOfAuditedEntitiesStampAudit`가 운영 그래프에서 그것을 확인한다. -## Explicitly unsupported +## 지원하지 않는다고 밝힌 것 -- Reactive JPA. JPA is a blocking specification; a reactive facade over it moves the blocking call - onto an event loop rather than removing it. -- Hibernate as the production schema writer. `ddl-auto` never mutates a deployed schema. -- A platform-owned generic CRUD repository. Domains own their repositories (design §10.1). -- Automatic reconciliation of a completion-unknown transaction. The platform records; the domain - resolves. +- Reactive JPA. JPA는 blocking 명세다. 그 위의 reactive facade는 blocking 호출을 없애는 게 아니라 event loop로 옮긴다. +- 운영 스키마를 쓰는 Hibernate. `ddl-auto`는 배포된 스키마를 절대 바꾸지 않는다. +- 플랫폼이 가진 generic CRUD repository. 도메인이 자기 repository를 가진다(설계서 §10.1). +- 완료를 모르는 트랜잭션의 자동 맞추기. 플랫폼은 기록하고, 도메인이 푼다. diff --git a/docs/jpa/transaction-guide.md b/docs/jpa/transaction-guide.md index 491d7530..b4c45ef3 100644 --- a/docs/jpa/transaction-guide.md +++ b/docs/jpa/transaction-guide.md @@ -1,65 +1,56 @@ -# Transaction Guide +# 트랜잭션 가이드 -Design §15-§20. What owns a transaction, what may be retried, and what must never be. +설계서 §15-§20. 무엇이 트랜잭션을 가지고, 무엇을 다시 시도해도 되고, 무엇은 절대 안 되나. -## The application service owns the boundary +## 경계는 애플리케이션 서비스가 가진다 -Repository adapters do not open transactions. The use case does, through `TransactionPort`, -because the unit of work is a business decision and only the use case knows where it starts and -ends. `SpringTransaction` is the only implementation: one pre-built `TransactionTemplate` per -mode over Spring's `PlatformTransactionManager`, every mode running at `READ_COMMITTED` and -bounded in time. +repository 어댑터는 트랜잭션을 열지 않는다. use case가 `TransactionPort`로 연다. 작업 단위는 업무 결정이고, 그것이 어디서 +시작하고 끝나는지는 use case만 알기 때문이다. 구현은 `SpringTransaction` 하나다. Spring의 `PlatformTransactionManager` 위에 +mode마다 미리 만든 `TransactionTemplate` 하나를 두고, 모든 mode가 `READ_COMMITTED`로 돌며 시간 상한이 있다. -- **Isolation** is pinned on the pool, not per transaction: the module defaults set - `spring.datasource.hikari.transaction-isolation: TRANSACTION_READ_COMMITTED` and - `HikariPoolConstraintValidator` refuses any other level. A template that names the level makes - pgjdbc ask the server for it (`SHOW TRANSACTION ISOLATION LEVEL`) at every begin. -- **Time bound**: `app.persistence-jpa.transaction.write-timeout` (`inWrite`, `inRootWrite`) and - `read-timeout` (`inRead`), 30 s each by default; `inNew` is fixed at 30 s. Spring hands the - remaining time to each statement, so the server cancels a slow statement or lock wait - (`DB_QUERY_CANCELED`) and the connection returns to the pool. A unit of work that needs longer - is usually a batch job that should be split, not a reason to raise the bound. +- **격리 수준**은 트랜잭션마다가 아니라 풀에 고정한다. module defaults가 + `spring.datasource.hikari.transaction-isolation: TRANSACTION_READ_COMMITTED`를 두고, `HikariPoolConstraintValidator`가 다른 + 수준을 거부한다. 수준을 이름 대는 template은 begin마다 pgjdbc가 서버에 그것을 묻게 한다(`SHOW TRANSACTION ISOLATION LEVEL`). +- **시간 상한**: `app.persistence-jpa.transaction.write-timeout`(`inWrite`, `inRootWrite`)과 `read-timeout`(`inRead`), 기본값은 + 각각 30 s다. `inNew`는 30 s로 고정이다. Spring이 남은 시간을 문장마다 넘기므로 서버가 느린 문장이나 잠금 대기를 취소하고 + (`DB_QUERY_CANCELED`) 연결은 풀로 돌아간다. 더 오래 걸려야 하는 작업 단위는 보통 상한을 올릴 이유가 아니라 나눠야 할 batch + 작업이다. -| Call | Propagation | When | +| 호출 | 전파 | 언제 | |---|---|---| -| `inWrite` | `REQUIRED`, read-write | command default | -| `inRootWrite` | `REQUIRED`, read-write, rejects an ambient transaction before running | orchestration that must prove a physical commit | -| `inRead` | `REQUIRED`, read-only | query default | -| `inNew` | `REQUIRES_NEW`, read-write | outbox / audit / compensation that must commit on its own | +| `inWrite` | `REQUIRED`, 읽기-쓰기 | command 기본 | +| `inRootWrite` | `REQUIRED`, 읽기-쓰기, 돌기 전에 바깥 트랜잭션을 거부 | 물리 커밋을 증명해야 하는 조율 | +| `inRead` | `REQUIRED`, 읽기 전용 | query 기본 | +| `inNew` | `REQUIRES_NEW`, 읽기-쓰기 | 혼자 커밋해야 하는 outbox / 감사 / 보상 | -Open Session In View is off in every runtime profile. It is on by default in Spring Boot, which is -why `JpaDangerousConfigurationGuard` fails startup rather than trusting configuration review. +Open Session In View는 모든 런타임 profile에서 꺼져 있다. Spring Boot에서는 기본으로 켜져 있어서, 설정 리뷰를 믿지 않고 +`JpaDangerousConfigurationGuard`가 기동을 실패시킨다. -`REQUIRES_NEW` acquires a second physical connection while pinning the first, so the pool must -satisfy: +`REQUIRES_NEW`는 첫 물리 연결을 쥔 채 두 번째를 잡으므로 풀은 다음을 채워야 한다. ```text maximumPoolSize >= (concurrent_threads x (1 + max_requires_new_depth)) + 1 ``` -## Nothing is retried by the port +## port는 아무것도 다시 시도하지 않는다 -`SpringTransaction` runs the action once. A failure rolls back and propagates, translated to -the shared persistence error codes where the SQLSTATE is known; a lost `@Version` race has no -SQLSTATE and is reported as `DB_OPTIMISTIC_CONFLICT` (409). A caller that decides to retry must -re-run the whole use case in a new transaction — never re-issue one statement — because an -optimistic conflict or a serialization failure means the state the attempt computed against is no -longer the committed state. +`SpringTransaction`은 action을 한 번 돌린다. 실패하면 롤백하고 넘기며, SQLSTATE를 알면 공유 영속성 오류 코드로 바꾼다. +잃은 `@Version` 경주는 SQLSTATE가 없고 `DB_OPTIMISTIC_CONFLICT`(409)로 보고한다. 다시 시도하기로 한 호출자는 문장 하나를 다시 +보내지 말고 use case 전체를 새 트랜잭션에서 다시 돌린다. 낙관적 충돌이나 직렬화 실패는 시도가 기준으로 계산한 상태가 더는 +커밋된 상태가 아니라는 뜻이기 때문이다. -A second engine with named policies, deadline budgets, transaction-local timeouts and automatic -full-transaction retry (`SpringJpaTransactionExecutor`, `FullTransactionRetryCoordinator`, -`PolicyTransactionPort`) existed next to this one and was removed on 2026-09-25. Its last commit is -recorded in `docs/capability-status.md`. +> 이력: 이름 있는 정책, 마감 예산, 트랜잭션 로컬 시간 상한, 자동 전체 트랜잭션 재시도를 가진 두 번째 엔진 +> (`SpringJpaTransactionExecutor`, `FullTransactionRetryCoordinator`, `PolicyTransactionPort`)이 이것 옆에 있다가 +> 2026-09-25에 지워졌다. 마지막 커밋은 `docs/capability-status.md`에 있다. -## Completion unknown +## 완료를 모름 -A connection can break while a commit is in flight; the server may have committed and only the -acknowledgement was lost. `TransactionCompletionUnknownException` is never retried, and the type -system enforces it: `JpaFailureContext` refuses to represent a retryable completion-unknown failure. -The port itself retries nothing, so such a commit surfaces to the caller as a failure exactly once +커밋이 진행 중일 때 연결이 끊길 수 있다. 서버는 커밋했고 확인 응답만 잃었을 수 있다. `TransactionCompletionUnknownException`은 +절대 다시 시도하지 않고, 타입 체계가 그것을 강제한다. `JpaFailureContext`는 다시 시도할 수 있는 완료 모름 실패를 표현하기를 +거부한다. port 자신은 아무것도 다시 시도하지 않으므로, 그런 커밋은 호출자에게 실패로 정확히 한 번 나타난다 (`PostgreSqlTransactionIntegrationTest#connectionLossDuringCommitSurfacesAsCompletionUnknownAndIsNeverRetried`). -Recovery is reconciliation, not retry: +복구는 재시도가 아니라 맞추기다. ```text check the idempotency record -> check the business row -> check the outbox diff --git a/docs/manual/01-generator.md b/docs/manual/01-generator.md index fe9a0c8e..51adb4c1 100644 --- a/docs/manual/01-generator.md +++ b/docs/manual/01-generator.md @@ -64,7 +64,7 @@ verify-feature-scaffold.sh -> new-feature.sh Operation / Notification / Common (템플릿 패키지 이름: 거절되고 아무것도 안 씀) -> new-feature.sh Invoice, new-feature.sh PurchaseOrder (한 단어 / 여러 단어) -> 생성 파일이 있는지 확인 - -> ./gradlew 5 leaf check + architectureCheck + -> 생성물이 닿는 leaf(domain-core, application-core, identifier, web, app-bootstrap) check + architectureCheck -> 각 leaf 테스트 결과에 생성된 테스트 클래스가 실행·통과로 남았는지 확인 -> 임시 디렉터리 삭제 ``` diff --git a/docs/mongodb/advanced/encryption.md b/docs/mongodb/advanced/encryption.md index aef26fc3..a097f173 100644 --- a/docs/mongodb/advanced/encryption.md +++ b/docs/mongodb/advanced/encryption.md @@ -1,99 +1,97 @@ -# Advanced — CSFLE and Queryable Encryption +# Advanced — CSFLE와 Queryable Encryption -**Capabilities:** `MongoCapability.CSFLE`, `MongoCapability.QUERYABLE_ENCRYPTION` -**Enablement:** library API, no configuration property. The service's own adapter constructs the -entry point with a `MongoAdvancedCapabilityGuard` built from `MongoAdvancedCapabilityFlags` that -enables the capability; construction is refused otherwise. -**Status:** Advanced. +**Capability:** `MongoCapability.CSFLE`, `MongoCapability.QUERYABLE_ENCRYPTION` +**켜는 법:** 라이브러리 API다. 설정 속성은 없다. 서비스의 어댑터가 진입점을 만들 때 +`MongoAdvancedCapabilityGuard`를 넘긴다. 이 guard는 그 capability를 켠 `MongoAdvancedCapabilityFlags`로 +만든다. 켜지 않았으면 생성 자체가 거부된다. +**상태:** Advanced. -## Requirements +## 요구 사항 | | | |---|---| -| Topology | Replica set or sharded cluster. | -| Server | MongoDB 7.0 or 8.0 (see §4 for the 8.0 query-type limits). | -| Privilege | `MongoPrincipalRole.ENCRYPTION_ADMIN` for the key vault; the application role never holds it. | -| Environment | A real KMS and key vault. A local key provider does not exercise any of the failure modes that matter. | +| 토폴로지 | replica set 또는 sharded cluster. | +| 서버 | MongoDB 7.0 또는 8.0(8.0의 query type 제한은 4절). | +| 권한 | key vault에는 `MongoPrincipalRole.ENCRYPTION_ADMIN`이 필요하다. 애플리케이션 role은 이 권한을 갖지 않는다. | +| 환경 | 실제 KMS와 key vault. 로컬 key provider는 중요한 실패 모드를 하나도 재현하지 못한다. | ## 1. CSFLE -`MongoCsfleProfile` binds a collection (`database` + `collection`) to its `MongoCsfleFieldPolicy` -list, a key vault `MongoCredentialReference` and the key vault namespace. `MongoCsfleClientFactory` -builds the encrypted client settings from it: the `$jsonSchema` is generated from the field policies -(a dotted path becomes nested `properties`) and keyed by the namespace `database.collection`, and the -key vault client is built from the profile's own credential through `MongoCredentialResolver`. +`MongoCsfleProfile`은 collection 하나(`database` + `collection`)를 세 가지에 묶는다: +`MongoCsfleFieldPolicy` 목록, key vault용 `MongoCredentialReference`, key vault namespace. +`MongoCsfleClientFactory`가 이 profile로 암호화 client 설정을 만든다. -An automatic-encryption schema names a data key by id, not by alias. The adopter resolves each -`MongoCsfleFieldPolicy.keyAlias()` against the key vault (for example -`ClientEncryption.getKeyByAltName`) and passes the alias → key id map to `settingsFor`; an alias with -no id is refused. Deterministic fields are typed `string` in the schema. +- `$jsonSchema`는 field policy에서 생성한다. 점으로 이은 경로는 중첩된 `properties`가 된다. +- schema의 키는 namespace `database.collection`이다. +- key vault client는 profile 자신의 credential로 `MongoCredentialResolver`를 거쳐 만든다. + +자동 암호화 schema는 data key를 별칭이 아니라 id로 가리킨다. 그래서 도입하는 쪽이 각 +`MongoCsfleFieldPolicy.keyAlias()`를 key vault에서 찾아(예: `ClientEncryption.getKeyByAltName`) +별칭 → key id 맵을 `settingsFor`에 넘긴다. id가 없는 별칭은 거부한다. deterministic 필드는 schema에서 +`string` 타입이다. `MongoCsfleMode`: -| Mode | Queryable | Trade-off | +| 모드 | 조회 가능 | 득실 | |---|---|---| -| `RANDOMIZED` | no | Same plaintext encrypts differently each time. The safe default. | -| `DETERMINISTIC` | equality only | Same plaintext always yields the same ciphertext, so equality works — and so does frequency analysis. | -| `UNINDEXED` | no | Stored encrypted, excluded from any index. | +| `RANDOMIZED` | 아니다 | 같은 평문도 매번 다르게 암호화된다. 안전한 기본값이다. | +| `DETERMINISTIC` | 같음 비교만 | 같은 평문은 늘 같은 암호문이 된다. 그래서 같음 비교가 된다. 빈도 분석도 같이 된다. | +| `UNINDEXED` | 아니다 | 암호화해 저장하고 어떤 index에도 넣지 않는다. | -`MongoCsfleFieldPolicy.forPii(field, queryable)` defaults to `RANDOMIZED` when the field is not -queried. Deterministic encryption requires a written `equalityQueryJustification`; the constructor -refuses a blank one, naming frequency analysis. A low-cardinality deterministic field (a status, a -country, a boolean) leaks its distribution to anyone who can read the collection, which is the party -encryption was protecting against. +`MongoCsfleFieldPolicy.forPii(field, queryable)`는 조회하지 않는 필드면 `RANDOMIZED`를 고른다. +deterministic 암호화에는 글로 쓴 `equalityQueryJustification`이 필요하다. 생성자는 빈 값을 거부하고 +빈도 분석을 이유로 든다. 값의 가짓수가 적은 deterministic 필드(상태, 국가, boolean)는 collection을 읽을 +수 있는 누구에게나 분포를 드러낸다. 그 누구가 바로 암호화가 막으려던 상대다. ## 2. Queryable Encryption -`MongoQueryableEncryptionProfile` binds a collection to `MongoEncryptedFieldDescriptor` entries. -`MongoQueryableEncryptionQueryType` has exactly two values: +`MongoQueryableEncryptionProfile`은 collection 하나를 `MongoEncryptedFieldDescriptor` 항목들에 묶는다. +`MongoQueryableEncryptionQueryType`의 값은 둘뿐이다. - `EQUALITY` -- `RANGE` — must declare its domain (`min`, `max`). The constructor refuses a range field without one, - because changing the domain later means re-encrypting the field. +- `RANGE` — 값의 범위(`min`, `max`)를 선언해야 한다. 생성자는 범위가 없는 range 필드를 거부한다. + 범위를 나중에 바꾸면 그 필드를 다시 암호화해야 하기 때문이다. -`MongoQueryableEncryptionCollectionManager` owns the collection's lifecycle, because a QE collection -is not just a collection: it carries metadata collections. +`MongoQueryableEncryptionCollectionManager`가 collection의 생성부터 삭제까지를 맡는다. QE collection은 +collection 하나로 끝나지 않고 metadata collection을 같이 달고 다니기 때문이다. -## 3. Metadata ownership +## 3. Metadata 소유 -`MongoEncryptionMetadataOwnership` maps `customers` to `enxcol_.customers.esc` and -`enxcol_.customers.ecoc`, and reports `__safeContent__`-prefixed indexes as -`MongoMetadataOwnership.ENCRYPTION_MANAGED`. +`MongoEncryptionMetadataOwnership`은 `customers`를 `enxcol_.customers.esc`와 +`enxcol_.customers.ecoc`에 대응시킨다. 그리고 `__safeContent__`로 시작하는 index를 +`MongoMetadataOwnership.ENCRYPTION_MANAGED`로 보고한다. -These are never application-owned and never droppable by drift reconciliation. A drift tool that -drops `enxcol_.customers.ecoc` corrupts the collection's queryability. This is the single most -important integration point between encryption and -[ADR-MONGO-004](../../adr/ADR-MONGO-004-index-schema-admin-plane.md). +이것들은 애플리케이션 소유가 아니다. drift 정리(선언과 실제의 차이를 맞추는 작업)가 지울 수도 없다. +drift 도구가 `enxcol_.customers.ecoc`를 지우면 그 collection은 조회 능력을 잃는다. 암호화와 +[ADR-MONGO-004](../../adr/ADR-MONGO-004-index-schema-admin-plane.md)가 만나는 곳 중 가장 중요한 지점이다. -## 4. Unsupported combinations +## 4. 지원하지 않는 조합 -Refused at declaration, not discovered at runtime: +실행 중에 발견하지 않고 선언할 때 거부한다. -| Combination | Why | +| 조합 | 이유 | |---|---| -| CSFLE **and** QE on the same collection | Two incompatible encryption schemes over one namespace. Both profile constructors refuse it. | -| CSFLE on a time series collection | `requireNotTimeSeries(true)` raises `MongoOperationRejectedException`. | -| QE `prefix` / `suffix` / `substring` | Not available on the platform's 8.0 baseline. The factory methods throw `UnsupportedOperationException` rather than returning a profile that fails later. | -| Deterministic CSFLE without a justification | `IllegalArgumentException` naming frequency analysis. | -| Range QE without a declared domain | `IllegalArgumentException` naming re-encryption. | +| 같은 collection에 CSFLE **와** QE | namespace 하나에 서로 맞지 않는 암호화 방식 둘이다. 두 profile 생성자가 모두 거부한다. | +| time series collection에 CSFLE | `requireNotTimeSeries(true)`가 `MongoOperationRejectedException`을 던진다. | +| QE `prefix` / `suffix` / `substring` | 플랫폼의 8.0 기준에서 쓸 수 없다. factory 메서드가 나중에 실패할 profile을 돌려주지 않고 바로 `UnsupportedOperationException`을 던진다. | +| 근거 없는 deterministic CSFLE | 빈도 분석을 이유로 든 `IllegalArgumentException`. | +| 범위를 선언하지 않은 range QE | 재암호화를 이유로 든 `IllegalArgumentException`. | -## 5. Failure recovery +## 5. 실패 복구 -| Symptom | Cause | Action | +| 증상 | 원인 | 조치 | |---|---|---| -| `MongoEncryptionException` on read | Wrong data key, or the key vault is unreachable | Check KMS reachability and the key vault credential. Data is intact; the client cannot decrypt it. | -| `MongoEncryptionException` on write | KMS permission revoked mid-operation | Restore the grant. Writes fail closed — nothing was written in plaintext. | -| Queries return nothing on a deterministic field | The field was re-keyed | Equality matching is over ciphertext; a new key produces different ciphertext. Re-encrypt the field. | -| QE queries fail after a drift reconciliation | A metadata collection was dropped | Restore from backup. This is why ownership gates drops. | +| 읽을 때 `MongoEncryptionException` | data key가 틀렸거나 key vault에 닿지 못한다 | KMS 연결과 key vault credential을 확인한다. 데이터는 그대로다. client가 복호화하지 못할 뿐이다. | +| 쓸 때 `MongoEncryptionException` | 작업 도중 KMS 권한이 회수됐다 | 권한을 되돌린다. 쓰기는 닫힌 쪽으로 실패한다. 평문으로 쓴 것은 없다. | +| deterministic 필드 조회가 아무것도 돌려주지 않는다 | 필드의 key를 바꿨다 | 같음 비교는 암호문끼리 한다. 새 key는 다른 암호문을 만든다. 필드를 다시 암호화한다. | +| drift 정리 뒤 QE 조회가 실패한다 | metadata collection이 지워졌다 | 백업에서 복구한다. 그래서 삭제를 소유 여부로 막는다. | -**Key rotation.** Rotating the customer master key re-wraps the data keys and does not require -re-encrypting documents. Rotating a *data* key does require re-encrypting every document that used -it. These are different operations with different costs, and confusing them is how a rotation becomes -an outage. +**key 교체.** customer master key를 바꾸면 data key를 다시 감쌀 뿐이고 문서를 다시 암호화하지 않는다. +*data* key를 바꾸면 그 key를 쓴 문서를 모두 다시 암호화해야 한다. 둘은 비용이 다른 별개의 작업이다. +둘을 헷갈리면 key 교체가 장애가 된다. -## 6. Promotion evidence +## 6. 승격 증거 -Per [ADR-MONGO-ADV-001](../../adr/ADR-MONGO-ADV-001-capability-promotion.md), promotion requires the -real KMS and key vault, plus negative cases that fail closed: wrong key, missing permission, rotation -mid-operation. A local key provider certifies -none of these — it never rejects anything. +[ADR-MONGO-ADV-001](../../adr/ADR-MONGO-ADV-001-capability-promotion.md)에 따라 승격하려면 실제 KMS와 +key vault가 필요하다. 닫힌 쪽으로 실패하는 부정 사례도 필요하다: 틀린 key, 빠진 권한, 작업 도중 key 교체. +로컬 key provider는 이 중 아무것도 인증하지 못한다. 아무것도 거부하지 않기 때문이다. diff --git a/docs/mongodb/advanced/multi-tenancy.md b/docs/mongodb/advanced/multi-tenancy.md index 722cd872..f05e7ff5 100644 --- a/docs/mongodb/advanced/multi-tenancy.md +++ b/docs/mongodb/advanced/multi-tenancy.md @@ -1,93 +1,89 @@ # Advanced — Multi-tenancy -**Capabilities:** `MongoCapability.SHARED_COLLECTION_TENANCY` (Advanced), -`MongoCapability.DATABASE_PER_TENANT` (Experimental) -**Enablement:** library API, no configuration property. The service's own adapter constructs the -entry point with a `MongoAdvancedCapabilityGuard` built from `MongoAdvancedCapabilityFlags` that -enables the capability; construction is refused otherwise. -Shared-collection tenancy has no entry point (its types are policies), so only -`DATABASE_PER_TENANT` is ever checked. +**Capability:** `MongoCapability.SHARED_COLLECTION_TENANCY`(Advanced), +`MongoCapability.DATABASE_PER_TENANT`(Experimental) +**켜는 법:** 라이브러리 API다. 설정 속성은 없다. 서비스의 어댑터가 진입점을 만들 때 +`MongoAdvancedCapabilityGuard`를 넘긴다. 이 guard는 그 capability를 켠 `MongoAdvancedCapabilityFlags`로 +만든다. 켜지 않았으면 생성 자체가 거부된다. +shared collection tenancy에는 진입점이 없다(타입이 모두 정책이다). 그래서 실제로 검사하는 것은 +`DATABASE_PER_TENANT`뿐이다. ## 1. Shared collection -Every tenant's documents live in one collection, discriminated by a tenant field. +모든 tenant의 문서가 collection 하나에 있고, tenant 필드로 구분한다. -`MongoTenantContext` carries the tenant. `MongoTenantPredicateInjector` adds the tenant predicate to -every query, every atomic filter and the **first** aggregation stage. The adopter's repository calls -the injector on every tenant-scoped path; there is no tenant-scoped operations facade in this leaf. +`MongoTenantContext`가 tenant를 들고 다닌다. `MongoTenantPredicateInjector`가 tenant 조건을 세 곳에 +넣는다: 모든 query, 모든 atomic filter, aggregation의 **첫** stage. 도입하는 쪽의 repository가 tenant +범위의 모든 경로에서 이 injector를 부른다. 이 leaf에는 tenant 범위 작업을 대신해 주는 facade가 없다. -Three details are load-bearing: +빠지면 안 되는 세부가 셋이다. -- **Injection, not convention.** A tenant predicate that each query is expected to add itself is a - cross-tenant leak waiting for one missed `where(...)`. The injector adds it structurally. -- **First aggregation stage.** `firstStageMatch(...)` places the tenant `$match` before anything else. - A `$lookup` or `$group` that runs before the tenant filter has already crossed the boundary, even if - a later stage filters the output. -- **An absent tenant is not "all tenants".** The injector takes an `Optional` so - the missing case is a decision the policy makes explicitly, not a predicate that quietly disappears. +- **관례가 아니라 주입이다.** query마다 tenant 조건을 스스로 넣기를 기대하면 `where(...)` 하나만 빠져도 + tenant 사이로 데이터가 샌다. injector는 조건을 구조적으로 넣는다. +- **aggregation 첫 stage.** `firstStageMatch(...)`는 tenant `$match`를 맨 앞에 둔다. tenant filter보다 + 먼저 도는 `$lookup`이나 `$group`은 뒤 stage가 결과를 걸러도 이미 경계를 넘은 것이다. +- **tenant가 없으면 「모든 tenant」가 아니다.** injector는 `Optional`를 받는다. + tenant가 빠진 경우를 정책이 명시적으로 정하게 하려는 것이다. 조건이 조용히 사라지면 안 된다. -`MongoTenantManifestValidator.validate(manifest, tenantScopedUniqueIndexes)` checks that every unique -index that should be per-tenant actually includes the tenant field. A unique index on `email` alone in -a shared collection makes an email globally unique across tenants — tenant B cannot register an -address tenant A already used, which is both a bug and an information leak. +`MongoTenantManifestValidator.validate(manifest, tenantScopedUniqueIndexes)`는 tenant별이어야 하는 unique +index가 정말 tenant 필드를 포함하는지 본다. shared collection에서 `email` 하나만으로 만든 unique index는 +email을 모든 tenant에 걸쳐 유일하게 만든다. 그러면 tenant A가 쓴 주소를 tenant B가 등록할 수 없다. +결함이면서 정보 유출이다. -`requireShardKeyAnalysed(...)` requires a shard-key readiness report before a shared-collection tenant -model is sharded: tenant id as a shard key prefix concentrates the largest tenant on one shard. +`requireShardKeyAnalysed(...)`는 shared collection tenant 모델을 shard하기 전에 shard key 준비 보고서를 +요구한다. tenant id를 shard key 앞부분으로 쓰면 가장 큰 tenant가 shard 하나에 몰린다. -### Observability +### 관측 -`tenantId` and `rawTenantId` are on `MongoObservationConvention`'s forbidden tag list. Cardinality -grows with the customer list, and the tag ships tenant identity into the metrics backend. +`tenantId`와 `rawTenantId`는 `MongoObservationConvention`의 금지 tag 목록에 있다. 값의 가짓수가 고객 +수만큼 늘고, tag가 tenant 식별자를 metric 저장소로 보낸다. -## 2. Database per tenant (Experimental) +## 2. tenant마다 database (Experimental) -`MongoTenantClientRegistry` holds one client per tenant under a cap with idle eviction; mapping a -tenant to its database is the adopter's code. +`MongoTenantClientRegistry`는 tenant마다 client를 하나 둔다. 개수 상한이 있고 쓰지 않는 client는 +내보낸다. tenant를 어느 database에 대응시킬지는 도입하는 쪽의 코드가 정한다. -Experimental for a specific reason: it is correct in the small and unbounded in the large. Each tenant -database costs connections, file handles and monitoring cardinality. It works beautifully at 20 -tenants and falls over at 2,000, and nothing in a functional test distinguishes the two. Promotion -requires operational scale evidence. +Experimental인 이유가 분명하다. 작을 때는 맞고, 클 때는 한계가 없다. tenant database마다 connection, +file handle, 모니터링 가짓수가 든다. tenant 20개에서는 잘 돌고 2,000개에서는 쓰러진다. 기능 테스트로는 +둘을 구분할 수 없다. 승격하려면 운영 규모의 증거가 필요하다. `MongoTenantLifecyclePolicy`: -- `requireActivationReady(tenantKey, schemaAndIndexesValidated)` — a tenant is not activated until its - schema and indexes are validated. Activating first means the first customer request is the migration - test. -- `requireDeleteAllowed(...)` — deletion requires an explicit retention decision. Dropping a tenant - database is irreversible and takes the backup surface with it. +- `requireActivationReady(tenantKey, schemaAndIndexesValidated)` — schema와 index를 검증하기 전에는 + tenant를 켜지 않는다. 먼저 켜면 첫 고객 요청이 마이그레이션 시험이 된다. +- `requireDeleteAllowed(...)` — 삭제에는 보존 기간에 대한 명시적 결정이 필요하다. tenant database를 지우면 + 되돌릴 수 없고 백업 대상도 함께 사라진다. -`MongoTenantMigrationCoordinator` runs a migration across tenant databases with per-tenant results. -Partial failure is normal and must be reported per tenant: "migration failed" across 500 databases is -not a report anyone can act on. +`MongoTenantMigrationCoordinator`는 tenant database 전체에 마이그레이션을 돌리고 결과를 tenant별로 낸다. +일부 실패는 정상이고 tenant별로 보고해야 한다. database 500개에 대해 「마이그레이션 실패」 한 줄은 아무도 +대응할 수 없는 보고다. -## 3. Choosing +## 3. 고르기 -| | Shared collection | Database per tenant | +| | Shared collection | tenant마다 database | |---|---|---| -| Isolation | Logical, enforced by injection | Physical | -| Tenant count | Unbounded | Bounded by connections and file handles | -| Per-tenant restore | Hard | Natural | -| Noisy neighbour | Shared resources | Isolated | -| Migration | One collection | N databases, partial failures | -| Cross-tenant query | Possible (and must be forbidden) | Structurally impossible | +| 격리 | 논리적, 주입으로 강제 | 물리적 | +| tenant 수 | 제한 없음 | connection과 file handle이 제한 | +| tenant별 복구 | 어렵다 | 자연스럽다 | +| 시끄러운 이웃 | 자원을 나눠 쓴다 | 격리된다 | +| 마이그레이션 | collection 하나 | database N개, 일부 실패가 생긴다 | +| tenant를 넘는 query | 가능하다(그래서 막아야 한다) | 구조상 불가능하다 | -Shared collection is the default. Database-per-tenant is for a small number of tenants with a -contractual isolation or per-tenant-restore requirement. +기본은 shared collection이다. tenant마다 database는 tenant 수가 적고, 계약상 격리나 tenant별 복구가 +필요한 경우에 쓴다. -## 4. Failure recovery +## 4. 실패 복구 -| Symptom | Cause | Action | +| 증상 | 원인 | 조치 | |---|---|---| -| Cross-tenant data visible | An operation skipped `MongoTenantPredicateInjector` | Treat as a security incident. Find the path, close it, audit access. | -| Unique constraint fires across tenants | Unique index missing the tenant field | Rebuild the index with the tenant field as prefix; the validator catches this before it ships. | -| One shard holds most data | Tenant id as shard-key prefix with a dominant tenant | Refine the shard key with a high-cardinality suffix. | -| Connection exhaustion | Database-per-tenant beyond the connection budget | The scale limit. Consolidate or move to shared collections. | -| Migration partially applied across tenants | Normal | `MongoTenantMigrationCoordinator` reports per tenant; re-run for the failures only. | +| 다른 tenant의 데이터가 보인다 | 어떤 작업이 `MongoTenantPredicateInjector`를 건너뛰었다 | 보안 사고로 다룬다. 그 경로를 찾아 막고 접근 기록을 감사한다. | +| tenant를 넘어 unique 제약이 걸린다 | unique index에 tenant 필드가 없다 | tenant 필드를 앞에 둔 index로 다시 만든다. validator가 배포 전에 잡는다. | +| shard 하나에 데이터 대부분이 있다 | tenant id가 shard key 앞부분이고 큰 tenant가 하나 있다 | 가짓수가 많은 뒷부분을 더해 shard key를 다듬는다. | +| connection이 바닥난다 | tenant마다 database가 connection 예산을 넘었다 | 규모 한계다. 합치거나 shared collection으로 옮긴다. | +| 마이그레이션이 tenant 일부에만 적용됐다 | 정상이다 | `MongoTenantMigrationCoordinator`가 tenant별로 보고한다. 실패한 것만 다시 돌린다. | -## 5. Promotion evidence +## 5. 승격 증거 -Shared-collection tenancy: actual-topology evidence, a security review covering cross-tenant access, -a migration path, failure cases (injection proven on query, atomic filter and first aggregation -stage), this runbook. Database-per-tenant additionally requires **operational scale evidence** and -stays Experimental until it exists. +shared collection tenancy: 실제 토폴로지 증거, tenant를 넘는 접근을 다룬 보안 검토, 마이그레이션 경로, +실패 사례(query·atomic filter·aggregation 첫 stage에서 주입이 되는지 증명), 이 runbook. +tenant마다 database는 여기에 **운영 규모 증거**가 더 필요하고, 그것이 생길 때까지 Experimental이다. diff --git a/docs/mongodb/advanced/sharding.md b/docs/mongodb/advanced/sharding.md index 2f308936..fb7ab2a1 100644 --- a/docs/mongodb/advanced/sharding.md +++ b/docs/mongodb/advanced/sharding.md @@ -1,84 +1,80 @@ # Advanced — Sharding **Capability:** `MongoCapability.SHARDING` -**Enablement:** library API, no configuration property. The service's own adapter constructs the -entry point with a `MongoAdvancedCapabilityGuard` built from `MongoAdvancedCapabilityFlags` that -enables the capability; construction is refused otherwise. -**Status:** Advanced. Reshard orchestration remains Experimental. +**켜는 법:** 라이브러리 API다. 설정 속성은 없다. 서비스의 어댑터가 진입점을 만들 때 +`MongoAdvancedCapabilityGuard`를 넘긴다. 이 guard는 그 capability를 켠 `MongoAdvancedCapabilityFlags`로 +만든다. 켜지 않았으면 생성 자체가 거부된다. +**상태:** Advanced. reshard 진행 관리는 Experimental로 남는다. -## Requirements +## 요구 사항 | | | |---|---| -| Topology | A real sharded cluster. A replica set cannot exercise routing. | -| Server | MongoDB 7.0 or 8.0. | -| Privilege | `MongoPrincipalRole.SHARD_ADMIN` for the admin plane; the application role is unchanged. | -| Gate | **Not promoted.** No `mongoShardedTest` lane is registered, and a sharded cluster is not an environment this repository stands up. Listed under `experimental_contracts` in `src/adapter/outbound/persistence-mongo/release/release-contracts.json`; promoting it needs the lane, its required class, and protected-environment evidence to exist first. | +| 토폴로지 | 실제 sharded cluster. replica set으로는 라우팅을 시험할 수 없다. | +| 서버 | MongoDB 7.0 또는 8.0. | +| 권한 | admin plane에는 `MongoPrincipalRole.SHARD_ADMIN`. 애플리케이션 role은 바뀌지 않는다. | +| 게이트 | **승격하지 않았다.** 등록된 `mongoShardedTest` lane이 없고, sharded cluster는 이 repo가 띄우는 환경이 아니다. `src/adapter/outbound/persistence-mongo/release/release-contracts.json`의 `experimental_contracts`에 있다. 승격하려면 lane, 그 lane이 요구하는 클래스, 보호된 환경의 증거가 먼저 있어야 한다. | ## Shard key -`ShardKeyDescriptor` declares the key as an ordered list of `ShardKeyPart` plus a `ShardStrategy`: +`ShardKeyDescriptor`는 key를 `ShardKeyPart`의 순서 있는 목록과 `ShardStrategy`로 선언한다. -| Strategy | Distributes | Cost | +| 전략 | 나누는 기준 | 비용 | |---|---|---| -| `RANGE` | by value ranges | Range queries stay targeted; a monotonic key (a timestamp, an `ObjectId`) sends every insert to one shard. | -| `HASHED` | by hash of the key | Inserts spread evenly; every range query becomes scatter-gather. | +| `RANGE` | 값의 범위 | 범위 조회가 특정 shard로 간다. 계속 커지는 key(timestamp, `ObjectId`)는 모든 insert를 shard 하나로 보낸다. | +| `HASHED` | key의 hash | insert가 고르게 퍼진다. 모든 범위 조회가 scatter-gather가 된다. | -There is no strategy that is good at both, which is why the choice is a declaration rather than a -default. +둘 다 잘하는 전략은 없다. 그래서 기본값으로 두지 않고 선언하게 한다. -## Routing classification +## 라우팅 분류 -`ShardAwareQueryValidator` classifies each query before execution: +`ShardAwareQueryValidator`는 실행 전에 query마다 분류한다. -| `MongoRoutingClassification` | Meaning | +| `MongoRoutingClassification` | 뜻 | |---|---| -| `TARGETED` | The full shard key is present. One shard answers. | -| `PREFIX_TARGETED` | A prefix of a compound key is present. A subset of shards answers. | -| `SCATTER_GATHER` | No shard-key predicate. Every shard answers. | -| `REJECTED` | Scatter-gather where the profile forbids it. | +| `TARGETED` | shard key 전체가 있다. shard 하나가 답한다. | +| `PREFIX_TARGETED` | 복합 key의 앞부분이 있다. shard 일부가 답한다. | +| `SCATTER_GATHER` | shard key 조건이 없다. 모든 shard가 답한다. | +| `REJECTED` | profile이 금지한 곳의 scatter-gather. | -A scatter-gather query is not an error — some queries legitimately need every shard — but it must be -declared. Undeclared scatter-gather raises `MongoShardRoutingException`. The reason is that -scatter-gather passes every test on a single-shard development cluster and only degrades once the -cluster grows, at which point the query is already in production and the fix is a schema change. +scatter-gather는 오류가 아니다. 모든 shard가 필요한 query도 있다. 다만 선언해야 한다. 선언하지 않은 +scatter-gather는 `MongoShardRoutingException`을 던진다. 이유는 이렇다. scatter-gather는 shard 하나짜리 +개발 cluster에서는 모든 테스트를 통과하고 cluster가 커진 뒤에야 느려진다. 그때는 query가 이미 운영에 +있고, 고치려면 schema를 바꿔야 한다. -## Unsupported combinations +## 지원하지 않는 조합 -- Unique index on a field that is not a prefix of the shard key. MongoDB cannot enforce it across - shards, and it fails at index creation, not at query time. -- Transactions that touch documents on multiple shards remain supported but cost a cross-shard - two-phase commit. Prefer a shard key that keeps a transaction's documents co-located. -- CSFLE on a sharded collection: see [encryption.md](encryption.md) for the combinations that are - refused. +- shard key의 앞부분이 아닌 필드의 unique index. MongoDB가 shard를 넘어 강제할 수 없다. 조회 때가 + 아니라 index를 만들 때 실패한다. +- 여러 shard의 문서를 건드리는 transaction은 지원하지만 shard를 넘는 two-phase commit 비용이 든다. + transaction의 문서를 한곳에 모으는 shard key를 고른다. +- sharded collection의 CSFLE: 거부하는 조합은 [encryption.md](encryption.md)를 본다. ## Admin plane -`MongoShardingAdminGateway` (D4, `SHARD_ADMIN` credential) covers shard-collection, refine-shard-key -and reshard. +`MongoShardingAdminGateway`(D4, `SHARD_ADMIN` credential)가 shard-collection, refine-shard-key, +reshard를 맡는다. -`ShardKeyAnalyzer` produces a `ShardKeyReadinessReport` before sharding a collection: cardinality, -frequency skew and monotonicity. A key with low cardinality creates jumbo chunks that cannot be split; -a monotonic key creates a hot shard. Both are visible in the report and invisible in a functional -test. +`ShardKeyAnalyzer`는 collection을 shard하기 전에 `ShardKeyReadinessReport`를 만든다: 값의 가짓수, +빈도 치우침, 단조 증가 여부. 가짓수가 적은 key는 나눌 수 없는 jumbo chunk를 만든다. 단조 증가하는 +key는 한 shard에 부하를 몰아준다. 둘 다 보고서에는 보이고 기능 테스트에는 보이지 않는다. -`ReshardApproval` is required for a reshard — a named approver and a stated window. Resharding -rewrites the collection: it duplicates the data during the operation and saturates IO. It is not a -runtime operation and the type refuses to pretend otherwise. +reshard에는 `ReshardApproval`이 필요하다: 승인한 사람 이름과 작업 시간대. reshard는 collection을 다시 +쓴다. 작업 중에 데이터를 복제하고 IO를 가득 채운다. 실행 중에 하는 작업이 아니고, 타입도 그런 척하지 +않는다. -## Failure recovery +## 실패 복구 -| Symptom | Cause | Action | +| 증상 | 원인 | 조치 | |---|---|---| -| `MongoShardRoutingException` | Undeclared scatter-gather | Add the shard key to the predicate, or declare the query as scatter-gather in its profile after review. | -| Jumbo chunks | Low-cardinality shard key | Refine the shard key (adds a suffix, non-destructive) before considering a reshard. | -| One hot shard | Monotonic range key | Refine with a high-cardinality prefix, or reshard to hashed if range queries are not needed. | -| Balancer never converges | Chunk migration blocked by long-running operations | Check for long transactions and cursors; the balancer waits on them. | +| `MongoShardRoutingException` | 선언하지 않은 scatter-gather | 조건에 shard key를 넣는다. 아니면 검토를 거쳐 그 query를 profile에서 scatter-gather로 선언한다. | +| Jumbo chunk | 가짓수가 적은 shard key | reshard를 생각하기 전에 shard key를 다듬는다(뒷부분을 더한다. 데이터를 지우지 않는다). | +| 한 shard에 부하가 몰린다 | 단조 증가하는 range key | 가짓수가 많은 앞부분으로 다듬거나, 범위 조회가 필요 없으면 hashed로 reshard한다. | +| balancer가 끝나지 않는다 | 오래 도는 작업이 chunk 이동을 막는다 | 긴 transaction과 cursor를 찾는다. balancer는 그것들을 기다린다. | -## Promotion evidence +## 승격 증거 -Per [ADR-MONGO-ADV-001](../../adr/ADR-MONGO-ADV-001-capability-promotion.md): actual sharded-cluster -evidence, security review of the `SHARD_ADMIN` role, a migration path for an existing unsharded -collection, failure cases (undeclared scatter-gather refused, jumbo chunk detected), and this -document as the runbook. Reshard orchestration stays Experimental until operational scale evidence -exists. +[ADR-MONGO-ADV-001](../../adr/ADR-MONGO-ADV-001-capability-promotion.md)에 따라: 실제 sharded cluster +증거, `SHARD_ADMIN` role의 보안 검토, 이미 있는 unsharded collection의 마이그레이션 경로, 실패 사례(선언하지 +않은 scatter-gather 거부, jumbo chunk 감지), 그리고 runbook으로서 이 문서. reshard 진행 관리는 운영 +규모 증거가 생길 때까지 Experimental이다. diff --git a/docs/mongodb/advanced/signoff/README.md b/docs/mongodb/advanced/signoff/README.md index e7c85c66..61ffde7c 100644 --- a/docs/mongodb/advanced/signoff/README.md +++ b/docs/mongodb/advanced/signoff/README.md @@ -1,18 +1,16 @@ -# Advanced capability sign-off +# Advanced capability 검토 기록(sign-off) -> **2026-08-15:** `scripts/verify-mongodb-advanced.sh` was removed, so nothing reads this directory -> automatically any more. The files below are still the record that a review happened, but a missing -> one no longer fails anything — a human has to check for it during promotion. +`scripts/verify-mongodb-advanced.sh`는 이 디렉터리의 파일을 검토가 있었다는 증거로 본다. -`scripts/verify-mongodb-advanced.sh` treated a file in this directory as the evidence that a review -happened: +- `security.md` — capability별 권한 검토. 부여한 role과 부여한 사람을 적는다. +- `migration.md` — capability별 마이그레이션 경로. 이미 있는 배포가 무엇을 해야 하는지 적는다. -- `security.md` — per-capability privilege review, naming the roles granted and by whom. -- `migration.md` — per-capability migration path, naming what an existing deployment has to do. +둘 중 하나가 없으면 스크립트는 그 항목을 빠진 증거로 적고 `ADVANCED GATE: NOT PROMOTABLE`로 끝난다 +(종료 코드 2). 실패(종료 코드 1)로 보지는 않는다. -These were previously appended to the gate's missing-evidence list unconditionally, so the gate had -no passing state at all. A gate that can never pass is one nobody can act on, and the thing it was -waiting for — a human review — has an artefact. This is that artefact. +예전에는 이 둘을 조건 없이 빠진 증거 목록에 넣었다. 그래서 게이트가 통과할 수 있는 상태가 아예 없었다. +절대 통과할 수 없는 게이트는 아무도 대응할 수 없다. 게이트가 기다리던 것, 곧 사람의 검토에는 남는 +결과물이 있다. 이 디렉터리의 파일이 그 결과물이다. -A file here asserts the review was done. Adding one without doing it is the failure mode; that is a -review-process problem, and no script can tell the difference. +여기 있는 파일은 검토를 했다고 주장한다. 검토 없이 파일만 더하는 것이 이 방식의 실패 모드다. 그것은 +검토 절차의 문제이고, 어떤 스크립트도 차이를 알 수 없다. diff --git a/docs/mongodb/bson-mapping-guide.md b/docs/mongodb/bson-mapping-guide.md index ffccb583..361b9e47 100644 --- a/docs/mongodb/bson-mapping-guide.md +++ b/docs/mongodb/bson-mapping-guide.md @@ -1,75 +1,72 @@ -# BSON Mapping Guide +# BSON 매핑 가이드 -Design §10 and decision D-06. The representation of a value in BSON is a data contract, not an -implementation detail: once a collection holds a million documents, changing how a `BigDecimal` is -stored is a migration with downtime, not a code change. `MongoTypeRepresentationManifest` pins the -representation so a library upgrade or a different default cannot move it. +설계서 §10과 결정 D-06. 값이 BSON에서 어떤 모양으로 저장되는지는 구현 세부가 아니라 데이터 계약이다. +collection에 문서가 백만 개 쌓인 뒤 `BigDecimal` 저장 방식을 바꾸면 코드 수정이 아니라 중단 시간이 드는 +마이그레이션이다. `MongoTypeRepresentationManifest`가 표현을 고정해서 라이브러리 업그레이드나 다른 +기본값이 그것을 바꾸지 못하게 한다. -## 1. The manifest +## 1. Manifest -`MongoTypeRepresentationManifest.standard()` fixes: +`MongoTypeRepresentationManifest.standard()`가 정하는 것: -| Java type | BSON | Representation type | +| Java 타입 | BSON | 표현 타입 | |---|---|---| | `UUID` | `Binary` subtype 4 | `MongoUuidRepresentation.STANDARD` | | `BigDecimal` | `Decimal128` | `MongoDecimalRepresentation.DECIMAL_128` | -| `BigInteger` | `Decimal128` (or `String` when out of range, declared) | `MongoBigIntegerRepresentation` | +| `BigInteger` | `Decimal128`(범위를 넘으면 선언한 경우 `String`) | `MongoBigIntegerRepresentation` | | `Instant` / `OffsetDateTime` / `ZonedDateTime` | UTC `Date` | `MongoTemporalRepresentation.UTC_DATE` | -| `LocalDate` | `String` (ISO-8601) or UTC `Date`, declared per field | `MongoTemporalRepresentation` | -| `enum` | `String` name | `MongoEnumRepresentation.NAME` | +| `LocalDate` | `String`(ISO-8601) 또는 UTC `Date`, 필드마다 선언 | `MongoTemporalRepresentation` | +| `enum` | `String` 이름 | `MongoEnumRepresentation.NAME` | -`MongoMappingConfiguration` and `MongoCustomConversionsFactory` build the Spring Data converters from -the manifest, so there is one place to read and one place to change. +`MongoMappingConfiguration`과 `MongoCustomConversionsFactory`가 이 manifest로 Spring Data converter를 +만든다. 그래서 읽을 곳도 한 곳, 바꿀 곳도 한 곳이다. ## 2. UUID -`UuidRepresentation.STANDARD` (subtype 4), always. The driver's legacy Java representation -(subtype 3) byte-swaps two halves of the UUID, so a document written by one representation and read -by the other yields a different — and valid-looking — UUID. Nothing errors; you just get the wrong -row. The golden snapshot kit pins the codec explicitly for this reason -(`MongoBsonSnapshot.defaultRegistry()`). +늘 `UuidRepresentation.STANDARD`(subtype 4)다. driver의 옛 Java 표현(subtype 3)은 UUID의 두 절반의 +바이트 순서를 뒤집는다. 그래서 한 표현으로 쓴 문서를 다른 표현으로 읽으면 다르면서도 멀쩡해 보이는 +UUID가 나온다. 오류는 나지 않고 엉뚱한 행을 얻는다. 같은 이유로 golden snapshot kit은 codec을 +명시적으로 고정한다(`MongoBsonSnapshot.defaultRegistry()`). ## 3. Decimal -`BigDecimal` → `Decimal128`, never `Double`. `12.30` stored as a double is `12.299999999999999`, and -a monetary comparison written against it will one day be wrong by a cent for a customer who notices. -`BigDecimalToDecimal128Converter` / `Decimal128ToBigDecimalConverter` are registered from the -manifest. +`BigDecimal` → `Decimal128`이다. `Double`은 쓰지 않는다. `12.30`을 double로 저장하면 +`12.299999999999999`가 된다. 그 값으로 쓴 금액 비교는 언젠가 1원 틀리고, 그것을 알아채는 고객이 있다. +`BigDecimalToDecimal128Converter` / `Decimal128ToBigDecimalConverter`는 manifest에서 등록한다. -`Decimal128` has 34 significant digits; a `BigDecimal` beyond that range fails on write rather than -rounding silently. +`Decimal128`의 유효 숫자는 34자리다. 그 범위를 넘는 `BigDecimal`은 조용히 반올림하지 않고 쓸 때 실패한다. -## 4. Time +## 4. 시간 -Store instants, not local times. `LocalDateTimeMappingGuard` refuses `LocalDateTime` fields on a -mapped document: a `LocalDateTime` has no offset, so the value that goes in depends on the JVM -default zone of whichever instance wrote it, and the two instances in a rolling deploy can disagree. -Use `Instant` when the moment matters and `LocalDate` when the calendar day matters. +지역 시각이 아니라 순간(instant)을 저장한다. `LocalDateTimeMappingGuard`는 매핑된 문서의 +`LocalDateTime` 필드를 거부한다. `LocalDateTime`에는 offset이 없다. 그래서 저장되는 값이 그 값을 쓴 +인스턴스의 JVM 기본 시간대에 따라 달라지고, rolling 배포 중인 두 인스턴스의 값이 어긋날 수 있다. +순간이 중요하면 `Instant`를, 달력의 날짜가 중요하면 `LocalDate`를 쓴다. -## 5. Type metadata +## 5. 타입 metadata -`MongoTypeMetadataPolicy` decides what goes in `_class`: +`MongoTypeMetadataPolicy`가 `_class`에 무엇을 넣을지 정한다. -| Policy | Stored | Use when | +| 정책 | 저장하는 것 | 쓰는 때 | |---|---|---| -| `NONE` | nothing | The collection holds exactly one type and never will hold a subtype. | -| `ALIAS` | a registered short alias | A polymorphic hierarchy in a long-lived collection. | -| `CLASS_NAME` | the FQCN | Short-lived or internal collections only. | +| `NONE` | 없음 | collection에 타입이 정확히 하나이고 앞으로도 하위 타입이 들어오지 않는다. | +| `ALIAS` | 등록한 짧은 별칭 | 오래 사는 collection의 다형 계층. | +| `CLASS_NAME` | FQCN | 짧게 사는 collection이나 내부 collection에만. | -`PolicyAwareMongoTypeMapper` enforces it, and `MongoTypeMetadataRegistry` holds alias → class. -A `@LongLivedMongoDocument` type with `CLASS_NAME` is refused: writing `com.example.OrderV2` into a -million documents means that renaming the package is a data migration. +`PolicyAwareMongoTypeMapper`가 이 정책을 강제하고, `MongoTypeMetadataRegistry`가 별칭 → 클래스를 +가진다. `@LongLivedMongoDocument` 타입에 `CLASS_NAME`을 쓰면 거부한다. 문서 백만 개에 +`com.example.OrderV2`를 써 두면 package 이름을 바꾸는 일이 데이터 마이그레이션이 된다. -## 6. Missing versus null +## 6. 없음과 null -The golden kit keeps these apart deliberately. `MongoBsonSnapshotAssert.hasNoField(...)` and -`hasExplicitNull(...)` are different assertions, because in MongoDB they are different documents: -`{"a": null}` matches `{a: null}` and `{a: {$exists: true}}`, while `{}` matches only the first. -A mapper change that starts writing explicit nulls silently changes what your queries return. +golden kit은 이 둘을 일부러 구분한다. `MongoBsonSnapshotAssert.hasNoField(...)`와 +`hasExplicitNull(...)`은 다른 단언이다. MongoDB에서 둘은 다른 문서이기 때문이다. +`{"a": null}`은 `{a: null}`과 `{a: {$exists: true}}`에 모두 걸리지만 `{}`는 앞의 것에만 걸린다. +mapper가 바뀌어 null을 명시적으로 쓰기 시작하면 query 결과가 조용히 달라진다. -## 7. Golden representation tests +## 7. Golden 표현 테스트 -Every collection with a fixed representation should have a snapshot test: +표현이 고정된 collection에는 snapshot 테스트를 둔다. ```java MongoBsonSnapshot snapshot = MongoBsonSnapshot.of(storedDocument); @@ -80,13 +77,13 @@ MongoBsonSnapshotAssert.assertThat(snapshot) .hasTypeSignature("_id:OBJECT_ID,amount:DECIMAL128,createdAt:DATE_TIME,externalId:BINARY"); ``` -`hasTypeSignature` is the regression gate: it fails on *any* representation change, including ones a -value-equality assertion would pass. When it fails, the question is whether the change was intended -and has a migration — not whether to update the string. +`hasTypeSignature`가 회귀 게이트다. 값이 같은지만 보는 단언이 통과시킬 변화까지 포함해 *어떤* 표현 +변화에도 실패한다. 실패하면 물을 것은 문자열을 고칠지가 아니라, 그 변화가 의도한 것이고 마이그레이션이 +있는지다. -## 8. Round trips +## 8. 왕복 -`MongoRoundTripContract` asserts that `write → read` returns an equal domain object *and* that -`write → read → write` produces an identical BSON document. The second half is what catches an -asymmetric converter: a value that reads back equal but re-serialises differently makes every -subsequent `save()` a spurious update, and turns change streams into a noise generator. +`MongoRoundTripContract`는 두 가지를 단언한다. `write → read`가 같은 도메인 객체를 돌려준다. *그리고* +`write → read → write`가 똑같은 BSON 문서를 만든다. 뒤의 것이 비대칭 converter를 잡는다. 읽으면 같지만 +다시 직렬화하면 달라지는 값은 이후의 모든 `save()`를 쓸데없는 update로 만들고, change stream을 잡음 +발생기로 만든다. diff --git a/docs/mongodb/consistency-transaction-guide.md b/docs/mongodb/consistency-transaction-guide.md index 17771a94..9d590da5 100644 --- a/docs/mongodb/consistency-transaction-guide.md +++ b/docs/mongodb/consistency-transaction-guide.md @@ -1,67 +1,63 @@ -# Consistency and Transaction Guide +# 일관성과 transaction 가이드 -Design §12–§16, decisions D-07 through D-10. This is the part of the platform where the wrong -default is most expensive and the least visible in testing, because every failure mode here needs a -primary change to reproduce. +설계서 §12–§16, 결정 D-07에서 D-10까지. 플랫폼에서 기본값을 잘못 고르면 가장 비싸고, 테스트에서는 가장 +안 보이는 곳이다. 여기의 실패 모드는 모두 primary가 바뀌어야 재현되기 때문이다. -## 1. Prefer a single-document atomic operation +## 1. 문서 하나의 atomic 연산을 먼저 쓴다 -D-09: a transaction is for a **multi-document invariant**, nothing else. A single document is already -atomic in MongoDB, so wrapping a one-document update in a transaction buys nothing and costs a -session, a two-phase commit and a new ambiguous outcome. +D-09: transaction은 **여러 문서에 걸친 불변식**에만 쓴다. MongoDB에서 문서 하나는 이미 atomic이다. +문서 하나를 바꾸는 update를 transaction으로 감싸면 얻는 것은 없고, session 하나, two-phase commit, +결과를 모르는 새 경우 하나가 든다. -D-07: partial change uses update operators, not `save()`. `MongoAtomicOperations` / -`MongoAtomicOperationsTemplate` expose the operator set through `MongoUpdateOperator` -(`$set`, `$inc`, `$push`, `$pull`, `$addToSet`, `$min`, `$max`, `$currentDate`, …) with an -`AtomicFilter` precondition and a `ReturnDocumentMode`. Read-modify-write through `save()` replaces -the whole document and silently discards any field another writer changed in between — a lost update -with no error. +D-07: 일부만 바꿀 때는 `save()`가 아니라 update operator를 쓴다. `MongoAtomicOperations` / +`MongoAtomicOperationsTemplate`은 `MongoUpdateOperator`로 operator(`$set`, `$inc`, `$push`, `$pull`, +`$addToSet`, `$min`, `$max`, `$currentDate`, …)를 내놓고, `AtomicFilter` 선행 조건과 +`ReturnDocumentMode`를 받는다. `save()`로 읽고-고치고-쓰면 문서 전체를 바꾼다. 그 사이에 다른 쓰기가 +바꾼 필드는 조용히 사라진다. 오류 없는 lost update다. -## 2. Whole-document replacement needs a revision +## 2. 문서 전체를 바꾸려면 revision이 필요하다 -D-08. `VersionedMongoUpdater` requires a `MongoRevision`: either a Spring Data `@Version` field or an -explicit expected-revision predicate in `VersionedUpdateCommand`. A replacement whose filter matched -zero documents is not "nothing to do" — `MongoOptimisticConflictTranslator` distinguishes: +D-08. `VersionedMongoUpdater`는 `MongoRevision`을 요구한다. Spring Data `@Version` 필드이거나, +`VersionedUpdateCommand` 안의 명시적인 기대 revision 조건이다. 교체 filter에 걸린 문서가 0개여도 +「할 일 없음」이 아니다. `MongoOptimisticConflictTranslator`가 둘을 구분한다. -- filter matched nothing and the id does not exist → `MongoDocumentNotFoundException` -- filter matched nothing and the id exists → `MongoOptimisticConflictException` +- filter에 걸린 것이 없고 그 id가 없다 → `MongoDocumentNotFoundException` +- filter에 걸린 것이 없고 그 id가 있다 → `MongoOptimisticConflictException` -Collapsing these two into one is how a concurrent overwrite becomes a 404. +이 둘을 하나로 합치면 동시 덮어쓰기가 404가 된다. -## 3. Consistency profiles +## 3. 일관성 profile -`MongoConsistencyProfile` names the read/write concern pair; `MongoConsistencyRegistry` binds a -profile to an operation or collection, and `MongoConsistencyBinder` applies it at execution. +`MongoConsistencyProfile`은 read/write concern 쌍에 이름을 붙인다. `MongoConsistencyRegistry`가 profile을 +연산이나 collection에 묶고, `MongoConsistencyBinder`가 실행할 때 적용한다. -| Profile | Meaning | Use for | +| Profile | 뜻 | 쓰는 곳 | |---|---|---| -| `PRIMARY_LOCAL` | primary read, local concern | Throughput-sensitive reads that tolerate a rollback window. | -| `PRIMARY_MAJORITY` | primary read, majority write | The default for anything a user will see again immediately. | -| `CAUSAL_MAJORITY` | majority inside a causal session | Read-your-writes across separate operations. | -| `STALE_READ_ALLOWED` | secondary reads permitted | Reporting and analytics that state their staleness. | -| `SNAPSHOT_TRANSACTION` | snapshot isolation | Multi-document reads inside a transaction. | +| `PRIMARY_LOCAL` | primary 읽기, local concern | rollback 구간을 견디는, 처리량이 중요한 읽기. | +| `PRIMARY_MAJORITY` | primary 읽기, majority 쓰기 | 사용자가 곧바로 다시 볼 모든 것의 기본값. | +| `CAUSAL_MAJORITY` | causal session 안의 majority | 따로 떨어진 연산 사이에서 자기가 쓴 것을 읽기. | +| `STALE_READ_ALLOWED` | secondary 읽기 허용 | 얼마나 낡았는지 밝히는 보고·분석. | +| `SNAPSHOT_TRANSACTION` | snapshot 격리 | transaction 안의 여러 문서 읽기. | -A profile is a declaration, not a hint: the registry is consulted per operation and an operation -without a registered profile is rejected rather than defaulting. +profile은 힌트가 아니라 선언이다. registry는 연산마다 조회되고, profile을 등록하지 않은 연산은 기본값으로 +가지 않고 거부된다. -## 4. Causal sessions +## 4. Causal session -`MongoCausalSessionContext` plus `SpringMongoCausalSessionExecutor` carry the cluster time and -operation time between operations, so -"write then read" returns the write even when the read lands on a different node. Without a causal -session, `PRIMARY_MAJORITY` gives you durability but not read-your-writes across two calls. +`MongoCausalSessionContext`와 `SpringMongoCausalSessionExecutor`가 연산 사이에 cluster time과 operation +time을 옮긴다. 그래서 「쓰고 나서 읽기」가 다른 노드로 가도 쓴 값을 돌려받는다. causal session이 없으면 +`PRIMARY_MAJORITY`는 내구성은 주지만, 호출 두 번에 걸쳐 자기가 쓴 것을 읽는 것은 보장하지 않는다. -## 5. Transactions +## 5. Transaction -`MongoTransactionExecutor` opens a session through the session -factory, run the body, and commit. `MongoTransactionProfile` carries the consistency profile, the -`maxCommitTime` and the retry budget. Topology matters: a transaction requires a replica set, and -`MongoStartupValidator` refuses a transaction-declaring profile on `STANDALONE` at startup rather -than at the first call. +`MongoTransactionExecutor`는 session factory로 session을 열고, 본문을 돌리고, commit한다. +`MongoTransactionProfile`은 일관성 profile, `maxCommitTime`, 재시도 예산을 가진다. 토폴로지가 중요하다. +transaction에는 replica set이 필요하다. `MongoStartupValidator`는 `STANDALONE`에서 transaction을 선언한 +profile을 첫 호출이 아니라 시작할 때 거부한다. -## 6. Retry: body and commit are different loops +## 6. 재시도: 본문과 commit은 다른 loop다 -D-10, and the single most consequential rule in the design. +D-10이고, 설계에서 결과가 가장 큰 규칙이다. ``` for each body attempt: @@ -72,56 +68,53 @@ for each body attempt: UnknownTransactionCommitResult -> retry COMMIT ONLY, same session ``` -`MongoTransactionRetryCoordinator` implements exactly this: +`MongoTransactionRetryCoordinator`가 정확히 이것을 구현한다. -- **A new session per body attempt.** Reusing the session after an abort carries the aborted - transaction's state into the retry. -- **The body is never replayed after a commit ambiguity.** An unknown commit means the commit may - already have applied. Re-running the body would apply it a second time. Only the commit is retried, - and a commit retry on an already-committed transaction is a no-op by design. -- **A budget bounds both loops.** `MongoRetryBudget` limits attempts *and* elapsed time, with jittered - backoff (`delayBefore(attempt, random)`), so a struggling primary is not retried into the ground. +- **본문 시도마다 새 session.** abort한 뒤 session을 다시 쓰면 abort한 transaction의 상태가 재시도로 + 넘어간다. +- **commit 결과를 모르면 본문을 다시 돌리지 않는다.** commit 결과를 모른다는 것은 commit이 이미 적용됐을 + 수 있다는 뜻이다. 본문을 다시 돌리면 두 번 적용된다. commit만 재시도하고, 이미 commit된 transaction에 + 대한 commit 재시도는 설계상 아무 일도 하지 않는다. +- **예산이 두 loop를 모두 제한한다.** `MongoRetryBudget`은 시도 횟수 *와* 흐른 시간을 제한하고, 흔들림을 + 준 backoff(`delayBefore(attempt, random)`)를 쓴다. 힘든 primary를 재시도로 짓누르지 않는다. -`MongoRetryDecision` and `MongoRetryScope` (in `…api.error`) say what may be retried: -`MongoRetryScope.BODY`, `COMMIT_ONLY`, or `NONE`. +`MongoRetryDecision`과 `MongoRetryScope`(`…api.error`에 있다)가 무엇을 재시도해도 되는지 말한다: +`MongoRetryScope.BODY`, `COMMIT_ONLY`, `NONE`. -## 7. Ambiguous outcomes +## 7. 결과를 모르는 경우 -`MongoExecutionOutcome` has six values, two of which are ambiguous and must not be collapsed: +`MongoExecutionOutcome`의 값은 여섯이고, 그중 둘은 결과를 모르는 경우라 합치면 안 된다. -| Outcome | Did the write happen? | +| 결과 | 쓰기가 일어났나? | |---|---| -| `NOT_SENT` | No. Safe to retry. | -| `NO_WRITE_PERFORMED` | No — the server answered and did nothing. | -| `WRITE_CONFIRMED` | Yes. | -| `PARTIAL_BULK_WRITE` | Some of it. See `MongoBulkResult`. | -| `WRITE_RESULT_UNKNOWN` | **Unknown.** | -| `TRANSACTION_COMMIT_UNKNOWN` | **Unknown.** | +| `NOT_SENT` | 아니다. 재시도해도 안전하다. | +| `NO_WRITE_PERFORMED` | 아니다. 서버가 답했고 아무것도 하지 않았다. | +| `WRITE_CONFIRMED` | 그렇다. | +| `PARTIAL_BULK_WRITE` | 일부만. `MongoBulkResult`를 본다. | +| `WRITE_RESULT_UNKNOWN` | **모른다.** | +| `TRANSACTION_COMMIT_UNKNOWN` | **모른다.** | -An unknown outcome is not a failure and must not be reported to a caller as one. The caller either -reconciles (`MongoCommitReconciler` re-reads a deterministic marker the body wrote) or surfaces the -ambiguity. See [runbooks/unknown-commit.md](runbooks/unknown-commit.md). +결과를 모르는 것은 실패가 아니고, 호출자에게 실패로 알리면 안 된다. 호출자는 맞춰 보거나 +(`MongoCommitReconciler`가 본문이 쓴 결정적 표시를 다시 읽는다) 모른다는 사실을 그대로 위로 올린다. +[runbooks/unknown-commit.md](runbooks/unknown-commit.md)를 본다. -`MongoFailureContext` records only the design-permitted fields — outcome, category, operation name, -collection profile, retry scope, attempt — never the query, the document, or the values. +`MongoFailureContext`는 설계가 허락한 필드만 남긴다: 결과, 분류, 연산 이름, collection profile, 재시도 +범위, 시도 번호. query, 문서, 값은 남기지 않는다. -## 8. Failure translation +## 8. 실패 변환 -`DefaultMongoFailureClassifier` classifies **labels before codes**. The server's error labels -(`TransientTransactionError`, `UnknownTransactionCommitResult`, `RetryableWriteError`) are the -authoritative statement about retryability; an error code is a secondary signal whose meaning varies -by server version. `DefaultMongoFailureTranslator` maps a classification onto the stable exception -hierarchy, and anything unmatched becomes `MongoUnclassifiedFailureException` rather than leaking a -driver type. +`DefaultMongoFailureClassifier`는 **코드보다 label을 먼저** 본다. 서버의 error label +(`TransientTransactionError`, `UnknownTransactionCommitResult`, `RetryableWriteError`)이 재시도 가능 여부에 +대한 권위 있는 답이다. error code는 서버 버전마다 뜻이 바뀌는 보조 신호다. +`DefaultMongoFailureTranslator`가 분류를 안정된 예외 계층에 대응시킨다. 맞는 것이 없으면 driver 타입을 +흘리지 않고 `MongoUnclassifiedFailureException`이 된다. -## 9. Bulk writes +## 9. Bulk 쓰기 -`MongoBulkExecutor` returns a `MongoBulkResult` with per-item `MongoBulkItemFailure` entries. An -unordered bulk write that partially fails is `PARTIAL_BULK_WRITE`, not a failure: some documents were -written. The result's per-item outcomes say which indexes succeeded and which failed, so a caller can -resume rather than replay. +`MongoBulkExecutor`는 항목별 `MongoBulkItemFailure`를 담은 `MongoBulkResult`를 돌려준다. 순서 없는 bulk +쓰기가 일부 실패하면 실패가 아니라 `PARTIAL_BULK_WRITE`다. 일부 문서는 쓰였다. 결과의 항목별 결과가 +어느 index가 성공하고 어느 것이 실패했는지 말해 주므로, 호출자는 처음부터 다시 하지 않고 이어서 할 수 있다. -`execute(context, documentType, plan)` maps every filter and update through the document type, as -the single-document path does, so `@Field` names and registered converters (`DomainDocumentId`, -`BigInteger`) mean the same thing in a batch. The command's byte ceiling is measured on those mapped -documents before anything is sent. +`execute(context, documentType, plan)`은 문서 하나 경로와 같이 모든 filter와 update를 document type에 +맞춰 변환한다. 그래서 `@Field` 이름과 등록한 converter(`DomainDocumentId`, `BigInteger`)가 batch에서도 +같은 뜻이다. 명령의 바이트 상한은 무엇이든 보내기 전에 그렇게 변환한 문서로 잰다. diff --git a/docs/mongodb/consumer-leaf-guide.md b/docs/mongodb/consumer-leaf-guide.md index 06d8699f..9b7dd563 100644 --- a/docs/mongodb/consumer-leaf-guide.md +++ b/docs/mongodb/consumer-leaf-guide.md @@ -84,7 +84,12 @@ leaf 목록과 허용 의존 방향의 원본은 `src/config/architecture/module runtimeOnly project(':adapter:outbound:persistence-note') ``` -5. 확인: `./gradlew :adapter:outbound:persistence-note:check architectureCheck --console=plain`. +5. 확인: 새 leaf의 `check`와 `architectureCheck`를 돈다. 아래 Gradle 경로는 서비스가 만든 leaf의 것이라 + 이 템플릿에는 없다. + + ```bash + ./gradlew :adapter:outbound:persistence-note:check architectureCheck --console=plain + ``` ## 3. 서비스 leaf가 등록해야 하는 bean diff --git a/docs/mongodb/document-modeling-guide.md b/docs/mongodb/document-modeling-guide.md index a110e341..e11d95ef 100644 --- a/docs/mongodb/document-modeling-guide.md +++ b/docs/mongodb/document-modeling-guide.md @@ -1,85 +1,84 @@ -# Document Modeling Guide +# 문서 모델링 가이드 -Design §7–§9. The platform does not own your documents — D-01 is explicit that the domain owns -`@Document`, repositories, queries, index requirements and schema version. What the platform owns is -the set of modeling decisions that are expensive to reverse once a collection holds production data. +설계서 §7–§9. 플랫폼은 여러분의 문서를 소유하지 않는다. D-01이 분명히 말한다: `@Document`, repository, +query, index 요구 사항, schema 버전은 도메인이 소유한다. 플랫폼이 소유하는 것은 collection에 운영 +데이터가 쌓인 뒤에는 되돌리기 비싼 모델링 결정들이다. -## 1. There is no `CommonMongoRepository` +## 1. `CommonMongoRepository`는 없다 -A generic `CommonMongoRepository` is listed under explicitly unsupported (§3.4), and the -reason is not purity. A shared supertype forces every collection to share an id strategy, a -consistency profile and a query surface, and the first collection that needs a different one either -gets a cast or a leaky generic parameter. Declare a Spring Data repository per aggregate. +범용 `CommonMongoRepository`는 명시적으로 지원하지 않는 목록(§3.4)에 있다. 이유는 순수성이 아니다. +공통 상위 타입은 모든 collection에 같은 id 전략, 같은 일관성 profile, 같은 query 면을 강요한다. 다른 것이 +필요한 첫 collection은 cast를 하거나 새는 generic 인자를 얻는다. aggregate마다 Spring Data repository를 +선언한다. -## 2. Embed or reference +## 2. 넣을까, 가리킬까 -`MongoDocumentModelManifest` records the decision per collection so it is reviewable, and -`MongoDocumentModelValidator` refuses the combinations that do not survive growth. +`MongoDocumentModelManifest`가 collection마다 이 결정을 적어 검토할 수 있게 하고, +`MongoDocumentModelValidator`가 커지면 버티지 못하는 조합을 거부한다. -| Descriptor | Use when | +| Descriptor | 쓰는 때 | |---|---| -| `EmbeddedCollectionDescriptor` | The child is read with the parent, is bounded, and has no independent lifecycle. Declare `maxElements`; an unbounded array is the single most common way a document reaches the size limit. | -| `MongoReferenceDescriptor` | The child is queried independently, is unbounded, or outlives the parent. Declare `MongoReferenceLifecycle` so the deletion story is written down rather than discovered. | +| `EmbeddedCollectionDescriptor` | 자식을 부모와 함께 읽고, 개수에 상한이 있고, 따로 사는 수명이 없다. `maxElements`를 선언한다. 상한 없는 배열이 문서가 크기 한도에 닿는 가장 흔한 길이다. | +| `MongoReferenceDescriptor` | 자식을 따로 조회하거나, 개수에 상한이 없거나, 부모보다 오래 산다. `MongoReferenceLifecycle`을 선언해서 삭제 방식을 나중에 발견하지 않고 미리 적어 둔다. | -The validator rejects an embedded collection without a bound, and a reference whose lifecycle says -the child is owned by the parent but which is also referenced from elsewhere. +validator는 상한 없는 embedded collection을 거부한다. lifecycle이 「부모가 자식을 소유한다」고 하면서 +다른 곳에서도 가리키는 reference도 거부한다. -## 3. Size budget +## 3. 크기 예산 `MongoDocumentSizeBudget`: -| Constant | Bytes | Meaning | +| 상수 | 바이트 | 뜻 | |---|---|---| -| `MONGODB_HARD_LIMIT_BYTES` | 16 MiB | MongoDB's own limit. | -| `PLATFORM_CEILING_BYTES` | 4 MiB | The largest budget the platform will accept. | +| `MONGODB_HARD_LIMIT_BYTES` | 16 MiB | MongoDB 자체 한도. | +| `PLATFORM_CEILING_BYTES` | 4 MiB | 플랫폼이 받아들이는 가장 큰 예산. | | `DEFAULT_BYTES` | 2 MiB | `MongoDocumentSizeBudget.standard()`. | -A budget above the ceiling is refused at construction. Budgeting to 16 MiB means the failing write -is the first symptom, and by then the collection is already full of near-limit documents. +상한을 넘는 예산은 생성할 때 거부한다. 예산을 16 MiB로 잡으면 실패한 쓰기가 첫 증상이고, 그때는 이미 +collection이 한도 가까운 문서로 가득하다. -## 4. Identity +## 4. 식별자 -`DomainDocumentId` is written to `_id` as a BSON string by `DomainIdWriteConverter`. Any other -representation is the document class's own field type. Pick the representation once per collection: +`DomainIdWriteConverter`가 `DomainDocumentId`를 `_id`에 BSON 문자열로 쓴다. 그 밖의 표현은 문서 클래스 +자신의 필드 타입이 정한다. collection마다 표현을 한 번 고른다. -- `OBJECT_ID` — server-generated, monotonic, 12 bytes. Good default when the domain has no natural id. -- `UUID_BINARY` — a domain UUID stored as `Binary` subtype 4 (`STANDARD`). Never store a UUID as a - string "because it is easier to read"; it doubles the index size and loses the type. -- `STRING` — a natural key that is genuinely a string (a slug, an external system's id). +- `OBJECT_ID` — 서버가 만들고, 단조 증가하며, 12바이트다. 도메인에 자연 id가 없을 때 좋은 기본값이다. +- `UUID_BINARY` — 도메인 UUID를 `Binary` subtype 4(`STANDARD`)로 저장한다. 「읽기 쉬워서」 UUID를 + 문자열로 저장하지 않는다. index 크기가 두 배가 되고 타입을 잃는다. +- `STRING` — 정말 문자열인 자연 key(slug, 외부 시스템의 id). -An `_id` choice is effectively permanent: it is the shard key candidate, the resume-token join key -and the pagination tie-breaker. +`_id` 선택은 사실상 영구적이다. shard key 후보이고, resume token의 join key이고, 페이지 나누기의 동률 +처리 기준이다. -## 5. Schema version +## 5. Schema 버전 -Every long-lived collection carries `DocumentSchemaVersion`. `MongoSchemaVersionPolicy` and -`MongoSchemaVersionRange` say which versions the running code can read; a document outside the range -raises `MongoDataSchemaUnsupportedException` rather than being silently mapped with missing fields. +오래 사는 collection은 모두 `DocumentSchemaVersion`을 가진다. `MongoSchemaVersionPolicy`와 +`MongoSchemaVersionRange`가 실행 중인 코드가 읽을 수 있는 버전을 말한다. 범위 밖의 문서는 필드가 빠진 +채 조용히 매핑되지 않고 `MongoDataSchemaUnsupportedException`을 던진다. -Write the range down before the migration, not after: the range is what lets old and new instances -run at once during a rolling deploy. +범위는 마이그레이션 뒤가 아니라 앞에 적는다. 범위가 있어야 rolling 배포 중에 옛 인스턴스와 새 인스턴스가 +함께 돈다. -## 6. Type metadata +## 6. 타입 metadata -`@LongLivedMongoDocument` marks a document whose stored type alias must not be a Java class name. -`MongoTypeMetadataRegistry` maps alias → class. Storing the FQCN means moving or renaming the class -becomes a data migration; storing an alias keeps it a refactor. See -[bson-mapping-guide.md](bson-mapping-guide.md) §4. +`@LongLivedMongoDocument`는 저장하는 타입 별칭이 Java 클래스 이름이면 안 되는 문서를 표시한다. +`MongoTypeMetadataRegistry`가 별칭 → 클래스를 대응시킨다. FQCN을 저장하면 클래스를 옮기거나 이름을 바꾸는 +일이 데이터 마이그레이션이 된다. 별칭을 저장하면 리팩터링으로 남는다. +[bson-mapping-guide.md](bson-mapping-guide.md) §5를 본다. -## 7. Collection profiles +## 7. Collection profile -`MongoCollectionProfileRegistry` binds a `CollectionProfileName` to its consistency profile, budget -and allowlist. A collection that is not registered cannot be reached through -`MongoImperativeExecutor` — the allowlist is the mechanism that keeps an -unreviewed collection from appearing in production by accident. +`MongoCollectionProfileRegistry`는 `CollectionProfileName`을 그 일관성 profile, 예산, 허용 목록에 묶는다. +등록하지 않은 collection에는 `MongoImperativeExecutor`로 닿을 수 없다. 허용 목록이 검토하지 않은 +collection이 실수로 운영에 나타나는 것을 막는다. -## 8. What to write down before the first insert +## 8. 첫 insert 전에 적어 둘 것 -1. Embed/reference decision per child collection, with bounds. -2. Size budget. -3. `_id` representation. -4. Schema version range. -5. Index manifest (see [schema-index-migration-guide.md](schema-index-migration-guide.md)). -6. Consistency profile (see [consistency-transaction-guide.md](consistency-transaction-guide.md)). +1. 자식 collection마다 넣을지/가리킬지와 그 상한. +2. 크기 예산. +3. `_id` 표현. +4. Schema 버전 범위. +5. Index manifest([schema-index-migration-guide.md](schema-index-migration-guide.md)). +6. 일관성 profile([consistency-transaction-guide.md](consistency-transaction-guide.md)). -Each of these is cheap now and a migration later. +모두 지금은 싸고, 나중에는 마이그레이션이다. diff --git a/docs/mongodb/query-aggregation-guide.md b/docs/mongodb/query-aggregation-guide.md index ad2712ae..cb3f5805 100644 --- a/docs/mongodb/query-aggregation-guide.md +++ b/docs/mongodb/query-aggregation-guide.md @@ -1,110 +1,105 @@ -# Query and Aggregation Guide +# Query와 aggregation 가이드 -Design §17–§19, decision D-11. Every query and every pipeline is a registered, bounded thing. Free-form -JSON queries and unbounded pipelines are explicitly unsupported (§3.4). +설계서 §17–§19, 결정 D-11. 모든 query와 모든 pipeline은 등록하고 상한을 둔 것이어야 한다. 자유 형식 +JSON query와 상한 없는 pipeline은 명시적으로 지원하지 않는다(§3.4). -## 1. Registered operations +## 1. 등록한 연산 -Every execution carries a `MongoOperationContext`: a `MongoOperationName`, a `DatabaseProfileName`, a -`CollectionProfileName`, a `MongoOperationType` and a `MongoOperationScope`. +모든 실행은 `MongoOperationContext`를 가진다: `MongoOperationName`, `DatabaseProfileName`, +`CollectionProfileName`, `MongoOperationType`, `MongoOperationScope`. -`MongoOperationName` matches `[a-z][a-z0-9.-]{2,95}`. It is the join key for the budget registry, the -consistency registry, the metric tag and the log line — a free-form or interpolated name breaks all -four at once, which is why the pattern is enforced at construction. +`MongoOperationName`은 `[a-z][a-z0-9.-]{2,95}`에 맞아야 한다. 이 이름이 예산 registry, 일관성 registry, +metric tag, 로그 줄을 잇는 key다. 자유 형식이나 값을 끼워 넣은 이름은 넷을 한꺼번에 깨뜨린다. 그래서 +생성할 때 패턴을 강제한다. -`MongoOperationScope` uses an `UNSPECIFIED` sentinel rather than `null`, so "the caller did not say" -is a value the policy layer can reject rather than an NPE further down. +`MongoOperationScope`는 `null` 대신 `UNSPECIFIED` 표시값을 쓴다. 「호출자가 말하지 않았다」가 아래에서 +터지는 NPE가 아니라 정책 계층이 거부할 수 있는 값이 된다. -## 2. Query guardrails +## 2. Query 보호 장치 -`PolicyAwareMongoQueryBuilder` builds a query from `MongoFieldDescriptor` + `MongoOperator` pairs -against a `MongoQueryPolicy`. The policy refuses: +`PolicyAwareMongoQueryBuilder`는 `MongoFieldDescriptor` + `MongoOperator` 쌍으로 `MongoQueryPolicy`에 +맞춰 query를 만든다. 정책이 거부하는 것: -- a field not in the collection's allowlist -- an operator not allowed for that field -- a sort on an unindexed field -- `$where`, `$expr` with arbitrary JavaScript, and server-side evaluation generally -- an unbounded `$regex` +- collection 허용 목록에 없는 필드 +- 그 필드에 허용하지 않은 operator +- index 없는 필드의 정렬 +- `$where`, 임의 JavaScript를 쓰는 `$expr`, 그리고 서버 쪽 평가 전반 +- 상한 없는 `$regex` -`MongoRegexPolicy` requires an anchored prefix pattern and bounds the pattern length. An unanchored -regex is a collection scan wearing an index's clothes, and a user-supplied one is a denial-of-service -primitive. +`MongoRegexPolicy`는 앞을 고정한 prefix 패턴을 요구하고 패턴 길이에 상한을 둔다. 앞을 고정하지 않은 +regex는 index를 쓰는 척하는 collection 전체 scan이고, 사용자가 넣은 regex는 서비스 거부 공격의 재료다. -`MongoSortDescriptor` pairs a field with a direction and is validated against the index manifest, so -a sort that would spill to disk fails review rather than production. +`MongoSortDescriptor`는 필드와 방향을 짝짓고 index manifest와 대조한다. 디스크로 넘칠 정렬은 운영이 아니라 +검토에서 실패한다. -## 3. Operation budgets +## 3. 연산 예산 -`MongoOperationBudget` bounds four things at once: +`MongoOperationBudget`은 네 가지를 한꺼번에 제한한다. -| Bound | Why | +| 상한 | 이유 | |---|---| -| `maxTimeMS` | The server stops working on a query nobody is waiting for. | -| result limit | An unbounded result set is an OOM with extra steps. | -| batch size | Bounds the per-round-trip memory. | -| examined-document ceiling | Catches an index regression that a time limit alone would hide on a fast day. | +| `maxTimeMS` | 아무도 기다리지 않는 query를 서버가 멈춘다. | +| 결과 개수 상한 | 상한 없는 결과는 단계가 몇 개 더 붙은 OOM이다. | +| batch 크기 | 왕복 한 번의 메모리를 제한한다. | +| 검사한 문서 수 상한 | 빠른 날에는 시간 상한만으로 숨겨지는 index 회귀를 잡는다. | -`MongoBudgetPolicyRegistry` binds a budget to an operation name; `MongoBudgetEnforcer` applies it and -raises `MongoOperationRejectedException` before execution when a request exceeds it, and -`MongoTimeoutException` when the server enforces it. +`MongoBudgetPolicyRegistry`가 예산을 연산 이름에 묶는다. `MongoBudgetEnforcer`가 그것을 적용한다. 요청이 +예산을 넘으면 실행 전에 `MongoOperationRejectedException`을 던지고, 서버가 상한을 집행하면 +`MongoTimeoutException`이 난다. -## 4. Keyset pagination +## 4. Keyset 페이지 나누기 -Unbounded `skip` is unsupported: `skip(1_000_000)` makes the server walk a million documents to throw -them away, so page 1000 costs a thousand times page 1. +상한 없는 `skip`은 지원하지 않는다. `skip(1_000_000)`은 서버가 버릴 문서 백만 개를 훑게 한다. 그래서 +1000쪽은 1쪽의 천 배가 든다. -`MongoKeysetQueryBuilder` builds the resume predicate lexicographically. For a sort on `(a DESC, _id -DESC)` resuming after `(A, I)`: +`MongoKeysetQueryBuilder`는 이어 읽기 조건을 사전순으로 만든다. `(a DESC, _id DESC)` 정렬에서 `(A, I)` +다음부터 읽으면 이렇다. ``` (a < A) OR (a = A AND _id < I) ``` -`validate()` rejects a `MongoKeysetSort` without a unique tie-breaker. Without one, two documents with -the same sort value straddle the page boundary and one of them is skipped or repeated — invisibly, -and only under concurrency. +`validate()`는 유일한 동률 처리 기준이 없는 `MongoKeysetSort`를 거부한다. 기준이 없으면 정렬 값이 같은 두 +문서가 페이지 경계에 걸쳐 하나가 빠지거나 두 번 나온다. 눈에 띄지 않고, 동시 요청이 있을 때만 생긴다. -`MongoNullSortOrdering` makes null placement explicit, because MongoDB's own ordering of missing -versus null versus present is not what most people assume. +`MongoNullSortOrdering`은 null의 위치를 명시한다. 필드 없음, null, 값 있음에 대한 MongoDB 자체 정렬 순서는 +대부분이 짐작하는 것과 다르다. -### Cursors are authenticated +### Cursor는 인증한다 -`MongoKeysetCursorCodec` signs the cursor with HMAC-SHA256 and compares with -`MessageDigest.isEqual` (constant time). An unsigned cursor is a client-controlled query predicate: a -caller can edit it to read a range they were never offered. A tampered or truncated cursor yields -`MongoCursorException`, never a partially-decoded resume position. +`MongoKeysetCursorCodec`은 cursor에 HMAC-SHA256 서명을 하고 `MessageDigest.isEqual`(일정 시간 비교)로 +비교한다. 서명 없는 cursor는 client가 조종하는 query 조건이다. 호출자가 그것을 고쳐 받은 적 없는 범위를 +읽을 수 있다. 고치거나 잘린 cursor는 `MongoCursorException`이 되고, 반쯤 해석한 이어 읽기 위치가 되지 +않는다. -## 5. Aggregation guardrails +## 5. Aggregation 보호 장치 -`MongoAggregationPlan` is a registered pipeline: an ordered list of `MongoAggregationStageDescriptor` -validated against a `MongoAggregationProfile`. `PolicyAwareMongoAggregationExecutor` runs only a -registered plan. +`MongoAggregationPlan`은 등록한 pipeline이다. `MongoAggregationStageDescriptor`의 순서 있는 목록이고 +`MongoAggregationProfile`과 대조한다. `PolicyAwareMongoAggregationExecutor`는 등록한 plan만 돌린다. -`MongoAggregationRisk` grades each stage, and the profile sets the ceiling: +`MongoAggregationRisk`가 stage마다 위험 등급을 매기고, profile이 허용 상한을 정한다. -| Risk | Stages | Policy | +| 위험 | Stage | 정책 | |---|---|---| -| low | `$match` on an indexed prefix, `$limit`, `$project` | Always allowed. | -| moderate | `$group`, `$sort` with an index, `$unwind` with a bound | Allowed within budget. | -| high | `$lookup`, `$graphLookup`, `$facet`, unindexed `$sort` | Requires explicit approval in the profile. | -| forbidden | `$out`, `$merge` outside the admin plane, `$function`, `$accumulator` | Refused. | +| low | index 앞부분에 대한 `$match`, `$limit`, `$project` | 늘 허용한다. | +| moderate | `$group`, index 있는 `$sort`, 상한 있는 `$unwind` | 예산 안에서 허용한다. | +| high | `$lookup`, `$graphLookup`, `$facet`, index 없는 `$sort` | profile의 명시적 승인이 필요하다. | +| forbidden | admin plane 밖의 `$out`·`$merge`, `$function`, `$accumulator` | 거부한다. | -`allowDiskUse` is a declared property of the plan, not a runtime flag. A pipeline that needs disk is a -pipeline whose shape should be reviewed. +`allowDiskUse`는 실행 중 flag가 아니라 plan에 선언하는 속성이다. 디스크가 필요한 pipeline은 모양을 검토해야 +하는 pipeline이다. -## 6. Geospatial +## 6. 지리 공간 -`MongoGeoQuery` + `MongoGeoPoint` + `MongoGeoDistance` over a `2dsphere` index. Distances are metres -on a sphere (`nearSphere` with `maxDistance`), never degrees — a degree of longitude is a different -distance in Oslo than in Nairobi, and a radius expressed in degrees is a bug that only shows up away -from the equator. `SpringMongoGeospatialOperations` is the Spring Data binding; -`MongoGeospatialOperations` is the port. +`MongoGeoQuery` + `MongoGeoPoint` + `MongoGeoDistance`를 `2dsphere` index 위에서 쓴다. 거리는 구 위의 +미터다(`nearSphere`와 `maxDistance`). 도(degree)는 쓰지 않는다. 경도 1도는 오슬로와 나이로비에서 거리가 +다르다. 도로 적은 반경은 적도에서 멀어져야 드러나는 결함이다. `SpringMongoGeospatialOperations`가 Spring +Data 연결이고, `MongoGeospatialOperations`가 port다. ## 7. Native capability gateway -When a registered operation genuinely needs something outside the Stable API, it goes through -`MongoNativeCapabilityGateway` (`PolicyAwareMongoNativeGateway`), never through the driver directly. -The admission order is fixed: +등록한 연산에 정말 Stable API 밖의 것이 필요하면 driver를 바로 쓰지 않고 +`MongoNativeCapabilityGateway`(`PolicyAwareMongoNativeGateway`)를 거친다. 허가 순서는 고정이다. ``` capability registered @@ -121,6 +116,6 @@ capability registered → execute ``` -`ApprovedMongoNativeOperation` is the registration record; `MongoNativeOperationPolicy` is the policy. -An admin-plane command reaching this gateway is refused regardless of capability — the admin plane has -its own credential and its own client (see [security-observability.md](security-observability.md)). +`ApprovedMongoNativeOperation`이 등록 기록이고 `MongoNativeOperationPolicy`가 정책이다. admin plane 명령이 +이 gateway에 오면 capability와 상관없이 거부한다. admin plane은 자기 credential과 자기 client를 쓴다 +([security-observability.md](security-observability.md)). diff --git a/docs/mongodb/repository-adaptation.md b/docs/mongodb/repository-adaptation.md index e50c4795..28ab0d0f 100644 --- a/docs/mongodb/repository-adaptation.md +++ b/docs/mongodb/repository-adaptation.md @@ -1,43 +1,46 @@ -# MongoDB Document Persistence Platform — Repository Adaptation Contract +# MongoDB 문서 영속성 플랫폼 — 저장소 적응 계약 -**Design source:** `docs/design/2026-08-11-mongodb-document-persistence-platform-design.md` -**Stable plan:** `docs/history/plans/2026-08-11-mongodb-document-persistence-platform-implementation-plan.md` -**Advanced plan:** `docs/history/plans/2026-08-11-mongodb-advanced-capabilities-expansion-plan.md` +**설계서:** `docs/design/2026-08-11-mongodb-document-persistence-platform-design.md` +**Stable 계획서:** `docs/history/plans/2026-08-11-mongodb-document-persistence-platform-implementation-plan.md` +**Advanced 계획서:** `docs/history/plans/2026-08-11-mongodb-advanced-capabilities-expansion-plan.md` -The design package declares its own module root (`modules/mongodb`) and root package -(`io.backend.skeleton.mongodb`) as *implementation assumptions*, not as contract. This file is the -single record of how that assumed layout was mapped onto this repository. Only paths, build DSL, -and composition-root ownership changed. Public contracts, policy order, and error semantics are -implemented exactly as specified. +설계 패키지는 자기 모듈 root(`modules/mongodb`)와 root package(`io.backend.skeleton.mongodb`)를 계약이 +아니라 *구현 가정*으로 적었다. 이 파일은 그 가정한 배치를 이 저장소에 어떻게 옮겼는지 적은 유일한 +기록이다. 바뀐 것은 경로, 빌드 DSL, 조립 루트의 소유뿐이다. 공개 계약, 정책 순서, 오류 의미는 명세대로 +구현했다. -## 1. Why the module layout differs +## 1. 모듈 배치가 다른 이유 -The design assumes 19 Stable Gradle projects under `modules/mongodb/` and 12 Advanced projects -under `modules/mongodb-advanced/`. This repository is a Clean Architecture template whose -**fail-closed registry** (`src/config/architecture/modules.json`, enforced by `src/settings.gradle` -and `verifyCleanArchitectureDependencies`) declares **exactly 19 leaf identities**. Creating 31 more -Gradle projects would violate HARD-STOP #5 in `AGENTS.md`. +설계는 `modules/mongodb/` 아래에 Stable Gradle 프로젝트 19개, `modules/mongodb-advanced/` 아래에 Advanced +프로젝트 12개를 가정한다. 이 저장소는 Clean Architecture 템플릿이고, **닫힌 쪽으로 실패하는 registry** +(`src/config/architecture/modules.json`)가 Gradle 프로젝트 목록을 정한다. `src/settings.gradle`이 +registry에 있는 프로젝트만 포함하고, `verifyCleanArchitectureDependencies`가 허용하지 않은 의존을 막는다. +설계의 모듈마다 Gradle 프로젝트를 만들면 `AGENTS.md`의 HARD-STOP 5번(registry·Gradle 의존성 검증 위반)에 +걸린다. -Therefore the design's 31 modules become **package boundaries inside the registered leaf** -`:adapter:outbound:persistence-mongo`, following the precedent already set by -[docs/httpclient/repository-adaptation.md](../httpclient/repository-adaptation.md). The design's -module dependency table (§6.3) is enforced by `MongoModuleBoundaryTest` as a **closed edge matrix**: -every top-level package is declared with the packages it may import, the matrix is compared against -the tree for exact equality, and every observed edge must appear in it. A forbidden edge fails the -build the same way a missing Gradle dependency would, and so does a new package nobody registered. +그래서 설계의 모듈 31개는 등록된 leaf `:adapter:outbound:persistence-mongo` **안의 package 경계**가 +된다. [docs/httpclient/repository-adaptation.md](../httpclient/repository-adaptation.md)가 먼저 세운 +방식을 따른다. 설계의 모듈 의존 표(§6.3)는 `MongoModuleBoundaryTest`가 **닫힌 edge 행렬**로 강제한다. -This used to be a stronger claim than the test. The rules forbade a handful of reverse dependencies -and said nothing about the rest, so edges outside the design's DAG existed and passed, among them -`geo → imperative`. They are declared in the matrix now rather than removed — each is a real coupling the code relies on, and -the point of recording them is that the next one is a decision instead of an accident. +- 최상위 package마다 import해도 되는 package를 선언한다. +- 행렬과 실제 트리가 정확히 같은지 비교한다. +- 관측한 edge는 모두 행렬에 있어야 한다. -## 2. Package mapping +금지된 edge는 Gradle 의존이 빠졌을 때와 똑같이 빌드를 실패시킨다. 아무도 등록하지 않은 새 package도 +그렇다. + +예전에는 이 문서의 주장이 테스트보다 강했다. 규칙은 역방향 의존 몇 개만 막고 나머지는 말하지 않았다. +그래서 설계의 DAG 밖의 edge가 있었고 통과했다. `geo → imperative`가 그중 하나다. 지금은 그런 edge를 +지우지 않고 행렬에 선언했다. 하나하나가 코드가 실제로 기대는 결합이다. 적어 두는 이유는 다음 edge가 +사고가 아니라 결정이 되게 하려는 것이다. + +## 2. Package 대응 Root package: `io.backend.skeleton.mongodb` → `dev.caskeleton.adapter.outbound.mongo`. -### 2.1 Stable modules +### 2.1 Stable 모듈 -| Design module | Repository package | +| 설계 모듈 | 저장소 package | |---|---| | `mongodb-core-api` | `…outbound.mongo.api` (+ `.capability`, `.consistency`, `.error`, `.mapping`, `.observation`, `.profile`, `.schema`) | | `mongodb-spring-data` | `…outbound.mongo.mapping` (+ `.type`), `…outbound.mongo.failure` | @@ -52,79 +55,76 @@ Root package: `io.backend.skeleton.mongodb` → `dev.caskeleton.adapter.outbound | `mongodb-observability` | `…outbound.mongo.observation` | | `mongodb-security` | `…outbound.mongo.security` (+ `.admin`), `…outbound.mongo.nativecap` | | `mongodb-spring-boot-starter` | `…outbound.mongo.autoconfigure` | -| `mongodb-testkit-core` | `…outbound.mongo.testkit.mapping`, `.compat`, `.performance` (`testkit` source set) | -| `mongodb-testkit-replicaset` | `…outbound.mongo.testkit.rs` (`testkit` source set) | -| `mongodb-testkit-failover` | `…outbound.mongo.testkit.failover` (`testkit` source set) | -| `mongodb-testkit-migration` | `…outbound.mongo.testkit.migration` (`testkit` source set) | +| `mongodb-testkit-core` | `…outbound.mongo.testkit.mapping`, `.compat`, `.performance` (`testFixtures` source set) | +| `mongodb-testkit-replicaset` | `…outbound.mongo.testkit.rs` (`testFixtures`, 컨테이너 fixture는 `mongoProviderTestkit` source set) | +| `mongodb-testkit-failover` | `…outbound.mongo.testkit.failover` (`testFixtures`, 컨테이너 fixture는 `mongoProviderTestkit` source set) | +| `mongodb-testkit-migration` | `…outbound.mongo.testkit.migration` (`testFixtures` source set) | -`…outbound.mongo.architecture` has no design counterpart: it holds the `@MongoOperation` marker and -the reusable ArchUnit rule set a fork applies to its own document/repository code. +`…outbound.mongo.architecture`는 설계에 짝이 없다. `testFixtures` source set에 있고, `@MongoOperation` +표시 annotation과, 파생 서비스가 자기 document·repository 코드에 적용하는 재사용 ArchUnit 규칙 묶음 +(`MongoRepositoryArchitectureRules`)을 가진다. -### 2.2 Advanced modules +### 2.2 Advanced 모듈 -| Design module | Repository package | +| 설계 모듈 | 저장소 package | |---|---| -| `mongodb-sharding` | `…outbound.mongo.advanced.sharding` (+ `.admin` for the D4 shard plane) | +| `mongodb-sharding` | `…outbound.mongo.advanced.sharding` (+ D4 shard plane용 `.admin`) | | `mongodb-csfle` | `…outbound.mongo.advanced.encryption.csfle` | | `mongodb-queryable-encryption` | `…outbound.mongo.advanced.encryption.qe` | | `mongodb-tenancy-shared` | `…outbound.mongo.advanced.tenancy.shared` | | `mongodb-tenancy-database` | `…outbound.mongo.advanced.tenancy.database` | -| `mongodb-testkit-sharded` | `…outbound.mongo.testkit.sharded` (`testkit` source set) | +| `mongodb-testkit-sharded` | `…outbound.mongo.testkit.sharded` (`testFixtures` source set) | -`mongodb-timeseries`, `mongodb-search`, `mongodb-vector-search`, `mongodb-gridfs-compat` and -`mongodb-testkit-atlas` have no package any more: each was an operations interface with no -implementation plus the descriptors that parametrised it, and was removed on 2026-09-25 -(`docs/capability-status.md`). +`mongodb-timeseries`, `mongodb-search`, `mongodb-vector-search`, `mongodb-gridfs-compat`, +`mongodb-testkit-atlas`는 이제 package가 없다. 각각 구현 없는 operations interface와 그것을 매개변수로 +채우던 descriptor뿐이었고, 2026-09-25에 지웠다(`docs/capability-status.md`). -The design's rule that a Stable module never depends on an Advanced one survives as an ArchUnit rule -(`stableNeverDependsOnAdvanced`). Every Advanced entry point takes a `MongoAdvancedCapabilityGuard` -and refuses construction unless its `MongoAdvancedCapabilityFlags` enable the matching capability. -There is no configuration property behind the flags: the Advanced types are library API, and the -adopter's adapter that constructs them builds the guard. +설계의 「Stable 모듈은 Advanced 모듈에 의존하지 않는다」 규칙은 ArchUnit 테스트로 남았다 +(`MongoModuleBoundaryTest`의 `noStablePackageDependsOnAnAdvancedCapability`). 모든 Advanced 진입점은 +`MongoAdvancedCapabilityGuard`를 받고, 그 `MongoAdvancedCapabilityFlags`가 해당 capability를 켜지 않았으면 +생성을 거부한다. flag 뒤에 설정 속성은 없다. Advanced 타입은 라이브러리 API이고, 그것을 만드는 도입 측 +어댑터가 guard를 만든다. -## 3. Other deliberate substitutions +## 3. 그 밖에 일부러 바꾼 것 -| Design assumption | Repository reality | Adaptation | +| 설계 가정 | 저장소 현실 | 적응 | |---|---|---| -| Gradle Kotlin DSL under `modules/mongodb*` | Groovy DSL, root `build.gradle` conventions, `LockMode.STRICT` locking | Dependencies declared in `src/adapter/outbound/persistence-mongo/build.gradle`; `gradle.lockfile` regenerated. | -| `mongodb-spring-boot-starter` is a separate module the app depends on | `modules.json` gives `adapter-outbound-persistence-mongo` an explicit project boundary; runtime membership is derived from resolved runtime classpaths rather than a per-leaf registry field | The `autoconfigure` package stays inside the leaf and registers through the leaf's own `META-INF/spring/…AutoConfiguration.imports`. This differs from the httpclient precedent; dependency and runtime-membership gates decide whether the leaf is actually composed. | -| Spring Boot 4.1 / Spring Data MongoDB 5.1 baseline | Repository baseline is Spring Boot 4.0.8 / Spring Data MongoDB 5.0.x | The platform targets the Spring Data MongoDB **API surface** common to both; no 5.1-only type is referenced. The support matrix records the actual pinned versions. | -| `MongoRetryScope` lives in `mongodb-transaction` | The `mongodb-spring-data` failure translator must classify retry scope, and it cannot depend on `mongodb-transaction` | `MongoRetryScope` lives in `…api.error` (core-api), which both packages already depend on. Same values, same meaning, one legal position in the DAG. | -| `mongodb-migration-flamingock` depends on Flamingock | Adding an unvetted external dependency is out of scope for this task, and the design itself requires the public contract not to depend on Flamingock types | The adapter is provider-neutral: it consumes a platform-owned `FlamingockChangeUnitView`. Wiring an actual Flamingock distribution is a one-file change behind that view. | -| Testkit as its own Gradle module | The design forbids production modules depending on the testkit | A dedicated `testkit` source set whose output is on the test compile/runtime classpaths only. ArchUnit rule `productionNeverDependsOnTestkit` enforces the direction. | -| Per-task `git commit` | `AGENTS.md`: commit policy is `human-only` | Implementation is delivered unstaged; commits are the human's action. This is the only plan step intentionally not executed, and it is recorded here. | -| `docs/mongodb/**`, `scripts/verify-mongodb-*.sh` | Repository already owns `docs/` and `scripts/` | Created at the same repository-relative paths. The two gate scripts were later removed (2026-08-15); see §5. | +| `modules/mongodb*` 아래 Gradle Kotlin DSL | Groovy DSL, root `build.gradle` convention, `LockMode.STRICT` 잠금 | 의존성은 `src/adapter/outbound/persistence-mongo/build.gradle`에 선언하고 `gradle.lockfile`을 다시 만들었다. | +| `mongodb-spring-boot-starter`는 앱이 의존하는 별도 모듈 | `modules.json`이 `adapter-outbound-persistence-mongo`에 명시적 프로젝트 경계를 준다. 런타임 편입은 leaf별 registry 필드가 아니라 해석한 런타임 classpath에서 정해진다 | `autoconfigure` package는 leaf 안에 두고 leaf 자신의 `META-INF/spring/…AutoConfiguration.imports`로 등록한다. httpclient 선례와 다르다. leaf를 실제로 조립하는지는 의존성 게이트와 런타임 편입 게이트가 정한다. | +| Spring Boot 4.1 / Spring Data MongoDB 5.1 기준 | 저장소 기준은 Spring Boot 4.0 계열 / Spring Data MongoDB 5.0 계열이다. 정확한 버전은 `src/gradle/libs.versions.toml`의 `springBoot`와 leaf의 `gradle.lockfile`이다 | 플랫폼은 둘에 공통인 Spring Data MongoDB **API 면**만 쓴다. 5.1에만 있는 타입은 참조하지 않는다. 실제 고정 버전은 support matrix가 가리킨다. | +| `MongoRetryScope`는 `mongodb-transaction`에 있다 | `mongodb-spring-data`의 실패 변환기가 재시도 범위를 분류해야 하는데 `mongodb-transaction`에 의존할 수 없다 | `MongoRetryScope`는 두 package가 이미 의존하는 `…api.error`(core-api)에 둔다. 값도 뜻도 같고, DAG에서 놓일 수 있는 자리는 하나다. | +| `mongodb-migration-flamingock`은 Flamingock에 의존한다 | 검증하지 않은 외부 의존성을 더하는 것은 이 작업 범위 밖이었다. 설계도 공개 계약이 Flamingock 타입에 의존하지 않기를 요구한다 | 어댑터는 provider 중립이다. 플랫폼이 소유한 `FlamingockChangeUnitView`를 받는다. 실제 Flamingock 배포판을 잇는 일은 그 view 뒤의 파일 하나만 바꾸면 된다. | +| Testkit은 따로 된 Gradle 모듈 | 설계는 production 모듈이 testkit에 의존하는 것을 금한다 | testkit은 `testFixtures` source set(ADR-BUILD-001)에 둔다. 컨테이너가 필요한 provider fixture는 별도 `mongoProviderTestkit` source set에 두어 보통 단위 테스트가 Testcontainers를 얻지 않게 한다. 방향은 `MongoModuleBoundaryTest`의 `noProductionPackageDependsOnTheTestkit`이 강제한다. | +| 작업마다 `git commit` | `AGENTS.md`: 커밋 정책은 `human-only` | 구현은 stage하지 않은 채 넘겼고, 커밋은 사람이 했다. 계획 중 일부러 실행하지 않은 단계는 이것 하나이고, 여기 적어 둔다. | +| `docs/mongodb/**`, `scripts/verify-mongodb-*.sh` | 저장소가 이미 `docs/`와 `scripts/`를 가진다 | 같은 저장소 상대 경로에 만들었다. 게이트 스크립트 둘은 지금도 있다(5절). | -## 4. What is unchanged from the design +## 4. 설계에서 바뀌지 않은 것 -- D1 / D2 / D3 / D4 exposure planes and the ordered D3 admission sequence (§5). -- Stable API V1 with `apiStrict=true` on the D1/D2 client generation; D3/D4 on separate generations. -- `MongoExecutionOutcome`, including both ambiguous outcomes (`WRITE_RESULT_UNKNOWN`, - `TRANSACTION_COMMIT_UNKNOWN`), and `MongoFailureContext`'s permitted-field list. -- The complete stable exception hierarchy and the label-before-code classification order. -- The BSON representation manifest (UUID `STANDARD`, `Decimal128`, UTC instants, alias type metadata) - and the document-size budget. -- Update-operator-first writes, and optimistic revision as the precondition for whole-document - replacement. -- Transaction body retry and commit retry as separate loops: a new session per body attempt, and - commit-only retry on unknown commit. The body is never replayed after a commit ambiguity. -- Registered operation names and manifests for query, aggregation and index; no free-form JSON query - and no unbounded pipeline. -- Keyset pagination with an authenticated cursor and a unique tie-breaker requirement. -- TTL as physical cleanup only, never the sole basis for access denial or business scheduling. -- Manifest-owned index/validator state with an apply policy that never drops what it does not own. -- Low-cardinality observation tags, command redaction, and the credential reference indirection. -- The Stable release gate's evidence categories. The Advanced promotion requirements - (actual-topology evidence) are a review obligation in ADR-MONGO-ADV-001; no class checks them. +- D1 / D2 / D3 / D4 노출 plane과 순서가 정해진 D3 허가 절차(§5). +- D1/D2 client 세대에는 `apiStrict=true`인 Stable API V1. D3/D4는 별도 세대. +- 결과를 모르는 두 경우(`WRITE_RESULT_UNKNOWN`, `TRANSACTION_COMMIT_UNKNOWN`)를 포함한 + `MongoExecutionOutcome`, 그리고 `MongoFailureContext`가 허락하는 필드 목록. +- 안정된 예외 계층 전체와, 코드보다 label을 먼저 보는 분류 순서. +- BSON 표현 manifest(UUID `STANDARD`, `Decimal128`, UTC 순간, 별칭 타입 metadata)와 문서 크기 예산. +- update operator를 먼저 쓰는 쓰기, 그리고 문서 전체 교체의 선행 조건인 낙관적 revision. +- 별개 loop인 transaction 본문 재시도와 commit 재시도: 본문 시도마다 새 session, commit 결과를 모르면 + commit만 재시도. commit 결과를 모르면 본문을 다시 돌리지 않는다. +- query, aggregation, index의 등록된 연산 이름과 manifest. 자유 형식 JSON query와 상한 없는 pipeline은 + 없다. +- 인증한 cursor와 유일한 동률 처리 기준을 요구하는 keyset 페이지 나누기. +- TTL은 물리적 정리일 뿐이다. 접근 거부나 업무 일정의 유일한 근거가 아니다. +- manifest가 소유한 index/validator 상태와, 소유하지 않은 것은 절대 지우지 않는 적용 정책. +- 가짓수가 적은 관측 tag, 명령 가리기, credential 참조 간접화. +- Stable 릴리스 게이트의 증거 분류. Advanced 승격 요건(실제 토폴로지 증거)은 ADR-MONGO-ADV-001의 검토 + 의무다. 그것을 검사하는 클래스는 없다. `scripts/verify-mongodb-advanced.sh`는 빠진 증거를 보고할 뿐이다. -## 5. Verification +## 5. 검증 -The release-gate scripts `scripts/verify-mongodb-platform.sh` and -`scripts/verify-mongodb-advanced.sh` are present and wrap the named Gradle lanes with no-skip evidence -and promotion metadata. Use them when producing release/promotion evidence; the focused commands -below remain useful for local diagnosis. +릴리스 게이트 스크립트 `scripts/verify-mongodb-platform.sh`와 `scripts/verify-mongodb-advanced.sh`가 있다. +이름을 지정한 Gradle lane을 돌리고, 건너뛴 lane을 통과로 세지 않으며, 승격 정보를 보고한다. 릴리스·승격 +증거를 만들 때 쓴다. 아래 명령은 로컬 진단에 계속 쓸모가 있다. -From `src/`: +`src/`에서: ```bash ./gradlew :adapter:outbound:persistence-mongo:check --console=plain @@ -132,6 +132,6 @@ From `src/`: ./gradlew :app-bootstrap:architectureTest --console=plain ``` -The container-backed lanes the gate ran behind `MONGODB_DOCKER=1` — `mongoCompatibilityTest`, -`mongoMigrationTest`, `mongoSecurityIntegrationTest`, `mongoReplicaSetTest`, `mongoFailoverTest`, -`mongoPerformanceTest` — are now invoked by name or not at all. +컨테이너가 필요한 lane(`mongoCompatibilityTest`, `mongoMigrationTest`, `mongoSecurityIntegrationTest`, +`mongoReplicaSetTest`, `mongoFailoverTest`, `mongoPerformanceTest`)은 `check`에 들어 있지 않다. +`MONGODB_DOCKER=1 bash scripts/verify-mongodb-platform.sh`로 돌리거나, 이름으로 하나씩 돌린다. diff --git a/docs/mongodb/runbooks/failover.md b/docs/mongodb/runbooks/failover.md index 3f9df62c..374c43e5 100644 --- a/docs/mongodb/runbooks/failover.md +++ b/docs/mongodb/runbooks/failover.md @@ -1,98 +1,92 @@ --- -title: Runbook — MongoDB primary failover +title: Runbook — MongoDB primary 장애 조치(failover) category: mongodb severity: P2 owner: oncall last_updated: 2026-08-13 -status: active +status: 운영 --- -# Runbook: MongoDB primary failover +# Runbook: MongoDB primary 장애 조치(failover) -Design §29, scenarios `PRIMARY_KILL`, `NETWORK_PARTITION`, `SERVER_SELECTION_TIMEOUT`, +설계서 §29, 시나리오 `PRIMARY_KILL`, `NETWORK_PARTITION`, `SERVER_SELECTION_TIMEOUT`, `WRITE_RESPONSE_LOSS`. -## Symptoms +## 증상 -- `MongoServerSelectionException` / `MongoConnectionException` spike, then recovery within seconds. -- `MongoSdamObservationListener` reports a topology change (primary removed, new primary elected). -- `MongoPoolObservationListener` shows checkout wait times rising while server-side command duration - stays flat — the wait is topology, not query cost. -- Latency spike on writes with no corresponding rise in read latency. +- `MongoServerSelectionException` / `MongoConnectionException`이 치솟았다가 몇 초 안에 회복한다. +- `MongoSdamObservationListener`가 토폴로지 변화를 보고한다(primary 빠짐, 새 primary 선출). +- `MongoPoolObservationListener`에서 connection checkout 대기 시간은 오르는데 서버 쪽 명령 시간은 평평하다. + 기다린 원인은 query 비용이 아니라 토폴로지다. +- 쓰기 지연이 치솟는데 읽기 지연은 그만큼 오르지 않는다. -A failover that resolves in under ~15 s and produces no `WRITE_RESULT_UNKNOWN` is normal replica-set -behaviour and needs no action beyond confirming it self-healed. +약 15초 안에 끝나고 `WRITE_RESULT_UNKNOWN`을 만들지 않은 failover는 정상적인 replica set 동작이다. +스스로 회복했는지 확인하는 것 말고는 할 일이 없다. -## Diagnosis +## 진단 -1. Confirm an election actually happened. SDAM events distinguish an election from "the database got - slow"; without them the two are indistinguishable in application metrics. -2. Split the failure categories. Metric tag `failureCategory`: - - `SERVER_SELECTION` / `CONNECTION` → the driver could not reach a primary. `NOT_SENT`; safe. - - `TIMEOUT` with outcome `WRITE_RESULT_UNKNOWN` → a write may have applied. Not safe; see below. - - `TRANSACTION_COMMIT_UNKNOWN` → go to [unknown-commit.md](unknown-commit.md) instead. -3. Check the election duration against `MongoRetryBudget`. If the election outlasted the budget, the - retries were exhausted before a primary existed and callers saw errors that a longer budget would - have absorbed. -4. Check whether the new primary is in the expected region/AZ. A failover to a distant node changes - write latency permanently, not transiently. +1. 선출이 실제로 있었는지 확인한다. SDAM 이벤트가 있어야 선출과 「DB가 느려졌다」를 구분한다. 없으면 + 애플리케이션 metric으로는 둘을 구분할 수 없다. +2. 실패 분류를 나눈다. Metric tag `failureCategory`: + - `SERVER_SELECTION` / `CONNECTION` → driver가 primary에 닿지 못했다. `NOT_SENT`이고 안전하다. + - 결과가 `WRITE_RESULT_UNKNOWN`인 `TIMEOUT` → 쓰기가 적용됐을 수 있다. 안전하지 않다. 아래를 본다. + - `TRANSACTION_COMMIT_UNKNOWN` → 대신 [unknown-commit.md](unknown-commit.md)로 간다. +3. 선출에 걸린 시간을 `MongoRetryBudget`과 비교한다. 선출이 예산보다 길었으면 primary가 생기기 전에 + 재시도를 다 써 버렸고, 예산이 더 길었으면 흡수했을 오류를 호출자가 봤다. +4. 새 primary가 기대한 region/AZ에 있는지 본다. 먼 노드로 failover하면 쓰기 지연이 잠깐이 아니라 계속 + 바뀐다. -## Action +## 조치 -**Self-healed (the common case).** -Confirm outcome distribution contains no `WRITE_RESULT_UNKNOWN`, record the election in the incident -log, and close. Nothing to replay. +**스스로 회복했다(흔한 경우).** +결과 분포에 `WRITE_RESULT_UNKNOWN`이 없는지 확인하고, 선출을 장애 기록에 남기고 닫는다. 다시 돌릴 것은 없다. -**Writes with `WRITE_RESULT_UNKNOWN`.** -These writes may or may not have applied. Do not blind-retry. -- Idempotent operation (registered `MongoUpdateOperator` with an `AtomicFilter` precondition): retry. - The precondition makes the second application a no-op. -- Non-idempotent operation: reconcile by reading the target document and comparing against the - intended post-state. Retry only if it does not reflect the write. +**`WRITE_RESULT_UNKNOWN`인 쓰기가 있다.** +이 쓰기는 적용됐을 수도, 아닐 수도 있다. 확인 없이 재시도하지 않는다. +- 멱등 연산(`AtomicFilter` 선행 조건이 붙은 등록된 `MongoUpdateOperator`): 재시도한다. 선행 조건 덕분에 + 두 번째 적용은 아무 일도 하지 않는다. +- 멱등이 아닌 연산: 대상 문서를 읽어 의도한 결과 상태와 비교해 맞춰 본다. 쓰기가 반영되지 않았을 때만 + 재시도한다. -**Server selection never recovers.** -The set has lost quorum — two of three nodes are down or partitioned. No client-side action fixes -this; escalate to the database owner to restore a majority. The application should be failing closed, -not queueing. +**server selection이 끝내 회복하지 않는다.** +set이 quorum을 잃었다. 노드 셋 중 둘이 죽었거나 끊겼다. client 쪽에서 고칠 방법은 없다. 과반을 되살리도록 +DB 소유자에게 올린다. 애플리케이션은 큐에 쌓지 않고 닫힌 쪽으로 실패하고 있어야 한다. -**Elections are frequent (more than one a day, unprompted).** -This is an infrastructure symptom, not an application one: check node resource saturation, disk -latency on the primary, and network stability between members. Repeated elections cause repeated -unknown-outcome windows. +**선출이 잦다(이유 없이 하루 한 번 넘게).** +애플리케이션이 아니라 인프라 증상이다. 노드 자원 포화, primary의 디스크 지연, member 사이 네트워크 안정성을 +본다. 선출이 반복되면 결과를 모르는 구간도 반복된다. -## Escalation +## 상향 보고 -- P2 → P1 if server selection has failed for more than 2 minutes, or if any non-idempotent write - returned `WRITE_RESULT_UNKNOWN` and cannot be reconciled. -- Page the database owner for quorum loss, and the service owner for reconciliation of ambiguous - writes. +- server selection이 2분 넘게 실패했거나, 멱등이 아닌 쓰기가 `WRITE_RESULT_UNKNOWN`을 돌려받고 맞춰 볼 수 + 없으면 P2 → P1. +- quorum 손실은 DB 소유자를, 결과를 모르는 쓰기를 맞춰 보는 일은 서비스 소유자를 호출한다. -## Verification +## 확인 -The failover lane reproduces this deliberately: +failover lane이 이 상황을 일부러 재현한다. ```bash cd src ./gradlew :adapter:outbound:persistence-mongo:mongoFailoverTest --console=plain ``` -It starts a real three-node set (`MongoThreeNodeReplicaSet`), stops the primary -(`MongoPrimaryController`), and injects network faults through Toxiproxy -(`ToxiproxyMongoNetworkFaultController`). A single-node set is not sufficient for the election: it -never holds one, so every guarantee that depends on a primary change goes untested. +이 lane은 실제 노드 세 개짜리 set(`MongoThreeNodeReplicaSet`)을 띄우고, primary를 멈추고 +(`MongoPrimaryController`), Toxiproxy로 네트워크 장애를 넣는다(`ToxiproxyMongoNetworkFaultController`). +노드 하나짜리 set으로는 선출을 시험할 수 없다. 선출이 일어나지 않으니 primary 교체에 기대는 보장은 모두 +시험되지 않는다. -The network faults need their own fixture (`MongoProxiedReplicaSetNode`) because a stopped container -cannot produce them. Stopping a node tells the client the write did not happen; cutting the *path* -while the server keeps running produces a client that cannot tell. `MongoNetworkFaultLaneTest` -asserts the difference by reaching the same server twice — once through the proxy, once directly: +네트워크 장애에는 따로 fixture(`MongoProxiedReplicaSetNode`)가 필요하다. 멈춘 container로는 만들 수 없기 +때문이다. 노드를 멈추면 client는 쓰기가 일어나지 않았다는 것을 안다. 서버는 살려 둔 채 *경로*를 끊으면 +client는 알 수 없다. `MongoNetworkFaultLaneTest`는 같은 서버에 두 번 닿아 그 차이를 단언한다. 한 번은 +proxy를 거쳐, 한 번은 바로. -- **Partition**: the proxied client fails, the direct client finds the server healthy and the earlier - write intact. The path was cut, not the server. -- **Response loss**: the proxied client fails, and the direct client then finds the document - *present*. The write applied and only the acknowledgement was lost — - `DefaultMongoFailureClassifier` returns `WRITE_RESULT_UNKNOWN`, and a retry would have inserted a - second document. +- **분할**: proxy를 거친 client는 실패하고, 바로 닿은 client는 서버가 멀쩡하고 앞서 쓴 것이 그대로임을 + 본다. 끊긴 것은 서버가 아니라 경로다. +- **응답 유실**: proxy를 거친 client는 실패하고, 바로 닿은 client는 문서가 *있음*을 본다. 쓰기는 적용됐고 + 확인 응답만 사라졌다. `DefaultMongoFailureClassifier`는 `WRITE_RESULT_UNKNOWN`을 돌려준다. 재시도했다면 + 문서가 하나 더 생겼을 것이다. -One detail the lane depends on: the connection is warmed before the toxic is applied. On a cold -connection it is the driver's handshake whose response is dropped, so the write is never transmitted -— `NOT_SENT`, the opposite of the ambiguity being tested. +lane이 기대는 세부가 하나 있다. toxic을 걸기 전에 connection을 먼저 데운다. 차가운 connection에서는 +응답이 사라지는 것이 driver의 handshake이므로 쓰기는 아예 전송되지 않는다. 그러면 `NOT_SENT`가 되어 +시험하려던 「결과를 모름」과 정반대가 된다. diff --git a/docs/mongodb/runbooks/unknown-commit.md b/docs/mongodb/runbooks/unknown-commit.md index 164b1576..8799f965 100644 --- a/docs/mongodb/runbooks/unknown-commit.md +++ b/docs/mongodb/runbooks/unknown-commit.md @@ -1,87 +1,80 @@ --- -title: Runbook — MongoDB unknown transaction commit result +title: Runbook — MongoDB transaction commit 결과를 모름 category: mongodb severity: P1 owner: oncall last_updated: 2026-08-13 -status: active +status: 운영 --- -# Runbook: unknown transaction commit result +# Runbook: transaction commit 결과를 모름 -Design §16, decision D-10, scenario `UNKNOWN_TRANSACTION_COMMIT_RESULT`. +설계서 §16, 결정 D-10, 시나리오 `UNKNOWN_TRANSACTION_COMMIT_RESULT`. -`MongoExecutionOutcome.TRANSACTION_COMMIT_UNKNOWN` means the commit **may have applied**. It is not a -failure and must never be reported to a caller as one. The single worst response is to re-run the -transaction body: if the commit did apply, the body applies a second time. +`MongoExecutionOutcome.TRANSACTION_COMMIT_UNKNOWN`은 commit이 **적용됐을 수 있다**는 뜻이다. 실패가 아니고, +호출자에게 실패로 알리면 절대 안 된다. 가장 나쁜 대응은 transaction 본문을 다시 돌리는 것이다. commit이 +적용됐다면 본문이 두 번 적용된다. -## Symptoms +## 증상 -- `MongoTransactionCommitUnknownException` in logs. +- 로그의 `MongoTransactionCommitUnknownException`. - Metric `failureCategory=TRANSACTION_COMMIT_UNKNOWN`. -- Usually accompanies a primary election — see [failover.md](failover.md). -- Downstream reports of duplicated effects (double charge, double increment) are the symptom of this - being handled wrongly, not of the condition itself. +- 보통 primary 선출과 함께 온다. [failover.md](failover.md)를 본다. +- 하류에서 효과가 두 번 났다는 보고(이중 결제, 이중 증가)는 이 상황 자체가 아니라 이것을 잘못 다룬 결과다. -## Diagnosis +## 진단 -1. **Confirm the platform did the right thing automatically.** - `MongoTransactionRetryCoordinator` retries the *commit only*, on the same session, within - `MongoRetryBudget`. A commit retry against an already-committed transaction is a no-op by design. - Most occurrences resolve here and never reach a human. +1. **플랫폼이 자동으로 옳게 했는지 확인한다.** + `MongoTransactionRetryCoordinator`는 같은 session에서 `MongoRetryBudget` 안에서 *commit만* 재시도한다. + 이미 commit된 transaction에 대한 commit 재시도는 설계상 아무 일도 하지 않는다. 대부분은 여기서 끝나고 + 사람에게 오지 않는다. -2. **If the budget was exhausted, determine the actual state.** The commit either applied or it did - not; you must find out which, not guess. - - If the transaction body wrote a deterministic marker (an idempotency key, a business id, a - revision), read it back. That is exactly what `MongoCommitReconciler` does, and it is the - reason the design requires transactions to write one. - - If there is no marker: reconstruct from a downstream artefact — an outbox row, an audit record, - an external side effect. If nothing exists to compare against, the transaction was not - designed to be reconcilable and that is the finding to record. +2. **예산을 다 썼으면 실제 상태를 알아낸다.** commit은 적용됐거나 안 됐다. 짐작하지 말고 어느 쪽인지 + 알아내야 한다. + - 본문이 결정적 표시(멱등 key, 업무 id, revision)를 썼으면 그것을 다시 읽는다. `MongoCommitReconciler`가 + 하는 일이 정확히 이것이고, 설계가 transaction에 표시를 쓰라고 요구하는 이유다. + - 표시가 없으면 하류 흔적에서 되짚는다: outbox 행, 감사 기록, 외부 부수 효과. 비교할 것이 아무것도 + 없으면 그 transaction은 맞춰 볼 수 있게 설계되지 않은 것이고, 그것을 발견 사항으로 적는다. -3. **Check whether the body was replayed.** Grep for a second execution with the same operation name - and correlation id. If the body ran twice, the effects need reversing, and the code path that - replayed it is a defect: an ambiguous commit is `COMMIT_ONLY` scope - (`MongoRetryScope.COMMIT_ONLY`), never `BODY`. +3. **본문이 다시 돌았는지 본다.** 같은 연산 이름과 correlation id로 두 번째 실행이 있는지 grep한다. 본문이 + 두 번 돌았으면 효과를 되돌려야 하고, 다시 돌린 코드 경로는 결함이다. 결과를 모르는 commit의 범위는 + `COMMIT_ONLY`(`MongoRetryScope.COMMIT_ONLY`)이고 `BODY`가 아니다. -## Action +## 조치 -**Commit applied.** Nothing to do. Record the reconciliation. +**commit이 적용됐다.** 할 일은 없다. 맞춰 본 결과를 기록한다. -**Commit did not apply.** Re-run the whole operation from the top — a new session, a new body -attempt. This is safe precisely because you established the previous attempt left no trace. +**commit이 적용되지 않았다.** 연산 전체를 처음부터 다시 돌린다. 새 session, 새 본문 시도. 앞 시도가 흔적을 +남기지 않았음을 확인했으므로 안전하다. -**Cannot determine.** Do not retry. Escalate. A blind retry here is a coin flip between "no effect" -and "duplicate effect", and duplicates in a financial or notification path are worse than a delay. -Freeze the affected entity if the domain supports it, and hand off with: operation name, correlation -id, document id, the time window, and what you checked. +**알아낼 수 없다.** 재시도하지 않는다. 상향 보고한다. 여기서 확인 없이 재시도하면 「효과 없음」과 +「효과 두 번」 사이의 동전 던지기다. 결제나 알림 경로에서는 중복이 지연보다 나쁘다. 도메인이 지원하면 +대상 엔티티를 얼리고, 연산 이름, correlation id, 문서 id, 시간 구간, 확인한 것을 넘긴다. -**Recurring.** More than one an hour means the commit path is racing something structural — a -`maxCommitTime` shorter than the observed election duration, an oversized transaction, or an -undersized retry budget. Fix the budget or the transaction shape; do not raise the retry count and -call it resolved. +**반복된다.** 한 시간에 한 번을 넘으면 commit 경로가 구조적인 무언가와 경쟁하고 있다. 관측한 선출 시간보다 +짧은 `maxCommitTime`, 너무 큰 transaction, 너무 작은 재시도 예산 같은 것이다. 예산이나 transaction 모양을 +고친다. 재시도 횟수만 올리고 해결됐다고 하지 않는다. -## Prevention +## 예방 -- Every transaction body writes a deterministic marker that identifies its own commit. -- `maxCommitTime` exceeds the observed p99 election duration. -- Callers surface the ambiguity to their own callers rather than mapping it to a generic 500 — an - ambiguous outcome reported as a failure invites the caller to retry, which is the one thing that - must not happen. -- Prefer a single-document atomic operation (D-09). A transaction that exists only to wrap one - document write has invented this failure mode for nothing. +- 모든 transaction 본문은 자기 commit을 식별하는 결정적 표시를 쓴다. +- `maxCommitTime`은 관측한 선출 시간의 p99보다 길다. +- 호출자는 결과를 모른다는 사실을 일반 500으로 바꾸지 않고 자기 호출자에게 그대로 올린다. 결과를 모르는 + 것을 실패로 알리면 호출자가 재시도하고, 그것이 일어나면 안 되는 단 하나의 일이다. +- 문서 하나의 atomic 연산을 먼저 쓴다(D-09). 문서 하나의 쓰기를 감싸려고만 있는 transaction은 이 실패 + 모드를 쓸데없이 만든 것이다. -## Escalation +## 상향 보고 -- Always P1 when the state cannot be determined and the operation has an external effect. -- Page the service owner immediately; the database owner only if elections are the trigger. +- 상태를 알아낼 수 없고 연산에 외부 효과가 있으면 늘 P1. +- 서비스 소유자를 바로 호출한다. DB 소유자는 선출이 원인일 때만 호출한다. -## Verification +## 확인 ```bash cd src ./gradlew :adapter:outbound:persistence-mongo:mongoFailoverTest --console=plain ``` -`MongoFailoverScenario.UNKNOWN_TRANSACTION_COMMIT_RESULT` runs this path against a real three-node -set, and the coordinator test asserts the body is never replayed after a commit ambiguity. +`MongoFailoverScenario.UNKNOWN_TRANSACTION_COMMIT_RESULT`가 이 경로를 실제 노드 세 개짜리 set에서 돌리고, +coordinator 테스트가 commit 결과를 모를 때 본문을 다시 돌리지 않음을 단언한다. diff --git a/docs/mongodb/schema-index-migration-guide.md b/docs/mongodb/schema-index-migration-guide.md index bf6913d6..f9150be8 100644 --- a/docs/mongodb/schema-index-migration-guide.md +++ b/docs/mongodb/schema-index-migration-guide.md @@ -1,137 +1,130 @@ -# Schema, Index and Migration Guide +# Schema, index, 마이그레이션 가이드 -Design §21–§25, decision D-13. Indexes and validators are **declared** in a manifest and **applied** -by an explicit plane. Automatic index creation in production is explicitly unsupported (§3.4): an -index build on a large collection is a capacity event, and discovering it because a deployment -started one is not an operating model. +설계서 §21–§25, 결정 D-13. index와 validator는 manifest에 **선언**하고, 명시적인 plane이 **적용**한다. +운영에서 index를 자동으로 만드는 것은 명시적으로 지원하지 않는다(§3.4). 큰 collection의 index 생성은 용량 +사건이다. 배포가 그것을 시작해서야 알게 되는 것은 운영 방식이라 할 수 없다. -## 1. The manifest is the source of truth +## 1. Manifest가 정본이다 -`MongoManifestRegistry` holds one `MongoCollectionManifest` per collection, containing: +`MongoManifestRegistry`는 collection마다 `MongoCollectionManifest`를 하나 가진다. 그 안에 있는 것: -- `MongoIndexManifest` — the declared indexes (`MongoIndexKey`, `MongoIndexDirection`, uniqueness, - partial filter, collation) -- `MongoSchemaManifest` — the declared `$jsonSchema` validator -- `MongoMetadataOwnership` — who owns each observed object +- `MongoIndexManifest` — 선언한 index(`MongoIndexKey`, `MongoIndexDirection`, unique 여부, partial + filter, collation) +- `MongoSchemaManifest` — 선언한 `$jsonSchema` validator +- `MongoMetadataOwnership` — 관측한 객체마다 누가 소유하는지 -Ownership is the field that makes drift handling safe: +drift(선언과 실제의 차이) 처리를 안전하게 만드는 것이 소유 필드다. -| Ownership | Owner | Droppable on drift | +| 소유 | 소유자 | drift일 때 지워도 되나 | |---|---|---| -| `APPLICATION_MANAGED` | this manifest | yes | -| `SEARCH_MANAGED` | the search service | no | -| `ENCRYPTION_MANAGED` | Queryable Encryption | no | -| `EXTERNAL` | someone else (a DBA, another service) | no | +| `APPLICATION_MANAGED` | 이 manifest | 그렇다 | +| `SEARCH_MANAGED` | 검색 서비스 | 아니다 | +| `ENCRYPTION_MANAGED` | Queryable Encryption | 아니다 | +| `EXTERNAL` | 다른 누군가(DBA, 다른 서비스) | 아니다 | -A diff engine that does not know about ownership eventually proposes dropping -`enxcol_.customers.esc` or a search index, and "the drift tool cleaned it up" is a very bad incident -summary. +소유를 모르는 diff 엔진은 결국 `enxcol_.customers.esc`나 검색 index를 지우자고 한다. 「drift 도구가 +정리했다」는 아주 나쁜 장애 요약이다. -## 2. Index diff and apply +## 2. Index diff와 적용 -`MongoIndexDiffEngine` compares the manifest against `MongoIndexDescriptorView` observations and -produces a `MongoIndexDiff`: missing, extra, and *changed* (same name, different definition — -MongoDB will not silently rebuild these, so they must be reported rather than re-issued). +`MongoIndexDiffEngine`은 manifest를 `MongoIndexDescriptorView` 관측값과 비교해 `MongoIndexDiff`를 만든다: +빠진 것, 남는 것, *바뀐* 것(이름은 같고 정의가 다름. MongoDB는 이것을 조용히 다시 만들지 않으므로 다시 +내보내지 말고 보고해야 한다). -`MongoIndexApplyPolicy` decides what happens with a diff: +`MongoIndexApplyPolicy`가 diff로 무엇을 할지 정한다. -| Policy | Behaviour | Environment | +| 정책 | 동작 | 환경 | |---|---|---| -| `APPLY` | create what is missing | local / test | -| `APPLY_WITH_DIFF` | create what is missing and report the rest | staging | -| `DIFF_WITH_APPROVED_APPLY` | apply only what a human approved | production | -| `REPORT_ONLY` | never write | audit | +| `APPLY` | 빠진 것을 만든다 | local / test | +| `APPLY_WITH_DIFF` | 빠진 것을 만들고 나머지는 보고한다 | staging | +| `DIFF_WITH_APPROVED_APPLY` | 사람이 승인한 것만 적용한다 | production | +| `REPORT_ONLY` | 절대 쓰지 않는다 | 감사 | -Dropping is never implicit. `MongoIndexRetirementPlan` moves an index through -`MongoIndexRetirementState` — declared → hidden → observed-unused → droppable — and each transition -is a separate deployment. Hiding an index makes the planner ignore it while keeping it maintained, so -an unexpected regression is one command to undo. Dropping it is not. +삭제는 암묵적으로 일어나지 않는다. `MongoIndexRetirementPlan`이 index를 `MongoIndexRetirementState`로 +옮긴다 — 선언됨 → 숨김 → 안 쓰임 관측 → 지워도 됨 — 그리고 단계마다 따로 배포한다. index를 숨기면 +planner는 무시하지만 유지는 계속된다. 그래서 뜻밖의 회귀는 명령 하나로 되돌린다. 지운 것은 그렇게 되돌릴 +수 없다. -## 3. Validators +## 3. Validator -`MongoValidatorDescriptor` carries the `$jsonSchema`, a `MongoValidationLevel` -(`OFF` / `MODERATE` / `STRICT`) and a `MongoValidationAction`. +`MongoValidatorDescriptor`는 `$jsonSchema`, `MongoValidationLevel`(`OFF` / `MODERATE` / `STRICT`), +`MongoValidationAction`을 가진다. -**Stable validation actions are `error` and `warn` only.** `errorAndLog` is not part of the Stable -contract on MongoDB 7.0 or 8.0 and the descriptor refuses it. +**Stable validation action은 `error`와 `warn`뿐이다.** `errorAndLog`는 MongoDB 7.0이나 8.0에서 Stable 계약에 +들지 않고, descriptor가 거부한다. -`MongoValidatorDiffEngine` produces a `MongoValidatorDiff`; `MongoValidatorApplyPolicy` gates the -apply. Tightening a validator on a collection with existing data is the dangerous direction: introduce -it as `warn` + `MODERATE`, confirm the warning count is zero, then promote to `error` + `STRICT` in a -second deployment. +`MongoValidatorDiffEngine`이 `MongoValidatorDiff`를 만들고 `MongoValidatorApplyPolicy`가 적용을 막거나 +허락한다. 데이터가 이미 있는 collection의 validator를 조이는 것이 위험한 방향이다. `warn` + `MODERATE`로 +넣고, 경고 수가 0인지 확인한 뒤, 두 번째 배포에서 `error` + `STRICT`로 올린다. ## 4. TTL -D-13: TTL is **physical cleanup**, nothing else. +D-13: TTL은 **물리적 정리**일 뿐이다. -`MongoTtlIndexDescriptor` declares the field and `expireAfterSeconds`. `MongoTtlPolicyValidator` -enforces what `MongoTtlPolicy` allows, and `MongoExpirationAccessPolicy` states the rule that matters: +`MongoTtlIndexDescriptor`가 필드와 `expireAfterSeconds`를 선언한다. `MongoTtlPolicyValidator`가 +`MongoTtlPolicy`가 허락하는 것을 강제하고, `MongoExpirationAccessPolicy`가 중요한 규칙을 말한다. -> A document's presence is not authorization, and its absence is not a deadline. +> 문서가 있다고 권한이 있는 것이 아니고, 문서가 없다고 기한이 지난 것도 아니다. -The TTL monitor runs about once a minute and deletes in batches, so a document can outlive its -expiry by minutes to hours under load. Consequences: +TTL monitor는 대략 1분에 한 번 돌고 묶어서 지운다. 그래서 부하가 있으면 문서가 만료 후 몇 분에서 몇 시간 +더 남는다. 따라서: -- Access control must check the expiry field, not the document's existence. A still-present expired - session is a valid document and an invalid session. -- Business scheduling must not be built on TTL. If something must happen at a time, schedule it. -- A TTL field must be a BSON date. A TTL index on a string silently never deletes anything. +- 접근 제어는 문서가 있는지가 아니라 만료 필드를 본다. 아직 남아 있는 만료된 session은 유효한 문서이자 + 무효한 session이다. +- 업무 일정을 TTL 위에 세우지 않는다. 정해진 때에 일어나야 하는 일이면 일정을 잡는다. +- TTL 필드는 BSON date여야 한다. 문자열에 건 TTL index는 조용히 아무것도 지우지 않는다. -## 5. Migrations +## 5. 마이그레이션 -`MongoMigrationRunner` executes `MongoMigration` units with: +`MongoMigrationRunner`는 다음과 함께 `MongoMigration` 단위를 실행한다. -- `MongoMigrationId` — ordered, unique -- `MongoMigrationChecksum` — content hash; a changed checksum for an applied id is a hard failure, not - a re-run. Editing an applied migration means two environments ran different code under the same id. -- `MongoMigrationLedger` — what has been applied -- `MongoMigrationLock` — one runner at a time; a rolling deploy starts several instances at once -- `MongoMigrationPrecondition` / `MongoMigrationPostcondition` — checked before and after; a migration - that cannot verify its own result is a migration whose failure is discovered by a customer -- `MongoMigrationCheckpoint` — a resumable position for a backfill +- `MongoMigrationId` — 순서가 있고 유일하다 +- `MongoMigrationChecksum` — 내용 hash. 이미 적용한 id의 checksum이 바뀌면 다시 돌리지 않고 바로 실패한다. + 적용한 마이그레이션을 고치면 두 환경이 같은 id로 다른 코드를 돌린 것이 된다. +- `MongoMigrationLedger` — 무엇이 적용됐는지 +- `MongoMigrationLock` — 한 번에 runner 하나. rolling 배포는 인스턴스 여럿을 한꺼번에 띄운다 +- `MongoMigrationPrecondition` / `MongoMigrationPostcondition` — 전후로 확인한다. 자기 결과를 확인하지 + 못하는 마이그레이션은 실패를 고객이 발견한다 +- `MongoMigrationCheckpoint` — backfill을 이어 할 수 있는 위치 -`MongoMigrationResult` reports applied / incomplete / dry-run with the reason. `INCOMPLETE` is not a -failure: a rate-limited backfill that ran out of its time budget has done real work and stored a -checkpoint, and reporting it as failed would send the next run back to the beginning. +`MongoMigrationResult`는 applied / incomplete / dry-run과 그 이유를 보고한다. `INCOMPLETE`는 실패가 아니다. +속도를 제한한 backfill이 시간 예산을 다 썼으면 실제 일을 했고 checkpoint를 저장했다. 그것을 실패로 알리면 +다음 실행이 처음으로 돌아간다. -`MongoCollectionMigrationLedger` and `MongoCollectionMigrationLock` are the MongoDB-backed -implementations. Two details are load-bearing and only exist on a server: +`MongoCollectionMigrationLedger`와 `MongoCollectionMigrationLock`이 MongoDB에 기대는 구현이다. 빠지면 안 +되는 세부가 둘 있고, 둘 다 서버에만 있다. -- The ledger's **unique index** on the migration id, created by `ensureIndexes()`. Without it, two - runners that both pass the "not applied yet" read both insert, and the ledger then reports one - migration applied twice with two checksums — indistinguishable from tampering. -- The lease is taken with **one conditional update**, not read-then-write. A filter matching only a - free or expired lease lets the server pick the winner; two runners that each read "free" and then - write would both believe they hold it. +- `ensureIndexes()`가 만드는 ledger의 마이그레이션 id **unique index**. 이것이 없으면 「아직 적용 안 됨」 + 읽기를 둘 다 통과한 runner 둘이 둘 다 insert한다. 그러면 ledger는 마이그레이션 하나가 checksum 둘로 두 번 + 적용됐다고 보고한다. 조작과 구분할 수 없다. +- lease는 읽고-쓰기가 아니라 **조건부 update 한 번**으로 잡는다. 비었거나 만료된 lease에만 맞는 filter를 + 쓰면 서버가 승자를 고른다. runner 둘이 각자 「비었음」을 읽고 쓰면 둘 다 자기가 잡았다고 믿는다. -The lease expires so a runner killed mid-migration does not block every future deployment, and -`refresh` between batches is what proves the holder is still alive. +lease에는 만료가 있다. 그래야 마이그레이션 도중 죽은 runner가 이후 모든 배포를 막지 않는다. batch 사이의 +`refresh`가 lease를 가진 쪽이 아직 살아 있다는 증거다. -### Backfills restart, they do not restart-from-zero +### Backfill은 이어서 시작하고, 처음부터 다시 하지 않는다 -A long backfill will be interrupted — a deploy, an OOM, a node replacement. The checkpoint records -the last completed key so the restart continues rather than re-processing from the beginning. -`MongoBackfillRestartFixture` in the testkit asserts exactly this: kill mid-run, restart, and the -result is identical to the uninterrupted run and does not re-apply completed work. +긴 backfill은 끊긴다. 배포, OOM, 노드 교체. checkpoint가 마지막으로 끝낸 key를 적어 두므로 다시 시작하면 +처음부터 다시 처리하지 않고 이어 간다. testkit의 `MongoBackfillRestartFixture`가 정확히 이것을 단언한다: +도중에 죽이고 다시 시작해도 결과가 끊기지 않은 실행과 같고, 끝낸 일을 다시 적용하지 않는다. ### Flamingock -`FlamingockMongoMigrationAdapter` bridges to Flamingock through the platform-owned -`FlamingockChangeUnitView`, with `FlamingockLedgerAdapter` and `FlamingockLockAdapter` mapping the -ledger and lock. The public contract does not reference Flamingock types, so the provider can be -replaced without touching a migration. +`FlamingockMongoMigrationAdapter`가 플랫폼이 소유한 `FlamingockChangeUnitView`를 거쳐 Flamingock에 +잇는다. `FlamingockLedgerAdapter`와 `FlamingockLockAdapter`가 ledger와 lock을 대응시킨다. 공개 계약은 +Flamingock 타입을 참조하지 않으므로 마이그레이션을 건드리지 않고 provider를 바꿀 수 있다. -## 6. Ordering with deployments +## 6. 배포와의 순서 -``` -1. Add the index (hidden if it is large) -> deployment N -2. Unhide / verify usage -> deployment N+1 -3. Ship code that depends on the index -> deployment N+1 -4. Backfill data -> migration, resumable -5. Tighten the validator from warn to error -> deployment N+2 -6. Retire the old index through the retirement states -> deployments N+3… +```text +1. index를 더한다(크면 숨긴 채로) -> 배포 N +2. 숨김을 풀고 쓰이는지 확인한다 -> 배포 N+1 +3. 그 index에 기대는 코드를 내보낸다 -> 배포 N+1 +4. 데이터를 backfill한다 -> 마이그레이션, 이어 할 수 있음 +5. validator를 warn에서 error로 조인다 -> 배포 N+2 +6. 옛 index를 은퇴 단계에 따라 내린다 -> 배포 N+3… ``` -Each step is independently reversible. A deployment that adds an index and the code that requires it -at the same time has no safe rollback: rolling back the code leaves the index build running, and -rolling back the index breaks the code that is still live on half the fleet. +단계마다 따로 되돌릴 수 있다. index와 그 index가 필요한 코드를 같은 배포에 넣으면 안전하게 되돌릴 길이 +없다. 코드를 되돌리면 index 생성은 계속 돌고, index를 되돌리면 아직 절반의 인스턴스에서 도는 코드가 깨진다. diff --git a/docs/mongodb/security-observability.md b/docs/mongodb/security-observability.md index dc140065..047bb276 100644 --- a/docs/mongodb/security-observability.md +++ b/docs/mongodb/security-observability.md @@ -1,148 +1,141 @@ -# Security and Observability +# 보안과 관측 -Design §26–§28, decision D-05. The application plane and the admin plane are different credentials on -different clients, and telemetry never becomes an exfiltration path. +설계서 §26–§28, 결정 D-05. 애플리케이션 plane과 admin plane은 다른 client 위의 다른 credential이다. +그리고 telemetry는 절대 데이터 유출 경로가 되지 않는다. -## 1. Roles +## 1. Role -`MongoPrincipalRole` — one credential per role, least privilege: +`MongoPrincipalRole` — role마다 credential 하나, 최소 권한: -| Role | Grants | +| Role | 주는 권한 | |---|---| -| `APP_READ` | `find` on allowlisted collections | -| `APP_WRITE` | `insert`, `update`, `delete` on allowlisted collections | +| `APP_READ` | 허용 목록 collection의 `find` | +| `APP_WRITE` | 허용 목록 collection의 `insert`, `update`, `delete` | | `CHANGE_STREAM` | `changeStream`, `find` | -| `MIGRATION` | index and validator management on the target collections | -| `SEARCH_ADMIN` | search index management | -| `SHARD_ADMIN` | shard key operations | -| `ENCRYPTION_ADMIN` | key vault access | -| `DBA` | the human plane; never used by an application | +| `MIGRATION` | 대상 collection의 index·validator 관리 | +| `SEARCH_ADMIN` | 검색 index 관리 | +| `SHARD_ADMIN` | shard key 작업 | +| `ENCRYPTION_ADMIN` | key vault 접근 | +| `DBA` | 사람의 plane. 애플리케이션은 절대 쓰지 않는다 | -`MongoSecurityProfileValidator` checks the profile at startup. `forbiddenPrivilegesHeld()` names the -privileges the profile holds and must not — the validator reports *which* one, because "your -credential is over-privileged" without a name is an unactionable finding. +`MongoSecurityProfileValidator`가 시작할 때 profile을 검사한다. `forbiddenPrivilegesHeld()`는 profile이 갖고 +있으면 안 되는데 가진 권한의 이름을 댄다. validator가 *어느* 권한인지 말하는 이유는, 이름 없이 「credential +권한이 너무 크다」고만 하면 대응할 수 없는 발견이기 때문이다. -The privileges that must never appear on an application credential: `dropDatabase`, -`dropCollection`, `shutdown`, `killop`, `root`, `__system`, `dbOwner`, `userAdminAnyDatabase`. +애플리케이션 credential에 절대 있으면 안 되는 권한: `dropDatabase`, `dropCollection`, `shutdown`, `killop`, +`root`, `__system`, `dbOwner`, `userAdminAnyDatabase`. -## 2. Credentials are references, not values +## 2. Credential은 값이 아니라 참조다 -`MongoCredentialReference` holds a `secret://…` reference plus the role. The reference is resolved at -connection time by the secret provider; the password is never a property value, a log field, or a -constructor argument that could end up in a stack trace. +`MongoCredentialReference`는 `secret://…` 참조와 role을 가진다. 참조는 연결할 때 secret provider가 푼다. +비밀번호는 속성 값, 로그 필드, stack trace에 남을 수 있는 생성자 인자가 절대 되지 않는다. -`MongoCredentialRotationPolicy` states the rotation contract: overlapping validity, a drain window, -and a rotation that never requires a restart. `MongoClientGenerationRegistry` implements the swap — -a new `MongoClientGeneration` starts serving new operations while the previous generation is -`markDraining()` until its in-flight operations finish. Killing the old client immediately fails every -in-flight request, which is why rotation without generations is an outage. +`MongoCredentialRotationPolicy`가 교체 계약을 말한다: 유효 기간이 겹치고, 비우는 구간(drain window)이 있고, +교체에 재시작이 필요 없다. `MongoClientGenerationRegistry`가 바꿔 끼우기를 구현한다. 새 +`MongoClientGeneration`이 새 연산을 받는 동안 앞 세대는 `markDraining()` 상태로 처리 중인 연산이 끝날 때까지 +남는다. 옛 client를 바로 죽이면 처리 중인 요청이 모두 실패한다. 세대 없는 교체가 장애인 이유다. -Rotation is a failover scenario in the release gate (`MongoFailoverScenario.CREDENTIAL_ROTATION`), -not a runbook step people hope works. +교체는 릴리스 게이트의 failover 시나리오(`MongoFailoverScenario.CREDENTIAL_ROTATION`)다. 잘 되기를 바라는 +runbook 단계가 아니다. -## 3. TLS and connection policy +## 3. TLS와 연결 정책 -`MongoSecurityProfile.production(...)` requires TLS and refuses `tlsAllowInvalidCertificates` / -`tlsAllowInvalidHostnames`. `MongoSecurityProfile.local(...)` exists so a developer does not have to -weaken the production factory to get a container to connect; the startup validator refuses a local -profile on a production runtime profile. +`MongoSecurityProfile.production(...)`은 TLS를 요구하고 `tlsAllowInvalidCertificates` / +`tlsAllowInvalidHostnames`를 거부한다. `MongoSecurityProfile.local(...)`이 있는 것은 개발자가 container에 +붙으려고 production factory를 약하게 만들지 않게 하려는 것이다. 시작 validator는 운영 runtime profile에서 +local profile을 거부한다. ## 4. Admin plane (D4) -`MongoAdminGateway` is the only path to `MongoAdminOperation`, and it runs on the D4 client with the -DBA-scoped credential — not the application's. +`MongoAdminGateway`가 `MongoAdminOperation`으로 가는 유일한 길이고, 애플리케이션 것이 아니라 DBA 범위 +credential을 쓰는 D4 client에서 돈다. -- `MongoAdminAuthorization` checks the caller's role against the operation. -- `MongoAdminRuntimeGuard` refuses high-risk operations (`highRisk()`) unless the runtime profile - explicitly permits them; a `dropCollection` reachable from a running application is a data-loss - vector regardless of how well-reviewed the calling code is. -- `MongoAdminAuditRecord` records who ran what, when and against which collection profile — before - execution, so a failed attempt is recorded too. +- `MongoAdminAuthorization`이 호출자의 role을 연산과 대조한다. +- `MongoAdminRuntimeGuard`는 runtime profile이 명시적으로 허락하지 않으면 위험한 연산(`highRisk()`)을 + 거부한다. 실행 중인 애플리케이션에서 닿을 수 있는 `dropCollection`은 호출 코드를 아무리 잘 검토했어도 + 데이터 손실 경로다. +- `MongoAdminAuditRecord`가 누가 무엇을, 언제, 어느 collection profile에 돌렸는지 실행 *전에* 기록한다. + 그래서 실패한 시도도 남는다. -The native capability gateway (D3) refuses any admin-category command, so there is no path from the -application plane into the admin plane. +native capability gateway(D3)는 admin 분류의 명령을 모두 거부한다. 그래서 애플리케이션 plane에서 admin +plane으로 가는 길은 없다. -## 5. Observability tags +## 5. 관측 tag -`MongoObservationConvention` allowlists exactly eight tag names: +`MongoObservationConvention`은 tag 이름을 정확히 여덟 개만 허용한다. ``` mongoProfile, databaseProfile, collectionProfile, operationName, operationType, result, failureCategory, consistencyProfile ``` -and explicitly forbids: +그리고 다음을 명시적으로 금지한다. ``` documentId, rawTenantId, tenantId, dynamicCollectionName, queryParameter, query, fullBson, resumeToken, shardKeyValue, plaintextPII, credential ``` -Two reasons, and both matter. Cardinality: a tag whose values are document ids produces one time -series per document, which is how a metrics backend falls over. Confidentiality: a metric label is -stored, shipped and retained by systems with a different access model than the database. -`requireAllowed(tagName)` throws on anything outside the list, so a new tag is a deliberate change to -the convention rather than a line in a service. +이유는 둘이고 둘 다 중요하다. 가짓수: 값이 문서 id인 tag는 문서마다 시계열 하나를 만들고, 그렇게 metric +저장소가 쓰러진다. 기밀성: metric label은 DB와 접근 모델이 다른 시스템이 저장하고, 보내고, 보관한다. +`requireAllowed(tagName)`는 목록 밖의 것에 예외를 던진다. 그래서 새 tag는 서비스 코드의 한 줄이 아니라 +convention의 의도적인 변경이 된다. -`MicrometerMongoOperationObserver` implements the `MongoOperationObserver` port; -`NoOpMongoOperationObserver` is the default so observation is opt-in and never a hard dependency. +`MicrometerMongoOperationObserver`가 `MongoOperationObserver` port를 구현한다. 기본값은 +`NoOpMongoOperationObserver`라서 관측은 켜야 생기고 필수 의존이 되지 않는다. -## 6. Driver-native listeners +## 6. Driver 자체 listener -`MongoDriverObservabilityConfiguration` registers three driver listeners, because they answer -questions the application-level timer cannot: +`MongoDriverObservabilityConfiguration`은 driver listener 셋을 등록한다. 애플리케이션 수준 timer로는 답할 수 +없는 질문에 답하기 때문이다. -| Listener | Answers | +| Listener | 답하는 질문 | |---|---| -| `MongoCommandObservationListener` | How long did the *server* take, versus how long the caller waited? | -| `MongoPoolObservationListener` | Was the wait time connection checkout rather than query execution? | -| `MongoSdamObservationListener` | Did the topology change — an election, a node removed — during the window? | +| `MongoCommandObservationListener` | *서버*가 걸린 시간과 호출자가 기다린 시간은 각각 얼마인가? | +| `MongoPoolObservationListener` | 기다린 시간이 query 실행이 아니라 connection checkout이었나? | +| `MongoSdamObservationListener` | 그 구간에 토폴로지가 바뀌었나 — 선출, 노드 빠짐? | -Without pool and SDAM events, every failover looks like "the database got slow", and the difference -between "we need a bigger pool" and "we lost a primary" is invisible. +pool과 SDAM 이벤트가 없으면 모든 failover가 「DB가 느려졌다」로 보이고, 「pool을 늘려야 한다」와 +「primary를 잃었다」의 차이가 보이지 않는다. -## 7. Command redaction +## 7. 명령 가리기 `MongoObservationRedactor.describe(commandName)`: -- Authentication and user-management commands (`authenticate`, `saslStart`, `saslContinue`, - `getnonce`, `createUser`, `updateUser`, `copydb*`) render as `` — their arguments carry - credentials and key material. -- Structural commands (`ping`, `hello`, `buildInfo`, `listCollections`, `listIndexes`, `collStats`) - render by name; their arguments are not data-bearing. -- Everything else renders as `name(...)`: you get the command, never the filter or the document. +- 인증·사용자 관리 명령(`authenticate`, `saslStart`, `saslContinue`, `getnonce`, `createUser`, + `updateUser`, `copydb*`)은 ``로 보인다. 인자에 credential과 key 재료가 있다. +- 구조 명령(`ping`, `hello`, `buildInfo`, `listCollections`, `listIndexes`, `collStats`)은 이름으로 + 보인다. 인자에 데이터가 없다. +- 나머지는 모두 `name(...)`으로 보인다. 명령은 보이고 filter나 문서는 보이지 않는다. -`isAlwaysRedacted(...)` is the assertion hook so a test can prove no logging path can render an auth -command's arguments. +`isAlwaysRedacted(...)`는 테스트가 어떤 로그 경로도 인증 명령의 인자를 그리지 못함을 증명하는 단언 hook이다. -## 8. Startup validation +## 8. 시작 검증 -`MongoStartupValidator` runs at context refresh, before the first request: +`MongoStartupValidator`는 context refresh 때, 첫 요청 전에 돈다. -1. `MongoTopologyProbe` reports the actual `MongoTopology` and its `MongoCapabilitySet`. -2. Every profile's declared topology must match it, and a production profile on `STANDALONE` fails. -3. With `platform.transactions=true`, the probe must report `TRANSACTION` as `STABLE`; on - `STANDALONE` it does not, so startup fails. -4. `MongoSecurityProfileValidator` checks credentials and TLS, and that the admin credential differs - from the runtime one; the `MongoSchemaVersionRange` must not be inverted. -5. `MongoPlatformHealthIndicator` reports topology mismatch and secondary availability for the - readiness probe. +1. `MongoTopologyProbe`가 실제 `MongoTopology`와 그 `MongoCapabilitySet`을 보고한다. +2. profile마다 선언한 토폴로지가 그것과 맞아야 하고, `STANDALONE` 위의 production profile은 실패한다. +3. `platform.transactions=true`이면 probe가 `TRANSACTION`을 `STABLE`로 보고해야 한다. `STANDALONE`에서는 + 그렇지 않으므로 시작이 실패한다. +4. `MongoSecurityProfileValidator`가 credential과 TLS, 그리고 admin credential이 runtime credential과 + 다른지를 검사한다. `MongoSchemaVersionRange`는 거꾸로면 안 된다. +5. `MongoPlatformHealthIndicator`가 readiness probe에 토폴로지 불일치와 secondary 가용성을 보고한다. -A misconfiguration found at startup costs a failed deploy. The same misconfiguration found at runtime -costs an incident, and the failing operation is rarely the one that reveals the cause. +시작할 때 발견한 설정 오류는 배포 한 번 실패로 끝난다. 같은 오류를 실행 중에 발견하면 장애가 되고, 실패한 +연산이 원인을 드러내는 일은 드물다. -## 9. How the security lane proves any of this +## 9. 보안 lane이 이것을 어떻게 증명하나 ```bash cd src ./gradlew :adapter:outbound:persistence-mongo:mongoSecurityIntegrationTest --console=plain ``` -The lane runs against `MongoAuthenticatedReplicaSetContainer`, which starts mongod with `--auth` and a -generated keyfile. That detail is the whole lane: Testcontainers' `MongoDBContainer` starts mongod -*without* `--auth`, so users created on it all have every privilege and a least-privilege assertion -passes no matter how wrong the roles are. A security test that cannot fail is not a security test. +이 lane은 `MongoAuthenticatedReplicaSetContainer`에서 돈다. 이것은 `--auth`와 생성한 keyfile로 mongod를 +띄운다. 그 세부가 lane의 전부다. Testcontainers의 `MongoDBContainer`는 mongod를 `--auth` *없이* 띄운다. +그 위에서 만든 사용자는 모두 모든 권한을 가지므로, role이 아무리 틀려도 최소 권한 단언이 통과한다. 실패할 +수 없는 보안 테스트는 보안 테스트가 아니다. -What the lane asserts is the refusal: the `read` role's insert is rejected, and the application role's -`dropDatabase` is rejected. Then it checks that `MongoSecurityProfileValidator` names the same -privilege the server just refused. +lane이 단언하는 것은 거부다. `read` role의 insert가 거부되고, 애플리케이션 role의 `dropDatabase`가 +거부된다. 그다음 `MongoSecurityProfileValidator`가 서버가 방금 거부한 바로 그 권한을 이름으로 대는지 본다. diff --git a/docs/mongodb/support-matrix.md b/docs/mongodb/support-matrix.md index 7eedc004..3e2c773e 100644 --- a/docs/mongodb/support-matrix.md +++ b/docs/mongodb/support-matrix.md @@ -1,91 +1,91 @@ -# MongoDB Platform — Support Matrix +# MongoDB 플랫폼 — 지원 매트릭스 -Design §4. This file records what the platform is *certified* on, not what it happens to run on. -A configuration absent from this table is unsupported until someone runs the gate against it and -adds a row. +설계서 §4. 이 파일은 플랫폼이 우연히 돌아가는 환경이 아니라 *인증한* 환경을 적는다. 이 표에 없는 구성은 +누군가 그 구성으로 게이트를 돌리고 행을 더하기 전까지 지원하지 않는다. -## 1. Runtime baseline +## 1. 런타임 기준 -| Component | Version | Policy | +| 구성 요소 | 버전 | 정책 | |---|---|---| -| Java | 21 | Repository runtime baseline. | -| Spring Boot | 4.0.0 | BOM-managed. Individual driver overrides are forbidden. | -| Spring Data MongoDB | 5.0.0 | Repository and `MongoTemplate` integration. Version comes from the Boot BOM. | -| MongoDB Java Driver | 5.6.1 | BOM-managed. Never pinned directly in the module. | -| Micrometer | 1.16.0 | Driver-native observability. | -| Testcontainers | 2.0.2 | Replica-set, failover, migration and compatibility lanes. | +| Java | 21 | 저장소 런타임 기준. | +| Spring Boot | `src/gradle/libs.versions.toml`의 `springBoot` | BOM이 관리한다. driver를 따로 덮어쓰는 것은 금지한다. | +| Spring Data MongoDB | Boot BOM이 정한다 | repository와 `MongoTemplate` 통합. | +| MongoDB Java Driver | Boot BOM이 정한다 | 모듈에서 직접 고정하지 않는다. | +| Micrometer | Boot BOM이 정한다 | driver 자체 관측. | +| Testcontainers | Boot BOM이 정한다 | replica set, failover, migration, compatibility lane. | -The design's baseline is Spring Boot 4.1.x / Spring Data MongoDB 5.1.x. This repository is on -4.0.0 / 5.0.0, so the platform targets only the API surface common to both. See -[repository-adaptation.md](repository-adaptation.md) §3. +BOM이 정한 실제 버전은 leaf의 잠금 파일 `src/adapter/outbound/persistence-mongo/gradle.lockfile`에 있다. +버전을 이 표에 옮겨 적지 않는다. 옮겨 적은 숫자는 다음 업그레이드에서 틀린 글이 된다. -## 2. Server versions +설계의 기준은 Spring Boot 4.1 계열 / Spring Data MongoDB 5.1 계열이다. 이 저장소는 Spring Boot 4.0 계열 / +Spring Data MongoDB 5.0 계열이므로, 플랫폼은 둘에 공통인 API 면만 쓴다. +[repository-adaptation.md](repository-adaptation.md) §3을 본다. -| Lane | Version | Pinned image | Gradle task | +## 2. 서버 버전 + +| Lane | 버전 | 고정한 이미지(key) | Gradle task | |---|---|---|---| -| Primary certification | MongoDB 8.0 | `mongo:8.0.16` | `mongoReplicaSetTest`, `mongoFailoverTest` | -| Compatibility | MongoDB 7.0 | `mongo:7.0.28` | `mongoCompatibilityTest` | -| Network fault injection | — | `ghcr.io/shopify/toxiproxy:2.12.0` | `mongoFailoverTest` | +| 주 인증 | MongoDB 8.0 | `mongo-8` | `mongoReplicaSetTest`, `mongoFailoverTest` | +| 호환성 | MongoDB 7.0 | `mongo-7` | `mongoCompatibilityTest` | +| 네트워크 장애 주입 | — | `toxiproxy` | `mongoFailoverTest` | -Images are pinned, never `latest`: a mutable tag means the certification result describes whatever -was pulled that morning, not the version in the row. Override with -`-PmongoPrimaryImage=…` / `-PmongoCompatibilityImage=…` when testing a new patch level, and update -the row once the gate passes. +이미지는 고정하고 `latest`를 쓰지 않는다. 바뀌는 tag를 쓰면 인증 결과는 행에 적은 버전이 아니라 그날 아침 +받은 무언가를 설명한다. 이미지의 정본은 `src/config/testing/container-images.properties`다. 표의 key마다 +digest와 그 digest의 tag(주석)가 거기 있다. patch 버전은 이 표에 옮겨 적지 않는다. 새 patch 버전을 시험할 때는 +`-PmongoPrimaryImage=…` / `-PmongoCompatibilityImage=…`로 덮어쓰고, 게이트가 통과하면 그 파일을 고친다. -`MongoVersionMatrix.standard()` is the machine-readable form of this table; a version outside it -fails `certifies()`. +`MongoVersionMatrix.standard()`가 이 표의 기계용 형태다. 그 밖의 버전은 `certifies()`에서 실패한다. -## 3. Topologies +## 3. 토폴로지 -| Topology | Status | What is certified | What is not | +| 토폴로지 | 상태 | 인증하는 것 | 인증하지 않는 것 | |---|---|---|---| -| Standalone | **Smoke only** | Basic CRUD and mapping. | Not a production profile and never counts as Stable release evidence (D-03). A production profile, or `platform.transactions=true`, on a Standalone server is refused at startup by `MongoStartupValidator`. | -| Single-node replica set | **Local default** (D-02) | Transactions, retryable writes, change streams — the same semantics as production. | Elections. A single-node set never holds one, so failover behaviour is untested here. | -| 3-node replica set | **Stable production gate** | Everything above plus primary failover and unknown-commit handling. | Shard routing. | -| Sharded cluster | **Advanced gate** | Shard-key routing classification, scatter-gather refusal, `admin` plane operations. | Not included in the Stable gate. | -| Atlas / provider-managed | **Not certified** | Encryption against the actual target deployment is the adopter's evidence to produce. | Search and vector search have no implementation in this leaf; a native `$search` command can only go through `PolicyAwareMongoNativeGateway` as a registered D3 operation. | +| Standalone | **smoke만** | 기본 CRUD와 매핑. | 운영 profile이 아니고 Stable 릴리스 증거로 세지 않는다(D-03). Standalone 서버 위의 운영 profile이나 `platform.transactions=true`는 `MongoStartupValidator`가 시작할 때 거부한다. | +| 노드 하나짜리 replica set | **로컬 기본값**(D-02) | transaction, retryable write, change stream — 운영과 같은 의미. | 선출. 노드 하나짜리 set은 선출을 하지 않으므로 여기서는 failover 동작을 시험하지 않는다. | +| 노드 세 개짜리 replica set | **Stable 운영 게이트** | 위의 모든 것과 primary failover, commit 결과를 모를 때의 처리. | shard 라우팅. | +| Sharded cluster | **Advanced 게이트** | shard key 라우팅 분류, scatter-gather 거부, `admin` plane 작업. | Stable 게이트에 들지 않는다. | +| Atlas / provider 관리형 | **인증 안 함** | 실제 대상 배포에서의 암호화는 도입하는 쪽이 만들 증거다. | 검색과 vector 검색은 이 leaf에 구현이 없다. native `$search` 명령은 등록한 D3 연산으로 `PolicyAwareMongoNativeGateway`를 거쳐야만 갈 수 있다. | -## 4. Stable API and client generations +## 4. Stable API와 client 세대 -| Plane | Stable API | Purpose | +| Plane | Stable API | 용도 | |---|---|---| -| D1 Standard document persistence | V1, `apiStrict=true` | Repositories, typed queries, atomic updates, optimistic revision. | -| D2 Advanced document operations | V1, `apiStrict=true` | `MongoTemplate`, transactions, bulk, aggregation, keyset cursors. | -| D3 Explicit Mongo capability | Not strict | Native BSON, CSFLE/QE, shard-aware operations — each behind a registered capability. | -| D4 Admin plane | Not strict | Collection, validator, index, migration, shard and repair commands. Separate credential, separate client. | +| D1 표준 문서 영속성 | V1, `apiStrict=true` | repository, 타입 있는 query, atomic update, 낙관적 revision. | +| D2 고급 문서 연산 | V1, `apiStrict=true` | `MongoTemplate`, transaction, bulk, aggregation, keyset cursor. | +| D3 명시적 Mongo capability | strict 아님 | native BSON, CSFLE/QE, shard를 아는 연산 — 각각 등록한 capability 뒤에 있다. | +| D4 Admin plane | strict 아님 | collection, validator, index, migration, shard, repair 명령. credential도 client도 따로다. | -D3 is not a raw-client escape. Every call passes capability registration → database profile → -collection allowlist → operation name → timeout → consistency profile → result limit → trace → -redaction → command category → D4 refusal, in that order. +D3는 날것의 client로 빠지는 출구가 아니다. 모든 호출은 이 순서대로 지나간다: capability 등록 → database +profile → collection 허용 목록 → 연산 이름 → timeout → 일관성 profile → 결과 상한 → trace → 가리기 → 명령 +분류 → D4 거부. -## 5. Validation actions +## 5. Validation action -Stable validation actions are `error` and `warn`. `errorAndLog` is **not** part of the Stable -contract on 7.0 or 8.0 and `MongoValidatorDescriptor` refuses it. +Stable validation action은 `error`와 `warn`이다. `errorAndLog`는 7.0이나 8.0에서 Stable 계약에 들지 +**않고**, `MongoValidatorDescriptor`가 거부한다. -## 6. Explicitly unsupported +## 6. 명시적으로 지원하지 않는 것 -Per design §3.4, none of the following is provided, and adding one is a design change rather than a -feature request: +설계 §3.4에 따라 아래는 하나도 제공하지 않는다. 하나라도 더하는 것은 기능 요청이 아니라 설계 변경이다. -- A generic `CommonMongoRepository`. -- Arbitrary runtime `runCommand`. -- Automatic index creation in production. -- A Standalone production contract. -- TTL as an exact business scheduler or as the only access control. -- Publishing raw change events as external business integration events. -- GridFS as the source of truth for new files. -- Java fully-qualified class names as a long-lived BSON schema. -- Unbounded skip pagination, unbounded aggregation pipelines, unbounded regex, unbounded results. +- 범용 `CommonMongoRepository`. +- 실행 중 임의의 `runCommand`. +- 운영에서 index 자동 생성. +- Standalone 운영 계약. +- 정확한 업무 일정 도구나 유일한 접근 제어로서의 TTL. +- 날것의 change event를 외부 업무 통합 이벤트로 내보내기. +- 새 파일의 정본으로서의 GridFS. +- 오래 사는 BSON schema로서의 Java FQCN. +- 상한 없는 skip 페이지 나누기, 상한 없는 aggregation pipeline, 상한 없는 regex, 상한 없는 결과. -## 7. Capability tiers +## 7. Capability 등급 -| Tier | Capabilities | Enablement | +| 등급 | Capability | 켜는 법 | |---|---|---| -| Stable, auto-configured | Mapping and BSON converters, imperative execution, atomic update, bulk partial results, consistency profiles, retry/translation, operation budgets, observability, typed client profiles, startup validation, health | Beans registered when `app.persistence-mongo.enabled=true`. | -| Stable, library API | Transactions, causal sessions, optimistic revision, query builder and keyset pagination, aggregation executor, schema/index/validator manifests and diffs, TTL contract, GeoJSON, migration runner, admin plane, native capability gateway | The adopter's adapter leaf takes this leaf as `implementation` and constructs the type. | -| Advanced, library API | Sharding-aware query and shard admin, CSFLE, Queryable Encryption (equality/range), shared-collection tenancy policies | Same, plus a `MongoAdvancedCapabilityGuard` whose flags enable the capability. No configuration property. | -| Experimental, library API | Database-per-tenant client registry and migration coordinator, reshard approval | Same as Advanced; promotion additionally requires the evidence in [ADR-MONGO-ADV-001](../adr/ADR-MONGO-ADV-001-capability-promotion.md). | +| Stable, 자동 구성 | 매핑과 BSON converter, 명령형 실행, atomic update, bulk 부분 결과, 일관성 profile, 재시도/변환, 연산 예산, 관측, 타입 있는 client profile, 시작 검증, health | `app.persistence-mongo.enabled=true`일 때 bean을 등록한다. | +| Stable, 라이브러리 API | transaction, causal session, 낙관적 revision, query builder와 keyset 페이지 나누기, aggregation executor, schema/index/validator manifest와 diff, TTL 계약, GeoJSON, migration runner, admin plane, native capability gateway | 도입하는 쪽의 어댑터 leaf가 이 leaf를 `implementation`으로 받고 타입을 만든다. | +| Advanced, 라이브러리 API | shard를 아는 query와 shard admin, CSFLE, Queryable Encryption(equality/range), shared collection tenancy 정책 | 위와 같고, 그 capability를 켠 flag의 `MongoAdvancedCapabilityGuard`가 더 필요하다. 설정 속성은 없다. | +| Experimental, 라이브러리 API | tenant마다 database client registry와 migration coordinator, reshard 승인 | Advanced와 같다. 승격에는 [ADR-MONGO-ADV-001](../adr/ADR-MONGO-ADV-001-capability-promotion.md)의 증거가 더 필요하다. | -Search, vector search, time series and GridFS compatibility were interfaces with no implementation -and were removed on 2026-09-25 (`docs/capability-status.md`). +검색, vector 검색, time series, GridFS 호환은 구현 없는 interface였고 2026-09-25에 지웠다 +(`docs/capability-status.md`). diff --git a/docs/notification/adr/NOTIF-ADR-001-durable-acceptance.md b/docs/notification/adr/NOTIF-ADR-001-durable-acceptance.md deleted file mode 100644 index fb7d5f2f..00000000 --- a/docs/notification/adr/NOTIF-ADR-001-durable-acceptance.md +++ /dev/null @@ -1,36 +0,0 @@ - -> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. - -- 상태: 채택 -- 작성일: 2026-08-14 -- 요약: 알림 submit()은 영속적으로 받아들였다는 뜻이라는 결정이다. -- 현재 정본: `docs/notification/support-matrix.md` - - -# NOTIF-ADR-001 — `submit()` means durable acceptance - -## Status - -Accepted. - -## Context - -The obvious API for a notification platform is `send()` returning success or failure. Every channel -this platform supports makes that return value a lie: - -- SES accepts a request, returns a `MessageId`, and can still decline to send. -- Twilio separates `accepted`, `sent` and `delivered` into distinct, later events. -- APNs accepts a notification and may then deliver, store or discard it. -- Web Push separates push-service acceptance from user-agent acknowledgement at the protocol level. - -## Decision - -`submit()` and `schedule()` return once the logical request and its recipient jobs are committed to -the database. The receipt carries `notificationId`, `RequestStatus` and `acceptedAt`, and has no -`delivered`, `sent` or `read` component. No provider is contacted while the transaction is open. - -## Consequences - -Callers cannot mistake acceptance for delivery, because the type does not offer that reading. -Delivery state is a separate query against the projection built from the provider event ledger. The -cost is that "did it arrive?" is a second question — which is the honest number of questions. diff --git a/docs/notification/adr/NOTIF-ADR-002-event-ledger-projection.md b/docs/notification/adr/NOTIF-ADR-002-event-ledger-projection.md deleted file mode 100644 index 67afe419..00000000 --- a/docs/notification/adr/NOTIF-ADR-002-event-ledger-projection.md +++ /dev/null @@ -1,34 +0,0 @@ - -> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. - -- 상태: 채택 -- 작성일: 2026-08-14 -- 요약: 알림 상태를 덧붙이기만 하는 이벤트 원장과 채널별 projector로 둔다는 결정이다. -- 현재 정본: `docs/notification/support-matrix.md` - - -# NOTIF-ADR-002 — append-only event ledger with channel projectors - -## Status - -Accepted. - -## Context - -A single linear delivery status has to be updated in place, which forces a rule for deciding whether -a new event outranks the stored one. The natural rule — compare ordinals — is wrong for real provider -traffic. Twilio does not guarantee callback ordering, so `sent` arrives after `delivered`. Email -generates complaints after deliveries. Both cases lose information under an ordinal rule. - -## Decision - -Provider events are appended to an immutable ledger before any projection runs. Channel-specific -projectors merge events into `SubmissionOutcome`, `DeliveryOutcome`, `EvidenceLevel`, -`EngagementFacts` and `SuppressionFacts` using explicit transition tables. Projection is idempotent -and can be replayed from the ledger. - -## Consequences - -Duplicate, out-of-order and late events are normal inputs rather than defects. A projector bug is -recoverable, because the events it mis-projected are still stored. Projector versions can be migrated -by replay. The cost is a second write per event and a projection that can lag its ledger. diff --git a/docs/notification/adr/NOTIF-ADR-003-ambiguous-submission.md b/docs/notification/adr/NOTIF-ADR-003-ambiguous-submission.md deleted file mode 100644 index c38e6184..00000000 --- a/docs/notification/adr/NOTIF-ADR-003-ambiguous-submission.md +++ /dev/null @@ -1,46 +0,0 @@ - -> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. - -- 상태: 채택 -- 작성일: 2026-08-14 -- 요약: 결과가 모호한 제출을 정식 상태로 둔다는 결정이다. -- 현재 정본: `docs/notification/support-matrix.md` - - -# NOTIF-ADR-003 — ambiguous submission is a first-class state - -## Status - -Accepted. - -## Context - -The most common serious failure is not a rejection. It is a request whose body reached the provider -and whose response never came back. The platform has no provider request id, and the user may or may -not have received the notification. - -Treating that as a failure produces duplicates: a retry sends a second message, and a cross-channel -fallback sends the SMS next to the push that already arrived. Treating it as a success loses real -failures. - -## Decision - -`AMBIGUOUS` is a stored `SubmissionOutcome` and `AttemptConfirmation`. Attempts record -`requestStarted`, `requestBodyCommitted` and `providerResponseReceived`, each with an -`EvidenceCertainty` of `PROVEN`, `INFERRED` or `UNKNOWN`, so an adapter that does not know is not -forced to answer `false`. - -While an ambiguous attempt exists on a recipient delivery: - -- automatic retry is blocked unless the provider proves per-request idempotency -- automatic cross-channel fallback is blocked unconditionally -- reconciliation runs where the provider supports a status query -- otherwise the delivery stops and waits for an operator - -Operator redrive of an ambiguous attempt requires explicit duplicate-risk approval. - -## Consequences - -Some notifications stop in a state that needs a human or a reconciliation pass. That is the intended -trade: an unresolved unknown is cheaper than a guaranteed duplicate, and the state is visible rather -than silently resolved in either direction. diff --git a/docs/notification/adr/NOTIF-ADR-004-fcm-fid-primary.md b/docs/notification/adr/NOTIF-ADR-004-fcm-fid-primary.md deleted file mode 100644 index e7b84c67..00000000 --- a/docs/notification/adr/NOTIF-ADR-004-fcm-fid-primary.md +++ /dev/null @@ -1,36 +0,0 @@ - -> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. - -- 상태: 채택 -- 작성일: 2026-08-14 -- 요약: FCM 대상은 installation id를 먼저 쓴다는 결정이다. -- 현재 정본: `docs/notification/provider-runbooks.md` - - -# NOTIF-ADR-004 — FCM installation id is the primary target - -## Status - -Accepted. - -## Context - -Firebase now recommends the installation id (FID) and treats registration-token multicast paths as -legacy. A contact point model built on a single `token` string would encode the older model as the -only one, and a later migration would be a runtime interpretation problem: the same string field -would mean different things for different rows. - -## Decision - -`MobilePushTarget` is a sealed hierarchy of `FcmInstallationId`, `LegacyFcmRegistrationToken` and -`ApnsDeviceToken`. The kinds are separate types, never a discriminator on one string field, and each -carries its own `ContactPointType` so the uniqueness scope and the encryption associated data differ. - -APNs tokens additionally carry their environment, because sandbox and production are separate -namespaces rather than a flag. - -## Consequences - -Migrating a target kind is a compile-time change with an exhaustive `switch`, not a runtime guess. -The adapter maps each kind to its own wire representation, so a provider changing one path cannot -silently change the other. The cost is one more type than a string field would need. diff --git a/docs/notification/at-rest-threat-model.md b/docs/notification/at-rest-threat-model.md index 0c067d6b..5f0cec82 100644 --- a/docs/notification/at-rest-threat-model.md +++ b/docs/notification/at-rest-threat-model.md @@ -1,77 +1,53 @@ -# Notification payload at rest — threat model and decision (NTF-INT-007) +# 저장된 알림 payload — 위협 모델과 결정 (NTF-INT-007) -Wave 2 Task D6 offers two branches and requires that one be chosen and implemented fully: +결론: 템플릿 변수(payload)는 저장소 경계에서 암호화한다(branch (a)). 변수를 「민감하지 않은 값」으로 제한하는 길 +(branch (b))은 쓸 수 없다. 변수가 곧 메시지의 내용이기 때문이다. -- **(a) encryption** — a codec/port, ciphertext envelope, key id, rotation and history, row migration, - and a decryption-failure contract; -- **(b) restriction** — this document plus a static restriction proving the variable types cannot - carry sensitive values. +Wave 2 Task D6은 두 길을 주고, 하나를 골라 끝까지 구현하라고 요구했다. -The plan recommends (b) **"if and only if the variable types can genuinely be restricted to -non-sensitive values"**. They cannot. This document records why, what that leaves, and when the -remaining branch lands. +- **(a) 암호화** — codec·port, 암호문 envelope, key id, 교체와 이력, 행 마이그레이션, 복호화 실패 계약. +- **(b) 제한** — 이 문서, 그리고 변수 타입이 민감한 값을 담을 수 없음을 보이는 정적 제한. -## What is stored, and where +계획은 **「변수 타입을 정말로 민감하지 않은 값으로 제한할 수 있을 때만」** (b)를 권했다. 제한할 수 없다. 이 문서는 +그 이유와, 그래서 고른 (a)가 지금 어떻게 들어가 있는지를 적는다. -`CanonicalNotificationPlanWriter.request(...)` puts `encoded.variablesPayload()` into -`NotificationRequestRecord` verbatim. `JpaNotificationRequestStore` writes that record to -`notification_request.variables_payload` with no transformation. There is no encryption anywhere on -this path. +## 지금 상태 -## Why the restriction branch is unavailable +- `NotificationPayloadProtection`이 애플리케이션이 가진 port이고, `AesGcmNotificationPayloadProtection`이 AES-GCM + 구현이다. +- `NotificationRecordMapper`가 그것을 **필수** 생성자 인자로 받아 적용한다. 그래서 payload를 평문으로 둔 채 알림 + 저장소를 조립할 수 없다. +- 쓰기 경로는 조립에서 닿는다. `NotificationJpaPersistenceFacade`는 persistence-notification leaf의 + `AutoConfiguration.imports`가 올린다. +- 평문 행이 이미 있는 배포는 마이그레이션에서 멈춘다. `V10__variables_payload_envelope_guard.sql`은 행을 다시 + 암호화하지 않고, 보호되지 않은 행이 있으면 실패한다. +- `NotificationPayloadAtRestContractTest`가 이 문서가 기대는 사실을 모두 단언한다. 하나라도 거짓이 되면 그 테스트가 + 실패하므로, 결정이 저절로 낡지 않는다. +- 알림은 Stable이 아니다(`docs/notification/support-matrix.md`). -Template variables are a closed algebra — `NotificationVariable` permits `TextValue`, `NumberValue`, -`BooleanValue`, `NullValue`, `ListValue`, `ObjectValue` — which is a real improvement over the -`Map` it replaced. But `TextValue` holds an arbitrary UTF-8 string of up to 8 KiB, -and that is not an oversight to be tightened: **the variables are the recipient-specific content of -the message**. A password-reset code, an order total, a delivery address, a patient's appointment -time — those are what a notification is for. +## 무엇이 어디에 저장되나 -A restriction to "non-sensitive values" would therefore be one of two things, and both are worse -than the problem: +`CanonicalNotificationPlanWriter.request(...)`는 `encoded.variablesPayload()`를 그대로 `NotificationRequestRecord`에 +넣는다. 애플리케이션은 그것을 렌더링해야 하므로 여기서는 평문이 맞다. 「저장된(at rest)」은 행 안을 뜻하므로 +envelope는 여기가 아니라 저장소 경계에서 씌운다. `notification_request.variables_payload`에는 base64 AES-GCM +envelope가 들어간다. -- **unenforceable** — a comment saying callers should not put sensitive data in a field designed to - carry the message's content, which is a policy no type checks and no reviewer can see violated; -- **enforced and useless** — a type that refuses free text, which does not restrict the capability so - much as delete it. +## 제한 가지를 쓸 수 없는 이유 -The precondition on the plan's recommendation is false. Branch (b) is not available. +템플릿 변수는 닫힌 대수다. `NotificationVariable`은 `TextValue`, `NumberValue`, `BooleanValue`, `NullValue`, +`ListValue`, `ObjectValue`만 허용한다. 이것이 대신한 `Map`보다 확실히 낫다. 그러나 `TextValue`는 8 KiB까지의 +아무 UTF-8 문자열을 담고, 그것은 조여야 할 실수가 아니다. **변수는 메시지의 수신자별 내용이다.** 비밀번호 재설정 +코드, 주문 합계, 배송 주소, 환자의 예약 시각, 알림은 그것을 보내려고 있다. -> **Status: branch (a) implemented at the storage boundary.** `NotificationPayloadProtection` is the -> application-owned port, `AesGcmNotificationPayloadProtection` the AES-GCM implementation, and -> `NotificationRecordMapper` applies it — as a **required** constructor argument, so a composition -> cannot assemble the notification stores while leaving the payload in plaintext. What remains before -> the facade can be imported is the row migration for any deployment that already has plaintext rows, -> and the `local-notification-*` lanes. The analysis below is kept as written, because it is what the -> decision rests on. +그래서 「민감하지 않은 값」으로의 제한은 둘 중 하나가 되고, 둘 다 문제보다 나쁘다. -## Decision: branch (a), landing with the persistence wiring +- **강제할 수 없음** — 메시지 내용을 담으려고 만든 칸에 민감한 데이터를 넣지 말라는 주석. 어떤 타입도 확인하지 + 않고, 어떤 리뷰어도 위반을 볼 수 없는 정책이다. +- **강제하지만 쓸모없음** — 자유 텍스트를 거부하는 타입. capability를 제한한다기보다 지운다. -Encryption is therefore the required branch. Its scope is unchanged from the plan: a codec behind an -application port, a ciphertext envelope carrying its key id, key rotation with history so an old row -stays readable, a migration for existing rows, and an explicit contract for what a decryption failure -does to a request. +계획의 권고에 붙은 전제가 거짓이다. (b)는 쓸 수 없다. -**It lands in the change unit that makes the write path reachable, and not before.** The reason is a -fact the spec did not have: `NotificationJpaPersistenceFacade`, which assembles -`JpaNotificationRequestStore`, is imported by nothing. The composition root's component scan excludes -the persistence package by design, and no configuration imports the facade — so the notification -capability has **no JPA persistence at all**, and no deployment currently writes this payload -anywhere. The defect is real in the code and latent in the runtime. - -Designing key rotation and a row migration for rows that no deployment produces would be building the -migration before the table. Worse, it would settle the envelope's shape before the store that has to -read it is wired, which is the order that produces an envelope the store cannot use. - -**One correction, learned by trying it.** This section said the envelope "lands with the wiring". -Wiring the facade first — to register the SMTP assembler — made -`NotificationPayloadAtRestContractTest` fail on the case asserting the write path is reachable from -no composition, which is exactly what that case is for. The wave forbids connecting wiring over a -known security finding on a runtime path, so the wiring was reverted and the envelope built first. -The honest ordering is **envelope before or with the wiring, never after**, and the contract test now -enforces it by failing on the wiring alone. - -### The envelope, and why it has a key id +## envelope와 key id를 두는 이유 ``` byte version always 1 @@ -81,36 +57,50 @@ byte[12] nonce byte[] ciphertext + GCM tag ``` -The key id is the reason there is a format at all. This repository's callback protection stores nonce -and ciphertext and nothing else, so the day the active key changes, every row written under the -previous one becomes unreadable and nothing in the row can say which key it needed — that is not a -rotation story with a gap in it, it is the absence of one. `SecretMaterialProvider` already exposes -`keyById`, so reading the id back and asking for that specific key makes rotation a change of default -rather than a data migration. The version byte costs one byte and is what allows the format to change -at all. +형식을 두는 이유는 key id다. 이 저장소의 콜백 보호는 한때 nonce와 암호문만 저장했다. 그러면 활성 키가 바뀌는 날 +앞 키로 쓴 행은 모두 읽을 수 없게 되고, 행 안의 어떤 것도 어느 키가 필요했는지 말하지 못한다. 틈 있는 교체가 아니라 +교체가 없는 것이다. `SecretMaterialProvider`가 이미 `keyById`를 드러내므로, id를 다시 읽어 바로 그 키를 달라고 하면 +교체는 데이터 마이그레이션이 아니라 기본값 변경이 된다. version 바이트는 1바이트이고, 형식을 바꿀 수 있게 해 준다. -The header is passed as **AAD**, not merely prefixed: without that, the key id is attacker-editable -and an envelope could be redirected at a key of the attacker's choosing. +header는 앞에 붙이기만 하는 것이 아니라 **AAD**로 넘긴다. 그러지 않으면 공격자가 key id를 고쳐 envelope를 자기가 +고른 키로 돌릴 수 있다. -A failed decryption throws `NotificationPayloadUnreadableException` rather than returning empty. A -caller handed an empty payload renders every variable as nothing and sends "Hello , your code is " to -a real person — the failure delivered instead of reported. All three causes (unknown key, wrong key, -modified ciphertext) collapse into one message, because telling them apart tells an attacker which of -the three they achieved. +복호화에 실패하면 빈 값을 돌려주지 않고 `NotificationPayloadUnreadableException`을 던진다. 빈 payload를 받은 +호출자는 모든 변수를 빈 값으로 렌더링해 실제 사람에게 "Hello , your code is "를 보낸다. 실패를 보고하는 대신 실패를 +배달하는 것이다. 세 원인(모르는 키, 틀린 키, 고쳐진 암호문)은 한 메시지로 합친다. 셋을 구별해 주면 공격자에게 셋 중 +무엇을 해냈는지 알려 주기 때문이다. -## What must not be done instead +## 키 교체 순서 -**Requiring `PAYLOAD_ENCRYPTION` in `INGEST_ONLY` is not a fix.** That secret is consumed by exactly -one thing — `AesGcmCallbackPayloadProtection`, which protects raw callback bodies — and by nothing on -the accept path. Demanding it would make a deployment supply a key that protects nothing while the -payload it appears to be about stays in plaintext. The repository already has one defect of that -exact shape: `app.graphql.cursor.key-ids` (key removed 2026-09-25), which production refuses to start without and which no -code signs a cursor with (GQL-INT-003). Adding a second would make the pattern a habit. +설정 키는 `app.notification.platform.secrets` 아래에 있다(`notification.yml`). -## Consequence +1. 새 키 값과 새 key id를 같은 배포에서 바꾼다(예: `APP_NOTIFICATION_PLATFORM_PAYLOAD_ENCRYPTION_KEY`와 + `APP_NOTIFICATION_PLATFORM_PAYLOAD_ENCRYPTION_KEY_ID`). 고정된 id는 교체를 앞 키와 구별할 수 없게 한다. +2. 같은 배포에서 밀려난 키 값을 `historical-keys.<목적>.<옛 id>` 아래에 둔다(예: + `historical-keys.PAYLOAD_ENCRYPTION.payload-2026-01`). 목적은 id에서 알아낼 수 없고, id로 키를 푸는 쪽은 목적이 다른 + 키를 거부한다. 그러니 다른 목적 아래 둔 옛 키는 풀리기는 해도 거부된다. +3. 옛 키로 쓴 행이 남아 있는 동안 옛 키를 그대로 둔다. `SettingsSecretMaterialProvider.keyById`는 모르는 id를 현재 + 키로 대신하지 않고 거부한다. 대신하면 이력의 모든 행이 읽을 때 인증 tag 실패가 된다. -Notification is **not promoted to Stable**, per the index's scope boundaries, until branch (a) is -complete. The three notification Compose lanes stay non-blocking. `NotificationPayloadAtRestContractTest` -holds every fact this decision rests on, so the decision expires automatically if any of them stops -being true — in particular, the assertion that no encryption sits on the accept path fails the moment -somebody adds one, which is the change this document is waiting for. +## 결정의 이력 + +> 이력: 결정 당시(Wave 2) `NotificationJpaPersistenceFacade`는 아무도 import하지 않았다. 조립 루트의 component scan은 +> 설계상 persistence 패키지를 빼고, 어떤 설정도 facade를 import하지 않아서, 알림 capability에는 JPA 영속성이 아예 없었다. +> 결함은 코드에는 있고 런타임에는 숨어 있었다. 그래서 처음에는 「envelope는 그 wiring과 함께 들어간다」고 정했다. +> 아무 배포도 만들지 않는 행을 위해 키 교체와 행 마이그레이션을 설계하는 것은 테이블보다 마이그레이션을 먼저 짓는 +> 일이었다. +> +> 해 보고 배운 정정이 하나 있다. SMTP assembler를 등록하려고 facade를 먼저 wiring하자, +> `NotificationPayloadAtRestContractTest`의 「쓰기 경로가 어느 조립에서도 닿지 않는다」 단언이 실패했다. 그 단언은 바로 +> 그것을 잡으려고 있었다. Wave는 런타임 경로에 알려진 보안 발견을 둔 채 wiring을 잇는 것을 막았으므로 wiring을 되돌리고 +> envelope를 먼저 지었다. 맞는 순서는 **envelope를 wiring 전이나 함께, 뒤에는 절대 아니다**이다. +> +> 결정 당시 `PAYLOAD_ENCRYPTION` secret을 쓰는 곳은 원본 콜백 본문을 보호하는 `AesGcmCallbackPayloadProtection` 하나뿐이었고 +> 받기 경로에는 없었다. 그래서 `INGEST_ONLY`에서 그것을 요구하는 것은 고침이 아니었다. 아무것도 보호하지 않는 키를 +> 배포에 요구하고, 그것이 다룬다고 보이는 payload는 평문으로 남는다. 저장소에는 이미 그런 꼴의 결함이 하나 있었다. +> `app.graphql.cursor.key-ids`(2026-09-25에 키를 지움)는 운영이 그것 없이는 뜨지 않으면서, 어떤 코드도 그것으로 cursor에 +> 서명하지 않았다(GQL-INT-003). 지금은 `AesGcmNotificationPayloadProtection` 하나가 같은 envelope로 받은 payload와 보관하는 +> 콜백을 모두 덮고, `NotificationSecretRequirements`가 이 목적을 모든 설정에서 요구한다. +> +> 결정 당시 결론은 이랬다. 알림은 색인의 범위 경계에 따라 (a)가 끝날 때까지 Stable로 올리지 않는다. 알림 Compose +> lane 셋은 막지 않는 lane으로 둔다. diff --git a/docs/notification/callback-reconciliation.md b/docs/notification/callback-reconciliation.md index 23e0dc36..7e2d833a 100644 --- a/docs/notification/callback-reconciliation.md +++ b/docs/notification/callback-reconciliation.md @@ -1,6 +1,6 @@ -# Callbacks and reconciliation +# 콜백과 맞추기(reconciliation) -## Ingestion order +## 받는 순서 ```text body size limit @@ -16,41 +16,40 @@ body size limit → 2xx ``` -Appending before projecting is what makes a fast 2xx honest. The provider is told the event is -recorded, and a projector defect becomes a replay problem rather than a lost event. +projection보다 ledger 추가를 먼저 하기 때문에 빠른 2xx가 정직하다. provider에게는 이벤트가 기록됐다고 알리고, +projector 결함은 이벤트 유실이 아니라 replay 문제가 된다. -A rejected signature is recorded in the security audit, never in the provider event ledger. Writing -it to the ledger would let anyone who can reach the endpoint fill a delivery history with noise. +서명이 거부된 콜백은 provider event ledger가 아니라 보안 감사에 기록한다. ledger에 쓰면 엔드포인트에 닿는 누구나 +전달 이력을 잡음으로 채울 수 있다. -## Duplicates and ordering +## 중복과 순서 -Duplicate suppression uses `(providerProfileId, providerEventId)` where the provider supplies an -event id, and a deterministic fingerprint over profile, request id, event type, occurrence time and -payload digest where it does not. A duplicate is acknowledged and projected exactly once. +중복 억제는 provider가 event id를 주면 `(providerProfileId, providerEventId)`를 쓰고, 주지 않으면 profile, request id, +event 종류, 발생 시각, payload digest로 만든 결정적 fingerprint를 쓴다. 중복은 확인 응답하고 projection은 정확히 한 번 +한다. -Out-of-order callbacks are normal. Ordering is resolved by event semantics, not by arrival time. +순서가 뒤바뀐 콜백은 보통이다. 순서는 도착 시각이 아니라 이벤트의 뜻으로 정한다. -## Unknown fields +## 모르는 칸 -Callback parsers tolerate unknown JSON fields. Normalization only rejects a payload when a field -required to identify the attempt is missing. Providers add fields; that must not stop ingestion. +콜백 parser는 모르는 JSON 칸을 받아들인다. 정규화는 attempt를 가리키는 데 필요한 칸이 없을 때만 payload를 거부한다. +provider는 칸을 더한다. 그것 때문에 받기가 멈추면 안 된다. -## Reconciliation +## 맞추기 -Reconciliation targets: +맞추기 대상: -- attempts stuck in `DISPATCHING` past their lease -- ambiguous submissions -- accepted attempts whose callback SLA has expired -- unmatched provider events +- lease가 지나도 `DISPATCHING`에 멈춘 attempt +- 모호한 제출 +- 콜백 SLA가 지난, 수락된 attempt +- 짝이 없는 provider 이벤트 -A confirmed query result is appended to the same ledger with `source = RECONCILIATION` and projected -by the same projector, so projection replay stays possible: there is no privileged second path that -writes projections directly. +확인된 조회 결과는 `source = RECONCILIATION`으로 같은 ledger에 추가하고 같은 projector가 projection한다. 그래서 +projection replay가 계속 가능하다. projection을 직접 쓰는 특별한 두 번째 길은 없다. -Where a provider has no status-query capability, the platform records `Unsupported` and leaves the -attempt ambiguous. It does not infer a final status. +provider에 상태 조회 기능이 없으면 플랫폼은 `Unsupported`를 기록하고 attempt를 모호한 채로 둔다. 최종 상태를 짐작하지 +않는다. -The shipped families, SES and SMTP, have no reconciliation: their assemblers contribute no -`ReconciliationCapability`, so every reconciliation job for them ends `Unsupported`. The slot on -`AssembledProvider` is for a provider family an adopter assembles with a status query of its own. +내보내는 family인 SES와 SMTP는 맞추기가 없다. 그 assembler는 `ReconciliationCapability`를 보태지 않으므로, 둘의 맞추기 +작업은 모두 `Unsupported`로 끝난다. `AssembledProvider`의 그 자리는 도입하는 쪽이 자기 상태 조회와 함께 조립하는 provider +family를 위한 것이다. diff --git a/docs/notification/configuration-reference.md b/docs/notification/configuration-reference.md index 1e161d49..f7749b92 100644 --- a/docs/notification/configuration-reference.md +++ b/docs/notification/configuration-reference.md @@ -1,211 +1,202 @@ -# Configuration reference +# 설정 참조 -The notification delivery platform binds under `app.notification.platform`. The tree lives in -`src/composition/notification-platform/src/main/resources/config/module-defaults/notification.yml`, -which the support leaf's `ModuleDefaultsEnvironmentPostProcessor` loads at the lowest precedence, -so an application without the module carries none of it. The module is in no default composition: a -service selects it with `runtimeOnly project(':composition:notification-platform')` (plus the -persistence-jpa line) in `app-bootstrap/build.gradle`, and it is on when present. Every value carries -an inline default, so a deployment that switches the platform off supplies nothing. +알림 전달 플랫폼은 `app.notification.platform` 아래에 묶인다. 설정 트리는 +`src/composition/notification-platform/src/main/resources/config/module-defaults/notification.yml`에 있고, +support leaf의 `ModuleDefaultsEnvironmentPostProcessor`가 가장 낮은 우선순위로 읽는다. 그래서 이 모듈이 없는 +애플리케이션에는 이 설정이 하나도 없다. 이 모듈은 어느 기본 조립에도 없다. 서비스가 +`app-bootstrap/build.gradle`에 `runtimeOnly project(':composition:notification-platform')`(와 persistence-jpa 줄)를 +더해 고르고, 모듈이 있으면 켜진다. 값마다 기본값이 붙어 있으므로 플랫폼을 끄는 배포는 아무것도 주지 않아도 된다. -Until 2026-08-15 this page named properties the binding did not have — `max-retry-concurrency`, -`scheduler-poll-interval`, `callback-worker-concurrency` — and omitted three it did. There was no -tree in `application.yml` at all, so the only way to configure the platform was to guess environment -variable names from Boot's relaxed binding. `NotificationEnvironmentRegistryTest` -(`:composition:notification-platform:test`) now fails when the shipped YAML and -`docs/registries/env-keys.yaml` disagree. +> 이력: 2026-08-15까지 이 문서는 바인딩에 없는 속성(`max-retry-concurrency`, `scheduler-poll-interval`, +> `callback-worker-concurrency`)을 적었고, 있는 속성 셋을 빠뜨렸다. `application.yml`에 트리가 아예 없어서, 플랫폼을 +> 설정하려면 Boot의 relaxed binding으로 환경 변수 이름을 짐작해야 했다. -## Master switch +지금은 내보내는 YAML과 `docs/registries/env-keys.yaml`이 다르면 `NotificationEnvironmentRegistryTest` +(`:composition:notification-platform:test`)가 실패한다. -| Property | Environment variable | Default | Meaning | +## 주 스위치 + +| 속성 | 환경 변수 | 기본값 | 뜻 | |---|---|---|---| -| `enabled` | `APP_NOTIFICATION_PLATFORM_ENABLED` | `true` | On while the module is present. `false` binds nothing at all: no runtime, no schema check, no scheduler thread, no secret required | -| `mode` | `APP_NOTIFICATION_PLATFORM_MODE` | `SERVING` | `SERVING` refuses to start without a working provider; `INGEST_ONLY` stores requests and does not dispatch: it builds no provider runtime but records each enabled profile's route, so a request accepted now is delivered later on that route by a `SERVING` deployment (handoff) | +| `enabled` | `APP_NOTIFICATION_PLATFORM_ENABLED` | `true` | 모듈이 있으면 켜진다. `false`면 아무것도 묶지 않는다. 런타임도, 스키마 검사도, scheduler 스레드도, 필요한 secret도 없다 | +| `mode` | `APP_NOTIFICATION_PLATFORM_MODE` | `SERVING` | `SERVING`은 동작하는 provider가 없으면 뜨기를 거부한다. `INGEST_ONLY`는 요청을 저장만 하고 보내지 않는다. provider 런타임을 만들지 않지만 켜진 profile마다 route를 기록하므로, 지금 받은 요청은 나중에 `SERVING` 배포가 그 route로 보낸다(handoff) | -## Dispatch +## 발송 -| Property | Environment variable | Default | Bound | +| 속성 | 환경 변수 | 기본값 | 범위 | |---|---|---|---| | `dispatch.claim-batch-size` | `APP_NOTIFICATION_PLATFORM_CLAIM_BATCH_SIZE` | `50` | 1..1000 | -| `dispatch.lease-duration` | `APP_NOTIFICATION_PLATFORM_LEASE_DURATION` | `2m` | positive, finite | -| `dispatch.poll-interval` | `APP_NOTIFICATION_PLATFORM_POLL_INTERVAL` | `1s` | positive, finite | -| `dispatch.max-global-concurrency` | `APP_NOTIFICATION_PLATFORM_MAX_CONCURRENCY` | `64` | positive | -| `dispatch.max-additional-attempts` | `APP_NOTIFICATION_PLATFORM_MAX_ADDITIONAL_ATTEMPTS` | `4` | non-negative | -| `dispatch.max-queue-age` | `APP_NOTIFICATION_PLATFORM_MAX_QUEUE_AGE` | `24h` | positive | +| `dispatch.lease-duration` | `APP_NOTIFICATION_PLATFORM_LEASE_DURATION` | `2m` | 양수, 유한 | +| `dispatch.poll-interval` | `APP_NOTIFICATION_PLATFORM_POLL_INTERVAL` | `1s` | 양수, 유한 | +| `dispatch.max-global-concurrency` | `APP_NOTIFICATION_PLATFORM_MAX_CONCURRENCY` | `64` | 양수 | +| `dispatch.max-additional-attempts` | `APP_NOTIFICATION_PLATFORM_MAX_ADDITIONAL_ATTEMPTS` | `4` | 0 이상 | +| `dispatch.max-queue-age` | `APP_NOTIFICATION_PLATFORM_MAX_QUEUE_AGE` | `24h` | 양수 | | `dispatch.allow-ambiguous-fallback` | `APP_NOTIFICATION_PLATFORM_ALLOW_AMBIGUOUS_FALLBACK` | `false` | boolean | -Every value is bounded. "Unlimited" is not an accepted configuration. +모든 값에 상한이 있다. 「무제한」은 받는 설정이 아니다. -The lease must outlast a provider call plus its timeout. Below that, a delivery a live worker is -still waiting on gets claimed by a second worker, and the recipient receives the notification twice. +lease는 provider 호출과 그 시간 상한보다 길어야 한다. 그보다 짧으면, 살아 있는 worker가 아직 기다리는 전달을 두 번째 +worker가 claim하고, 수신자는 알림을 두 번 받는다. -## Callbacks +## 콜백 -| Property | Environment variable | Default | Bound | +| 속성 | 환경 변수 | 기본값 | 범위 | |---|---|---|---| | `callbacks.enabled` | `APP_NOTIFICATION_PLATFORM_CALLBACKS_ENABLED` | `false` | boolean | | `callbacks.max-body-bytes` | `APP_NOTIFICATION_PLATFORM_CALLBACK_MAX_BODY_BYTES` | `65251` | 1..65251 | -| `callbacks.replay-skew` | `APP_NOTIFICATION_PLATFORM_CALLBACK_REPLAY_SKEW` | `1h` | positive; SNS messages whose `Timestamp` is further than this from receipt, either way, are rejected. The default is SNS's longest HTTP/S retry period (3,600 s), so a bounce or complaint SNS redelivers after an outage is still accepted; a replay inside the window is a duplicate in the provider event ledger, not a second event (review 05-20) | -| `callbacks.trusted-proxies` | `APP_NOTIFICATION_PLATFORM_CALLBACK_TRUSTED_PROXIES` | *(empty)* | CSV of peer addresses | +| `callbacks.replay-skew` | `APP_NOTIFICATION_PLATFORM_CALLBACK_REPLAY_SKEW` | `1h` | 양수. `Timestamp`가 받은 시각에서 이보다 멀리(앞이든 뒤든) 떨어진 SNS 메시지는 거절한다. 기본값은 SNS의 HTTP/S 재시도 기간 중 가장 긴 값(3,600 s)이라, 장애 뒤에 SNS가 다시 보내는 bounce·complaint도 받는다. 창 안의 replay는 provider event ledger에서 중복이지 두 번째 이벤트가 아니다(review 05-20) | -콜백 응답: 기록(중복 포함) `204`, 거절 `400`(서명·topic·시각·형식), 본문 초과 `413`. SNS 서명 인증서를 가져오지 못하면(5xx·408·429·네트워크 실패) 거절하지 않고 `503`+`Retry-After`로 답한다 — SNS는 4xx를 처리 완료로 보고 재전송을 멈추지만 5xx는 다시 보낸다(review 05-20). 인증서 URL이 그 밖의 4xx(403·404 등)로 답하면 SNS가 발급하지 않은 인증서를 가리킨 위조 콜백이므로 서명 검증 실패로 `400` 거절하고 보안 감사(`callbackSignatureRejected`)에 남긴다(review 2026-11-03 RR-07-03). 호스트 검사를 통과한 URL이라 답하는 쪽은 SNS다. +콜백 응답: 기록(중복 포함) `204`, 거절 `400`(서명·topic·시각·형식), 본문 초과 `413`. SNS 서명 인증서를 가져오지 +못하면(5xx·408·429·네트워크 실패) 거절하지 않고 `503`+`Retry-After`로 답한다. SNS는 4xx를 처리 완료로 보고 재전송을 +멈추지만 5xx는 다시 보낸다(review 05-20). 인증서 URL이 그 밖의 4xx(403·404 등)로 답하면 SNS가 발급하지 않은 인증서를 +가리킨 위조 콜백이므로 서명 검증 실패로 `400` 거절하고 보안 감사(`callbackSignatureRejected`)에 남긴다(review +2026-11-03 RR-07-03). 호스트 검사를 통과한 URL이라 답하는 쪽은 SNS다. -여러 provider가 요청 URL에 서명하므로, 그 URL을 잘못 재구성하면 정상 webhook이 전부 서명 실패가 된다. -`trusted-proxies`가 비어 있으면 forwarded 헤더를 **믿지 않고** 컨테이너가 관측한 값을 쓴다. 무조건 믿으면 -아무 호출자나 자기 서명이 검증될 URL을 고를 수 있어 서명 자체가 무의미해진다. 로드밸런서 뒤에 있는 배포는 -그 peer를 명시한다. +여러 provider가 요청 URL에 서명하므로, 그 URL을 잘못 재구성하면 정상 webhook이 전부 서명 실패가 된다. provider가 +서명한 URL은 컨테이너가 보고한 값으로 다시 만든다. 콜백 전용 proxy 목록은 없다. 로드밸런서 뒤에 있는 배포는 +`APP_SERVER_FORWARD_HEADERS_STRATEGY=native`로 두고 그 proxy를 `server.tomcat.remoteip.internal-proxies`에 적는다. +forwarded 헤더를 무조건 믿으면 아무 호출자나 자기 서명이 검증될 URL을 고를 수 있어 서명 자체가 무의미해진다. -65251 is not a round number by accident: it is the ciphertext column's 65536 bytes minus the largest -envelope the protector writes — a version byte, a key-id length byte, a key id of up to 255 bytes, the -AES-GCM nonce and tag. A larger configured value is refused when the settings bind, so the capability -does not start; before that check existed it passed every layer above the database and failed the -`CHECK` constraint after the callback had already been acknowledged to the provider. The shipped -default was 65508 (nonce and tag only) for a while after the envelope gained its key id, and every -deployment that turned the platform on failed to start until it was corrected (review 2026-11-01 -r3-i, found by booting the compose lanes). +65251은 우연히 고른 수가 아니다. 암호문 칸의 65536바이트에서 protector가 쓰는 가장 큰 envelope를 뺀 값이다. version +바이트, key id 길이 바이트, 255바이트까지의 key id, AES-GCM nonce와 tag다. 이보다 큰 값은 설정을 묶을 때 거부되므로 +capability가 뜨지 않는다. 그 검사가 생기기 전에는 DB 위의 모든 층을 통과한 뒤, 콜백을 provider에 이미 확인 응답한 다음 +`CHECK` 제약에서 실패했다. -## Provider profiles +> 이력: envelope에 key id가 붙은 뒤에도 한동안 내보낸 기본값이 65508(nonce와 tag만 뺀 값)이었고, 플랫폼을 켠 배포는 그 +> 값을 고칠 때까지 모두 뜨지 못했다(review 2026-11-01 r3-i, compose lane을 띄워서 찾음). -Profiles are a map under `providers`, keyed by profile id. Arbitrary deployment-chosen ids can be -supplied as YAML or through Spring relaxed binding (`APP_NOTIFICATION_PLATFORM_PROVIDERS__`). -The shipped reference profiles `smtp` and `ses` additionally expose explicit `APP_NOTIFICATION_PLATFORM_SMTP_*` -and `APP_NOTIFICATION_PLATFORM_SES_*` aliases so operators do not have to invent binding names. +## provider profile -| Field | Meaning | +profile은 `providers` 아래의 map이고, 키는 profile id다. 배포가 정한 아무 id나 YAML이나 Spring relaxed binding +(`APP_NOTIFICATION_PLATFORM_PROVIDERS__`)으로 줄 수 있다. 내보내는 참조 profile `smtp`와 `ses`는 그 밖에 +`APP_NOTIFICATION_PLATFORM_SMTP_*`와 `APP_NOTIFICATION_PLATFORM_SES_*` 별칭도 드러내므로, 운영자가 바인딩 이름을 +지어낼 필요가 없다. + +| 칸 | 뜻 | |---|---| -| `type` | `SES`, `SMTP` — a closed enum, so an unknown value fails binding rather than assembling into nothing | -| `enabled` | A disabled profile is bound and validated but contributes no runtime | -| `primary-for-channel` | Exactly one primary per channel | -| `environment` | Required when enabled | -| `credential-profile` | Provider credential key id resolved through `SecretMaterialProvider`; never inline secret material | -| `timeout` | Positive and finite | -| `max-concurrency` | Positive | -| `rate-per-second` | Positive | +| `type` | `SES`, `SMTP`. 닫힌 enum이라 모르는 값은 아무것도 조립하지 않고 넘어가는 대신 바인딩에서 실패한다 | +| `enabled` | 꺼진 profile도 묶이고 검증되지만 런타임에 아무것도 보태지 않는다 | +| `primary-for-channel` | 채널마다 primary는 정확히 하나 | +| `environment` | 켜면 필요하다 | +| `credential-profile` | `SecretMaterialProvider`로 푸는 provider 자격 증명 key id. secret 값을 직접 적지 않는다 | +| `timeout` | 양수, 유한 | +| `max-concurrency` | 양수 | +| `rate-per-second` | 양수 | -A profile pins provider type, environment, credential profile, timeouts, concurrency and rate limit. -Sender identity and credential profile are separate concerns. +profile 하나가 provider 종류, 환경, 자격 증명 profile, 시간 상한, 동시성, 속도 제한을 고정한다. 보내는 쪽 신원과 자격 +증명 profile은 서로 다른 문제다. -### SES profile fields +### SES profile 칸 -An enabled SES profile adds a typed `ses` block: +켜진 SES profile에는 타입이 있는 `ses` 블록이 더해진다. -| Field | Meaning | +| 칸 | 뜻 | |---|---| -| `ses.endpoint` | SES API base URI, used as the AWS SDK client's endpoint override | -| `ses.region` | AWS region the SDK signs for | -| `ses.sender-identity` | verified SES From identity | -| `ses.access-key-id` | AWS access key id; identifier only, not secret material | -| `ses.configuration-set` | optional SES configuration-set name | -| `ses.allowed-topic-arns` | SNS topic ARNs whose SES events this profile accepts (`APP_NOTIFICATION_PLATFORM_SES_ALLOWED_TOPIC_ARNS`, comma-separated). Required when `callbacks.enabled=true`: binding fails without it, because a valid SNS signature only proves AWS sent the message and anyone can own a topic | -| `credential-profile` | key id for the secret access-key material; generation 1 is activated at assembly | +| `ses.endpoint` | SES API 기본 URI. AWS SDK 클라이언트의 endpoint override로 쓴다 | +| `ses.region` | SDK가 서명하는 AWS region | +| `ses.sender-identity` | 검증된 SES From 신원 | +| `ses.access-key-id` | AWS access key id. 식별자일 뿐 secret 값이 아니다 | +| `ses.configuration-set` | 선택. SES configuration-set 이름 | +| `ses.allowed-topic-arns` | 이 profile이 SES 이벤트를 받는 SNS topic ARN(`APP_NOTIFICATION_PLATFORM_SES_ALLOWED_TOPIC_ARNS`, 쉼표로 구분). `callbacks.enabled=true`면 필요하다. 없으면 바인딩이 실패한다. 유효한 SNS 서명은 AWS가 메시지를 보냈다는 것만 증명하고, topic은 누구나 가질 수 있기 때문이다 | +| `credential-profile` | secret access key 값의 key id. 조립할 때 세대 1이 활성화된다 | -The shipped reference profile is `providers.ses` and is disabled by default. It is controlled by -`APP_NOTIFICATION_PLATFORM_SES_*`; its secret material comes from -`APP_NOTIFICATION_PLATFORM_PROVIDER_CREDENTIAL_KEY`, whose active key id must match -`APP_NOTIFICATION_PLATFORM_SES_CREDENTIAL_KEY_ID`. +내보내는 참조 profile은 `providers.ses`이고 기본으로 꺼져 있다. `APP_NOTIFICATION_PLATFORM_SES_*`로 다룬다. secret 값은 +`APP_NOTIFICATION_PLATFORM_PROVIDER_CREDENTIAL_KEY`에서 오고, 그 활성 key id는 +`APP_NOTIFICATION_PLATFORM_SES_CREDENTIAL_KEY_ID`와 같아야 한다. -`type` lists only the families the shipped composition can assemble. Current shipped -reachability is: +`type`에는 내보내는 조립이 만들 수 있는 family만 있다. 지금 내보내는 것으로 닿는 범위는 다음과 같다. -| Provider type | Contract/adapter code | Shipped dispatch assembler | Shipped callback assembler | What happens when enabled for dispatch | +| provider 종류 | 계약·어댑터 코드 | 내보내는 발송 assembler | 내보내는 콜백 assembler | 발송용으로 켜면 | |---|---|---|---|---| -| `SMTP` | yes | **yes** | no | assembles when Spring Mail relay settings are complete | -| `SES` | yes | **yes** | **yes** | assembles an EMAIL runtime from the typed `ses` block; SNS callback verification remains available in `INGEST_ONLY` | +| `SMTP` | 있음 | **있음** | 없음 | Spring Mail relay 설정이 다 있으면 조립한다 | +| `SES` | 있음 | **있음** | **있음** | 타입 있는 `ses` 블록으로 EMAIL 런타임을 조립한다. SNS 콜백 검증은 `INGEST_ONLY`에서도 쓸 수 있다 | -APNs, FCM, Twilio, Web Push and Webhook adapters used to ship as protocol code with no assembler, so -enabling one failed startup. They were removed; the `docs/capability-status.md` "제거된 코드" table -names the last commit that had them. Adding a family back means adding its adapter, a -`ProviderRuntimeAssembler`, its `ProviderType` constant and the settings/secret inputs it actually -needs, together. +APNs, FCM, Twilio, Web Push, Webhook 어댑터는 assembler 없이 프로토콜 코드로만 들어 있어서 켜면 기동이 실패했다. 그래서 +지웠다. 마지막으로 그것을 가진 커밋은 `docs/capability-status.md` 「제거된 코드」 표가 적는다. family를 다시 더하려면 +그 어댑터, `ProviderRuntimeAssembler`, `ProviderType` 상수, 실제로 필요한 설정·secret 입력을 함께 더한다. ## SMTP relay -The one provider profile the template ships, off. A deployment that wants the common case sets -`APP_NOTIFICATION_PLATFORM_SMTP_ENABLED=true` and the relay address; one that wants a different -profile id or a second family declares it in its own YAML instead. +템플릿이 내보내는 provider profile 하나이고, 꺼져 있다. 흔한 경우를 원하는 배포는 +`APP_NOTIFICATION_PLATFORM_SMTP_ENABLED=true`와 relay 주소를 준다. 다른 profile id나 두 번째 family를 원하는 배포는 +대신 자기 YAML에 선언한다. -The profile and the relay are separate tables below because they answer different questions. The -profile says *which* provider serves EMAIL and under what limits; the relay says *what the transport -is*. Host, port and credentials are not here at all — they stay `spring.mail.*`, because Spring -already owns them and a second spelling would be a second thing to keep in step. +profile과 relay는 다른 질문에 답하므로 아래 두 표로 나눈다. profile은 *어느* provider가 EMAIL을 어떤 한도로 맡는지를 +말하고, relay는 *전송이 무엇인지*를 말한다. host, port, 자격 증명은 여기에 아예 없다. `spring.mail.*`에 그대로 둔다. +Spring이 이미 그것을 가지고 있고, 두 번째 표기는 맞춰 둘 것을 하나 더 만든다. -| Property | Environment variable | Default | Bound | +| 속성 | 환경 변수 | 기본값 | 범위 | |---|---|---|---| | `providers.smtp.enabled` | `APP_NOTIFICATION_PLATFORM_SMTP_ENABLED` | `false` | boolean | -| `providers.smtp.primary-for-channel` | `APP_NOTIFICATION_PLATFORM_SMTP_PRIMARY` | `true` | boolean; exactly one primary per channel | -| `providers.smtp.environment` | `APP_NOTIFICATION_PLATFORM_SMTP_ENVIRONMENT` | `local` | required when enabled | -| `providers.smtp.credential-profile` | `APP_NOTIFICATION_PLATFORM_SMTP_CREDENTIAL_PROFILE` | `default` | resolved through `SecretMaterialProvider`, never inline material | -| `providers.smtp.timeout` | `APP_NOTIFICATION_PLATFORM_SMTP_TIMEOUT` | `10s` | positive, finite | -| `providers.smtp.max-concurrency` | `APP_NOTIFICATION_PLATFORM_SMTP_MAX_CONCURRENCY` | `4` | positive | -| `providers.smtp.rate-per-second` | `APP_NOTIFICATION_PLATFORM_SMTP_RATE_PER_SECOND` | `10` | positive | +| `providers.smtp.primary-for-channel` | `APP_NOTIFICATION_PLATFORM_SMTP_PRIMARY` | `true` | boolean. 채널마다 primary는 정확히 하나 | +| `providers.smtp.environment` | `APP_NOTIFICATION_PLATFORM_SMTP_ENVIRONMENT` | `local` | 켜면 필요하다 | +| `providers.smtp.credential-profile` | `APP_NOTIFICATION_PLATFORM_SMTP_CREDENTIAL_PROFILE` | `default` | `SecretMaterialProvider`로 푼다. 값을 직접 적지 않는다 | +| `providers.smtp.timeout` | `APP_NOTIFICATION_PLATFORM_SMTP_TIMEOUT` | `10s` | 양수, 유한 | +| `providers.smtp.max-concurrency` | `APP_NOTIFICATION_PLATFORM_SMTP_MAX_CONCURRENCY` | `4` | 양수 | +| `providers.smtp.rate-per-second` | `APP_NOTIFICATION_PLATFORM_SMTP_RATE_PER_SECOND` | `10` | 양수 | -| Property | Environment variable | Default | Bound | +| 속성 | 환경 변수 | 기본값 | 범위 | |---|---|---|---| -| `smtp.sender-identity` | `APP_NOTIFICATION_PLATFORM_SMTP_SENDER_IDENTITY` | `no-reply@example.invalid` | address | -| `smtp.dispatch-concurrency` | `APP_NOTIFICATION_PLATFORM_SMTP_DISPATCH_CONCURRENCY` | `4` | positive | +| `smtp.sender-identity` | `APP_NOTIFICATION_PLATFORM_SMTP_SENDER_IDENTITY` | `no-reply@example.invalid` | 주소 | +| `smtp.dispatch-concurrency` | `APP_NOTIFICATION_PLATFORM_SMTP_DISPATCH_CONCURRENCY` | `4` | 양수 | -SMTP transport configuration has one owner: Spring Mail. The actual `JavaMailSenderImpl` must use required STARTTLS (`mail.smtp.starttls.enable=true` plus `mail.smtp.starttls.required=true`) or implicit TLS (`mail.smtp.ssl.enable=true`). It must also have positive `mail.smtp.connectiontimeout`, `mail.smtp.timeout`, and `mail.smtp.writetimeout` values. SMTP assembly fails before serving traffic when those properties are absent or invalid. +SMTP 전송 설정의 소유자는 Spring Mail 하나다. 실제 `JavaMailSenderImpl`은 필수 STARTTLS +(`mail.smtp.starttls.enable=true`와 `mail.smtp.starttls.required=true`)나 암묵적 TLS(`mail.smtp.ssl.enable=true`)를 +써야 한다. `mail.smtp.connectiontimeout`, `mail.smtp.timeout`, `mail.smtp.writetimeout`도 양수여야 한다. 이 속성이 +없거나 틀리면 SMTP 조립이 트래픽을 받기 전에 실패한다. -The native environment contract is `SPRING_MAIL_HOST`, `SPRING_MAIL_PORT`, optional -`SPRING_MAIL_USERNAME` / secret `SPRING_MAIL_PASSWORD`, plus the -`SPRING_MAIL_PROPERTIES_MAIL_SMTP_*` TLS and timeout keys listed in `.env.example`. These names stay -Spring-native because Spring Boot itself owns and consumes `spring.mail.*`; the notification module -does not create a second alias for the same relay. +환경 변수 계약은 Spring 그대로다. `SPRING_MAIL_HOST`, `SPRING_MAIL_PORT`, 선택인 `SPRING_MAIL_USERNAME`과 secret +`SPRING_MAIL_PASSWORD`, 그리고 `.env.example`에 있는 `SPRING_MAIL_PROPERTIES_MAIL_SMTP_*` TLS·시간 상한 키다. Spring +Boot 자신이 `spring.mail.*`를 가지고 읽으므로 이름을 Spring 그대로 둔다. 알림 모듈은 같은 relay에 두 번째 별칭을 +만들지 않는다. -The default sender is an RFC 2606 reserved domain that resolves nowhere, so a deployment that forgot -to set one produces a traceable bounce instead of mail apparently sent from an address it does not -own. +기본 보내는 주소는 어디로도 풀리지 않는 RFC 2606 예약 도메인이다. 그래서 보내는 주소 설정을 잊은 배포는, 자기가 +가지지 않은 주소로 메일을 보낸 것처럼 보이는 대신 추적할 수 있는 bounce를 낸다. -## Startup failures +## 기동 실패 -Startup fails rather than degrading when: +다음이면 기능을 줄여 뜨지 않고 기동이 실패한다. -- a payload or queue setting is unbounded -- a timeout is negative -- a TTL-required profile has no expiry source -- a callback signing secret is missing -- a production profile enables trust-all -- an SES profile is missing its `ses` block, or callbacks are on and `ses.allowed-topic-arns` is empty -- two provider profiles share an id -- a route points only at disabled providers -- `mode` is `SERVING` and no provider profile is enabled -- the notification schema stream is not applied and promoted +- payload나 큐 설정에 상한이 없다 +- 시간 상한이 음수다 +- TTL이 필요한 profile에 만료 출처가 없다 +- 콜백 서명 secret이 없다 +- 운영 profile이 trust-all을 켠다 +- SES profile에 `ses` 블록이 없거나, 콜백이 켜졌는데 `ses.allowed-topic-arns`가 비어 있다 +- 두 provider profile의 id가 같다 +- route가 꺼진 provider만 가리킨다 +- `mode`가 `SERVING`인데 켜진 provider profile이 없다 +- 알림 스키마 stream이 적용·승격되지 않았다 -## Secrets +## secret -All key material arrives through `SecretMaterialProvider`. Nothing is read from source, from a -committed file, or from a plaintext log. Contact point encryption and lookup HMAC keys must be -distinct, and the encryption key must be exactly 256 bits. +키 값은 모두 `SecretMaterialProvider`로 들어온다. 소스, 커밋한 파일, 평문 로그에서는 아무것도 읽지 않는다. 연락처 +암호화 키와 조회 HMAC 키는 서로 달라야 하고, 암호화 키는 정확히 256비트여야 한다. -Seven purposes, seven keys. Each is base64 of at least 32 bytes and each must differ from every -other; the platform decodes them at startup and refuses to boot if one is blank, short or shared. A -blank value used to be skipped, which meant the platform started without the key and found out on -the first contact point — in production, on a recipient's notification. +목적 일곱, 키 일곱이다. 각각 32바이트 이상의 base64이고 다른 모든 키와 달라야 한다. 플랫폼은 기동할 때 키를 풀어 +보고, 하나라도 비었거나 짧거나 겹치면 뜨기를 거부한다. 전에는 빈 값을 건너뛰었고, 그래서 플랫폼이 키 없이 뜬 뒤 첫 +연락처에서야, 운영에서는 수신자의 알림에서야 그것을 알았다. -Every default below is **unset**, deliberately. Supply the values out of band, per environment. Do -not write one into this table, into `application.yml`, into an `.env` file that is tracked, or into -any example: a value that appears in the repository is a value that has been disclosed. +아래 기본값은 모두 일부러 **비어 있다**. 값은 환경마다 따로 준다. 이 표, `application.yml`, 추적되는 `.env` 파일, 어느 +예시에도 값을 쓰지 않는다. 저장소에 나타난 값은 이미 드러난 값이다. -| Purpose | Key material | Active key id | +| 목적 | 키 값 | 활성 key id | |---|---|---| -| Contact point encryption | `APP_NOTIFICATION_PLATFORM_CONTACT_ENCRYPTION_KEY` | `APP_NOTIFICATION_PLATFORM_CONTACT_ENCRYPTION_KEY_ID` | -| Contact point lookup HMAC | `APP_NOTIFICATION_PLATFORM_CONTACT_LOOKUP_HMAC_KEY` | `APP_NOTIFICATION_PLATFORM_CONTACT_LOOKUP_HMAC_KEY_ID` | -| Callback signing | `APP_NOTIFICATION_PLATFORM_CALLBACK_SIGNING_KEY` | `APP_NOTIFICATION_PLATFORM_CALLBACK_SIGNING_KEY_ID` | -| Callback fingerprint HMAC | `APP_NOTIFICATION_PLATFORM_CALLBACK_FINGERPRINT_HMAC_KEY` | `APP_NOTIFICATION_PLATFORM_CALLBACK_FINGERPRINT_HMAC_KEY_ID` | -| Provider credential encryption | `APP_NOTIFICATION_PLATFORM_PROVIDER_CREDENTIAL_KEY` | `APP_NOTIFICATION_PLATFORM_PROVIDER_CREDENTIAL_KEY_ID` | -| Provider request lookup HMAC | `APP_NOTIFICATION_PLATFORM_PROVIDER_REQUEST_LOOKUP_HMAC_KEY` | `APP_NOTIFICATION_PLATFORM_PROVIDER_REQUEST_LOOKUP_HMAC_KEY_ID` | -| Payload encryption | `APP_NOTIFICATION_PLATFORM_PAYLOAD_ENCRYPTION_KEY` | `APP_NOTIFICATION_PLATFORM_PAYLOAD_ENCRYPTION_KEY_ID` | +| 연락처 암호화 | `APP_NOTIFICATION_PLATFORM_CONTACT_ENCRYPTION_KEY` | `APP_NOTIFICATION_PLATFORM_CONTACT_ENCRYPTION_KEY_ID` | +| 연락처 조회 HMAC | `APP_NOTIFICATION_PLATFORM_CONTACT_LOOKUP_HMAC_KEY` | `APP_NOTIFICATION_PLATFORM_CONTACT_LOOKUP_HMAC_KEY_ID` | +| 콜백 서명 | `APP_NOTIFICATION_PLATFORM_CALLBACK_SIGNING_KEY` | `APP_NOTIFICATION_PLATFORM_CALLBACK_SIGNING_KEY_ID` | +| 콜백 fingerprint HMAC | `APP_NOTIFICATION_PLATFORM_CALLBACK_FINGERPRINT_HMAC_KEY` | `APP_NOTIFICATION_PLATFORM_CALLBACK_FINGERPRINT_HMAC_KEY_ID` | +| provider 자격 증명 암호화 | `APP_NOTIFICATION_PLATFORM_PROVIDER_CREDENTIAL_KEY` | `APP_NOTIFICATION_PLATFORM_PROVIDER_CREDENTIAL_KEY_ID` | +| provider 요청 조회 HMAC | `APP_NOTIFICATION_PLATFORM_PROVIDER_REQUEST_LOOKUP_HMAC_KEY` | `APP_NOTIFICATION_PLATFORM_PROVIDER_REQUEST_LOOKUP_HMAC_KEY_ID` | +| payload 암호화 | `APP_NOTIFICATION_PLATFORM_PAYLOAD_ENCRYPTION_KEY` | `APP_NOTIFICATION_PLATFORM_PAYLOAD_ENCRYPTION_KEY_ID` | -A key id is not secret — an id identifies key material without revealing it — but it is required, -and it has no default on purpose. A constant id makes a rotation indistinguishable from the key it -replaced, so nothing could decrypt what was written before it. Change the id in the same deployment -that changes the material, and keep the superseded key readable under its old id until the data it -wrote has been re-encrypted. The rotation sequence is in -[at-rest-threat-model.md](at-rest-threat-model.md). +key id는 secret이 아니다. id는 키 값을 드러내지 않고 그것을 가리킨다. 그래도 필요하고, 일부러 기본값이 없다. 고정된 +id는 교체를 바뀌기 전 키와 구별할 수 없게 만들어서, 그 전에 쓴 것을 아무것도 풀지 못하게 한다. 키 값을 바꾸는 배포에서 +id도 함께 바꾸고, 밀려난 키는 그 키로 쓴 데이터를 다시 암호화할 때까지 옛 id로 읽을 수 있게 둔다. 교체 순서는 +[at-rest-threat-model.md](at-rest-threat-model.md)에 있다. -## Readiness +## readiness -The platform contributes a `notifications` actuator endpoint and a health indicator. It reports DOWN -when a provider's credentials were rejected, when a configured provider has no channel route, and -when the measured backlog, stuck-lease count, projection lag or reconciliation lag passes the -thresholds in `NotificationServingThresholds`. See [operations.md](operations.md). +플랫폼은 `notifications` actuator 엔드포인트와 health indicator를 보탠다. provider 자격 증명이 거부됐을 때, 설정된 +provider에 채널 route가 없을 때, 그리고 잰 backlog, 멈춘 lease 수, projection 지연, 맞추기(reconciliation) 지연이 +`NotificationServingThresholds`의 임계값을 넘을 때 DOWN을 보고한다. [operations.md](operations.md)를 본다. diff --git a/docs/notification/delivery-evidence.md b/docs/notification/delivery-evidence.md index a01437d9..d71fc7ce 100644 --- a/docs/notification/delivery-evidence.md +++ b/docs/notification/delivery-evidence.md @@ -1,6 +1,6 @@ -# Delivery evidence model +# 전달 증거 모델 -## The shape +## 모양 ```text NotificationRequest @@ -12,39 +12,37 @@ NotificationRequest + EngagementFacts + SuppressionFacts ``` -Four identities, four lifecycles. A logical request is not a recipient job, a recipient job is not a -provider attempt, and a provider attempt is not the event stream that describes it. +신원 넷, 수명 주기 넷이다. 논리 요청은 수신자 작업이 아니고, 수신자 작업은 provider attempt가 아니고, provider attempt는 +그것을 설명하는 이벤트 흐름이 아니다. -## Why not one status enum +## 상태 enum 하나가 아닌 이유 -A single linear status would have to answer "what happened?" with one value, and the real answers do -not fit on one line: +일직선 상태 하나는 「무슨 일이 있었나」에 값 하나로 답해야 하는데, 실제 답은 한 줄에 들어가지 않는다. -- An email can be `DELIVERED` and then generate a complaint. Both facts are true and both matter: - one for reporting, the other for suppression. -- Twilio does not guarantee callback ordering, so `sent` routinely arrives after `delivered`. Under - an ordinal rule the later, weaker event silently overwrites the stronger one. -- APNs may accept a notification and then store, replace or discard it. +- 이메일은 `DELIVERED`가 된 뒤 complaint를 낼 수 있다. 두 사실이 다 참이고 다 중요하다. 하나는 보고에, 다른 하나는 + 억제에 쓴다. +- Twilio는 콜백 순서를 보장하지 않아서 `sent`가 `delivered` 뒤에 오는 일이 흔하다. 순번 규칙에서는 뒤에 온 약한 + 이벤트가 강한 이벤트를 조용히 덮어쓴다. +- APNs는 알림을 수락한 뒤 저장하거나, 바꾸거나, 버릴 수 있다. -So the ledger stores events and a channel projector merges them through an explicit transition table. -`StandardDeliveryProjector` holds the shared rules; provider projectors add only their own event -vocabulary. +그래서 ledger는 이벤트를 저장하고, channel projector가 명시한 전이 표로 그것을 합친다. 공통 규칙은 +`StandardDeliveryProjector`가 가지고, provider projector는 자기 이벤트 어휘만 더한다. -## Merge rules +## 합치는 규칙 -| Transition | Result | +| 전이 | 결과 | |---|---| -| `sent` → `delivered` | applied | -| `delivered` → `sent` | ignored, event still stored | -| `delivered` → `complaint` | complaint fact added, delivery preserved | -| `complaint` → `delivered` | delivery applied, complaint preserved | -| `accepted` → `bounced` | applied | -| `read` → `displayed` | ignored | -| hard bounce → `delivered` | ignored, hard bounce is terminal | +| `sent` → `delivered` | 적용 | +| `delivered` → `sent` | 무시, 이벤트는 저장 | +| `delivered` → `complaint` | complaint 사실을 더하고 전달은 유지 | +| `complaint` → `delivered` | 전달을 적용하고 complaint는 유지 | +| `accepted` → `bounced` | 적용 | +| `read` → `displayed` | 무시 | +| hard bounce → `delivered` | 무시, hard bounce는 끝 상태 | -Engagement (`opened`, `clicked`) is stored beside the delivery outcome and never changes it. +참여(`opened`, `clicked`)는 전달 결과 옆에 저장하고 그것을 바꾸지 않는다. -## Ambiguity +## 모호함 ```text platform ──── send ────▶ provider @@ -53,10 +51,9 @@ platform ──── send ────▶ provider ✗ connection reset ``` -The platform may hold no provider request id while the notification really was sent. The attempt -records `requestStarted`, `requestBodyCommitted`, `providerResponseReceived` and an -`EvidenceCertainty` for each, so a later decision can tell "we know nothing was sent" apart from "we -could not read the answer". +알림이 실제로 보내졌는데 플랫폼은 provider request id를 하나도 가지지 못할 수 있다. attempt는 `requestStarted`, +`requestBodyCommitted`, `providerResponseReceived`와 그 각각의 `EvidenceCertainty`를 기록한다. 그래서 나중의 판단이 +「아무것도 보내지 않았음을 안다」와 「답을 읽지 못했다」를 가릴 수 있다. -`ProviderSubmissionResult` enforces this: an ambiguous result may not claim `PROVIDER_ACCEPTED`, and -no submission result of any kind may carry a delivery outcome. +`ProviderSubmissionResult`가 이것을 강제한다. 모호한 결과는 `PROVIDER_ACCEPTED`를 주장할 수 없고, 어떤 제출 결과도 +전달 결과를 실을 수 없다. diff --git a/docs/notification/migration-guide.md b/docs/notification/migration-guide.md index 9e50ee4b..8813a32d 100644 --- a/docs/notification/migration-guide.md +++ b/docs/notification/migration-guide.md @@ -1,45 +1,38 @@ -# Migration guide +# 이행 안내 -## From the R0 routing seam +## R0 routing seam에서 -The pre-existing `dev.caskeleton.adapter.outbound.notification` router (`RoutingNotifier`, -`FailOpenNotificationProvider`, the Google email and Slack webhook seams) stays untouched. The -delivery platform lives beside it under `…notification.platform` and does not modify or delete any -R0 class. +이미 있던 `dev.caskeleton.adapter.outbound.notification` router(`RoutingNotifier`, `FailOpenNotificationProvider`, Google +email과 Slack webhook seam)는 건드리지 않는다. 전달 플랫폼은 그 옆 `…notification.platform` 아래에 있고, R0 클래스를 +고치거나 지우지 않는다. -Migration order per capability: +capability마다 이행 순서: -1. Register the contact points behind `ContactPointStorePort` so the platform owns protected values. -2. Publish the template version, and pin the template id, version and locale at every call site. -3. Move the call site from the router to the N1 typed facade for the channel. -4. Verify evidence in the snapshot rather than in the caller's return value: `submit()` is durable - acceptance and nothing more. -5. Remove the R0 route only after the platform route has produced provider evidence in the target - environment. +1. 플랫폼이 보호된 값을 가지도록 연락처를 `ContactPointStorePort` 뒤에 등록한다. +2. 템플릿 버전을 게시하고, 모든 호출 지점에서 템플릿 id, 버전, locale을 고정한다. +3. 호출 지점을 router에서 그 채널의 N1 typed facade로 옮긴다. +4. 증거는 호출자의 반환값이 아니라 snapshot에서 확인한다. `submit()`은 durable 수락일 뿐이다. +5. 대상 환경에서 플랫폼 route가 provider 증거를 낸 뒤에만 R0 route를 지운다. -## Return-value semantics change +## 반환값의 뜻이 바뀐다 -The R0 seam returned a send-shaped result. `NotificationReceipt` returns `notificationId`, a request -status and an acceptance time. Callers that treated the old return value as proof of delivery must be -changed; there is no compatibility shim, because a shim would have to invent the delivery claim this -platform exists to avoid. +R0 seam은 보낸 결과 모양을 돌려줬다. `NotificationReceipt`는 `notificationId`, 요청 상태, 수락 시각을 돌려준다. 옛 +반환값을 전달 증거로 다룬 호출자는 고쳐야 한다. 호환 shim은 없다. shim은 이 플랫폼이 피하려고 있는 전달 주장을 지어내야 +하기 때문이다. -## FCM target migration +## FCM 대상 이행 -Registration tokens keep working through `LegacyFcmRegistrationToken`. New registrations should use -`FcmInstallationId`. The two are distinct types, so a migration is a compile-time task rather than a -runtime guess. +registration token은 `LegacyFcmRegistrationToken`으로 계속 쓸 수 있다. 새 등록은 `FcmInstallationId`를 쓴다. 둘은 서로 +다른 타입이라 이행은 런타임 짐작이 아니라 컴파일 시점의 일이다. ## R1의 처분 (NOTIF-ADR-005) -이 문서는 R0 router → platform 이행만 설명해 왔고, `dev.caskeleton.application.notification` 직속의 -R1 public type 100개를 어떻게 할 것인지 다루지 않았다. 그래서 새 consumer가 어느 API를 써야 하는지 -문서 어디에도 답이 없었다. +이 문서는 R0 router → platform 이행만 설명해 왔고, `dev.caskeleton.application.notification` 직속의 R1 public type +100개를 어떻게 할 것인지 다루지 않았다. 그래서 새 consumer가 어느 API를 써야 하는지 문서 어디에도 답이 없었다. - **canonical은 `..notification.platform..`이다.** NOTIF-ADR-005가 근거와 함께 정한다. -- **application R1 public type은 2026-09-25에 삭제했다.** production consumer가 0건이었다. 남은 것은 - 단순 알림 포트 `NotificationPort`·`Notification`·`NotificationChannel`뿐이다. -- R1을 따라 만들어졌지만 composition root에서 한 번도 조립되지 않았던 outbound adapter의 - `catalog/`, `provider/`, `template/` 실험 구현도 제거했다. 실제 runtime은 - `dev.caskeleton.adapter.outbound.notification.platform..`만 사용한다. +- **application R1 public type은 2026-09-25에 삭제했다.** production consumer가 0건이었다. 남은 것은 단순 알림 포트 + `NotificationPort`·`Notification`·`NotificationChannel`뿐이다. +- R1을 따라 만들어졌지만 composition root에서 한 번도 조립되지 않았던 outbound adapter의 `catalog/`, `provider/`, + `template/` 실험 구현도 제거했다. 실제 runtime은 `dev.caskeleton.adapter.outbound.notification.platform..`만 사용한다. - 삭제 목록과 마지막 커밋은 `docs/capability-status.md`의 「제거된 코드」 표에 있다. diff --git a/docs/notification/module-mapping.md b/docs/notification/module-mapping.md index 13dd4e5e..24ad9f1a 100644 --- a/docs/notification/module-mapping.md +++ b/docs/notification/module-mapping.md @@ -1,39 +1,37 @@ -# Notification Delivery Platform — module mapping +# 알림 전달 플랫폼 — 모듈 대응표 -> Source design: `docs/design/2026-08-10-notification-platform-design.md` +> 출처 설계서: `docs/design/2026-08-10-notification-platform-design.md` > -> Source plan: `docs/history/plans/2026-08-10-notification-platform-implementation-plan.md` +> 출처 계획서: `docs/history/plans/2026-08-10-notification-platform-implementation-plan.md` -## Why a mapping exists +## 대응표가 있는 이유 -The plan was written against a hypothetical repository (`modules/notification/**`, root package -`io.backend.skeleton.notification`, 31 Gradle projects). This repository is a fail-closed -19-leaf Clean Architecture template: `src/settings.gradle` rejects any registry that does not -contain exactly the 19 modules in `src/config/architecture/modules.json`, and -`verifyCleanArchitectureDependencies` rejects any project edge outside `allowed_dependencies`. +계획은 가상의 저장소(`modules/notification/**`, root 패키지 `io.backend.skeleton.notification`, Gradle 프로젝트 31개)를 +두고 쓰였다. 이 저장소는 fail-closed Clean Architecture 템플릿이다. `src/settings.gradle`은 registry +(`src/config/architecture/modules.json`)를 읽고 검증한 뒤 등록된 프로젝트만 들이고, `verifyCleanArchitectureDependencies`는 +`allowed_dependencies` 밖의 프로젝트 edge를 거부한다. -Creating 31 new Gradle projects would violate HARD-STOP #5 of `AGENTS.md`. The package README -anticipates this and instructs the implementer to map dependency catalog and package/file paths onto -the host repository's rules while preserving the public contracts and reliability semantics. +Gradle 프로젝트 31개를 새로 만들면 `AGENTS.md`의 HARD-STOP #5를 어긴다. 패키지 README도 이것을 내다보고, 공개 계약과 +신뢰성 의미를 지키면서 의존성 카탈로그와 패키지·파일 경로를 받는 저장소의 규칙에 맞추라고 구현자에게 지시한다. -Every logical module of the plan is therefore implemented as a **package** inside the registered leaf -that owns its responsibility. No public contract, evidence rule, or reliability semantic is dropped. +그래서 계획의 논리 모듈마다 그 책임을 가진 등록 leaf 안의 **패키지**로 구현했다. 공개 계약, 증거 규칙, 신뢰성 의미는 +하나도 빠지지 않았다. -## Logical module → registered leaf +## 논리 모듈 → 등록 leaf -| Plan module | Registered leaf | Package | +| 계획 모듈 | 등록 leaf | 패키지 | |---|---|---| -| `notification-core-api` | `application-core` | `dev.caskeleton.application.notification.platform.api` | -| `notification-content-api` | `application-core` | `…platform.api.content` | -| `notification-contact-api` | `application-core` | `…platform.contact` | -| `notification-template-api` | `application-core` | `…platform.template` | -| `notification-policy` | `application-core` | `…platform.policy` | -| `notification-provider-spi` | `application-core` | `…platform.provider` | -| `notification-callback-api` | `application-core` | `…platform.callback` | -| `notification-inbox-api` | `application-core` | `…platform.inbox` | -| `notification-admin-api` | `application-core` | `…platform.admin` | -| `notification-security` (ports) | `application-core` | `…platform.security` | -| `notification-observability` (ports) | `application-core` | `…platform.observation` | +| `notification-core-api` | `application-notification` | `dev.caskeleton.application.notification.platform.api` | +| `notification-content-api` | `application-notification` | `…platform.api.content` | +| `notification-contact-api` | `application-notification` | `…platform.contact` | +| `notification-template-api` | `application-notification` | `…platform.template` | +| `notification-policy` | `application-notification` | `…platform.policy` | +| `notification-provider-spi` | `application-notification` | `…platform.provider` | +| `notification-callback-api` | `application-notification` | `…platform.callback` | +| `notification-inbox-api` | `application-notification` | `…platform.inbox` | +| `notification-admin-api` | `application-notification` | `…platform.admin` | +| `notification-security` (ports) | `application-notification` | `…platform.security` | +| `notification-observability` (ports) | `application-notification` | `…platform.observation` | | `notification-dispatch-runtime` | `adapter:outbound:notification` | `dev.caskeleton.adapter.outbound.notification.platform.dispatch` | | `notification-security` (AES-GCM/HMAC impl) | `adapter:outbound:notification` | `…platform.security` | | `notification-template-thymeleaf` (reference renderer) | `adapter:outbound:notification` | `…platform.template` | @@ -42,20 +40,20 @@ that owns its responsibility. No public contract, evidence rule, or reliability | `notification-observability` (Micrometer impl) | `adapter:outbound:notification` | `…platform.observation` | | `notification-admin-runtime` | `adapter:outbound:notification` | `…platform.admin` | | `notification-spring-boot-starter` | `adapter:outbound:notification` | `…platform.autoconfigure` | -| `notification-persistence-jpa` | `adapter:outbound:persistence-notification` | `dev.caskeleton.adapter.outbound.persistence.notification.platform` (store adapters), `….platform.entity` (JPA rows), `….platform.repository` (Spring Data interfaces and SQL text) | -| `notification-inbox-jpa` | `adapter:outbound:persistence-notification` | `…persistence.notification.platform` (`JpaNotificationInbox`, `InboxCommitEventPublisher`, `InboxOutboxRecordFactory`); row and repository in `….platform.entity` / `….platform.repository` | +| `notification-persistence-jpa` | `adapter:outbound:persistence-notification` | `dev.caskeleton.adapter.outbound.persistence.notification.platform`(저장소 어댑터), `….platform.entity`(JPA 행), `….platform.repository`(Spring Data interface와 SQL 문) | +| `notification-inbox-jpa` | `adapter:outbound:persistence-notification` | `…persistence.notification.platform`(`JpaNotificationInbox`, `InboxCommitEventPublisher`, `InboxOutboxRecordFactory`). 행과 repository는 `….platform.entity` / `….platform.repository` | | `notification-callback-mvc` | `adapter:inbound:web-notification` | `dev.caskeleton.adapter.inbound.web.notification.platform.callback` | | `notification-submission-mvc` | `adapter:inbound:web-notification` | `dev.caskeleton.adapter.inbound.web.notification.platform.submission` | -| application composition (use cases, callback bridge, `config/module-defaults/notification.yml`) | `composition:notification-platform` | `dev.caskeleton.composition.notification` | -| `notification-testkit` | test source sets of the owning leaves | `…platform.testkit` | +| 애플리케이션 조립(use case, 콜백 bridge, `config/module-defaults/notification.yml`) | `composition:notification-platform` | `dev.caskeleton.composition.notification` | +| `notification-testkit` | 소유 leaf의 test source set | `…platform.testkit` | -## Dependency-direction consequences +## 의존 방향의 결과 -The plan's module DAG (`*-api` → `provider-spi`/`policy` → runtime/adapters → starter) is preserved -by the leaf DAG that the registry already enforces: +계획의 모듈 DAG(`*-api` → `provider-spi`/`policy` → runtime/adapters → starter)는 registry가 이미 강제하는 leaf DAG로 +지켜진다. ```text -application-core (all *-api, provider SPI, policy, callback contracts) +application-notification (all *-api, provider SPI, policy, callback contracts; → application-core) ↑ ↑ ↑ adapter:outbound:notification adapter:outbound:persistence-notification adapter:inbound:web-notification ↑ ↑ (runtimeOnly, with persistence-jpa) ↑ (→ adapter:inbound:web) @@ -64,50 +62,40 @@ adapter:outbound:notification adapter:outbound:persistence-notification ad app-bootstrap (one line) ``` -Two plan edges cannot be expressed as project edges in this repository, and are replaced by ports: +계획의 edge 둘은 이 저장소에서 프로젝트 edge로 표현할 수 없어서 port로 바꿨다. -1. `notification-email-ses` → `httpclient platform`. (The Twilio, FCM, APNs, Web Push and - Webhook adapters that shared this edge were removed: none had an assembler.) - `adapter-outbound-notification` is not allowed to depend on `adapter-outbound-httpclient`, and - SES no longer needs it: the SES adapter sends through the AWS SDK v2 `sesv2` client (owner - decision 17), which signs requests itself. The adapter-local JDK HTTP gateway and SigV4 signer - were deleted with that change. The client is built per profile with SDK retries off, no default - credential chain (each request carries its profile's credential) and the profile's endpoint, - which still passes the notification routability guard. -2. `notification-inbox-jpa` → `optional messaging outbox integration`. - `adapter-outbound-persistence-notification` may not depend on `adapter-outbound-messaging`; the inbox - publishes through the existing persistence outbox tables plus the - `NotificationInboxSignalPort` application port, and `app-bootstrap` binds the relay. +1. `notification-email-ses` → `httpclient platform`. (이 edge를 함께 쓰던 Twilio, FCM, APNs, Web Push, Webhook 어댑터는 + assembler가 없어서 지웠다.) `adapter-outbound-notification`은 `adapter-outbound-httpclient`에 의존할 수 없고, SES는 + 이제 그것이 필요 없다. SES 어댑터는 스스로 요청에 서명하는 AWS SDK v2 `sesv2` 클라이언트로 보낸다(소유자 결정 17). + 어댑터 안의 JDK HTTP gateway와 SigV4 signer는 그 변경과 함께 지웠다. 클라이언트는 profile마다 SDK 재시도를 끄고, + 기본 credential chain 없이(요청마다 자기 profile의 자격 증명을 싣는다), profile의 endpoint로 만든다. 그 endpoint는 + 여전히 알림 routability guard를 통과한다. +2. `notification-inbox-jpa` → `optional messaging outbox integration`. `adapter-outbound-persistence-notification`은 + `adapter-outbound-messaging`에 의존할 수 없다. inbox는 이미 있는 persistence outbox 테이블과 애플리케이션 port + `NotificationInboxSignalPort`로 내보내고, outbox relay는 `composition:outbox-relay`가 조립한다. -## Commit policy +## 커밋 정책 -`AGENTS.md` pins commit policy to `human-only`. Step 5 (`git add` / `git commit`) of every plan task -is therefore intentionally **not** executed by the agent; the working tree carries the change and the -human owner commits. +`AGENTS.md`는 커밋 정책을 `human-only`로 고정한다. 그래서 계획의 모든 task에 있는 Step 5(`git add` / `git commit`)는 +에이전트가 일부러 **하지 않았다**. 작업 트리가 변경을 싣고, 사람 소유자가 커밋한다. -## Runtime reachability after the R1 adapter cleanup +## R1 어댑터 정리 뒤 런타임 도달 범위 -The application R1 contract covered by NOTIF-ADR-005 is a separate question from the abandoned -outbound implementation that had been built around it. The latter is gone: the notification leaf no -longer contains top-level `catalog/`, `provider/`, or `template/` R1 adapter packages. They had no -production composition consumer and were proved only by their own fakes. +NOTIF-ADR-005가 다루는 애플리케이션 R1 계약은, 그것을 둘러싸고 만들었다가 버린 outbound 구현과는 다른 문제다. 뒤의 것은 +없어졌다. 알림 leaf에는 최상위 `catalog/`, `provider/`, `template/` R1 어댑터 패키지가 더는 없다. 그것들은 운영 조립의 +consumer가 없었고 자기 fake로만 증명됐다. -The useful rendering invariant from that experiment was not discarded. R2 -`platform.template.TemplateSlotPolicy` now validates the final HTML against the reviewed tag and -attribute subset in addition to escaping substituted values. Active script markup, event-handler -attributes and non-HTTPS HTML links are refused. +그 실험의 쓸모 있던 렌더링 불변식은 버리지 않았다. R2 `platform.template.TemplateSlotPolicy`가 이제 치환한 값을 +escape하는 것에 더해, 최종 HTML을 검토한 태그·속성 부분집합과 대조한다. 실행되는 script markup, event handler 속성, +HTTPS가 아닌 HTML 링크는 거부한다. -R2 provider protocol packages remain because they implement the canonical platform SPI and have -contract tests. Their presence does **not** make them shipped dispatch runtimes. Current composition -reachability is SMTP and SES for dispatch, with SES also available for callback ingestion; the remaining -provider packages are extension assets until a composition contributes a `ProviderRuntimeAssembler` -with the settings and secret sources that family requires. See `support-matrix.md` for the explicit table. +R2 provider 프로토콜 패키지는 canonical 플랫폼 SPI를 구현하고 계약 테스트가 있어서 남아 있다. 남은 것은 `ses`와 +`smtp`이고, 둘 다 내보내는 조립이 발송에 쓴다(SES는 콜백 받기에도 쓴다). 다른 family는 조립이 그 family에 필요한 설정·secret +출처와 함께 `ProviderRuntimeAssembler`를 보탤 때 생긴다. 표는 `support-matrix.md`에 있다. -## R1 public types (NOTIF-ADR-005) +## R1 public type (NOTIF-ADR-005) -NOTIF-ADR-005 made `..notification.platform..` canonical. The R1 types directly under -`dev.caskeleton.application.notification` had no production consumer and were removed on -2026-09-25, together with the ArchUnit rule that kept the two namespaces apart. What remains there -is the simple notification port the adapter core implements — `NotificationPort`, `Notification`, -`NotificationChannel`. The removed types and their last commit are listed in -`docs/capability-status.md` under "제거된 코드". +NOTIF-ADR-005가 `..notification.platform..`을 canonical로 정했다. `dev.caskeleton.application.notification` 바로 아래의 +R1 타입은 운영 consumer가 없어서, 두 namespace를 떼어 놓던 ArchUnit 규칙과 함께 2026-09-25에 지웠다. 거기 남은 것은 +어댑터 core가 구현하는 단순 알림 port `NotificationPort`, `Notification`, `NotificationChannel`이다. 지운 타입과 마지막 +커밋은 `docs/capability-status.md` 「제거된 코드」에 있다. diff --git a/docs/notification/operations.md b/docs/notification/operations.md index dc47f3ff..707d7b55 100644 --- a/docs/notification/operations.md +++ b/docs/notification/operations.md @@ -1,6 +1,6 @@ -# Operations +# 운영 -## Runtime shape +## 런타임 모양 ```text durable queue (PostgreSQL, FOR UPDATE SKIP LOCKED) @@ -12,35 +12,31 @@ durable queue (PostgreSQL, FOR UPDATE SKIP LOCKED) → provider adapter ``` -Provider calls run outside every database transaction. The attempt row is committed first, so after a -crash the row is either absent (nothing was sent) or present in `DISPATCHING` (reconciliation has -something to ask about). +provider 호출은 모든 DB 트랜잭션 밖에서 돈다. attempt 행을 먼저 커밋하므로, 장애 뒤 그 행은 없거나(아무것도 보내지 +않음) `DISPATCHING`으로 있다(맞추기가 물어볼 것이 있음). -## Guards that exist for specific incidents +## 특정 장애를 막으려고 있는 장치 -| Guard | The incident it prevents | +| 장치 | 막는 장애 | |---|---| -| Credential failure opens the provider route | One expired key multiplied by a queue becomes a self-inflicted outage | -| Retry budget per provider profile | A provider outage turning every queued notification into its own retry loop | -| Ambiguous attempts block automatic fallback | A push whose response was lost arriving alongside the "just in case" SMS | -| Permits released during backoff | A slow provider pinning the whole concurrency budget on work that is only waiting | -| Fail-fast intake on capacity | An unbounded in-memory queue absorbing a burst it cannot survive | +| 자격 증명 실패가 provider route를 연다 | 만료된 키 하나가 큐만큼 곱해져 스스로 만든 장애가 된다 | +| provider profile마다 재시도 예산 | provider 장애가 큐의 모든 알림을 저마다의 재시도 반복으로 만든다 | +| 모호한 attempt는 자동 전환을 막는다 | 응답을 잃은 push와 「혹시 몰라」 보낸 SMS가 함께 도착한다 | +| 백오프 동안 허가를 돌려준다 | 느린 provider가 기다리기만 하는 일로 동시성 예산 전체를 붙잡는다 | +| 용량이 차면 받기를 바로 거부한다 | 상한 없는 메모리 큐가 버틸 수 없는 폭주를 받아들인다 | -## Scheduling +## 일정 -`scheduleAt` activates the job, `notBefore` is the earliest permitted provider submission, and -`expiresAt` blocks new attempts, retries and fallbacks. Suppression and expiry are re-checked -immediately before dispatch, because a scheduled notification can sit in the queue for hours and the -user may have opted out in the meantime. +`scheduleAt`은 작업을 활성화하고, `notBefore`는 provider 제출을 허용하는 가장 이른 시각이고, `expiresAt`은 새 attempt, +재시도, 전환을 막는다. 억제와 만료는 발송 직전에 다시 확인한다. 예약된 알림은 큐에서 몇 시간을 기다릴 수 있고, 그동안 +사용자가 수신을 거부했을 수 있다. -## Redrive +## 다시 보내기(redrive) -A redrive preserves `NotificationId` and `RecipientDeliveryId`, creates a new `DeliveryAttemptId`, and -reuses the pinned template version and rendered digest. Sending different content is a new -notification, not a redrive. Redriving an ambiguous attempt requires explicit duplicate-risk approval, -because the platform genuinely cannot tell whether the first submission reached the user. +redrive는 `NotificationId`와 `RecipientDeliveryId`를 유지하고, 새 `DeliveryAttemptId`를 만들고, 고정된 템플릿 버전과 +렌더링 digest를 다시 쓴다. 다른 내용을 보내는 것은 redrive가 아니라 새 알림이다. 모호한 attempt를 redrive하려면 중복 +위험 승인을 명시해야 한다. 첫 제출이 사용자에게 닿았는지 플랫폼이 정말로 알 수 없기 때문이다. -## Actuator surface +## actuator 표면 -Provider runtime states and generations, queue depth and age, callback and reconciliation health. -Never addresses, never credentials. +provider 런타임 상태와 세대, 큐 깊이와 나이, 콜백과 맞추기 상태. 주소와 자격 증명은 절대 싣지 않는다. diff --git a/docs/notification/provider-runbooks.md b/docs/notification/provider-runbooks.md index 1440bb31..ab5246b4 100644 --- a/docs/notification/provider-runbooks.md +++ b/docs/notification/provider-runbooks.md @@ -1,34 +1,34 @@ -# Provider runbooks +# provider runbook ## SMTP -| Symptom | Classification | Action | +| 증상 | 분류 | 조치 | |---|---|---| -| Final `2xx` after `DATA` | `CONFIRMED_ACCEPTED` / `PROVIDER_ACCEPTED` | None; this is acceptance, not inbox delivery | -| `4yz` | `TRANSIENT_PROVIDER` | Retry under budget and deadline | -| `5yz` | `PERMANENT_PROVIDER` or `INVALID_RECIPIENT` | Stop, or invalidate the contact point | -| Connection lost after `DATA` | `AMBIGUOUS_SUBMISSION` | Reconcile or escalate; do not resend automatically | +| `DATA` 뒤 최종 `2xx` | `CONFIRMED_ACCEPTED` / `PROVIDER_ACCEPTED` | 없음. 받은편지함 도착이 아니라 수락이다 | +| `4yz` | `TRANSIENT_PROVIDER` | 예산과 마감 안에서 다시 시도한다 | +| `5yz` | `PERMANENT_PROVIDER` 또는 `INVALID_RECIPIENT` | 멈추거나, 연락처를 무효로 한다 | +| `DATA` 뒤 연결 끊김 | `AMBIGUOUS_SUBMISSION` | 맞추거나 넘긴다. 자동으로 다시 보내지 않는다 | -Connection, read, write and pool-acquire timeouts are all finite. There is no unbounded timeout. +연결, 읽기, 쓰기, 풀 획득 시간 상한은 모두 유한하다. 상한 없는 시간 상한은 없다. ## Amazon SES -`MessageId` is acceptance evidence. SES itself documents that it can accept a request and then not -send, so `MessageId` is never mapped to `DELIVERED`. +`MessageId`는 수락 증거다. SES 자신이 요청을 수락한 뒤 보내지 않을 수 있다고 문서에 적으므로, `MessageId`는 절대 +`DELIVERED`로 매핑하지 않는다. -| Event | Normalized | +| 이벤트 | 정규화 | |---|---| -| `Send` | reinforces `PROVIDER_ACCEPTED` | +| `Send` | `PROVIDER_ACCEPTED`를 보강한다 | | `Delivery` | `DELIVERY_CONFIRMED` / `NETWORK_OR_CARRIER_ACCEPTED` | -| `DeliveryDelay` | delay fact | -| `Bounce` (permanent) | `BOUNCED_HARD` plus hard-bounce suppression | -| `Bounce` (transient) | `BOUNCED_SOFT`; retry policy input, not a suppression reason | -| `Complaint` | complaint fact plus suppression | +| `DeliveryDelay` | 지연 사실 | +| `Bounce` (permanent) | `BOUNCED_HARD`와 hard bounce 억제 | +| `Bounce` (transient) | `BOUNCED_SOFT`. 억제 사유가 아니라 재시도 정책의 입력이다 | +| `Complaint` | complaint 사실과 억제 | | `Reject` | `PROVIDER_REJECTED` | | `RenderingFailure` | `TEMPLATE_FAILURE` | -## Removed provider families +## 지운 provider family -Twilio, FCM, APNs, Web Push and Webhook adapters were removed because nothing assembled them; their -runbooks went with them. The last commit that had both is named in `docs/capability-status.md` -(제거된 코드). A deployment that adds one of these providers back writes its runbook here with it. +Twilio, FCM, APNs, Web Push, Webhook 어댑터는 아무것도 조립하지 않아서 지웠고, 그 runbook도 함께 지웠다. 둘을 모두 +가진 마지막 커밋은 `docs/capability-status.md`(제거된 코드)에 있다. 이 provider 중 하나를 다시 더하는 배포는 그 runbook을 +여기에 함께 쓴다. diff --git a/docs/notification/security-privacy.md b/docs/notification/security-privacy.md index 0bbf9e4f..99ef4919 100644 --- a/docs/notification/security-privacy.md +++ b/docs/notification/security-privacy.md @@ -1,54 +1,44 @@ -# Security and privacy +# 보안과 개인정보 -## Protected values +## 보호하는 값 -Email addresses, phone numbers, FCM installation ids and legacy tokens, APNs device tokens, Web Push -endpoints and keys, VAPID private keys, provider credentials, callback signing secrets, template -variables, rendered bodies, attachment references and unsubscribe tokens. +이메일 주소, 전화번호, FCM installation id와 legacy token, APNs device token, Web Push endpoint와 키, VAPID private key, +provider 자격 증명, 콜백 서명 secret, 템플릿 변수, 렌더링한 본문, 첨부 참조, 수신 거부 token. -## At rest +## 저장할 때 -Contact points are encrypted with AES-256-GCM. Equality lookup uses a separate HMAC-SHA-256 -fingerprint. +연락처는 AES-256-GCM으로 암호화한다. 같은지 찾는 조회는 따로 둔 HMAC-SHA-256 fingerprint를 쓴다. -Two keys, not one, because the requirements are opposite: the ciphertext must be non-deterministic so -two records of the same address are not visibly identical, while equality lookup must be -deterministic. The fingerprint is keyed rather than a plain digest because phone numbers and email -addresses come from a small, enumerable space — an unkeyed hash of a phone number is recoverable in -seconds. +요구가 반대라서 키가 하나가 아니라 둘이다. 암호문은 결정적이지 않아야 같은 주소의 두 기록이 겉으로 같아 보이지 않고, +같은지 찾는 조회는 결정적이어야 한다. fingerprint를 그냥 digest가 아니라 키가 있는 것으로 두는 이유는 전화번호와 이메일 +주소가 작고 셀 수 있는 공간에서 오기 때문이다. 키 없는 전화번호 hash는 몇 초면 되살린다. -The contact point kind is bound into the GCM associated data, so a ciphertext cannot be moved between -contact kinds without failing the authentication tag. +연락처 종류를 GCM associated data에 묶으므로, 암호문을 다른 연락처 종류로 옮기면 인증 tag가 실패한다. -An unknown key id is refused rather than silently falling back to the current key: a silent fallback -would turn every historical row into a tag failure at read time. +모르는 key id는 현재 키로 조용히 대신하지 않고 거부한다. 조용히 대신하면 이력의 모든 행이 읽을 때 tag 실패가 된다. -## Never logged, never a metric tag +## 로그에도 메트릭 태그에도 넣지 않는 것 -Addresses, tokens, Web Push endpoints and keys, message bodies, template variables, provider -credentials, unsubscribe tokens, attachment URLs, raw callback payloads and raw provider request ids. +주소, token, Web Push endpoint와 키, 메시지 본문, 템플릿 변수, provider 자격 증명, 수신 거부 token, 첨부 URL, 원본 콜백 +payload, 원본 provider request id. -`CardinalityGuard` enforces this for metrics rather than convention: it validates every metric tag -against a closed allowlist. +메트릭은 관례가 아니라 `CardinalityGuard`가 강제한다. 모든 메트릭 태그를 닫힌 허용 목록과 대조한다. -An allowlist rather than a denylist, because the failure mode of a denylist is that the one field -nobody thought of is the one that leaks. +거부 목록이 아니라 허용 목록인 이유가 있다. 거부 목록이 실패하는 꼴은, 아무도 생각하지 못한 그 칸 하나가 새는 것이다. -Every contact point value type overrides `toString()` to print `[redacted]`. That covers the case a -central redactor cannot: a value interpolated into a log line by accident. +모든 연락처 값 타입은 `toString()`을 고쳐 `[redacted]`를 찍는다. 그것은 중앙 redactor가 막지 못하는 경우, 실수로 로그 +줄에 끼워 넣은 값을 막는다. -## Web Push endpoints +## Web Push endpoint -RFC 8030 defines the push URI as a capability URL — knowing it is sufficient to push to the -subscriber. It is handled as a secret, not as a URL. +RFC 8030은 push URI를 capability URL로 정의한다. 그것을 알면 구독자에게 push할 수 있다. 그래서 URL이 아니라 secret으로 +다룬다. -## Callbacks +## 콜백 -TLS, provider signature verification over the exact received bytes and external URL, replay defence -where a timestamp or nonce is available, body-size and content-type limits, profile binding, rate -limiting, idempotent ingestion and a security audit trail for rejections. +TLS, 받은 그대로의 바이트와 외부 URL에 대한 provider 서명 검증, timestamp나 nonce가 있으면 replay 방어, 본문 크기와 +content type 한도, profile 묶기, 속도 제한, 멱등한 받기, 거부를 남기는 보안 감사 기록. -## Tenant isolation +## 테넌트 격리 -Every store port carries the tenant boundary in its signature. Administrative operations require an -explicit tenant or a global authority. +모든 저장소 port는 시그니처에 테넌트 경계를 싣는다. 관리 작업에는 명시한 테넌트나 전역 권한이 필요하다. diff --git a/docs/notification/support-matrix.md b/docs/notification/support-matrix.md index 9850179e..6ab818e9 100644 --- a/docs/notification/support-matrix.md +++ b/docs/notification/support-matrix.md @@ -1,109 +1,102 @@ -# Notification support matrix +# 알림 지원 매트릭스 -What each channel can actually prove, and what the platform refuses to claim. +채널마다 실제로 증명할 수 있는 것과, 플랫폼이 주장하기를 거부하는 것이다. -The grade column is not an opinion. `docs/notification/evidence-manifest.json` declares which claims -each grade requires and which executable artifact proves each claim, and -`NotificationEvidenceVerifierTest` (in `:adapter:outbound:notification:test`) refuses a grade whose -claims are not all backed by a file that exists. Raising a grade means adding the artifact first. +등급 칸은 의견이 아니다. `docs/notification/evidence-manifest.json`이 등급마다 필요한 claim과 claim마다 그것을 증명하는 +실행 산출물을 선언하고, `NotificationEvidenceVerifierTest`(`:adapter:outbound:notification:test`)가 claim이 모두 실제 +파일로 뒷받침되지 않은 등급을 거부한다. 등급을 올리려면 산출물을 먼저 더한다. -Five channels read `Stable` until 2026-08-15. Nothing in the pipeline had ever sent a request to a -provider — the sandbox job's whole body was two `echo` statements behind `continue-on-error` — and -no test killed a worker mid-dispatch. The protocols are implemented and their contracts are proven -against real PostgreSQL; the wire and the crash are not. That is what the grade now says. +2026-08-15까지 다섯 채널이 `Stable`이었다. 파이프라인의 어떤 것도 provider에 요청을 보낸 적이 없었고(sandbox job의 본문 +전체가 `continue-on-error` 뒤의 `echo` 두 줄이었다), 발송 도중 worker를 죽인 테스트도 없었다. 프로토콜은 구현돼 있고 그 +계약은 실제 PostgreSQL에서 증명됐지만, 실제 전송과 장애 중단은 증명되지 않았다. 지금 등급이 말하는 것이 그것이다. -## Channels +## 채널 -| Channel | Reference implementation | Grade | Strongest evidence the platform records by default | +| 채널 | 참조 구현 | 등급 | 플랫폼이 기본으로 기록하는 가장 강한 증거 | |---|---|---|---| -| Email | SMTP, Amazon SES API | Contract implemented / runtime unqualified | Provider acceptance; recipient mail-server delivery, bounce and complaint when the provider publishes events | -| SMS | none shipped — adapter removed; the channel type stays in the application API (see `docs/capability-status.md` 제거된 코드) | Extension | Whatever the added provider adapter can prove | -| Mobile push (FCM, APNs) | none shipped — adapter removed; the channel type stays in the application API (see `docs/capability-status.md` 제거된 코드) | Extension | Whatever the added provider adapter can prove | -| Web Push | none shipped — adapter removed; the channel type stays in the application API (see `docs/capability-status.md` 제거된 코드) | Extension | Whatever the added provider adapter can prove | -| In-app inbox | Own database | Optional stable | `PERSISTED`, `SEEN`, `READ` | -| Webhook | none shipped — adapter removed; the channel type stays in the application API (see `docs/capability-status.md` 제거된 코드) | Extension | Whatever the receiving HTTP contract states | +| Email | SMTP, Amazon SES API | Contract implemented / runtime unqualified | provider 수락. provider가 이벤트를 내면 수신 메일 서버 전달, bounce, complaint | +| SMS | 내보내지 않음 — 어댑터를 지웠고 채널 종류는 애플리케이션 API에 남아 있다(`docs/capability-status.md` 제거된 코드) | Extension | 더한 provider 어댑터가 증명할 수 있는 것 | +| 모바일 push(FCM, APNs) | 내보내지 않음 — 어댑터를 지웠고 채널 종류는 애플리케이션 API에 남아 있다(`docs/capability-status.md` 제거된 코드) | Extension | 더한 provider 어댑터가 증명할 수 있는 것 | +| Web Push | 내보내지 않음 — 어댑터를 지웠고 채널 종류는 애플리케이션 API에 남아 있다(`docs/capability-status.md` 제거된 코드) | Extension | 더한 provider 어댑터가 증명할 수 있는 것 | +| 앱 안 inbox | 자체 DB | Optional stable | `PERSISTED`, `SEEN`, `READ` | +| Webhook | 내보내지 않음 — 어댑터를 지웠고 채널 종류는 애플리케이션 API에 남아 있다(`docs/capability-status.md` 제거된 코드) | Extension | 받는 HTTP 계약이 말하는 것 | -## Shipped provider assembly reachability +## 내보내는 provider 조립이 닿는 범위 -The grade above describes protocol/reliability evidence. It does **not** mean every reference -implementation is selectable in the default composition. Dispatch reachability is a separate axis: +위 등급은 프로토콜·신뢰성 증거를 말한다. 모든 참조 구현을 기본 조립에서 고를 수 있다는 뜻이 **아니다**. 발송이 닿는지는 +따로 보는 축이다. -| Provider family | Dispatch assembler in shipped composition | Callback assembler | Current use | +| provider family | 내보내는 조립의 발송 assembler | 콜백 assembler | 지금 쓰임 | |---|---|---|---| -| SMTP | **yes** | no | EMAIL dispatch reference family | -| SES | **yes** | **yes** | EMAIL dispatch + SNS callback ingestion; disabled reference profile ships in `config/module-defaults/notification.yml` (`composition:notification-platform`) | +| SMTP | **있음** | 없음 | EMAIL 발송 참조 family | +| SES | **있음** | **있음** | EMAIL 발송 + SNS 콜백 수집. 꺼진 참조 profile이 `config/module-defaults/notification.yml`(`composition:notification-platform`)에 들어 있다 | -APNs, FCM, Twilio, Web Push and Webhook adapters shipped as protocol code with no assembler and -were removed; `ProviderType` now lists only SES and SMTP, so such a profile fails binding as an -unknown type. An enabled dispatch profile with no assembler fails startup by profile/family; it never silently -assembles into an empty runtime. SMTP additionally names `spring.mail.host` when its shipped -assembler is absent because the relay was not configured. +APNs, FCM, Twilio, Web Push, Webhook 어댑터는 assembler 없이 프로토콜 코드로만 들어 있다가 지워졌다. 이제 +`ProviderType`에는 SES와 SMTP만 있으므로 그런 profile은 모르는 종류로 바인딩에서 실패한다. assembler가 없는 켜진 발송 +profile은 profile·family 이름을 대며 기동에 실패한다. 빈 런타임으로 조용히 조립되는 일은 없다. SMTP는 relay가 설정되지 +않아 내보내는 assembler가 없으면 `spring.mail.host`도 이름 댄다. -## What each grade requires +## 등급마다 필요한 것 -| Grade | Requires | +| 등급 | 필요한 claim | |---|---| | Stable | durable, multi-worker-safe, callback-supported, recoverable, provider-wire-qualified | | Contract implemented / runtime unqualified | durable, multi-worker-safe, callback-supported | | Optional stable | durable | -| Extension | nothing; the receiving contract owns its own guarantees | -| Experimental | nothing; the grade is the warning | +| Extension | 없음. 받는 쪽 계약이 자기 보장을 가진다 | +| Experimental | 없음. 등급 자체가 경고다 | -`recoverable` is backed by two tests. `WorkerCrashRecoveryContractTest` walks the four phases a -dispatch passes through — claimed, attempt written, request started, body committed — and pins the -rows a dead worker leaves at each: a passed lease, and from the attempt insert on an unfinished -attempt carrying that phase's evidence. It writes those rows itself, so it checks recovery's input, -not recovery. `PostgreSqlNotificationBackgroundPassIntegrationTest` runs lease recovery and -reconciliation over rows the dispatcher's own factory wrote and asserts the outcome: requeued before -any attempt, reconciled after one (review 05-01, RR-03-07). +`recoverable`은 테스트 둘이 뒷받침한다. `WorkerCrashRecoveryContractTest`는 발송이 지나는 네 단계(claim됨, attempt 기록됨, +요청 시작됨, 본문 커밋됨)를 따라가며 단계마다 죽은 worker가 남기는 행을 고정한다. 지난 lease, 그리고 attempt insert부터는 +그 단계의 증거를 가진 끝나지 않은 attempt다. 그 행을 테스트가 직접 쓰므로, 복구가 아니라 복구의 입력을 확인한다. +`PostgreSqlNotificationBackgroundPassIntegrationTest`는 dispatcher 자신의 factory가 쓴 행에 lease 복구와 맞추기를 돌리고 +결과를 단언한다. attempt 전이면 다시 큐에 넣고, attempt 뒤면 맞춘다(review 05-01, RR-03-07). -The remaining unmet claim, and what would meet it: +남은 미충족 claim과 그것을 채울 것: -- **provider-wire-qualified** — a real provider sandbox call producing an immutable, uploaded - artifact with a correlation id. No request has ever left the process in CI. +- **provider-wire-qualified** — 실제 provider sandbox 호출로 correlation id가 있는 불변 산출물을 만들어 올린다. CI에서 + 프로세스 밖으로 요청이 나간 적이 한 번도 없다. -## Evidence levels +## 증거 수준 `NONE` → `PLATFORM_QUEUED` → `PROVIDER_ACCEPTED` → `NETWORK_OR_CARRIER_ACCEPTED` → `DEVICE_DELIVERED` → `USER_AGENT_DISPLAYED` → `USER_READ` -| Provider signal | Highest evidence it may produce | +| provider 신호 | 그 신호가 낼 수 있는 가장 높은 증거 | |---|---| -| Internal queue commit | `PLATFORM_QUEUED` | +| 내부 큐 커밋 | `PLATFORM_QUEUED` | | SES `MessageId` | `PROVIDER_ACCEPTED` | | SES `Delivery` | `NETWORK_OR_CARRIER_ACCEPTED` | -| In-app row commit | `PROVIDER_ACCEPTED` | -| In-app `seen` endpoint | `USER_AGENT_DISPLAYED` | -| In-app `read` endpoint, authenticated app receipt | `USER_READ` | +| 앱 안 행 커밋 | `PROVIDER_ACCEPTED` | +| 앱 안 `seen` 엔드포인트 | `USER_AGENT_DISPLAYED` | +| 앱 안 `read` 엔드포인트, 인증된 앱 수신 확인 | `USER_READ` | -Promotions the platform will not make, in code or in configuration: +플랫폼이 코드에서도 설정에서도 하지 않는 승격: -- A push or SMS acceptance, from any provider adapter a deployment adds, is not `DEVICE_DELIVERED`. -- A provider 2xx is not `DELIVERED`. -- An SES `MessageId` is not `DELIVERED`. -- An SMTP `250` is not inbox delivery. +- 배포가 더한 어느 provider 어댑터에서 온 것이든 push·SMS 수락은 `DEVICE_DELIVERED`가 아니다. +- provider의 2xx는 `DELIVERED`가 아니다. +- SES `MessageId`는 `DELIVERED`가 아니다. +- SMTP `250`은 받은편지함 도착이 아니다. -## Submission outcomes +## 제출 결과 `NOT_SUBMITTED`, `CONFIRMED_ACCEPTED`, `CONFIRMED_REJECTED`, `AMBIGUOUS`. -`AMBIGUOUS` is a first-class stored state, not an error path. It means the request body was committed -to the provider and the outcome could not be read. While an ambiguous attempt exists on a recipient -delivery, automatic retry and automatic cross-channel fallback are both blocked. +`AMBIGUOUS`는 오류 경로가 아니라 정식으로 저장되는 상태다. 요청 본문을 provider에 넘겼지만 결과를 읽지 못했다는 뜻이다. +수신자 전달에 모호한 attempt가 있는 동안에는 자동 재시도와 자동 채널 전환이 모두 막힌다. -## Not supported +## 지원하지 않는 것 -The platform will not claim any of the following, because no channel above can support them: +위의 어떤 채널도 뒷받침할 수 없으므로 플랫폼은 다음 중 어떤 것도 주장하지 않는다. -- guaranteed delivery -- guaranteed read -- exactly-once human notification -- unconditional multi-provider failover after an unread response -- provider SDK types in the public API -- audience selection, campaign segmentation or jurisdiction rulings +- 전달 보장(guaranteed delivery) +- 읽음 보장(guaranteed read) +- 사람에게 가는 알림의 정확히 한 번(exactly-once) 전달 +- 읽지 못한 응답 뒤의 조건 없는 다중 provider failover +- 공개 API의 provider SDK 타입 +- 대상 선정, 캠페인 세분화, 관할 판정 -## Target model +## 대상 모델 -`FCM_FID` is the primary mobile push target. `FCM_REGISTRATION_TOKEN_LEGACY` and -`APNS_DEVICE_TOKEN` are separate types with separate lifecycles; they are never flattened into one -string field. +`FCM_FID`가 모바일 push의 기본 대상이다. `FCM_REGISTRATION_TOKEN_LEGACY`와 `APNS_DEVICE_TOKEN`은 수명 주기가 다른 별도 +종류다. 하나의 문자열 칸으로 합치지 않는다. diff --git a/docs/observability/log-fields.md b/docs/observability/log-fields.md index e7177ec6..c9294a45 100644 --- a/docs/observability/log-fields.md +++ b/docs/observability/log-fields.md @@ -1,67 +1,63 @@ -# Structured log field dictionary +# 구조화 로그 칸 사전 -This file is the naming SSOT for structured fields emitted by application/bootstrap runtime code. -A new field should be added here before it becomes a new search/filter dimension. +이 파일은 application·bootstrap 런타임 코드가 내는 구조화 칸 이름의 정본이다. 새 칸은 새 검색·필터 기준이 되기 전에 여기에 +먼저 더한다. -The message text is for humans. These fields are the stable machine-query surface. +메시지 문장은 사람을 위한 것이다. 이 칸들이 기계가 조회하는 안정된 표면이다. -## Startup and error classification +## 기동과 오류 분류 -| Field | Meaning | Cardinality expectation | +| 칸 | 뜻 | 기대하는 cardinality | |---|---|---| -| `startup.phase` | Startup phase such as env-validation, migration or adapter-check | bounded | -| `error.code` | Stable error-code registry value | bounded | -| `error.category` | Stable error category | bounded | -| `error.root_cause.class` | Root exception class for startup failure diagnosis | bounded by codebase/dependencies | -| `error.root_cause.message` | Root exception message | unbounded; diagnosis only, not metric/tag material | +| `startup.phase` | 기동 단계. `env-validation`, `migration`, `profile-check`, `adapter-enablement` | 상한 있음 | +| `error.code` | 안정된 오류 코드 registry 값 | 상한 있음 | +| `error.category` | 안정된 오류 분류 | 상한 있음 | +| `error.root_cause.class` | 기동 실패 진단용 근본 예외 클래스 | 코드베이스·의존성이 상한 | +| `error.root_cause.message` | 근본 예외 메시지 | 상한 없음. 진단에만 쓰고 메트릭·태그 재료가 아니다 | -Startup failures go through `StartupFailures`; callers do not construct their own startup error -classification. +기동 실패는 `StartupFailures`를 거친다. 호출자는 기동 오류 분류를 스스로 만들지 않는다. -## Runtime warning and retry classification +## 런타임 경고와 재시도 분류 -| Field | Meaning | Cardinality expectation | +| 칸 | 뜻 | 기대하는 cardinality | |---|---|---| -| `warning.kind` | Stable warning shape, for example `meter-unavailable`, `setting-fallback`, `scheduled-task-failed`, `lease-expired-before-close` | bounded | -| `capability` | Capability that emitted the runtime event, for example `fileserver`, `outbox`, `distributed-lock` | bounded | -| `operation` | Bounded operation name such as `cleanup` or `relay` | bounded | -| `retry.disposition` | What the runtime will do after the event, for example `next-run` or `next-tick` | bounded | -| `meter` | Meter name or bounded meter operation that could not be updated | bounded by metrics registry | -| `env.key` | Configuration key involved in a fallback | bounded by env registry | -| `setting.rejected` | Rejected setting value rendered for diagnosis | potentially unbounded; never metric/tag material | -| `setting.applied` | Fallback value actually applied | bounded where possible | +| `warning.kind` | 안정된 경고 모양. 예: `meter-unavailable`, `setting-fallback`, `scheduled-task-failed`, `lease-expired-before-close` | 상한 있음 | +| `capability` | 런타임 이벤트를 낸 capability. 예: `fileserver`, `outbox`, `distributed-lock` | 상한 있음 | +| `operation` | `cleanup`이나 `relay` 같은 상한 있는 operation 이름 | 상한 있음 | +| `retry.disposition` | 이벤트 뒤 런타임이 할 일. 예: `next-run`, `next-tick` | 상한 있음 | +| `meter` | 갱신하지 못한 meter 이름이나 상한 있는 meter 연산 | 메트릭 registry가 상한 | +| `env.key` | fallback에 관련된 설정 키 | env registry가 상한 | +| `setting.rejected` | 진단용으로 찍은, 거부된 설정 값 | 상한이 없을 수 있다. 메트릭·태그 재료가 절대 아니다 | +| `setting.applied` | 실제로 적용한 fallback 값 | 될 수 있으면 상한 있음 | -A retry disposition does not imply an `error.code`. Add an error code only when the failure is -actually classified by the error registry. +재시도 처리 방식이 `error.code`를 뜻하지는 않는다. 오류 코드는 그 실패를 오류 registry가 실제로 분류할 때만 더한다. -## Fileserver cleanup +## 파일 서버 정리 -| Field | Meaning | +| 칸 | 뜻 | |---|---| -| `cleanup.deleted` | Objects deleted in one bounded cleanup run | -| `cleanup.skipped_active_lease` | Items skipped because an active upload lease still owns them | -| `cleanup.skipped_state_changed` | Items skipped because state changed after queueing | -| `cleanup.failed` | Cleanup items that failed in the batch | -| `cleanup.reclaimed_bytes` | Bytes reclaimed in the batch | +| `cleanup.deleted` | 상한 있는 정리 실행 한 번에 지운 객체 | +| `cleanup.skipped_active_lease` | 살아 있는 upload lease가 아직 가져서 건너뛴 항목 | +| `cleanup.skipped_state_changed` | 대기열에 넣은 뒤 상태가 바뀌어 건너뛴 항목 | +| `cleanup.failed` | 그 묶음에서 실패한 정리 항목 | +| `cleanup.reclaimed_bytes` | 그 묶음에서 되찾은 바이트 | -These are numeric event fields. They are not identity fields. +이것들은 숫자 이벤트 칸이다. 신원 칸이 아니다. -## Background executor rejection +## background executor 거부 -| Field | Meaning | +| 칸 | 뜻 | |---|---| -| `executor_name` | Bounded executor identifier | -| `policy` | Rejection policy, currently `AbortPolicy` | -| `queue_size` | Queue size observed at rejection | +| `executor_name` | 상한 있는 executor 식별자 | +| `policy` | 거부 정책. 지금은 `AbortPolicy` | +| `queue_size` | 거부할 때 본 큐 크기 | -Executor rejection also carries `error.code=JOB_EXECUTOR_REJECTED` and its `error.category`. +executor 거부는 `error.code=JOB_EXECUTOR_REJECTED`와 그 `error.category`도 싣는다. -## Cardinality and sensitive identifiers +## cardinality와 민감한 식별자 -Do not promote arbitrary identifiers to structured fields merely because they are useful in one -incident. Examples include distributed-lock keys, object keys, raw user identifiers, request -payloads and secret values. +한 장애에서 쓸모 있었다는 이유만으로 아무 식별자나 구조화 칸으로 올리지 않는다. 분산 락 키, 객체 키, 원본 사용자 식별자, +요청 payload, secret 값이 그 예다. -The distributed-lock lease-expiry warning intentionally keeps the lock key only in human-readable -message text and does not emit `lock.key`. If a future operational requirement needs a searchable -lock identity, define a bounded/pseudonymized contract first instead of adding the raw key. +분산 락 lease 만료 경고는 락 키를 사람이 읽는 메시지 문장에만 두고 `lock.key`를 내지 않는다. 일부러다. 앞으로 운영 요구가 +검색할 수 있는 락 신원을 필요로 하면, 원본 키를 더하지 말고 먼저 상한 있거나 가명화한 계약을 정한다. diff --git a/docs/redis/command-policy.md b/docs/redis/command-policy.md index 2aa5c325..10cba411 100644 --- a/docs/redis/command-policy.md +++ b/docs/redis/command-policy.md @@ -1,49 +1,48 @@ -# Command policy +# 명령 정책 -`src/adapter/outbound/redis-sdk/src/main/resources/redis-sdk/redis-command-policy.yml` is the -single source of truth for what this SDK is willing to do with each Redis command. Official server -metadata decides what a command *is*; this file decides what we allow. +`src/adapter/outbound/redis-sdk/src/main/resources/redis-sdk/redis-command-policy.yml`이 이 SDK가 Redis 명령마다 +무엇을 해도 되는지 정하는 유일한 정본이다. 명령이 *무엇인지*는 공식 서버 metadata가 정하고, 무엇을 허락할지는 이 +파일이 정한다. -A command that is not classified there is refused. Adding a command therefore means editing that -file, not writing code — and the edit is where the risk decision is made and reviewed. +거기에 분류되지 않은 명령은 거부한다. 그래서 명령을 더하는 것은 코드를 쓰는 일이 아니라 그 파일을 고치는 일이고, 위험 +판단을 내리고 검토하는 곳이 그 수정이다. -## Fields +## 필드 -| Field | Default | Meaning | +| 필드 | 기본값 | 뜻 | | --- | --- | --- | -| `risk` | required | `R1` routine, `R2` needs an explicit permit, `R3` administrative, `R4` never allowed | -| `support` | required | `TYPED`, `ADVANCED_TYPED`, `RAW_ONLY`, `ADMIN_ONLY`, `VERSION_GATED`, `BLOCKED` | -| `minimum-version` | `7.2` | lowest server version that carries the command | -| `access` | derived from `support` | which ACL account may issue it | -| `blocking` | `false` | occupies its connection until the server replies | -| `optional-block` | `false` | the command also has a non-blocking form; only `XREAD` and `XREADGROUP` carry it | -| `read-only` | `false` | never mutates the dataset | -| `retry-safe` | `read-only` | may be retried after a failure that could have reached the server | -| `may-be-ambiguous` | `!read-only` | a failure may leave the outcome unknown | -| `timeout-profile` | derived | `FAST`, `COLLECTION`, `ADMIN`, `BLOCKING` | -| `key-spec` | `1 1 1` | where the keys are, or `none`, or `movable` | -| `required-policy` | – | the permit policy an R2 command demands | +| `risk` | 필수 | `R1` 일상, `R2` 명시적 허가 필요, `R3` 관리, `R4` 절대 허락 안 함 | +| `support` | 필수 | `TYPED`, `ADVANCED_TYPED`, `RAW_ONLY`, `ADMIN_ONLY`, `VERSION_GATED`, `BLOCKED` | +| `minimum-version` | `7.2` | 그 명령이 있는 가장 낮은 서버 버전 | +| `access` | `support`에서 정함 | 어느 ACL 계정이 보낼 수 있는지 | +| `blocking` | `false` | 서버가 답할 때까지 connection을 잡는다 | +| `optional-block` | `false` | 그 명령에 blocking 아닌 형태도 있다. `XREAD`와 `XREADGROUP`만 가진다 | +| `read-only` | `false` | 데이터를 절대 바꾸지 않는다 | +| `retry-safe` | `read-only` | 서버에 닿았을 수 있는 실패 뒤에도 재시도해도 된다 | +| `may-be-ambiguous` | `!read-only` | 실패가 결과를 모르는 상태로 남길 수 있다 | +| `timeout-profile` | 정함 | `FAST`, `COLLECTION`, `ADMIN`, `BLOCKING` | +| `key-spec` | `1 1 1` | key가 있는 곳. 또는 `none`, `movable` | +| `required-policy` | – | R2 명령이 요구하는 허가 정책 | -## Rules the catalog enforces +## 목록이 강제하는 규칙 -- An R2 `ADVANCED_TYPED` command must name the permit policy it requires. There is no R2 command - that anyone may issue without an issued permit. -- An R4 command must be `BLOCKED`, and an R3 command must be `ADMIN_ONLY`. The type system refuses - the other combinations at load time. -- A `BLOCKED` command carries no ACL account, so no path in the SDK can reach it. -- A blocking command must use the `BLOCKING` timeout profile, and its request must declare a bounded - server block — unless it also declares `optional-block`, which only the two stream reads do. -- Deprecated command names stay `BLOCKED` even when the SDK offers their behaviour. The typed - sorted-set ranges issue `ZRANGE ... BYSCORE|BYLEX|REV`, not `ZRANGEBYSCORE`, so what the guard was - told and what reaches the wire are the same command. +- R2 `ADVANCED_TYPED` 명령은 요구하는 허가 정책의 이름을 대야 한다. 발급한 허가 없이 누구나 보낼 수 있는 R2 명령은 + 없다. +- R4 명령은 `BLOCKED`여야 하고, R3 명령은 `ADMIN_ONLY`여야 한다. 그 밖의 조합은 불러올 때 타입 체계가 거부한다. +- `BLOCKED` 명령에는 ACL 계정이 없다. 그래서 SDK의 어떤 경로도 그것에 닿을 수 없다. +- blocking 명령은 `BLOCKING` timeout profile을 써야 하고, 그 요청은 상한 있는 서버 block을 선언해야 한다. + `optional-block`도 선언하면 예외인데, stream 읽기 둘만 그렇다. +- 폐기된 명령 이름은 SDK가 그 동작을 제공하더라도 `BLOCKED`로 남는다. 타입 있는 sorted-set 범위 조회는 + `ZRANGEBYSCORE`가 아니라 `ZRANGE ... BYSCORE|BYLEX|REV`를 보낸다. 그래서 guard가 들은 명령과 wire에 닿는 명령이 + 같다. -## Where each support level is reachable from +## 지원 등급마다 닿는 곳 -| Support | Reachable from | +| 지원 | 닿는 곳 | | --- | --- | -| `TYPED` | the typed operations, no permit | -| `ADVANCED_TYPED` | the typed operations, with the named permit | -| `VERSION_GATED` | a capability bean that exists only when the probe found the feature | -| `RAW_ONLY` | `sdk.raw`, and only with a deployment-registered approval | -| `ADMIN_ONLY` | `sdk.admin`, read-only diagnostics only | -| `BLOCKED` | nowhere | +| `TYPED` | 타입 있는 연산, 허가 없이 | +| `ADVANCED_TYPED` | 타입 있는 연산, 이름 댄 허가와 함께 | +| `VERSION_GATED` | probe가 그 기능을 찾았을 때만 있는 capability bean | +| `RAW_ONLY` | `sdk.raw`, 그리고 배포가 등록한 승인이 있을 때만 | +| `ADMIN_ONLY` | `sdk.admin`, 읽기 전용 진단만 | +| `BLOCKED` | 어디에도 없음 | diff --git a/docs/redis/operations.md b/docs/redis/operations.md index d0cbd6ef..11276dfa 100644 --- a/docs/redis/operations.md +++ b/docs/redis/operations.md @@ -1,75 +1,65 @@ -# Operating the Redis SDK +# Redis SDK 운영 -## What the metrics can and cannot tell you +## metric이 알려 줄 수 있는 것과 없는 것 -Every observation carries the command family, the deployment mode, and latency. None carries a key, -a field, a member, or a value — not because they would be large, but because a metric dimension -built from caller data is unbounded cardinality and, for most deployments, tenant identity in a -dashboard. +모든 관측은 명령 계열, 배포 방식, 지연을 담는다. key, field, member, value는 담지 않는다. 값이 커서가 아니라, 호출자 +데이터로 만든 metric 차원은 가짓수에 상한이 없고 대부분의 배포에서 dashboard에 tenant 식별자를 띄우기 때문이다. -That means you can answer "which command family is slow" and "which one is failing", and you cannot -answer "which key is hot" from metrics. Use the admin plane's `SLOWLOG` projection for the first -question and `MEMORY USAGE` on a specific key for the second. +그래서 metric으로 「어느 명령 계열이 느린가」와 「어느 것이 실패하나」에는 답할 수 있지만 「어느 key가 뜨거운가」에는 +답할 수 없다. 앞의 질문에는 admin plane의 `SLOWLOG` 투영을, 뒤의 질문에는 특정 key에 대한 `MEMORY USAGE`를 쓴다. -## The failures worth alerting on +## 경보를 걸 만한 실패 -| Signal | What it means | What to do | +| 신호 | 뜻 | 할 일 | | --- | --- | --- | -| `RedisCommandRejectedException` | the SDK refused before sending | a caller exceeded a declared bound; the reason names which one | -| `RedisCrossSlotException` | a multi-key command spans slots | the keys need a shared hash tag | -| `RedisAmbiguousExecutionException` | a write may or may not have applied | reconcile; the SDK will not retry it | -| `RedisCapabilityUnavailableException` | the server lacks the feature | a capability bean was constructed by hand, or the probe result changed | -| `SentinelFailoverObserver.ambiguousWriteCount` | non-idempotent writes lost to a promotion | each one needs reconciling; the count is the workload | -| `ClusterTopologyObserver.reshardingObserved` | `ASK`/`TRYAGAIN` seen | a slot migration is in progress; latency will be uneven until it ends | +| `RedisCommandRejectedException` | SDK가 보내기 전에 거부했다 | 호출자가 선언한 상한을 넘었다. 이유가 어느 것인지 이름을 댄다 | +| `RedisCrossSlotException` | 여러 key 명령이 slot을 넘는다 | key들이 같은 hash tag를 가져야 한다 | +| `RedisAmbiguousExecutionException` | 쓰기가 적용됐을 수도, 아닐 수도 있다 | 맞춰 본다. SDK는 재시도하지 않는다 | +| `RedisCapabilityUnavailableException` | 서버에 그 기능이 없다 | capability bean을 손으로 만들었거나 probe 결과가 바뀌었다 | +| `SentinelFailoverObserver.ambiguousWriteCount` | 승격 때문에 잃은 멱등이 아닌 쓰기 | 하나하나 맞춰 봐야 한다. 그 수가 일의 양이다 | +| `ClusterTopologyObserver.reshardingObserved` | `ASK`/`TRYAGAIN`을 봤다 | slot 이동이 진행 중이다. 끝날 때까지 지연이 고르지 않다 | -## Things the SDK will never do for you +## SDK가 절대 대신해 주지 않는 것 -- Retry a non-idempotent write after a timeout. `ExecutionCertainty.AMBIGUOUS_FAILURE` is reported, - not resolved. -- Follow a cross-slot multi-key command by splitting it. It is refused instead. -- Read a whole collection, stream, or index. Every read declares a bound. -- Load a Lua script or a function library at request time. Both are deployment actions. -- Send a command it cannot classify. -- Tell you that an acknowledged write was lost. See below — this one is not a limitation you can - work around in application code. +- 시간 초과 뒤 멱등이 아닌 쓰기를 재시도하기. `ExecutionCertainty.AMBIGUOUS_FAILURE`를 보고할 뿐 풀지 않는다. +- slot을 넘는 여러 key 명령을 나눠서 따라가기. 대신 거부한다. +- collection, stream, index 전체를 읽기. 모든 읽기는 상한을 선언한다. +- 요청 시점에 Lua script나 function library를 불러오기. 둘 다 배포 작업이다. +- 분류할 수 없는 명령 보내기. +- 확인 응답을 받은 쓰기를 잃었다고 알려 주기. 아래를 본다. 애플리케이션 코드로 돌아갈 수 있는 한계가 아니다. -## The write loss the client cannot see +## client가 볼 수 없는 쓰기 손실 -Set these on every Redis node that can ever be a primary: +primary가 될 수 있는 모든 Redis 노드에 이것을 둔다. ``` min-replicas-to-write 1 min-replicas-max-lag 1 ``` -Without them a Sentinel promotion silently destroys acknowledged writes, and this is measured, not -theoretical. In `LiveRedisSentinelPromotionTest` on the 7.4 lane, Sentinel promoted the replica and -did not demote the old primary for **eleven seconds**. The client stayed connected to a primary that -had already been replaced, wrote, and was told `+OK` **2,086 times**. Every one of those writes was -discarded when the old primary resynced. Exactly one command failed. +이것이 없으면 Sentinel 승격이 확인 응답을 받은 쓰기를 조용히 없앤다. 이론이 아니라 잰 것이다. 7.4 lane의 +`LiveRedisSentinelPromotionTest`에서 Sentinel은 replica를 승격하고 옛 primary를 **11초** 동안 내리지 않았다. client는 +이미 교체된 primary에 연결된 채 썼고, `+OK`를 **2,086번** 받았다. 옛 primary가 다시 동기화할 때 그 쓰기는 모두 버려졌다. +실패한 명령은 정확히 하나였다. -Nothing on the client can detect this. The server answered, so the driver recorded a success, the -SDK recorded `CONFIRMED_SUCCESS`, and the caller was told the write landed. No metric here counts -it, `SentinelFailoverObserver` cannot count it, and no retry policy helps — there was no failure to -react to. A second run of the same promotion produced sixteen thousand writes, **zero** exceptions, -and the same silent loss. +client 쪽에서는 아무것도 이것을 알아챌 수 없다. 서버가 답했으니 driver는 성공을 기록했고, SDK는 +`CONFIRMED_SUCCESS`를 기록했고, 호출자는 쓰기가 들어갔다고 들었다. 여기의 어떤 metric도 그것을 세지 않고, +`SentinelFailoverObserver`도 셀 수 없고, 어떤 재시도 정책도 돕지 못한다. 반응할 실패가 없었다. 같은 승격을 두 번째로 +돌렸을 때는 쓰기 만 육천 개, 예외 **0**개, 그리고 같은 조용한 손실이 나왔다. -With the two settings, the identical promotion lost **one** write and refused 2,020 with -`NOREPLICAS`, which the SDK reports as a definite, non-ambiguous failure the caller can act on. That -is the whole difference: an outage you can see instead of data you cannot. +두 설정을 두자 똑같은 승격에서 잃은 쓰기는 **하나**였고, 2,020개는 `NOREPLICAS`로 거부됐다. SDK는 그것을 호출자가 +대응할 수 있는, 결과가 분명한 실패로 보고한다. 차이는 그것이 전부다. 볼 수 없는 데이터 대신 볼 수 있는 장애다. -The residual window is `min-replicas-max-lag` wide and cannot be closed by configuration alone. A -write that must survive a promotion under any circumstances needs `WAIT` after it, at the cost of a -round trip to the replica — decide that per write, not globally. +남은 구간은 `min-replicas-max-lag`만큼이고 설정만으로는 닫을 수 없다. 어떤 경우에도 승격을 견뎌야 하는 쓰기는 그 뒤에 +`WAIT`가 필요하고, replica까지 왕복하는 비용이 든다. 전역이 아니라 쓰기마다 정한다. -## Blocking work +## Blocking 작업 -Blocking pops and blocking stream reads run on a dedicated connection lane. If those saturate, the -symptom is blocking calls timing out while ordinary traffic is healthy — that is the lane doing its -job, not a fault. Size the blocking pool to the number of concurrent consumers, not to request rate. +blocking pop과 blocking stream 읽기는 전용 connection lane에서 돈다. 그것이 가득 차면 보통 트래픽은 건강한데 blocking +호출만 시간 초과가 나는 증상이 보인다. lane이 제 일을 하는 것이지 결함이 아니다. blocking pool은 요청률이 아니라 동시 +소비자 수에 맞춘다. ## Pub/Sub -At-most-once. A subscriber that reconnects misses whatever arrived while it was gone, and there is -no replay. Durable business events belong in a stream with a consumer group, which is at-least-once -and therefore requires idempotent consumers. +많아야 한 번(at-most-once)이다. 다시 연결한 구독자는 떠나 있던 동안 온 것을 놓치고, 다시 받을 길이 없다. 지속돼야 하는 +업무 이벤트는 consumer group이 있는 stream에 둔다. 그것은 적어도 한 번(at-least-once)이므로 멱등한 소비자가 필요하다. diff --git a/docs/redis/support-matrix.md b/docs/redis/support-matrix.md index 9a7bb58a..9702db78 100644 --- a/docs/redis/support-matrix.md +++ b/docs/redis/support-matrix.md @@ -1,159 +1,139 @@ -# Redis SDK support matrix +# Redis SDK 지원 매트릭스 -This file is a gate, not a summary. `RedisSupportMatrixTest` parses the tables below and fails when -the SDK grows a package or a capability that is not listed, so a module cannot ship without someone -stating its minimum version, its topology support, and what it does not do. +이 파일은 요약이 아니라 관문이다. `RedisSupportMatrixTest`가 아래 표를 파싱하고, SDK에 표에 없는 package나 +capability가 생기면 실패한다. 그래서 누군가 최소 버전, 토폴로지 지원, 하지 않는 것을 밝히기 전에는 모듈을 내보낼 수 +없다. 표의 첫 칸(package 이름, capability 이름, 토폴로지 이름)은 테스트가 그대로 읽으므로 원문으로 둔다. -Design: `docs/design/2026-08-07-redis-wrapper-typed-api-design.md`. -Delivery status and the decisions behind each module: `docs/history/plans/2026-08-07-redis-wrapper-typed-api-status.md`. +설계서: `docs/design/2026-08-07-redis-wrapper-typed-api-design.md`. +납품 상태와 모듈마다의 결정: `docs/history/plans/2026-08-07-redis-wrapper-typed-api-status.md`. -## Modules +## 모듈 -| Module | Minimum Redis | Topology | Risk exposure | Sync | Reactive | Known limitations | +| 모듈 | 최소 Redis | 토폴로지 | 위험 노출 | Sync | Reactive | 알려진 한계 | | --- | --- | --- | --- | --- | --- | --- | -| `api` | 7.2 | all | none | n/a | n/a | contract only; no driver types | -| `api/key` | 7.2 | all | none | n/a | n/a | slot tags must be low-cardinality | -| `api/codec` | 7.2 | all | none | n/a | n/a | no Java native serialization | -| `api/command` | 7.2 | all | none | n/a | n/a | permits never widen the ACL account | -| `api/error` | 7.2 | all | none | n/a | n/a | failure metadata carries no key or value | -| `api/operations` | 7.2 | all | none | n/a | n/a | contract only | -| `api/reactive` | 7.2 | all | none | n/a | n/a | Reactor confined to this package | -| `lettuce` | 7.2 | all | R1–R2 | yes | yes | pinned to Lettuce 6.8.2 | -| `lettuce/codec` | 7.2 | all | none | yes | yes | UTF-8 and byte array codecs only | -| `lettuce/command` | 7.2 | all | R1–R2 | yes | yes | policy catalog is the only command authority | -| `lettuce/connection` | 7.2 | all | none | yes | yes | five lanes; blocking work never shares the regular lane | -| `lettuce/observability` | 7.2 | all | none | yes | yes | command family only, never a key | -| `lettuce/operations` | 7.2 | all | R1–R2 | yes | yes | hash field TTL needs 7.4; sharded pub/sub needs 7.0; stream deletion needs 8.2 | -| `config` | 7.2 | all | none | n/a | n/a | permit provenance is HMAC-signed per process | -| `cluster` | 7.2 | cluster | none | n/a | n/a | slot arithmetic only; no redirect following | -| `programmability` | 7.2 | all | R2 | yes | no | transactions never roll back; scripts return one bulk reply; `FUNCTION LOAD` is admin-plane | -| `raw` | 7.2 | all | R2 | yes | no | `RAW_ONLY` commands only; movable key specs unapprovable | -| `admin` | 7.2 | all | R3 read-only | yes | no | replies are projected; no destructive command exists | -| `extensions` | 8.0 | all | none | yes | no | shared command runner; every extension declares its key | -| `extensions/json` | 8.0 | all | R1–R2 | yes | no | narrow JSONPath grammar; documents exchanged as text | -| `extensions/search` | 8.0 | all | R2 | yes | no | index names namespaced by the SDK; no drop index | -| `extensions/timeseries` | 8.0 | all | R1–R2 | yes | no | retention mandatory at creation | -| `extensions/probabilistic` | 8.0 | all | R1–R2 | yes | no | every answer is approximate by construction | +| `api` | 7.2 | 전부 | 없음 | 해당 없음 | 해당 없음 | 계약만. driver 타입 없음 | +| `api/key` | 7.2 | 전부 | 없음 | 해당 없음 | 해당 없음 | slot tag는 가짓수가 적어야 한다 | +| `api/codec` | 7.2 | 전부 | 없음 | 해당 없음 | 해당 없음 | Java native 직렬화 없음 | +| `api/command` | 7.2 | 전부 | 없음 | 해당 없음 | 해당 없음 | 허가는 ACL 계정을 절대 넓히지 않는다 | +| `api/error` | 7.2 | 전부 | 없음 | 해당 없음 | 해당 없음 | 실패 metadata에 key나 value가 없다 | +| `api/operations` | 7.2 | 전부 | 없음 | 해당 없음 | 해당 없음 | 계약만 | +| `api/reactive` | 7.2 | 전부 | 없음 | 해당 없음 | 해당 없음 | Reactor는 이 package 안에만 | +| `lettuce` | 7.2 | 전부 | R1–R2 | 됨 | 됨 | Lettuce 버전은 Boot BOM이 정한다(실제 버전은 leaf `gradle.lockfile`) | +| `lettuce/codec` | 7.2 | 전부 | 없음 | 됨 | 됨 | UTF-8과 byte array codec만 | +| `lettuce/command` | 7.2 | 전부 | R1–R2 | 됨 | 됨 | 정책 목록이 유일한 명령 권한이다 | +| `lettuce/connection` | 7.2 | 전부 | 없음 | 됨 | 됨 | lane 다섯. blocking 작업은 보통 lane을 절대 같이 쓰지 않는다 | +| `lettuce/observability` | 7.2 | 전부 | 없음 | 됨 | 됨 | 명령 계열만. key는 절대 없다 | +| `lettuce/operations` | 7.2 | 전부 | R1–R2 | 됨 | 됨 | hash field TTL은 7.4, sharded pub/sub은 7.0, stream 삭제는 8.2가 필요하다 | +| `config` | 7.2 | 전부 | 없음 | 해당 없음 | 해당 없음 | 허가 출처는 프로세스마다 HMAC 서명한다 | +| `cluster` | 7.2 | cluster | 없음 | 해당 없음 | 해당 없음 | slot 산수만. redirect를 따라가지 않는다 | +| `programmability` | 7.2 | 전부 | R2 | 됨 | 안 됨 | transaction은 절대 되돌리지 않는다. script는 bulk 답 하나를 돌려준다. `FUNCTION LOAD`는 admin plane이다 | +| `raw` | 7.2 | 전부 | R2 | 됨 | 안 됨 | `RAW_ONLY` 명령만. movable key 명세는 승인할 수 없다 | +| `admin` | 7.2 | 전부 | R3 읽기 전용 | 됨 | 안 됨 | 답은 투영한다. 파괴적인 명령은 없다 | +| `extensions` | 8.0 | 전부 | 없음 | 됨 | 안 됨 | 공용 명령 실행기. extension마다 자기 key를 선언한다 | +| `extensions/json` | 8.0 | 전부 | R1–R2 | 됨 | 안 됨 | 좁은 JSONPath 문법. 문서는 text로 주고받는다 | +| `extensions/search` | 8.0 | 전부 | R2 | 됨 | 안 됨 | index 이름은 SDK가 namespace를 붙인다. index 지우기 없음 | +| `extensions/timeseries` | 8.0 | 전부 | R1–R2 | 됨 | 안 됨 | 만들 때 보존 기간이 필수다 | +| `extensions/probabilistic` | 8.0 | 전부 | R1–R2 | 됨 | 안 됨 | 모든 답은 만든 방식상 근사값이다 | -## Capabilities +## Capability -| Capability | Minimum Redis | Gate | Bean when absent | +| Capability | 최소 Redis | 관문 | 없을 때의 bean | | --- | --- | --- | --- | -| `SHARDED_PUBSUB` | 7.0 | probe and catalog minimum | none | -| `FUNCTIONS` | 7.0 | probe and catalog minimum | none | -| `HASH_FIELD_EXPIRATION` | 7.4 | probe and catalog minimum | none | -| `HASH_FIELD_EXPIRATION_COMBINED` | 8.0 | probe and catalog minimum | none | -| `STREAM_ACKNOWLEDGE_DELETE` | 8.2 | probe and catalog minimum | none | -| `STREAM_NEGATIVE_ACKNOWLEDGE` | 8.8 | probe and catalog minimum | none, and no bean exists yet | -| `JSON` | 8.0 | probe is authoritative | none | -| `SEARCH` | 8.0 | probe is authoritative | none | -| `TIME_SERIES` | 8.0 | probe is authoritative | none | -| `PROBABILISTIC` | 8.0 | probe is authoritative | none | +| `SHARDED_PUBSUB` | 7.0 | probe와 목록 최소 버전 | 없음 | +| `FUNCTIONS` | 7.0 | probe와 목록 최소 버전 | 없음 | +| `HASH_FIELD_EXPIRATION` | 7.4 | probe와 목록 최소 버전 | 없음 | +| `HASH_FIELD_EXPIRATION_COMBINED` | 8.0 | probe와 목록 최소 버전 | 없음 | +| `STREAM_ACKNOWLEDGE_DELETE` | 8.2 | probe와 목록 최소 버전 | 없음 | +| `STREAM_NEGATIVE_ACKNOWLEDGE` | 8.8 | probe와 목록 최소 버전 | 없음. 아직 bean 자체가 없다 | +| `JSON` | 8.0 | probe가 정한다 | 없음 | +| `SEARCH` | 8.0 | probe가 정한다 | 없음 | +| `TIME_SERIES` | 8.0 | probe가 정한다 | 없음 | +| `PROBABILISTIC` | 8.0 | probe가 정한다 | 없음 | -## Certified versions +## 인증한 버전 -A version is certified by its lane producing evidence, not by the version number being newer. An -evidence claim here must name the test class that produced it; `RedisSupportMatrixTest` fails the -build on a row that claims anything else, so "verified" cannot be written into this table without a -test behind it. +버전은 숫자가 더 새것이라서가 아니라 그 lane이 증거를 만들어서 인증된다. 여기의 증거 주장은 그것을 만든 테스트 +클래스의 이름을 대야 한다. 다른 것을 주장하는 행이 있으면 `RedisSupportMatrixTest`가 빌드를 실패시킨다. 그래서 뒤에 +테스트 없이 이 표에 「확인함」을 쓸 수 없다. -All three lanes have now run on 7.4. The other declared versions are declared, not certified: -nothing in this repository has executed against 7.2 or 8.2. +세 lane 모두 7.4에서 돌았다. 다른 선언 버전은 선언만 했고 인증하지 않았다. 이 저장소의 어떤 것도 7.2나 8.2에 대해 돈 +적이 없다. -| Topology | Versions declared | Evidence status | +| 토폴로지 | 선언한 버전 | 증거 상태 | | --- | --- | --- | -| Standalone | 7.2, 7.4, 8.2 | `RedisTopologyContractTest`, `LiveRedisGuardrailTest` on 7.4 | -| Sentinel | 7.4, 8.2 | `RedisTopologyContractTest`, `LiveRedisSentinelPromotionTest` on 7.4 | -| Cluster | 7.4, 8.2 | `RedisTopologyContractTest`, `LiveRedisClusterTest` on 7.4 | +| Standalone | 7.2, 7.4, 8.2 | 7.4에서 `RedisTopologyContractTest`, `LiveRedisGuardrailTest` | +| Sentinel | 7.4, 8.2 | 7.4에서 `RedisTopologyContractTest`, `LiveRedisSentinelPromotionTest` | +| Cluster | 7.4, 8.2 | 7.4에서 `RedisTopologyContractTest`, `LiveRedisClusterTest` | -### What the standalone ACL run established +### standalone ACL 실행이 밝힌 것 -`RedisTopologyContractTest` runs the four accounts in `compose/redis/acl` against a live server and -asserts that each `CommandAccess` level grants exactly what the command policy catalog says it may -issue. Writing it found five defects that no amount of reading the files would have surfaced: +`RedisTopologyContractTest`는 `compose/redis/acl`의 계정 넷을 실제 서버에 대고 돌려, 각 `CommandAccess` 등급이 명령 정책 +목록이 허락한 것을 정확히 주는지 단언한다. 이 테스트를 쓰면서 파일을 아무리 읽어도 드러나지 않았을 결함 일곱을 찾았다. -1. A Redis ACL file accepts neither comments nor line continuations — the original files did not load - at all, and the server refused to start. -2. The advanced account granted `SMEMBERS` and `SORT`, both `RAW_ONLY` and therefore the raw gateway - account's alone. -3. The ordinary account granted `SORT_RO` for the same reason. -4. The ordinary account could not run `PUBLISH`, `SUBSCRIBE`, or `PING`, all classified `TYPED`. -5. The ordinary account could not run `MULTI`, `EXEC`, `UNWATCH`, or `DISCARD`, also `TYPED`. +1. Redis ACL 파일은 주석도 줄 이음도 받지 않는다. 원래 파일은 아예 불러와지지 않았고 서버가 시작을 거부했다. +2. advanced 계정이 `SMEMBERS`와 `SORT`를 허락했다. 둘 다 `RAW_ONLY`라서 raw gateway 계정만 가져야 한다. +3. 보통 계정이 같은 이유로 `SORT_RO`를 허락했다. +4. 보통 계정이 `TYPED`로 분류된 `PUBLISH`, `SUBSCRIBE`, `PING`을 실행할 수 없었다. +5. 보통 계정이 역시 `TYPED`인 `MULTI`, `EXEC`, `UNWATCH`, `DISCARD`를 실행할 수 없었다. +6. admin 계정에 목록이 내놓는 읽기 전용 진단 열두 개가 빠져 있었다. `OBJECT`, `PUBSUB`, `XINFO`, + `FUNCTION LIST`/`STATS`, `CLUSTER KEYSLOT` 하위 명령이다. +7. cursor scan 답 예산을 요청한 `COUNT`에 맞췄는데, Redis는 그것을 힌트로만 본다. 실제 `HSCAN COUNT 500`이 항목 501개로 + 돌아왔고 SDK가 맞는 답을 거부했다. -6. The admin account was missing twelve read-only diagnostics the catalog exposes — the `OBJECT`, - `PUBSUB`, `XINFO`, `FUNCTION LIST`/`STATS`, and `CLUSTER KEYSLOT` subcommands. +중요한 것은 2와 3이다. 계정이 마지막 강제 경계라서, 목록보다 넓은 계정은 설계가 기대는 두 번째 통제를 조용히 없앤다. -7. The cursor-scan reply budget was sized to the requested `COUNT`, which Redis treats as a hint — - a real `HSCAN COUNT 500` came back with 501 entries and the SDK refused a correct reply. +### standalone guardrail 실행이 밝힌 것 -Points 2 and 3 are the ones that matter: the account is the last enforcement boundary, so an account -wider than the catalog silently removes the second control the design relies on. +`LiveRedisGuardrailTest`는 실제 guard, 목록, 타입 있는 연산을 실제 서버에 잇는다. 명령을 인코딩하는 유일한 클래스인 +`LettuceRedisCommandGateway`가 메모리 안 대역이 아니라 SDK 자신의 계약 아래에서 처음 돈 것이다. 계획서의 데이터셋을 +싣는다: 1 MiB 상한의 값, field 십만 개짜리 hash, member 십만 개짜리 set과 sorted set, 원소 이만 개짜리 list, 항목 이만 +개를 덧붙이는 동안 1,000으로 잘리는 stream, 명령 오백 개짜리 batch. -### What the standalone guardrail run established +단언은 처리량이 아니라 한도가 지켜지는지에 관한 것이다. 절대 속도를 재는 guardrail 테스트는 부하 걸린 노트북에서 +실패하고 아무것도 가르쳐 주지 않는다. -`LiveRedisGuardrailTest` wires the real guard, catalog, and typed operations to a live server — -the first time `LettuceRedisCommandGateway`, the one class that encodes commands, runs under the -SDK's own contracts rather than against the in-memory stand-in. It carries the plan's datasets: a -value at the 1 MiB ceiling, a hundred-thousand-field hash, hundred-thousand-member set and sorted -set, a twenty-thousand-element list, a stream trimmed to 1,000 while twenty thousand entries are -appended, and a five-hundred-command batch. +### Sentinel 승격 실행이 밝힌 것 -The assertions are about limits holding, not throughput. A guardrail test that measured absolute -speed would fail on a loaded laptop and teach nobody anything. +`LiveRedisSentinelPromotionTest`는 실제 승격을 한 번 일으키고, 그에 대한 독립된 주장 여럿을 단언한다. 모든 쓰기는 그 +실행에만 있는 token을 싣는다. 그래서 승격된 primary의 list가 일어난 일을 글자 그대로 기록하고, 호출마다의 판정을 그것과 +대조할 수 있다. -### What the Sentinel promotion run established +이 납품에서 가장 심각한 결함을 찾았는데, SDK 코드에 있지 않다. -`LiveRedisSentinelPromotionTest` forces one real promotion and asserts several independent claims -about it. Every write carries a token unique to the run, so the list on the promoted primary is a -verbatim record of what happened and each per-call verdict can be checked against it. +> **교체된 primary가 계속 쓰기를 확인한다.** Sentinel은 `05:56:12.503`에 replica를 승격하고 `05:56:23.529`까지 옛 +> primary를 내리지 않았다. 그 11초 동안 아직 연결된 client가 썼고 `+OK`를 **2,086번** 받았다. 옛 primary가 새 primary에서 +> 다시 동기화할 때 그 쓰기는 모두 버려졌다. 실패한 명령은 정확히 **하나**였다. client 쪽 신호는 없다. 서버가 답했으니 +> driver, SDK, 호출자 모두 성공을 맞게 기록했다. -It found the most serious defect in this delivery, and it is not in the SDK's code: +`SentinelFailoverObserver`는 *결과를 모르는* 쓰기를 센다. 그 문서는 예전에 그것을 「운영자가 맞춰 봐야 하는 것」이라고 +불렀다. 세 자릿수만큼 틀렸고, 지금은 클래스가 그렇다고 말한다. -> **A superseded primary keeps acknowledging writes.** Sentinel promoted the replica at -> `05:56:12.503` and did not demote the old primary until `05:56:23.529` — eleven seconds in which -> the client, still connected, wrote and was told `+OK` **2,086 times**. Every one of those writes -> was discarded when the old primary resynced from the new one. Exactly **one** command failed. No -> client-side signal exists for this: the server answered, so the driver, the SDK, and the caller -> all correctly recorded a success. +구간을 닫는 것은 client가 아니라 서버에 있다. `min-replicas-to-write 1`과 `min-replicas-max-lag 1`을 설정하고 똑같은 +승격을 다시 돌리자, 확인했다가 버려진 쓰기가 **2,086개에서 1개**로 줄었다. 외톨이가 된 primary가 2,020개를 +`NOREPLICAS`로 거부했고, SDK는 그것을 호출자가 대응할 수 있는 결과가 분명한 실패로 바꾼다. 두 설정은 이제 lane에 있고, +`acknowledgedWriteLossIsBounded`가 허용하는 손실을 설정한 lag 구간에 묶는다. 그래서 설정을 빼면 수가 한 자릿수 이상 뛰고 +테스트가 실패한다. -`SentinelFailoverObserver` counts *ambiguous* writes, and its documentation used to call those "the -ones an operator has to reconcile". That was wrong by three orders of magnitude, and the class now -says so. +그 단언은 쓴 지 하루 만에 같은 실수의 두 번째 판을 잡았다. 첫 보호 실행은 통과했는데 둘째는 버려진 쓰기 2,099개로 +실패했다. 설정을 lane의 `primary` 서비스에만 썼기 때문이다. 두 데이터 노드는 failover마다 역할을 바꾼다. 그래서 마침 +primary로 시작한 쪽에만 건 보호 장치는 lane이 존재 이유인 일을 하는 순간 적용되지 않는다. 이제 두 노드 모두 정의 하나에서 +설정 전체를 받는다. 그 뒤로 양쪽 방향의 연속 승격 세 번에서 확인했다가 잃은 쓰기는 0, 0, 1개였다. -What closes the window is on the server, not the client. Re-running the identical promotion with -`min-replicas-to-write 1` and `min-replicas-max-lag 1` configured cut acknowledged-and-discarded -writes from **2,086 to 1**: the orphaned primary refused 2,020 writes with `NOREPLICAS`, which the -SDK translates to a definite, non-ambiguous failure the caller can act on. Both settings are now in -the lane, and `acknowledgedWriteLossIsBounded` ties the tolerated loss to the configured lag window, -so removing them makes the count jump by an order of magnitude and fails the test. +이 실행은 변환기 결함도 찾았다. 승격이 진행 중인 `RPUSH` 아래의 channel을 닫았고, driver는 맨 `RedisException`을 +던졌다. 그것은 어느 분기에도 맞지 않아 *확실히 실행되지 않음*으로 보고하는 일반 실패로 떨어졌다. 알아보지 못한 실패는 +그 주장을 뒷받침하지 않고, 그것을 믿는 호출자는 멱등이 아닌 쓰기를 재시도한다. 지금은 분류하지 못한 쓰기 실패를 결과 +모름으로 다룬다. -That assertion then caught a second version of the same mistake within a day of being written. The -first guarded run passed; the second failed with 2,099 lost writes, because the setting had been -written into the lane's `primary` service only. The two data nodes swap roles on every failover, so -a guardrail applied to whichever one happens to start as primary stops applying the moment the lane -does the thing it exists to do. Both nodes now take their whole configuration from one definition. -Three consecutive promotions in both directions since: 0, 0, and 1 acknowledged write lost. +### Cluster 실행이 밝힌 것 -The run also found a translator defect. A promotion closed the channel under an in-flight `RPUSH` -and the driver raised a bare `RedisException`, which matched no branch and fell through to a generic -failure reported as *definitely did not run*. Nothing about an unrecognised failure supports that -claim, and a caller who believes it retries a non-idempotent write. The fallback now treats an -unclassified write failure as ambiguous. +`LiveRedisClusterTest`는 `sdk.cluster` 중 순수한 client 쪽 산수인 부분을 마지막 결정권을 가진 서버와 대조한다. 손으로 +쓴 구현이 틀리는 중괄호 규칙으로 만든 묶음 — 빈 tag `{}`, `foo{}{bar}`, `foo{{bar}}zap`, 닫히지 않은 중괄호, `}{`, +빈 key, ASCII가 아닌 key — 의 모든 항목에서 계산기가 `CLUSTER KEYSLOT`과 같은 답을 냈다. 그리고 그린 key 불변식이 +지켜진다. SDK가 tag만으로 계산한 slot이 서버가 그린 key 전체로 계산한 slot과 같다. -### What the Cluster run established +slot을 넘는 거부는 양쪽 방향으로 확인했다. cluster보다 엄격한 guard는 이유 없이 가용성을 깎고, 느슨한 guard는 성공할 +수 없는 요청을 보낸다. guard가 거부하는 key 쌍이 서버가 `CROSSSLOT`으로 답하는 쌍과 같다. -`LiveRedisClusterTest` checks the part of `sdk.cluster` that is pure client-side arithmetic against -the server that has the last word. The calculator agreed with `CLUSTER KEYSLOT` on every entry of a -corpus built from the brace rules a hand-written implementation gets wrong — an empty tag `{}`, -`foo{}{bar}`, `foo{{bar}}zap`, an unclosed brace, `}{`, the empty key, and non-ASCII keys — and the -rendered-key invariant holds: the slot the SDK computes from a tag alone equals the slot the server -computes from the whole rendered key. - -Cross-slot refusal was checked in both directions, because a guard stricter than the cluster costs -availability for no reason and a looser one sends requests that cannot succeed. The same key pair -the guard refuses is the pair the server answers `CROSSSLOT` for. - -Redirects were observed rather than assumed: a `MOVED` names the slot the client computed, and a -slot put into a real `MIGRATING`/`IMPORTING` state answers `ASK` for an absent key and `TRYAGAIN` -for a multi-key request that straddles the migration. The lane restores the slot to `STABLE` -afterwards, so a run leaves the cluster as it found it. +redirect는 가정하지 않고 관측했다. `MOVED`는 client가 계산한 slot을 이름 댄다. 실제 `MIGRATING`/`IMPORTING` 상태로 둔 +slot은 없는 key에 `ASK`로, 이동에 걸친 여러 key 요청에 `TRYAGAIN`으로 답한다. lane은 그 뒤 slot을 `STABLE`로 되돌린다. +그래서 실행이 cluster를 처음 상태 그대로 남긴다. diff --git a/docs/redis/upgrade-guide.md b/docs/redis/upgrade-guide.md index 07144bd0..184aed94 100644 --- a/docs/redis/upgrade-guide.md +++ b/docs/redis/upgrade-guide.md @@ -1,66 +1,56 @@ -# Redis and client upgrade gate +# Redis와 client 업그레이드 관문 -Changing the Redis server version or the Lettuce version is not a dependency bump. Both change what -commands exist, what they reply, and what an ACL account is allowed to do — all three are things this -SDK encodes as fixed decisions. The checks below must pass before either version moves, and each one -exists because skipping it produces a specific failure that only shows up in production. +Redis 서버 버전이나 Lettuce 버전을 바꾸는 것은 의존성 올리기가 아니다. 둘 다 어떤 명령이 있는지, 무엇을 답하는지, +ACL 계정이 무엇을 해도 되는지를 바꾼다. 셋 모두 이 SDK가 고정된 결정으로 담고 있는 것이다. 어느 버전이든 움직이기 전에 +아래 검사를 통과해야 하고, 각 검사를 건너뛰면 운영에서만 드러나는 특정한 실패가 생긴다. -## 1. Command metadata diff +## 1. 명령 metadata diff -Compare `COMMAND DOCS` / `COMMAND INFO` from the new server with the policy by hand: every command -the server reports must be classified in -`src/adapter/outbound/redis-sdk/src/main/resources/redis-sdk/redis-command-policy.yml`, and every -key specification, ACL category and deprecation the policy relies on must still match. There is no -automated diff: `RedisCommandMetadataDiff` compared against server metadata nothing ever fetched, -and was removed (see `docs/capability-status.md`). +새 서버의 `COMMAND DOCS` / `COMMAND INFO`를 정책과 손으로 비교한다. 서버가 보고하는 모든 명령이 +`src/adapter/outbound/redis-sdk/src/main/resources/redis-sdk/redis-command-policy.yml`에 분류돼 있어야 하고, 정책이 +기대는 모든 key 명세, ACL 분류, 폐기 표시가 여전히 맞아야 한다. 자동 diff는 없다. `RedisCommandMetadataDiff`는 아무도 +가져온 적 없는 서버 metadata와 비교했고, 지웠다(`docs/capability-status.md`). -*Why:* an unclassified command is refused by `CommandPolicyGuard`, so a server that grew a command -does not create a hole — but a command whose **risk changed upstream** and is still classified R1 -here does. The comparison is what surfaces that. +*이유:* 분류하지 않은 명령은 `CommandPolicyGuard`가 거부한다. 그래서 명령이 늘어난 서버는 구멍을 만들지 않는다. 다만 +**상위에서 위험도가 바뀌었는데** 여기서 아직 R1로 분류된 명령은 구멍을 만든다. 그것을 드러내는 것이 비교다. -## 2. ACL regression +## 2. ACL 회귀 -Re-run `ACL DRYRUN` for every account against every command the SDK can issue, using -`RedisAdminOperations.aclDryRun`. +`RedisAdminOperations.aclDryRun`으로, SDK가 보낼 수 있는 모든 명령에 대해 모든 계정의 `ACL DRYRUN`을 다시 돌린다. -*Why:* a permit never widens an ACL account, so the account is the last boundary. A new server -version that moved a command into a different ACL category silently turns a working call into a -runtime refusal on the first request that needs it. +*이유:* 허가는 ACL 계정을 절대 넓히지 않는다. 그래서 계정이 마지막 경계다. 새 서버 버전이 명령을 다른 ACL 분류로 +옮기면, 되던 호출이 그것이 필요한 첫 요청에서 실행 중 거부로 조용히 바뀐다. -## 3. Serializer golden bytes +## 3. Serializer golden byte -Compare the encoded form of every registered codec against the stored golden bytes. +등록한 모든 codec의 인코딩 결과를 저장해 둔 golden byte와 비교한다. -*Why:* a value written by the old version must still decode after the upgrade. A codec change that -looks harmless in a round-trip test is not harmless against data already in the instance. +*이유:* 옛 버전이 쓴 값이 업그레이드 뒤에도 디코딩돼야 한다. 왕복 테스트에서 해롭지 않아 보이는 codec 변경도 이미 +인스턴스에 있는 데이터에 대해서는 해롭다. -## 4. Support matrix +## 4. 지원 매트릭스 -Update `docs/redis/support-matrix.md`. `RedisSupportMatrixTest` fails when a module or capability is -missing, and the certified-version table must not claim a version until its topology lane has -actually run. +`docs/redis/support-matrix.md`를 고친다. `RedisSupportMatrixTest`는 모듈이나 capability가 빠지면 실패한다. 인증 버전 +표는 그 토폴로지 lane이 실제로 돌기 전까지 버전을 주장하면 안 된다. -## 5. Topology suite +## 5. 토폴로지 suite -Run the standalone, Sentinel, and Cluster lanes declared in `src/adapter/outbound/redis-sdk/compose/`. A version is -certified by the lane passing, not by the version number being newer. +`src/adapter/outbound/redis-sdk/compose/`에 선언한 standalone, Sentinel, Cluster lane을 돌린다. 버전은 숫자가 더 새것이라서가 +아니라 lane이 통과해서 인증된다. -*Why:* failover certainty and cross-slot behaviour are the two things the in-memory fixture cannot -prove. `ExecutionCertainty` and `RedisSlotCalculator` are classification and arithmetic; whether the -driver actually behaves that way during a promotion or a resharding is only observable on a real -topology. +*이유:* failover 확실성과 slot을 넘는 동작은 메모리 안 fixture가 증명할 수 없는 두 가지다. `ExecutionCertainty`와 +`RedisSlotCalculator`는 분류와 산수다. 승격이나 재분배 중에 driver가 정말 그렇게 동작하는지는 실제 토폴로지에서만 볼 수 +있다. -## 6. Rollback +## 6. 되돌리기 -Before the upgrade, record the previous server version, the previous Lettuce version, and the -`SCRIPT LOAD` digests of every registered script. A rollback is not complete until the digests -resolve again on the restored version. +업그레이드 전에 앞 서버 버전, 앞 Lettuce 버전, 등록한 모든 script의 `SCRIPT LOAD` digest를 적어 둔다. 되돌린 버전에서 +digest가 다시 풀릴 때까지 되돌리기는 끝나지 않은 것이다. -*Why:* digests are cached per process and invalidated by `SCRIPT FLUSH` and by restarts. A rollback -that leaves a process holding digests the restored server does not know produces `NOSCRIPT` on -every scripted call until the cache is dropped. +*이유:* digest는 프로세스마다 cache되고 `SCRIPT FLUSH`와 재시작으로 무효가 된다. 되돌린 서버가 모르는 digest를 쥔 +프로세스가 남으면, cache를 버릴 때까지 script를 쓰는 모든 호출에서 `NOSCRIPT`가 난다. -## What this gate does not cover +## 이 관문이 다루지 않는 것 -Data migration. Nothing here moves or reshapes stored values; a change that alters what is stored, -rather than how it is addressed, needs its own plan. +데이터 마이그레이션. 여기의 어떤 것도 저장된 값을 옮기거나 모양을 바꾸지 않는다. 주소 잡는 방식이 아니라 저장하는 것을 +바꾸는 변경에는 따로 계획이 필요하다. diff --git a/docs/registries/capabilities.yaml b/docs/registries/capabilities.yaml index 2fc161d4..049d314d 100644 --- a/docs/registries/capabilities.yaml +++ b/docs/registries/capabilities.yaml @@ -3,19 +3,19 @@ # Owner branch: feature-repository-access-permission-contract # Last updated: 2026-06-05 # -# Notes -# - capability는 사용자 권한이 아니라 application use case가 infrastructure capability를 -# 사용할 수 있는지에 대한 계약 (feature-repository-access-permission-contract). -# - enforcement default = ArchUnit annotation-based rule. compile-time annotation processor는 -# alternative. runtime AOP는 forbidden. -# - capability 제거는 항상 breaking change. 추가는 additive (registry row 동반 시). -# - annotation 표기 (as-built, F1/F2 reconciled 2026-06-05): 코드 SSOT는 단일 -# `@UseCaseCapability` (TYPE target, typed attribute). 노트 D2/D11의 flat -# `@UseCaseRepositoryAccess(Capability[])` 모델은 superseded. 7 capability ↔ as-built 매핑: +# 읽는 법 +# - capability는 사용자 권한이 아니라, application use case가 인프라 기능을 쓸 수 있는지에 대한 +# 계약이다 (feature-repository-access-permission-contract). +# - 강제(enforcement) 기본값 = annotation을 보는 ArchUnit 규칙. compile-time annotation processor는 +# 대안이다. runtime AOP는 쓰지 않는다. +# - capability를 지우면 언제나 breaking change다. 더하는 것은 additive다(registry 행을 같이 더할 때). +# - annotation 표기 (구현된 모양, F1/F2를 2026-06-05에 맞춤): 코드의 정본은 `@UseCaseCapability` 하나다 +# (TYPE target, 타입이 있는 속성). 노트 D2/D11의 평평한 `@UseCaseRepositoryAccess(Capability[])` +# 모델은 대체됐다. capability와 구현된 속성의 대응: # READ_REPOSITORY/WRITE_REPOSITORY → repositoryAccess, TRANSACTION_REQUIRED → transactionMode, # EXTERNAL_OUTBOUND_ALLOWED → externalOutboundAllowed, SENSITIVE_READ → sensitiveRead, # BULK_WRITE → bulkWrite, CROSS_TENANT_ADMIN → crossTenantAdmin. -# 각 row의 annotation: 필드는 아래에서 as-built 표기로 정합됨. +# 각 행의 annotation: 칸은 아래에서 구현된 표기로 맞췄다. capabilities: @@ -46,7 +46,7 @@ capabilities: required_test: architecture-enforcement:write-repository-capability # source: feature-repository-access-permission-contract — decisions 2026-05-22 - # "SENSITIVE_READ marker = registry-managed metadata table (entity FQN + field name 단위)" + # "SENSITIVE_READ marker = registry-managed metadata table (entity FQN + field name 단위)" - name: SENSITIVE_READ scope: use_case_method enforcement: archunit @@ -59,7 +59,7 @@ capabilities: required_test: architecture-enforcement:sensitive-read-capability # source: feature-repository-access-permission-contract — decisions 2026-05-22 - # "BULK_WRITE threshold = N > 100 또는 batch size > 100. 미만은 일반 WRITE_REPOSITORY로 충분" + # "BULK_WRITE threshold = N > 100 또는 batch size > 100. 미만은 일반 WRITE_REPOSITORY로 충분" - name: BULK_WRITE scope: use_case_method enforcement: archunit @@ -72,7 +72,7 @@ capabilities: required_test: architecture-enforcement:bulk-write-capability # source: feature-repository-access-permission-contract — decisions 2026-05-22 - # "TRANSACTION_REQUIRED는 application-port branch의 TransactionPort contract와 연결되어야 하며 Spring @Transactional 직접 import로 충족하지 않음" + # "TRANSACTION_REQUIRED는 application-port branch의 TransactionPort contract와 연결되어야 하며 Spring @Transactional 직접 import로 충족하지 않음" # source: feature-application-port-usecase-contract — TransactionPort Contract - name: TRANSACTION_REQUIRED scope: use_case_method @@ -86,7 +86,7 @@ capabilities: required_test: architecture-enforcement:transaction-required-capability # source: feature-repository-access-permission-contract — decisions 2026-05-22 - # "EXTERNAL_OUTBOUND_ALLOWED 분류 = outbox row INSERT는 in-process(불요), polling publisher의 broker publish는 outbound(필요)" + # "EXTERNAL_OUTBOUND_ALLOWED 분류 = outbox row INSERT는 in-process(불요), polling publisher의 broker publish는 outbound(필요)" # source: feature-application-port-usecase-contract — "outbound adapter 호출 use case에 EXTERNAL_OUTBOUND_ALLOWED가 없으면 실패" - name: EXTERNAL_OUTBOUND_ALLOWED scope: use_case_method @@ -100,7 +100,7 @@ capabilities: required_test: architecture-enforcement:external-outbound-capability # source: feature-repository-access-permission-contract — decisions 2026-05-22 - # "CROSS_TENANT_ADMIN capability를 capability vocabulary에 추가 (tenant branch feature-tenant-context-policy와 cross-link)" + # "CROSS_TENANT_ADMIN capability를 capability vocabulary에 추가 (tenant branch feature-tenant-context-policy와 cross-link)" - name: CROSS_TENANT_ADMIN scope: use_case_method enforcement: archunit diff --git a/docs/registries/env-keys.yaml b/docs/registries/env-keys.yaml index 6536d1ae..fb2a3b8a 100644 --- a/docs/registries/env-keys.yaml +++ b/docs/registries/env-keys.yaml @@ -3,30 +3,30 @@ # Owner branch: feature-env-driven-runtime-configuration # Last updated: 2026-09-25 # -# Conventions: -# - Application-owned env uses `APP_` prefix, fully unified (D2, 2026-06-05): -# datasource/server/etc. keys that map onto Spring properties are renamed APP_* -# as well (e.g. SERVER_PORT -> APP_SERVER_PORT). -# - Only env the Spring runtime reads natively stays native: SPRING_* and -# SPRING_PROFILES_ACTIVE (D6 — profile selector is Spring-native, not APP_). -# - `classification: secret` rows only reference secrets-classification.yaml; full row owned there. -# - reload_policy default = `restart-only` (env-driven branch "config reload: no runtime reload"). -# - boolean encoding = true/false only (env-driven branch 2026-05-22). -# - Duration encoding = Spring shorthand (`30s`); ISO-8601 (`PT30S`) forbidden (env-driven branch 2026-05-22). -# - DataSize encoding = `10MB` (env-driven branch 2026-05-22). +# 표기 규칙 +# - 애플리케이션이 가진 env는 모두 `APP_` 접두어를 쓴다(D2, 2026-06-05). Spring 속성으로 이어지는 +# datasource·server 등의 키도 APP_*로 바꿨다(예: SERVER_PORT -> APP_SERVER_PORT). +# - Spring 런타임이 직접 읽는 env만 원래 이름으로 둔다: SPRING_*와 SPRING_PROFILES_ACTIVE +# (D6 — profile 선택자는 APP_가 아니라 Spring 자체 이름이다). +# - `classification: secret` 행은 secrets-classification.yaml을 가리키기만 한다. 행 전체는 그 파일이 가진다. +# - reload_policy 기본값 = `restart-only` (env-driven branch "config reload: no runtime reload" — 실행 중 +# 다시 읽지 않는다). +# - boolean 값은 true/false만 쓴다 (env-driven branch 2026-05-22). +# - Duration 값은 Spring 줄임 표기(`30s`)다. ISO-8601(`PT30S`)은 쓰지 않는다 (env-driven branch 2026-05-22). +# - DataSize 값은 `10MB` 꼴이다 (env-driven branch 2026-05-22). +# - required_when은 둘 중 하나다. `<속성>=<값>` 꼴(공백 없음)은 테스트가 그 조건에서 기동 실패를 확인하고, +# 공백이 든 설명 꼴은 사람이 읽는 조건이다(RequiredWhenIsEnforcedTest). env_keys: - # === Profile / Identity (feature-env-driven-runtime-configuration) === + # === Profile / 정체성 (feature-env-driven-runtime-configuration) === - name: SPRING_PROFILES_ACTIVE - # source: feature-env-driven-runtime-configuration D6 (2026-06-06), amended by - # five-adapter-runtime-remediation §7.1. Profile selector is Spring-native and sole - # (APP_PROFILE was dropped). Exactly one value, not a CSV list: two environments cannot both - # have their safety rules apply, and whichever lost did so silently. + # source: feature-env-driven-runtime-configuration D6 (2026-06-06), five-adapter-runtime-remediation §7.1에서 + # 고침. profile 선택자는 Spring 자체 키 하나뿐이다(APP_PROFILE은 지웠다). CSV 목록이 아니라 값 정확히 + # 하나다: 두 환경의 안전 규칙이 함께 적용될 수 없고, 진 쪽은 소리 없이 빠졌다. type: enum - # No default. A profile that is guessed is a deployment nobody chose: a jar started - # with none used to become local, which before persistence was gated also meant an - # in-memory database that loses every write on restart. + # 기본값이 없다. 짐작한 profile은 아무도 고르지 않은 배포다: 예전에는 profile 없이 띄운 jar가 local이 + # 됐고, 영속성을 조건으로 묶기 전에는 재기동 때 쓴 것을 모두 잃는 in-memory DB이기도 했다. allowed_values: [local, dev, prod] classification: public-config required: true @@ -36,9 +36,9 @@ env_keys: compatibility_impact: behavior-change required_test: env-contract:profile-active - # APP_PROFILE intentionally removed (D6, 2026-06-06): profile = SPRING_PROFILES_ACTIVE - # alone. A duplicate APP_PROFILE would only add information doubling + mismatch-fail - # cost. See design record feature-env-driven-runtime-configuration Claims (wont-fix). + # APP_PROFILE은 일부러 지웠다 (D6, 2026-06-06): profile = SPRING_PROFILES_ACTIVE 하나. APP_PROFILE을 + # 따로 두면 같은 정보를 두 번 두고, 어긋날 때 실패하는 비용만 늘어난다. 설계 기록 + # feature-env-driven-runtime-configuration Claims (wont-fix) 참고. - name: APP_NAME # source: feature-env-driven-runtime-configuration 2026-05-22 @@ -54,12 +54,13 @@ env_keys: compatibility_impact: behavior-change required_test: env-contract:app-name-present - # === HTTP server (APP_ unified per D2) === + # === HTTP 서버 (D2에 따라 APP_로 통일) === - name: APP_SERVER_PORT - # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — full APP_ - # unification; server.port maps from APP_SERVER_PORT. - # + feature-management-actuator-security-contract 2026-05-22 "management port default = 9001 (separate from app 8080)" + # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_로 전부 통일. server.port는 + # APP_SERVER_PORT에서 온다. + # + feature-management-actuator-security-contract 2026-05-22 "management port default = 9001 (separate from app 8080)" + # (관리 포트 기본값 9001, 앱 8080과 분리) type: int default: 8080 allowed_values: null @@ -86,8 +87,8 @@ env_keys: required_test: actuator-contract:management-port-separated - name: APP_SERVER_SHUTDOWN - # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ unification - # (server.shutdown mode; graceful drains in-flight requests) + # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ 통일 + # (server.shutdown 방식. graceful은 처리 중인 요청을 끝내고 내린다) type: enum default: graceful allowed_values: [graceful, immediate] @@ -100,9 +101,9 @@ env_keys: required_test: env-contract:server-shutdown-mode - name: APP_SERVER_SHUTDOWN_TIMEOUT - # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ unification. - # Supersedes the old APP_SHUTDOWN_TIMEOUT row. Must stay <= k8s - # terminationGracePeriod (cross-ref feature-container-runtime-contract). + # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ 통일. + # 옛 APP_SHUTDOWN_TIMEOUT 행을 대신한다. k8s terminationGracePeriod 이하여야 한다 + # (feature-container-runtime-contract 참고). type: duration default: 30s allowed_values: null @@ -115,11 +116,11 @@ env_keys: required_test: env-contract:server-shutdown-timeout-aligned - name: APP_SERVER_FORWARD_HEADERS_STRATEGY - # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ unification. - # Fail closed: forwarded headers are trusted only when a deployment opts in behind a - # sanitizing/trusted proxy. native = Tomcat RemoteIpValve, which honours them only from - # peers matching server.tomcat.remoteip.internal-proxies. framework is not allowed: its - # ForwardedHeaderFilter believes every peer, and the rate limiter refuses to start on it. + # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ 통일. + # 기본은 닫힘(fail closed): forwarded 헤더는 배포가 정리·신뢰 proxy 뒤에서 직접 켤 때만 믿는다. + # native = Tomcat RemoteIpValve. server.tomcat.remoteip.internal-proxies에 맞는 상대에게서 온 헤더만 + # 따른다. framework는 허용하지 않는다: 그 ForwardedHeaderFilter는 모든 상대를 믿고, rate limiter가 + # 그 값으로는 기동을 거부한다. type: enum default: none allowed_values: [none, native] @@ -132,8 +133,8 @@ env_keys: required_test: env-contract:server-forward-headers-strategy - name: APP_SERVER_TOMCAT_MAX_THREADS - # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ unification - # (ceiling on concurrent request workers) + # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ 통일 + # (동시 요청 worker 상한) type: int default: 200 allowed_values: null @@ -146,8 +147,8 @@ env_keys: required_test: env-contract:tomcat-max-threads-bounded - name: APP_SERVER_TOMCAT_MIN_SPARE_THREADS - # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ unification - # (idle worker pool floor) + # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ 통일 + # (쉬는 worker pool의 하한) type: int default: 10 allowed_values: null @@ -160,8 +161,8 @@ env_keys: required_test: env-contract:tomcat-min-spare-threads-valid - name: APP_SERVER_TOMCAT_ACCEPT_COUNT - # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ unification - # (OS-level backlog queue depth for incoming TCP connections) + # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ 통일 + # (들어오는 TCP 연결의 OS backlog queue 깊이) type: int default: 100 allowed_values: null @@ -174,8 +175,8 @@ env_keys: required_test: env-contract:tomcat-accept-count-valid - name: APP_SERVER_TOMCAT_MAX_CONNECTIONS - # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ unification - # (hard cap on simultaneously open connections) + # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ 통일 + # (동시에 열린 연결 수의 상한) type: int default: 8192 allowed_values: null @@ -188,8 +189,8 @@ env_keys: required_test: env-contract:tomcat-max-connections-bounded - name: APP_SERVER_TOMCAT_CONNECTION_TIMEOUT - # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ unification - # (connection timeout for the Tomcat connector) + # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ 통일 + # (Tomcat connector 연결 timeout) type: duration default: 20s allowed_values: null @@ -202,8 +203,8 @@ env_keys: required_test: env-contract:tomcat-connection-timeout-set - name: APP_SERVER_COMPRESSION_ENABLED - # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ unification - # (server.compression toggle) + # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ 통일 + # (server.compression 켜고 끄기) type: boolean default: true allowed_values: [true, false] @@ -216,8 +217,8 @@ env_keys: required_test: env-contract:server-compression-toggle - name: APP_SERVER_COMPRESSION_MIN_RESPONSE_SIZE - # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ unification - # (payloads below this threshold are not compressed) + # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ 통일 + # (이 크기보다 작은 응답은 압축하지 않는다) type: data_size default: 1KB allowed_values: null @@ -230,8 +231,8 @@ env_keys: required_test: env-contract:server-compression-min-size - name: APP_SERVER_ERROR_INCLUDE_STACKTRACE - # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ unification - # (spring.web.error.include-stacktrace policy) + # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ 통일 + # (spring.web.error.include-stacktrace 정책) type: enum default: never allowed_values: [always, never, on_param] @@ -244,8 +245,8 @@ env_keys: required_test: env-contract:server-error-stacktrace-policy - name: APP_SERVER_ERROR_INCLUDE_MESSAGE - # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ unification - # (spring.web.error.include-message policy) + # source: feature-env-driven-runtime-configuration D2 (2026-06-05) — APP_ 통일 + # (spring.web.error.include-message 정책) type: enum default: never allowed_values: [always, never, on_param] @@ -259,12 +260,12 @@ env_keys: - name: APP_MULTI_INSTANCE_ENABLED # source: feature-env-driven-runtime-configuration D8 (2026-06-06) - # When true, StartupSafetyValidator (a StartupRule, run before any other singleton) - # requires a cross-instance DistributedLockPort bean named distributedLockProvider, - # else startup fails (exit 72). Consumed - # by feature-runtime-health-lifecycle-contract, feature-background-job-async-contract, - # feature-cache-consistency-contract, feature-domain-event-outbox-contract, - # feature-rate-limit-idempotency-contract, feature-migration-startup-contract. + # true면 StartupSafetyValidator(다른 singleton보다 먼저 도는 StartupRule)가 이름이 + # distributedLockProvider인 인스턴스 간 DistributedLockPort bean을 요구한다. 없으면 기동이 실패한다 + # (exit 72). 이 값을 쓰는 곳: feature-runtime-health-lifecycle-contract, + # feature-background-job-async-contract, feature-cache-consistency-contract, + # feature-domain-event-outbox-contract, feature-rate-limit-idempotency-contract, + # feature-migration-startup-contract. type: boolean default: false allowed_values: [true, false] @@ -278,8 +279,8 @@ env_keys: - name: APP_MIGRATION_ON_STARTUP # source: feature-migration-startup-contract - # When true, Flyway migrations are executed automatically during application startup. - # When false, migrations are bypassed (delegated to out-of-app container/pipeline jobs). + # true면 애플리케이션이 기동하면서 Flyway migration을 자동으로 돌린다. + # false면 migration을 건너뛴다(앱 밖의 container·pipeline job에 맡긴다). type: boolean default: true allowed_values: [true, false] @@ -295,7 +296,8 @@ env_keys: - name: APP_DATASOURCE_URL # source: feature-env-driven-runtime-configuration "Required config: datasource" - # + feature-persistence-failure-baseline "datasource/pool/timeout/connection exhaustion log field" + # + feature-persistence-failure-baseline "datasource/pool/timeout/connection exhaustion log field" + # (datasource·pool·timeout·연결 고갈 로그 필드) type: url default: null allowed_values: null @@ -322,7 +324,7 @@ env_keys: - name: APP_DATASOURCE_PASSWORD # source: feature-env-driven-runtime-configuration "Required config: datasource" - # + feature-secrets-config-source-contract — secret 분류로 secrets-classification.yaml에서 owns + # + feature-secrets-config-source-contract — secret 분류라 secrets-classification.yaml이 행을 가진다 type: string default: null allowed_values: null @@ -335,8 +337,8 @@ env_keys: required_test: secrets-contract:db-password-not-leaked - name: APP_PERSISTENCE_VENDOR - # source: persistence vendor selector used by application-local.yml and bootRunH2. - # PostgreSQL is the shipped default; H2 is an explicit developer-only selection. + # source: application-local.yml과 bootRunH2가 쓰는 영속성 vendor 선택자. + # PostgreSQL이 기본으로 들어 있고, H2는 개발자가 명시적으로 고를 때만 쓴다. property: app.persistence.vendor type: enum default: postgresql @@ -379,10 +381,10 @@ env_keys: required_test: jpa-contract:realtime-replay-env - name: APP_FLYWAY_ENABLED - # source: local PostgreSQL parity / explicit H2 developer lane. - # Every profile runs migrations by default — the persistence-jpa module default reads this key - # (07-08; dev/prod no longer pin a literal over it); bootRunH2 disables them because the - # migration tree is PostgreSQL-specific. + # source: 로컬 PostgreSQL을 운영과 맞춤 / 명시적 H2 개발 lane. + # 모든 profile이 기본으로 migration을 돌린다 — persistence-jpa 모듈 기본값이 이 키를 읽는다 + # (07-08; dev/prod가 그 위에 값을 박지 않는다). bootRunH2는 migration tree가 PostgreSQL 전용이라 + # 끈다. property: spring.flyway.enabled type: boolean default: true @@ -397,7 +399,7 @@ env_keys: - name: APP_DATASOURCE_POOL_MAX_SIZE # source: feature-env-driven-runtime-configuration "datasource/pool env" - # + feature-persistence-failure-baseline "Hikari metric 노출 기준" + # + feature-persistence-failure-baseline "Hikari metric 노출 기준" type: int default: 10 allowed_values: null @@ -424,12 +426,12 @@ env_keys: - name: APP_DATASOURCE_CONNECTION_TIMEOUT # source: feature-env-driven-runtime-configuration "datasource/pool env" - # + feature-persistence-failure-baseline "Hikari Alert Threshold: pool wait p99 > 100ms" - # unit: milliseconds. It feeds spring.datasource.hikari.connection-timeout, which binds onto - # HikariConfig#setConnectionTimeout(long) — a duration shorthand such as "5s" does not bind and - # fails the boot. This row said `duration` / `5s`, application.yml copied that default, and - # every prod and dev deployment refused to start; five-adapter-runtime-remediation Wave 2 found - # it in the prod-smoke lane. Corrected to what the property actually accepts. + # + feature-persistence-failure-baseline "Hikari Alert Threshold: pool wait p99 > 100ms" + # 단위: 밀리초. 이 값은 spring.datasource.hikari.connection-timeout으로 가고, 그 키는 + # HikariConfig#setConnectionTimeout(long)에 바인딩된다 — "5s" 같은 duration 줄임 표기는 바인딩되지 않아 + # 기동이 실패한다. 이 행이 `duration` / `5s`라 했고, application.yml이 그 기본값을 복사했고, 모든 prod·dev + # 배포가 기동을 거부했다. five-adapter-runtime-remediation Wave 2가 prod-smoke lane에서 찾았다. 실제로 + # 받는 값으로 고쳤다. type: integer default: 5000 allowed_values: null @@ -443,7 +445,7 @@ env_keys: - name: APP_DATASOURCE_DRIVER # source: feature-env-driven-runtime-configuration "Required config: datasource" - # (JDBC driver class for the configured datasource URL) + # (설정한 datasource URL의 JDBC driver class) type: string default: org.postgresql.Driver allowed_values: null @@ -457,7 +459,7 @@ env_keys: - name: APP_DATASOURCE_DDL_AUTO # source: feature-env-driven-runtime-configuration "Required config: datasource" - # (Hibernate ddl-auto; prod must be validate|none, local update convenient) + # (Hibernate ddl-auto. prod는 validate|none이어야 하고, local은 update가 편하다) type: enum default: validate allowed_values: [none, validate, update, create, create-drop] @@ -471,7 +473,7 @@ env_keys: - name: APP_DATASOURCE_SHOW_SQL # source: feature-env-driven-runtime-configuration "Required config: datasource" - # (echo SQL to logs) + # (SQL을 로그에 찍는다) type: boolean default: false allowed_values: [true, false] @@ -485,7 +487,7 @@ env_keys: - name: APP_DATASOURCE_FORMAT_SQL # source: feature-env-driven-runtime-configuration "Required config: datasource" - # (pretty-print SQL — only useful when SHOW_SQL=true) + # (SQL을 보기 좋게 찍는다 — SHOW_SQL=true일 때만 쓸모 있다) type: boolean default: false allowed_values: [true, false] @@ -499,7 +501,7 @@ env_keys: - name: APP_DATASOURCE_OPEN_IN_VIEW # source: feature-env-driven-runtime-configuration "Required config: datasource" - # (Hibernate OSIV — don't enable in prod) + # (Hibernate OSIV — prod에서 켜지 않는다) type: boolean default: false allowed_values: [true, false] @@ -513,7 +515,7 @@ env_keys: - name: APP_DATASOURCE_POOL_IDLE_TIMEOUT # source: feature-env-driven-runtime-configuration "datasource/pool env" - # (Hikari milliseconds; idle connection eviction threshold) + # (Hikari 밀리초. 쉬는 연결을 내보내는 기준) type: int default: 600000 allowed_values: null @@ -527,7 +529,7 @@ env_keys: - name: APP_DATASOURCE_POOL_MAX_LIFETIME # source: feature-env-driven-runtime-configuration "datasource/pool env" - # (Hikari milliseconds; max lifetime — rotate before broker timeout) + # (Hikari 밀리초. 연결 최대 수명 — broker timeout 전에 교체한다) type: int default: 1800000 allowed_values: null @@ -539,14 +541,14 @@ env_keys: compatibility_impact: behavior-change required_test: env-contract:pool-max-lifetime-valid - # === Tracing / Observability (feature-distributed-tracing-contract) === + # === 추적 / 관측 (feature-distributed-tracing-contract) === - name: OTEL_EXPORTER_OTLP_ENDPOINT # source: feature-distributed-tracing-contract 2026-05-22 # "Micrometer Tracing + OpenTelemetry exporter를 기본 기준으로 둠" - # OTLP base address (OpenTelemetry spec). TracingEnvironmentPostProcessor bridges it to - # management.opentelemetry.tracing.export.otlp.endpoint as /v1/traces (OTLP/HTTP); - # blank = no span exporter bean (review 07-01, 2026-11-01). + # OTLP 기본 주소(OpenTelemetry 규격). TracingEnvironmentPostProcessor가 이 값을 + # management.opentelemetry.tracing.export.otlp.endpoint의 /v1/traces(OTLP/HTTP)로 잇는다. + # 빈 값 = span exporter bean 없음 (review 07-01, 2026-11-01). type: url default: null allowed_values: null @@ -575,10 +577,9 @@ env_keys: - name: APP_TRACING_SAMPLE_RATE # source: feature-distributed-tracing-contract 2026-05-22 # "trace sampling rate default = prod 1%, dev/local 100%" - # D-1 ISSUE-1 fix (2026-06-16): blank = per-profile resolver 기본값 사용. - # RuntimeEnvironment is the profile SSOT; resolver policy is prod=0.01, dev/local=1.0. - # TracingEnvironmentPostProcessor bridges resolved rate to - # management.tracing.sampling.probability. + # D-1 ISSUE-1 fix (2026-06-16): 빈 값 = profile별 resolver 기본값을 쓴다. + # RuntimeEnvironment가 profile의 정본이다. resolver 정책은 prod=0.01, dev/local=1.0. + # TracingEnvironmentPostProcessor가 정한 비율을 management.tracing.sampling.probability로 잇는다. type: string default: "" allowed_values: null @@ -590,13 +591,13 @@ env_keys: compatibility_impact: behavior-change required_test: tracing-contract:sample-rate-per-profile - # === Log management (feature-log-management-contract) === + # === 로그 관리 (feature-log-management-contract) === - # APP_LOG_LEVEL (single key) replaced by the 5 granular APP_LOG_LEVEL_* rows below - # (root / app / spring / web / sql) — as built by feature-log-management-contract. + # APP_LOG_LEVEL 키 하나를 아래 APP_LOG_LEVEL_* 행 다섯(root / app / spring / web / sql)으로 나눴다 + # — feature-log-management-contract가 만든 대로. - name: APP_LOG_LEVEL_ROOT - # source: feature-log-management-contract — root logger level + # source: feature-log-management-contract — root logger 레벨 type: enum default: INFO allowed_values: [TRACE, DEBUG, INFO, WARN, ERROR, OFF] @@ -609,7 +610,7 @@ env_keys: required_test: log-contract:root-level - name: APP_LOG_LEVEL_APP - # source: feature-log-management-contract — application package level + # source: feature-log-management-contract — 애플리케이션 패키지 레벨 type: enum default: INFO allowed_values: [TRACE, DEBUG, INFO, WARN, ERROR, OFF] @@ -622,7 +623,7 @@ env_keys: required_test: log-contract:app-level - name: APP_LOG_LEVEL_SPRING - # source: feature-log-management-contract — Spring framework package level + # source: feature-log-management-contract — Spring framework 패키지 레벨 type: enum default: INFO allowed_values: [TRACE, DEBUG, INFO, WARN, ERROR, OFF] @@ -635,7 +636,7 @@ env_keys: required_test: log-contract:spring-level - name: APP_LOG_LEVEL_WEB - # source: feature-log-management-contract — web/MVC package level + # source: feature-log-management-contract — web/MVC 패키지 레벨 type: enum default: INFO allowed_values: [TRACE, DEBUG, INFO, WARN, ERROR, OFF] @@ -648,7 +649,7 @@ env_keys: required_test: log-contract:web-level - name: APP_LOG_LEVEL_SQL - # source: feature-log-management-contract — JPA/JDBC SQL package level (DEBUG prints SQL) + # source: feature-log-management-contract — JPA/JDBC SQL 패키지 레벨 (DEBUG면 SQL을 찍는다) type: enum default: WARN allowed_values: [TRACE, DEBUG, INFO, WARN, ERROR, OFF] @@ -661,7 +662,7 @@ env_keys: required_test: log-contract:sql-level - name: APP_LOG_FILE_ENABLED - # source: feature-log-management-contract — rolling JSON file appender toggle + # source: feature-log-management-contract — 순환(rolling) JSON 파일 appender 켜고 끄기 type: boolean default: false allowed_values: [true, false] @@ -674,7 +675,7 @@ env_keys: required_test: log-contract:file-appender-toggle - name: APP_LOG_FILE_PATH - # source: feature-log-management-contract — file path (relative to bootRun cwd or absolute) + # source: feature-log-management-contract — 파일 경로 (bootRun 실행 위치 기준 상대 경로 또는 절대 경로) type: string default: logs/ca-skeleton.json allowed_values: null @@ -687,7 +688,7 @@ env_keys: required_test: log-contract:file-path-set - name: APP_LOG_FILE_MAX_SIZE - # source: feature-log-management-contract — per-file rolling size cap + # source: feature-log-management-contract — 파일 하나의 순환 크기 상한 type: data_size default: 100MB allowed_values: null @@ -700,7 +701,7 @@ env_keys: required_test: log-contract:file-max-size - name: APP_LOG_FILE_MAX_HISTORY - # source: feature-log-management-contract — number of rolled archives to retain + # source: feature-log-management-contract — 남길 순환 보관 파일 수 type: int default: 14 allowed_values: null @@ -713,7 +714,7 @@ env_keys: required_test: log-contract:file-max-history - name: APP_LOG_FILE_TOTAL_SIZE_CAP - # source: feature-log-management-contract — total size cap across rolled files + # source: feature-log-management-contract — 순환 파일 전체의 크기 상한 type: data_size default: 3GB allowed_values: null @@ -726,7 +727,7 @@ env_keys: required_test: log-contract:file-total-size-cap - name: APP_LOG_ASYNC_ENABLED - # source: feature-log-management-contract — AsyncAppender wrap for non-blocking I/O + # source: feature-log-management-contract — 막히지 않는 I/O를 위한 AsyncAppender 감싸기 type: boolean default: true allowed_values: [true, false] @@ -739,7 +740,7 @@ env_keys: required_test: log-contract:async-appender-toggle - name: APP_LOG_ASYNC_QUEUE_SIZE - # source: feature-log-management-contract — in-memory queue depth before back-pressure + # source: feature-log-management-contract — 역압(back-pressure) 전 메모리 queue 깊이 type: int default: 512 allowed_values: null @@ -752,8 +753,8 @@ env_keys: required_test: log-contract:async-queue-size - name: APP_LOG_ASYNC_DISCARDING_THRESHOLD - # source: feature-log-management-contract — remaining-capacity floor below which - # TRACE/DEBUG/INFO events drop (WARN/ERROR always kept). 0 = never drop. + # source: feature-log-management-contract — 남은 용량이 이 값 아래로 내려가면 + # TRACE/DEBUG/INFO 이벤트를 버린다(WARN/ERROR는 늘 남긴다). 0 = 버리지 않는다. type: int default: 20 allowed_values: null @@ -766,7 +767,7 @@ env_keys: required_test: log-contract:async-discarding-threshold - name: APP_LOG_JSON_TIMEZONE - # source: feature-log-management-contract — IANA timezone for JSON encoder timestamps + # source: feature-log-management-contract — JSON encoder 시각에 쓰는 IANA timezone type: string default: UTC allowed_values: null @@ -779,7 +780,7 @@ env_keys: required_test: log-contract:json-timezone - name: APP_LOG_JSON_TIMESTAMP_PATTERN - # source: feature-log-management-contract — JSON encoder timestamp pattern (ISO 8601 default) + # source: feature-log-management-contract — JSON encoder 시각 형식 (기본 ISO 8601) type: string default: "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" allowed_values: null @@ -792,7 +793,7 @@ env_keys: required_test: log-contract:json-timestamp-pattern - name: APP_LOG_JSON_INCLUDE_CALLER_DATA - # source: feature-log-management-contract — include file/method/line (significant perf cost) + # source: feature-log-management-contract — 파일·메서드·줄 번호를 넣는다 (성능 비용이 크다) type: boolean default: false allowed_values: [true, false] @@ -805,7 +806,7 @@ env_keys: required_test: log-contract:json-include-caller-data - name: APP_LOG_JSON_LOGGER_NAME_LENGTH - # source: feature-log-management-contract — logger name abbreviation (0 = full name) + # source: feature-log-management-contract — logger 이름 줄이기 (0 = 전체 이름) type: int default: 0 allowed_values: null @@ -831,12 +832,13 @@ env_keys: compatibility_impact: behavior-change required_test: log-contract:sample-rate-per-profile - # === Privacy: user_principal pseudonymization (feature-data-retention-privacy-contract) === + # === 개인정보: user_principal 가명화 (feature-data-retention-privacy-contract) === - name: APP_PRIVACY_PSEUDONYMIZATION_SALT # source: feature-data-retention-privacy-contract — "pseudonymization key = HMAC-SHA-256 - # with rotating salt (90d)". Consumed by feature-log-management-contract (DRIFT-6) - # to record user_principal in pseudonymized form. secret 분류로 secrets-classification.yaml에서 owns. + # with rotating salt (90d)" (가명화 키는 90일마다 바뀌는 salt의 HMAC-SHA-256). feature-log-management-contract + # (DRIFT-6)가 user_principal을 가명 형태로 남기는 데 쓴다. secret 분류라 secrets-classification.yaml이 행을 + # 가진다. type: string default: null allowed_values: null @@ -865,7 +867,7 @@ env_keys: required_test: security-contract:cors-allowlist - name: APP_SECURITY_CORS_ENABLED - # source: feature-security-operational-baseline — CORS filter master toggle + # source: feature-security-operational-baseline — CORS filter 전체 켜고 끄기 type: boolean default: false allowed_values: [true, false] @@ -878,8 +880,8 @@ env_keys: required_test: security-contract:cors-enabled-toggle - name: APP_SECURITY_CORS_ALLOWED_METHODS - # source: feature-security-operational-baseline — allowed methods - # (empty -> sensible method defaults in CorsSettings) + # source: feature-security-operational-baseline — 허용 method + # (빈 값 -> CorsSettings의 무난한 method 기본값) type: csv_list default: null allowed_values: null @@ -892,7 +894,7 @@ env_keys: required_test: security-contract:cors-allowed-methods - name: APP_SECURITY_CORS_ALLOWED_HEADERS - # source: feature-security-operational-baseline — allowed request headers ("*" = any) + # source: feature-security-operational-baseline — 허용 요청 헤더 ("*" = 모두) type: csv_list default: "*" allowed_values: null @@ -1029,9 +1031,8 @@ env_keys: required_test: redis-session-contract:csrf-enabled - name: APP_SESSION_REDIS_NAMESPACE_ENVIRONMENT - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: string @@ -1046,9 +1047,8 @@ env_keys: required_test: redis-session-contract:key-namespace - name: APP_SESSION_IDLE_TIMEOUT - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: duration @@ -1063,9 +1063,8 @@ env_keys: required_test: redis-session-contract:idle-expiry - name: APP_SESSION_ABSOLUTE_LIFETIME - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: duration @@ -1080,9 +1079,8 @@ env_keys: required_test: redis-session-contract:absolute-expiry - name: APP_SESSION_TOUCH_INTERVAL - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: duration @@ -1097,9 +1095,8 @@ env_keys: required_test: redis-session-contract:bounded-touch - name: APP_SESSION_TOMBSTONE_TTL - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: duration @@ -1114,9 +1111,8 @@ env_keys: required_test: redis-session-contract:logout-tombstone - name: APP_SESSION_MAXIMUM_ENVELOPE_BYTES - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: int @@ -1131,9 +1127,8 @@ env_keys: required_test: redis-session-contract:serializer-bounded - name: APP_SESSION_MAXIMUM_ATTRIBUTES - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: int @@ -1148,9 +1143,8 @@ env_keys: required_test: redis-session-contract:serializer-bounded - name: APP_SESSION_MAXIMUM_SCALAR_BYTES - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: int @@ -1193,7 +1187,7 @@ env_keys: required_test: security-contract:jwt-audience-set - name: APP_RATE_LIMIT_ENABLED - # Inbound enforcement stays disabled until an exact provider is selected. + # 정확한 provider를 고르기 전까지 inbound 강제는 꺼져 있다. type: boolean default: false allowed_values: [true, false] @@ -1205,14 +1199,14 @@ env_keys: compatibility_impact: additive required_test: redis-rate-limit-contract:transport-provider-default-pair - # APP_RATE_LIMIT_CLIENT_IP_MODE removed (2026-09-25, review follow-up I-5a): its - # forwarded-headers-trusted value keyed unauthenticated callers by the leftmost X-Forwarded-For - # entry, which the caller writes. The client IP is getRemoteAddr(); behind a proxy set - # APP_SERVER_FORWARD_HEADERS_STRATEGY=native and server.tomcat.remoteip.internal-proxies. + # APP_RATE_LIMIT_CLIENT_IP_MODE는 지웠다 (2026-09-25, review follow-up I-5a): 그 값 + # forwarded-headers-trusted는 인증하지 않은 호출자를 X-Forwarded-For의 맨 왼쪽 값으로 구분했는데, 그 값은 + # 호출자가 쓴다. client IP는 getRemoteAddr()다. proxy 뒤라면 + # APP_SERVER_FORWARD_HEADERS_STRATEGY=native와 server.tomcat.remoteip.internal-proxies를 설정한다. - name: APP_RATE_LIMIT_REDIS_ENABLED - # DEPRECATED 2026-08-10: the rate limiter no longer owns a Redis client of its own. One client, built by RedisRuntimeAutoConfiguration, serves every capability, so a second endpoint and a second set of ceilings could only ever disagree with it. - # Replaced by: app.redis.enabled (APP_REDIS_ENABLED). + # 폐기 2026-08-10: rate limiter는 이제 자기 Redis client를 갖지 않는다. RedisRuntimeAutoConfiguration이 만든 client 하나가 모든 capability를 맡으므로, 두 번째 endpoint와 두 번째 상한은 그 client와 어긋날 수밖에 없었다. + # 대체: app.redis.enabled (APP_REDIS_ENABLED). deprecated_orphaned: true removal_deadline: 2026-11-30 type: boolean @@ -1299,8 +1293,8 @@ env_keys: required_test: rate-limit-contract:key-version-bounded - name: APP_RATE_LIMIT_REDIS_HOST - # DEPRECATED 2026-08-10: the rate limiter no longer owns a Redis client of its own. One client, built by RedisRuntimeAutoConfiguration, serves every capability, so a second endpoint and a second set of ceilings could only ever disagree with it. - # Replaced by: app.redis.nodes (APP_REDIS_NODES). + # 폐기 2026-08-10: rate limiter는 이제 자기 Redis client를 갖지 않는다. RedisRuntimeAutoConfiguration이 만든 client 하나가 모든 capability를 맡으므로, 두 번째 endpoint와 두 번째 상한은 그 client와 어긋날 수밖에 없었다. + # 대체: app.redis.nodes (APP_REDIS_NODES). deprecated_orphaned: true removal_deadline: 2026-11-30 type: string @@ -1315,8 +1309,8 @@ env_keys: required_test: rate-limit-contract:redis-host-required - name: APP_RATE_LIMIT_REDIS_PORT - # DEPRECATED 2026-08-10: the rate limiter no longer owns a Redis client of its own. One client, built by RedisRuntimeAutoConfiguration, serves every capability, so a second endpoint and a second set of ceilings could only ever disagree with it. - # Replaced by: app.redis.nodes (APP_REDIS_NODES). + # 폐기 2026-08-10: rate limiter는 이제 자기 Redis client를 갖지 않는다. RedisRuntimeAutoConfiguration이 만든 client 하나가 모든 capability를 맡으므로, 두 번째 endpoint와 두 번째 상한은 그 client와 어긋날 수밖에 없었다. + # 대체: app.redis.nodes (APP_REDIS_NODES). deprecated_orphaned: true removal_deadline: 2026-11-30 type: int @@ -1343,8 +1337,8 @@ env_keys: required_test: rate-limit-contract:redis-password-no-leak - name: APP_RATE_LIMIT_REDIS_TRUST_PEM - # DEPRECATED 2026-08-10: the rate limiter no longer owns a Redis client of its own. One client, built by RedisRuntimeAutoConfiguration, serves every capability, so a second endpoint and a second set of ceilings could only ever disagree with it. - # Replaced by: app.redis.tls.trust-material-resource. + # 폐기 2026-08-10: rate limiter는 이제 자기 Redis client를 갖지 않는다. RedisRuntimeAutoConfiguration이 만든 client 하나가 모든 capability를 맡으므로, 두 번째 endpoint와 두 번째 상한은 그 client와 어긋날 수밖에 없었다. + # 대체: app.redis.tls.trust-material-resource. deprecated_orphaned: true removal_deadline: 2026-11-30 type: string @@ -1383,8 +1377,8 @@ env_keys: required_test: redis-contract:session-password-no-leak - name: APP_SESSION_REDIS_TRUST_PEM - # DEPRECATED 2026-08-10: the session generation that bound this was removed, and the replacement does not own a Redis client of its own either. - # Replaced by: app.redis.tls.trust-material-resource. + # 폐기 2026-08-10: 이 값을 바인딩하던 session 세대를 지웠고, 대신한 것도 자기 Redis client를 갖지 않는다. + # 대체: app.redis.tls.trust-material-resource. deprecated_orphaned: true removal_deadline: 2026-11-30 type: string @@ -1399,9 +1393,8 @@ env_keys: required_test: redis-contract:session-trust-material-no-leak - name: APP_SESSION_REDIS_KEY_HMAC_SECRET - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: string @@ -1428,8 +1421,8 @@ env_keys: required_test: rate-limit-contract:redis-timeout-bounded - name: APP_RATE_LIMIT_REDIS_MAXIMUM_COMMAND_BYTES - # DEPRECATED 2026-08-10: the rate limiter no longer owns a Redis client of its own. One client, built by RedisRuntimeAutoConfiguration, serves every capability, so a second endpoint and a second set of ceilings could only ever disagree with it. - # Replaced by: app.redis.limits.max-batch-request-bytes. + # 폐기 2026-08-10: rate limiter는 이제 자기 Redis client를 갖지 않는다. RedisRuntimeAutoConfiguration이 만든 client 하나가 모든 capability를 맡으므로, 두 번째 endpoint와 두 번째 상한은 그 client와 어긋날 수밖에 없었다. + # 대체: app.redis.limits.max-batch-request-bytes. deprecated_orphaned: true removal_deadline: 2026-11-30 type: int @@ -1444,8 +1437,8 @@ env_keys: required_test: rate-limit-contract:redis-command-bytes-bounded - name: APP_RATE_LIMIT_REDIS_MAXIMUM_QUEUED_COMMANDS - # DEPRECATED 2026-08-10: the rate limiter no longer owns a Redis client of its own. One client, built by RedisRuntimeAutoConfiguration, serves every capability, so a second endpoint and a second set of ceilings could only ever disagree with it. - # Replaced by: app.redis.capacity.maximum-in-flight-commands. + # 폐기 2026-08-10: rate limiter는 이제 자기 Redis client를 갖지 않는다. RedisRuntimeAutoConfiguration이 만든 client 하나가 모든 capability를 맡으므로, 두 번째 endpoint와 두 번째 상한은 그 client와 어긋날 수밖에 없었다. + # 대체: app.redis.capacity.maximum-in-flight-commands. deprecated_orphaned: true removal_deadline: 2026-11-30 type: int @@ -1460,8 +1453,8 @@ env_keys: required_test: rate-limit-contract:redis-queue-bounded - name: APP_RATE_LIMIT_REDIS_MAXIMUM_IN_FLIGHT_BYTES - # DEPRECATED 2026-08-10: the rate limiter no longer owns a Redis client of its own. One client, built by RedisRuntimeAutoConfiguration, serves every capability, so a second endpoint and a second set of ceilings could only ever disagree with it. - # Replaced by: app.redis.capacity.maximum-in-flight-bytes. + # 폐기 2026-08-10: rate limiter는 이제 자기 Redis client를 갖지 않는다. RedisRuntimeAutoConfiguration이 만든 client 하나가 모든 capability를 맡으므로, 두 번째 endpoint와 두 번째 상한은 그 client와 어긋날 수밖에 없었다. + # 대체: app.redis.capacity.maximum-in-flight-bytes. deprecated_orphaned: true removal_deadline: 2026-11-30 type: int @@ -1476,8 +1469,8 @@ env_keys: required_test: rate-limit-contract:redis-byte-admission-bounded - name: APP_RATE_LIMIT_REDIS_NAMESPACE_ENVIRONMENT - # DEPRECATED 2026-08-10: the rate limiter no longer renders its own key prefix. Four capabilities each joining two free-form tokens produced four prefixes, and the ACL pattern matched none of them. - # Replaced by: app.redis.namespace.environment (APP_REDIS_NAMESPACE_ENVIRONMENT), shared by every capability. + # 폐기 2026-08-10: rate limiter는 이제 key prefix를 스스로 만들지 않는다. capability 넷이 각자 자유 형식 토큰 둘을 이어 prefix 넷이 생겼고, ACL 패턴은 그중 어느 것과도 맞지 않았다. + # 대체: app.redis.namespace.environment (APP_REDIS_NAMESPACE_ENVIRONMENT). 모든 capability가 함께 쓴다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: string @@ -1600,12 +1593,11 @@ env_keys: required_test: rate-limit-contract:cleanup-grace-bounded - name: APP_IDEMPOTENCY_TTL - # app.capabilities.idempotency.replay-ttl: how long a completed response stays - # replayable. One value for every provider; IdempotencySettings refuses more than 72h, less than - # APP_IDEMPOTENCY_PROCESSING_LEASE (re-review 2026-11-04 RR-03-11), and more than - # APP_IDEMPOTENCY_FAILURE_RETENTION (RR3-03-02, owner decision 2026-11-04), at startup: raising - # this key alone past the failure retention (default 24h) fails startup, so raise both - # (RR5-03-01). Each record lives for the processing lease plus this value in both stores. + # app.capabilities.idempotency.replay-ttl: 끝난 응답을 다시 돌려줄 수 있는 기간. 모든 provider가 + # 같은 값을 쓴다. IdempotencySettings는 기동할 때 72h보다 길거나, APP_IDEMPOTENCY_PROCESSING_LEASE보다 + # 짧거나(re-review 2026-11-04 RR-03-11), APP_IDEMPOTENCY_FAILURE_RETENTION보다 긴 값(RR3-03-02, 소유자 + # 결정 2026-11-04)을 거부한다. 이 키만 실패 보관 기간(기본 24h)보다 길게 올리면 기동이 실패하니 둘을 같이 + # 올린다(RR5-03-01). 두 저장소 모두에서 기록 하나는 처리 lease에 이 값을 더한 만큼 남는다. type: duration default: 24h allowed_values: null @@ -1618,12 +1610,12 @@ env_keys: required_test: idempotency-contract:ttl-applied - name: APP_IDEMPOTENCY_PROVIDER - # app.capabilities.idempotency.provider. redis and postgresql each contribute only the - # store; app-bootstrap builds the one IdempotencyExecutor and refuses startup unless exactly one - # store exists. postgresql uses the primary data source, applies its Flyway streams at startup - # and refuses a non-PostgreSQL data source, so bootRunH2 runs with disabled or redis. Selection - # is explicit and disabled by default; no implementation wins merely by being on the classpath. - # 2026-09-25: jdbc (the V1 store) was removed; a deployment still setting it fails to bind. + # app.capabilities.idempotency.provider. redis와 postgresql은 각각 저장소만 기여한다. app-bootstrap이 + # IdempotencyExecutor 하나를 만들고, 저장소가 정확히 하나가 아니면 기동을 거부한다. postgresql은 주 + # data source를 쓰고, 기동할 때 자기 Flyway stream을 적용하고, PostgreSQL이 아닌 data source를 거부한다. + # 그래서 bootRunH2는 disabled나 redis로 돈다. 선택은 명시적이고 기본은 disabled다. classpath에 있다는 + # 것만으로 고르는 구현은 없다. + # 2026-09-25: jdbc(V1 저장소)를 지웠다. 아직 이 값을 쓰는 배포는 바인딩에서 실패한다. type: enum default: disabled allowed_values: [disabled, redis, postgresql] @@ -1636,7 +1628,7 @@ env_keys: required_test: redis-idempotency-contract:provider-exclusive - name: APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET - # DEPRECATED 2026-09-22: the Redis idempotency adapter consumes caller-supplied scope digests and never read this secret. + # 폐기 2026-09-22: Redis idempotency adapter는 호출자가 준 scope digest를 쓰고 이 비밀을 읽은 적이 없다. deprecated_orphaned: true removal_deadline: 2026-12-31 type: string @@ -1651,8 +1643,8 @@ env_keys: required_test: redis-idempotency-contract:key-hmac-no-leak - name: APP_IDEMPOTENCY_REDIS_NAMESPACE_ENVIRONMENT - # DEPRECATED 2026-08-10: the idempotency store no longer renders its own key prefix. Four capabilities each joining two free-form tokens produced four prefixes, and the ACL pattern matched none of them. - # Replaced by: app.redis.namespace.environment (APP_REDIS_NAMESPACE_ENVIRONMENT), shared by every capability. + # 폐기 2026-08-10: idempotency store는 이제 key prefix를 스스로 만들지 않는다. capability 넷이 각자 자유 형식 토큰 둘을 이어 prefix 넷이 생겼고, ACL 패턴은 그중 어느 것과도 맞지 않았다. + # 대체: app.redis.namespace.environment (APP_REDIS_NAMESPACE_ENVIRONMENT). 모든 capability가 함께 쓴다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: string @@ -1667,10 +1659,9 @@ env_keys: required_test: redis-idempotency-contract:key-namespace - name: APP_IDEMPOTENCY_PROCESSING_LEASE - # app.capabilities.idempotency.processing-lease: how long one attempt holds its claim. Longer - # than the in-flight Retry-After (2s), at most 1h, and not longer than APP_IDEMPOTENCY_TTL. A - # claim whose lease runs out is taken over only if it never started; an execution whose lease - # ran out is answered IDEMPOTENCY_RECOVERY_REQUIRED and never run again. + # app.capabilities.idempotency.processing-lease: 시도 하나가 claim을 쥐는 기간. in-flight + # Retry-After(2s)보다 길고, 최대 1h이며, APP_IDEMPOTENCY_TTL보다 길지 않다. lease가 끝난 claim은 시작하지 + # 않았을 때만 넘겨받는다. lease가 끝난 실행은 IDEMPOTENCY_RECOVERY_REQUIRED로 답하고 다시 돌리지 않는다. type: duration default: 30s allowed_values: null @@ -1683,11 +1674,11 @@ env_keys: required_test: redis-idempotency-contract:processing-lease-bounded - name: APP_IDEMPOTENCY_FAILURE_RETENTION - # app.capabilities.idempotency.failure-retention: how long a record the executor marked failed - # (abandoned with an unknown effect, or retryable without one) stays, from the marking. At most - # 30d, and IdempotencySettings refuses less than APP_IDEMPOTENCY_TTL at startup: a shorter one - # lets an abandoned record go first, and a same-key resend runs the work again (re-review - # 2026-11-04 RR3-03-02, owner decision 2026-11-04). + # app.capabilities.idempotency.failure-retention: executor가 실패로 표시한 기록(결과를 모른 채 + # 버렸거나, 결과 없이 다시 시도할 수 있는 것)이 표시한 때부터 남는 기간. 최대 30d이고, + # IdempotencySettings는 기동할 때 APP_IDEMPOTENCY_TTL보다 짧은 값을 거부한다: 더 짧으면 버린 기록이 먼저 + # 사라지고, 같은 key로 다시 보낸 요청이 일을 한 번 더 한다(re-review 2026-11-04 RR3-03-02, 소유자 결정 + # 2026-11-04). type: duration default: 24h allowed_values: null @@ -1712,7 +1703,7 @@ env_keys: required_test: redis-lease-contract:provider-exclusive - name: APP_LEASE_REDIS_KEY_HMAC_SECRET - # DEPRECATED 2026-09-22: the Redis lease adapter consumes caller-supplied resource digests and never read this secret. + # 폐기 2026-09-22: Redis lease adapter는 호출자가 준 resource digest를 쓰고 이 비밀을 읽은 적이 없다. deprecated_orphaned: true removal_deadline: 2026-12-31 type: string @@ -1727,8 +1718,8 @@ env_keys: required_test: redis-lease-contract:key-hmac-no-leak - name: APP_LEASE_REDIS_NAMESPACE_ENVIRONMENT - # DEPRECATED 2026-08-10: the lease no longer renders its own key prefix. Four capabilities each joining two free-form tokens produced four prefixes, and the ACL pattern matched none of them. - # Replaced by: app.redis.namespace.environment (APP_REDIS_NAMESPACE_ENVIRONMENT), shared by every capability. + # 폐기 2026-08-10: lease는 이제 key prefix를 스스로 만들지 않는다. capability 넷이 각자 자유 형식 토큰 둘을 이어 prefix 넷이 생겼고, ACL 패턴은 그중 어느 것과도 맞지 않았다. + # 대체: app.redis.namespace.environment (APP_REDIS_NAMESPACE_ENVIRONMENT). 모든 capability가 함께 쓴다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: string @@ -1754,10 +1745,10 @@ env_keys: compatibility_impact: additive required_test: redis-lease-contract:drift-budget-bounded - # === Cache / Redis (feature-cache-consistency-contract + integration-adapter-templates) === + # === 캐시 / Redis (feature-cache-consistency-contract + integration-adapter-templates) === - name: APP_CACHE_CANONICAL_DEFAULT_PROVIDER - # Canonical default semantic region provider selection; legacy enable is a separate migration path. + # 기본 캐시 영역(canonical default semantic region)의 provider 선택. 옛 켜기 키는 따로 옮겨 가는 경로다. type: enum default: disabled allowed_values: [disabled, redis] @@ -1770,12 +1761,12 @@ env_keys: required_test: redis-cache:canonical-cache-role-composition - name: APP_REDIS_ENABLED - # 2026-09-25 capability packaging: the cache-redis module is on when present (its - # config/module-defaults/cache-redis.yml maps this key with default true); false is the explicit - # off. Absent from the build is the ordinary off state. - # False loads no Redis settings, requires no Redis secret, and creates no client, connection, - # thread or health contributor. Role selectors choose which capabilities compose once Redis is - # on; none of them is a second on/off key. + # 2026-09-25 capability 포장: cache-redis 모듈은 있으면 켜진다(모듈의 + # config/module-defaults/cache-redis.yml이 이 키를 기본 true로 잇는다). false가 명시적으로 끄는 값이다. + # 빌드에 모듈이 없는 것이 보통의 꺼진 상태다. + # false면 Redis 설정을 읽지 않고, Redis 비밀을 요구하지 않고, client·연결·thread·health contributor를 + # 만들지 않는다. Redis가 켜진 뒤 어떤 capability를 조립할지는 role 선택자가 고른다. 그중 어느 것도 두 + # 번째 켜고 끄기 키가 아니다. property: app.redis.enabled owner_module: adapter-outbound-cache-redis type: boolean @@ -1792,8 +1783,8 @@ env_keys: - name: APP_CACHE_REDIS_POSITIVE_HARD_TTL - # How long a cache entry stays usable. The physical Redis TTL equals this and nothing else, so - # an entry can never outlive the deployment's own notion of usability or be discarded early. + # 캐시 항목을 쓸 수 있는 기간. Redis의 실제 TTL은 이 값과 같고 다른 것이 아니다. 그래서 항목이 배포가 + # 정한 사용 기간보다 오래 남거나 일찍 버려지지 않는다. type: duration default: 5m allowed_values: null @@ -1806,8 +1797,8 @@ env_keys: required_test: redis-capability:cache-region-composition - name: APP_CACHE_REDIS_NEGATIVE_TTL - # How long an authoritative absence is cached. Separate from the positive TTL because "the - # source says this does not exist" is a fact with a different shelf life from a value. + # 권위 있는 「없음」을 캐시하는 기간. 「원천에 이것이 없다」는 사실은 값과 유통 기한이 달라서 값의 + # TTL과 따로 둔다. type: duration default: 10s allowed_values: null @@ -1820,9 +1811,9 @@ env_keys: required_test: redis-capability:cache-region-composition - name: APP_CACHE_REDIS_MAXIMUM_SCRIPT_CONNECTIONS - # The cache's own script-lane connections. Separate from APP_REDIS_CAPACITY_MAXIMUM_SCRIPT_CONNECTIONS, - # which idempotency, rate limiting and leases share, so cache fills cannot starve them (review - # 2026-11-03 README section 4, RR-04-02). + # 캐시 자신의 script lane 연결 수. idempotency·rate limit·lease가 함께 쓰는 + # APP_REDIS_CAPACITY_MAXIMUM_SCRIPT_CONNECTIONS와 따로 두어, 캐시 채우기가 그 셋을 굶기지 않게 한다 + # (review 2026-11-03 README 4절, RR-04-02). property: app.capabilities.cache.maximum-script-connections owner_module: adapter-outbound-cache-redis type: integer @@ -1838,7 +1829,7 @@ env_keys: required_test: redis-capability:cache-script-lane-separate-from-correctness - name: APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT - # The ceiling on one owner-safe transition. + # owner-safe 전이 하나의 상한. type: duration default: 200ms allowed_values: null @@ -1851,7 +1842,7 @@ env_keys: required_test: redis-capability:idempotency-store-composition - name: APP_LEASE_REDIS_COMMAND_TIMEOUT - # The ceiling on one lease operation. + # lease 연산 하나의 상한. type: duration default: 200ms allowed_values: null @@ -1864,8 +1855,8 @@ env_keys: required_test: redis-capability:lease-composition - name: APP_LEASE_REDIS_CONTENTION_RETRY_AFTER - # What a contended acquire tells the caller to wait. Distinct from the drift budget: one is - # advice to a caller that lost, the other is how much of its own lease a winner does not trust. + # 경합으로 acquire에 실패한 호출자에게 기다리라고 알려 줄 시간. drift 예산과 다르다: 하나는 진 + # 호출자에게 주는 조언이고, 다른 하나는 이긴 쪽이 자기 lease 중 믿지 않는 부분이다. type: duration default: 50ms allowed_values: null @@ -1877,14 +1868,14 @@ env_keys: compatibility_impact: additive required_test: redis-capability:lease-composition - # --- Redis runtime settings (app.redis.*) ---------------------------------- - # Bound only by RedisRuntimeAutoConfiguration in adapter-outbound-redis-runtime while - # APP_REDIS_ENABLED is true. application.yml does not force these values into Redis-free - # deployments; src/.env.example merely documents explicit operator inputs. verifyEnvKeys checks - # the registry against the runtime module's configuration metadata. + # --- Redis 런타임 설정 (app.redis.*) ---------------------------------- + # APP_REDIS_ENABLED가 true일 때만 adapter-outbound-redis-runtime의 RedisRuntimeAutoConfiguration이 + # 바인딩한다. application.yml은 Redis 없는 배포에 이 값을 넣지 않는다. src/.env.example은 운영자가 + # 명시적으로 넣을 값을 적어 둘 뿐이다. verifyEnvKeys가 이 레지스트리를 런타임 모듈의 설정 메타데이터와 + # 대조한다. - name: APP_REDIS_DATABASE - # Cluster supports database 0 only; a non-zero value fails startup there. + # Cluster는 database 0만 지원한다. 0이 아니면 거기서 기동이 실패한다. property: app.redis.database owner_module: adapter-outbound-redis-runtime type: integer @@ -1961,7 +1952,7 @@ env_keys: required_test: redis-sdk:typed-settings-bound-and-validated - name: APP_REDIS_NODES - # CSV of host:port. Cluster and Sentinel take every seed node. + # host:port CSV. Cluster와 Sentinel은 모든 seed node를 받는다. property: app.redis.nodes owner_module: adapter-outbound-redis-runtime type: csv @@ -1992,7 +1983,7 @@ env_keys: required_test: redis-sdk:typed-settings-bound-and-validated - name: APP_REDIS_TIMEOUT_FAST - # Single-key command profile; above 5s produces a startup warning. + # 단일 key 명령 profile. 5s를 넘으면 기동 때 경고를 남긴다. property: app.redis.timeout.fast owner_module: adapter-outbound-redis-runtime type: duration @@ -2022,16 +2013,15 @@ env_keys: compatibility_impact: additive required_test: redis-sdk:typed-settings-bound-and-validated - # --- Redis runtime composition settings (app.redis.*) ---------------------- - # Authentication, Sentinel discovery, TLS, lifecycle, Cluster routing and capacity. Same rule as the rest of app.redis.*: bound only while - # APP_REDIS_ENABLED is true, and deliberately absent from application.yml and .env. + # --- Redis 런타임 조립 설정 (app.redis.*) ---------------------- + # 인증, Sentinel 탐색, TLS, 수명 주기, Cluster 라우팅, 용량. 다른 app.redis.*와 규칙이 같다: + # APP_REDIS_ENABLED가 true일 때만 바인딩하고, application.yml과 .env에는 일부러 두지 않는다. - name: APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE - # Pointer to the account registered scripts run as, in the same - # secret://@/ form as the application reference. Unset, scripts run - # as the application account and startup logs a warning saying so. The Compose Redis lanes use - # secret://ca-skeleton-application-advanced@environment/REDIS_LANE_ADVANCED_PASSWORD, a fixture - # account of compose/redis/acl/lane-fixture-accounts.acl. + # 등록된 script가 실행될 계정을 가리키는 참조. 애플리케이션 참조와 같은 + # secret://@/ 형식이다. 비우면 script가 애플리케이션 계정으로 돌고 기동 때 그렇다고 + # 경고를 남긴다. Compose Redis lane은 compose/redis/acl/lane-fixture-accounts.acl의 fixture 계정인 + # secret://ca-skeleton-application-advanced@environment/REDIS_LANE_ADVANCED_PASSWORD를 쓴다. property: app.redis.authentication.advanced-credential-reference owner_module: adapter-outbound-cache-redis type: string @@ -2049,19 +2039,18 @@ env_keys: - name: APP_REDIS_AUTHENTICATION_ANONYMOUS_ACCESS_ACCEPTED property: app.redis.authentication.anonymous-access-accepted owner_module: adapter-outbound-cache-redis - # Explicit acknowledgement that Redis runs with no credential. Startup fails without it when - # no credential reference is set, because booting anyway builds an unauthenticated client that - # cannot run a single command on any deployment which disabled the `default` ACL user — the - # failure moves from startup to the first request, where it reads as an outage rather than a - # missing setting. Setting this to true keeps the deployment running and logs the trade. - # No Compose lane sets it: the Redis lanes authenticate with the fixture accounts instead, because - # the warning this logs is the one their "startup is silent" check exists to catch. + # Redis가 자격 증명 없이 돈다는 것을 명시적으로 인정하는 값. 자격 증명 참조가 없을 때 이 값이 없으면 + # 기동이 실패한다. 그대로 기동하면 인증 없는 client가 만들어지고, `default` ACL 사용자를 끈 배포에서는 + # 명령 하나도 돌리지 못한다 — 실패가 기동에서 첫 요청으로 옮겨 가고, 빠진 설정이 아니라 장애처럼 보인다. + # true로 두면 배포는 돌고 그 trade-off를 로그에 남긴다. + # 이 값을 쓰는 Compose lane은 없다: Redis lane은 대신 fixture 계정으로 인증한다. 이 값이 남기는 경고가 바로 + # lane의 「기동은 조용하다」 검사가 잡으려는 것이기 때문이다. type: boolean default: false allowed_values: [true, false] classification: public-config required: false - required_when: app.redis.enabled=true and no credential reference is configured + required_when: app.redis.enabled=true이고 자격 증명 참조를 설정하지 않았을 때 reload_policy: restart-only owner_branch: redis-optionality-and-composition validation: boolean_strict @@ -2069,12 +2058,11 @@ env_keys: required_test: redis-sdk:authentication-required-unless-anonymous-accepted - name: APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE - # Pointer to the application ACL account credential. The value lives in the secret manager. - # Form: secret://@/; the environment source reads the variable - # . Without the account part the client authenticates as `default`, which a hardened - # Redis turns off. The Compose Redis lanes use - # secret://ca-skeleton-application@environment/REDIS_LANE_APPLICATION_PASSWORD, a fixture - # account of compose/redis/acl/lane-fixture-accounts.acl. + # 애플리케이션 ACL 계정 자격 증명을 가리키는 참조. 값은 secret manager에 있다. + # 형식: secret://@/. environment source는 변수 을 읽는다. 계정 부분이 + # 없으면 client가 `default`로 인증하는데, 단단히 설정한 Redis는 그 사용자를 끈다. Compose Redis lane은 + # compose/redis/acl/lane-fixture-accounts.acl의 fixture 계정인 + # secret://ca-skeleton-application@environment/REDIS_LANE_APPLICATION_PASSWORD를 쓴다. property: app.redis.authentication.credential-reference owner_module: adapter-outbound-cache-redis type: string @@ -2105,7 +2093,7 @@ env_keys: required_test: redis-sdk:runtime-composition-binds-and-validates - name: APP_REDIS_CAPACITY_MAXIMUM_SCRIPT_CONNECTIONS - # Physical SCRIPT lane connections are bounded separately from the per-connection command queue. + # 실제 SCRIPT lane 연결 수는 연결마다의 명령 queue와 따로 제한한다. property: app.redis.capacity.maximum-script-connections owner_module: adapter-outbound-redis-runtime type: integer @@ -2121,7 +2109,7 @@ env_keys: required_test: redis-runtime:script-lane-physical-connections-bounded - name: APP_REDIS_CAPACITY_REJECT_WHEN_DISCONNECTED - # True refuses commands while disconnected. False restores the driver offline queue, which replays a burst of writes on reconnect in arbitrary order relative to the outage. + # true면 연결이 끊긴 동안 명령을 거부한다. false면 driver의 offline queue를 되살리는데, 다시 연결될 때 쌓인 쓰기를 끊긴 동안의 순서와 상관없이 몰아서 다시 보낸다. property: app.redis.capacity.reject-when-disconnected owner_module: adapter-outbound-cache-redis type: boolean @@ -2167,7 +2155,7 @@ env_keys: required_test: redis-sdk:runtime-composition-binds-and-validates - name: APP_REDIS_LIFECYCLE_ACQUIRE_TIMEOUT - # How long a lane borrow waits for a returned connection before it is refused as not sent. + # lane이 연결을 빌릴 때, 돌려받은 연결을 기다리는 시간. 넘으면 보내지 않은 것으로 거부한다. property: app.redis.lifecycle.acquire-timeout owner_module: adapter-outbound-cache-redis type: duration @@ -2213,7 +2201,7 @@ env_keys: required_test: redis-sdk:runtime-composition-binds-and-validates - name: APP_REDIS_LIFECYCLE_DRAIN_TIMEOUT - # How long shutdown waits for in-flight commands before closing connections. + # 종료할 때 연결을 닫기 전에 처리 중인 명령을 기다리는 시간. property: app.redis.lifecycle.drain-timeout owner_module: adapter-outbound-cache-redis type: duration @@ -2266,11 +2254,10 @@ env_keys: allowed_values: null classification: sensitive-config required: false - # Applied only when present: RedisTopologyClientFactory sets the sentinel credentials provider - # through ifPresent, so a Sentinel deployment whose sentinels accept unauthenticated discovery - # starts without it. The unconditional "app.redis.mode=sentinel" this used to declare was a - # requirement the runtime never enforced. - required_when: app.redis.mode=sentinel and the sentinels require authentication + # 있을 때만 적용한다: RedisTopologyClientFactory가 sentinel 자격 증명 provider를 ifPresent로 설정한다. + # 그래서 sentinel이 인증 없는 탐색을 받는 Sentinel 배포는 이 값 없이 뜬다. 예전에 적었던 무조건 + # "app.redis.mode=sentinel"은 런타임이 강제한 적 없는 요구였다. + required_when: app.redis.mode=sentinel이고 sentinel이 인증을 요구할 때 reload_policy: restart-only owner_branch: redis-optionality-and-composition validation: nonblank_when_required @@ -2300,9 +2287,9 @@ env_keys: allowed_values: null classification: public-config required: false - # Falls back to app.redis.nodes by design, so a deployment that points nodes at its sentinels - # and says nothing else is the common case rather than a misconfiguration. - required_when: app.redis.mode=sentinel and app.redis.nodes does not list the sentinels + # 설계상 app.redis.nodes로 돌아간다. 그래서 nodes에 sentinel을 적고 다른 것은 말하지 않은 배포가 잘못된 + # 설정이 아니라 흔한 경우다. + required_when: app.redis.mode=sentinel이고 app.redis.nodes에 sentinel이 없을 때 reload_policy: restart-only owner_branch: redis-optionality-and-composition validation: csv_nonempty @@ -2317,9 +2304,9 @@ env_keys: allowed_values: null classification: public-config required: false - # A key manager is configured only when this is present. Ordinary one-way TLS needs no client - # certificate, so requiring one whenever TLS is on was a claim the runtime never made. - required_when: app.redis.tls.enabled=true and the server requires mutual TLS + # key manager는 이 값이 있을 때만 설정한다. 보통의 단방향 TLS에는 client 인증서가 필요 없으니, TLS가 + # 켜질 때마다 요구하는 것은 런타임이 한 적 없는 주장이었다. + required_when: app.redis.tls.enabled=true이고 서버가 mutual TLS를 요구할 때 reload_policy: restart-only owner_branch: redis-optionality-and-composition validation: nonblank_when_required @@ -2334,10 +2321,10 @@ env_keys: allowed_values: null classification: sensitive-config required: false - # A relationship between two settings rather than a switch: a client certificate without its - # key cannot build a key manager. Enforced in RedisRuntimeSettings.validate and covered by - # RedisRuntimeSettingsTest, which is where the registry's prose conditions are proven. - required_when: app.redis.tls.client-certificate-resource is configured + # 켜고 끄는 값이 아니라 두 설정 사이의 관계다: key 없는 client 인증서로는 key manager를 만들 수 없다. + # RedisRuntimeSettings.validate가 강제하고 RedisRuntimeSettingsTest가 다룬다. 레지스트리의 글로 쓴 조건은 + # 거기서 증명한다. + required_when: app.redis.tls.client-certificate-resource를 설정했을 때 reload_policy: restart-only owner_branch: redis-optionality-and-composition validation: nonblank_when_required @@ -2360,7 +2347,7 @@ env_keys: required_test: redis-sdk:runtime-composition-binds-and-validates - name: APP_REDIS_TLS_HOSTNAME_VERIFICATION - # Disabling this accepts any certificate the trust material signs, for any host. + # 이 값을 끄면 trust material이 서명한 모든 인증서를 어떤 host에 대해서도 받는다. property: app.redis.tls.hostname-verification owner_module: adapter-outbound-cache-redis type: boolean @@ -2383,9 +2370,9 @@ env_keys: allowed_values: null classification: public-config required: false - # A trust manager is installed only when this is present; otherwise the JDK default trust - # anchors apply, which is enough for a server certificate from a public CA. - required_when: app.redis.tls.enabled=true and the server certificate is not publicly trusted + # trust manager는 이 값이 있을 때만 설치한다. 없으면 JDK 기본 신뢰 앵커를 쓰고, 공개 CA가 발급한 서버 + # 인증서에는 그것으로 충분하다. + required_when: app.redis.tls.enabled=true이고 서버 인증서가 공개 신뢰 체인에 없을 때 reload_policy: restart-only owner_branch: redis-optionality-and-composition validation: nonblank_when_required @@ -2394,11 +2381,10 @@ env_keys: - name: APP_CACHE_REDIS_ENABLED # source: feature-integration-adapter-templates 2026-05-22 # "Redis | disabled optional module | cache consistency" + Adapter Template Defaults 표 - # DEPRECATED 2026-08-10: this was a second Redis master switch, and the settings class that - # bound it was removed with the previous Redis generation, so the key reached nothing. - # APP_REDIS_ENABLED is the sole global activation authority; the cache role is selected by - # app.capabilities.cache.bindings.default. The row is kept rather than deleted so a - # deployment still setting this key can be told what replaced it. + # 폐기 2026-08-10: 두 번째 Redis 전체 스위치였고, 이를 바인딩하던 settings class를 옛 Redis 세대와 함께 + # 지워서 이 키는 어디에도 닿지 않는다. 전역 켜기는 APP_REDIS_ENABLED 하나가 정한다. 캐시 role은 + # app.capabilities.cache.bindings.default가 고른다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 + # 행을 지우지 않고 둔다. deprecated_orphaned: true deprecated_alias_for: APP_REDIS_ENABLED removal_deadline: 2026-11-30 @@ -2414,9 +2400,8 @@ env_keys: required_test: adapter-contract:redis-disabled-default - name: APP_CACHE_REDIS_CLIENT_MODE - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: enum @@ -2431,12 +2416,11 @@ env_keys: required_test: adapter-contract:redis-client-mode-explicit - name: APP_CACHE_REDIS_HOST - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 - # source: feature-cache-consistency-contract — Redis adapter (활성화 시 endpoint 필요) + # source: feature-cache-consistency-contract — Redis adapter (켜면 endpoint가 필요하다) type: string default: null allowed_values: null @@ -2449,9 +2433,8 @@ env_keys: required_test: cache-contract:redis-host-when-enabled - name: APP_CACHE_REDIS_PORT - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 # source: feature-cache-consistency-contract — Redis adapter endpoint @@ -2467,9 +2450,8 @@ env_keys: required_test: cache-contract:redis-port-bound - name: APP_CACHE_REDIS_PASSWORD - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: string @@ -2484,8 +2466,8 @@ env_keys: required_test: secrets-contract:redis-password-no-leak - name: APP_CACHE_REDIS_TRUST_PEM - # DEPRECATED 2026-08-10: the cache no longer owns a Redis client of its own, so no code reads this. - # Replaced by: app.redis.tls.trust-material-resource (APP_REDIS_TLS_TRUST_MATERIAL_RESOURCE), which the one Redis client uses for every capability. + # 폐기 2026-08-10: 캐시는 이제 자기 Redis client를 갖지 않아서 이 값을 읽는 코드가 없다. + # 대체: app.redis.tls.trust-material-resource (APP_REDIS_TLS_TRUST_MATERIAL_RESOURCE). Redis client 하나가 모든 capability에 이 값을 쓴다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: string @@ -2500,9 +2482,8 @@ env_keys: required_test: redis-contract:cache-trust-material-no-leak - name: APP_REDIS_SEMANTIC_PROBE_MINIMUM_INTERVAL - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: duration @@ -2517,9 +2498,8 @@ env_keys: required_test: redis-contract:semantic-probe-cadence-bounded - name: APP_REDIS_SENTINEL_DISCOVERY_REFRESH_PERIOD - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: duration @@ -2534,9 +2514,8 @@ env_keys: required_test: redis-contract:sentinel-discovery-refresh-period-bounded - name: APP_REDIS_SEMANTIC_PROBE_MAXIMUM_STALENESS - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: duration @@ -2551,9 +2530,8 @@ env_keys: required_test: redis-contract:semantic-probe-staleness-bounded - name: APP_CACHE_REDIS_KEY_HMAC_SECRET - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: string @@ -2568,9 +2546,8 @@ env_keys: required_test: cache-contract:redis-hmac-secret-bounded - name: APP_CACHE_REDIS_COMMAND_TIMEOUT - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: duration @@ -2585,9 +2562,8 @@ env_keys: required_test: cache-contract:redis-command-timeout-bounded - name: APP_CACHE_REDIS_MAXIMUM_QUEUED_COMMANDS - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: int @@ -2602,9 +2578,8 @@ env_keys: required_test: cache-contract:redis-command-queue-bounded - name: APP_CACHE_REDIS_MAXIMUM_IN_FLIGHT_BYTES - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: int @@ -2631,9 +2606,9 @@ env_keys: required_test: cache-contract:redis-soft-hard-ttl-order - name: APP_CACHE_REDIS_TTL_JITTER - # DEPRECATED 2026-11-02: no settings class binds it. Its only reader was a block in the - # sample module's application.yml that nothing bound either (07-10), removed with it. - # Kept so a deployment still setting it is told it does nothing. + # 폐기 2026-11-02: 바인딩하는 settings class가 없다. 읽던 곳은 샘플 모듈 application.yml의 블록 하나뿐이었고 + # 그것도 바인딩되지 않았다(07-10). 샘플과 함께 지웠다. 아직 이 키를 쓰는 배포에 아무 일도 하지 않는다고 + # 알려 주려고 둔다. deprecated_orphaned: true removal_deadline: 2027-02-28 type: float @@ -2660,12 +2635,10 @@ env_keys: required_test: cache-contract:redis-hard-ttl-minimum - name: APP_CACHE_REDIS_NAMESPACE_ENVIRONMENT - # DEPRECATED 2026-08-10: the cache no longer renders its own key prefix. Four capabilities - # each joining two free-form tokens produced four prefixes, and the ACL pattern that was meant - # to fence the deployment in matched none of them. The row is kept (not deleted) so a - # deployment still setting it can be told what replaced it. - # Replaced by: app.redis.namespace.environment (APP_REDIS_NAMESPACE_ENVIRONMENT), shared by - # every capability. + # 폐기 2026-08-10: 캐시는 이제 key prefix를 스스로 만들지 않는다. capability 넷이 각자 자유 형식 토큰 둘을 + # 이어 prefix 넷이 생겼고, 배포를 가두려던 ACL 패턴은 그중 어느 것과도 맞지 않았다. 아직 이 키를 쓰는 + # 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. + # 대체: app.redis.namespace.environment (APP_REDIS_NAMESPACE_ENVIRONMENT). 모든 capability가 함께 쓴다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: string @@ -2680,9 +2653,8 @@ env_keys: required_test: cache-contract:redis-namespace-environment-bound - name: APP_CACHE_REDIS_SEMANTIC_REGION - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: string @@ -2697,9 +2669,8 @@ env_keys: required_test: cache-contract:redis-semantic-region-bound - name: APP_CACHE_REDIS_MAXIMUM_VALUE_BYTES - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: int @@ -2714,9 +2685,8 @@ env_keys: required_test: cache-contract:redis-value-size-bounded - name: APP_CACHE_REDIS_L1_ENABLED - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: boolean @@ -2731,9 +2701,8 @@ env_keys: required_test: cache-contract:redis-l1-disabled-default - name: APP_CACHE_REDIS_L1_MAXIMUM_ENTRIES - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: int @@ -2748,9 +2717,8 @@ env_keys: required_test: cache-contract:redis-l1-cardinality-bounded - name: APP_CACHE_REDIS_L1_MAXIMUM_WEIGHT_BYTES - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: int @@ -2765,9 +2733,8 @@ env_keys: required_test: cache-contract:redis-l1-weight-bounded - name: APP_CACHE_REDIS_L1_MAXIMUM_ENTRY_WEIGHT_BYTES - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: int @@ -2782,9 +2749,8 @@ env_keys: required_test: cache-contract:redis-l1-entry-weight-bounded - name: APP_CACHE_REDIS_L1_TTL - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: duration @@ -2799,9 +2765,8 @@ env_keys: required_test: cache-contract:redis-l1-ttl-bounded - name: APP_CACHE_REDIS_L1_GENERATION_RECHECK_INTERVAL - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: duration @@ -2816,9 +2781,8 @@ env_keys: required_test: cache-contract:redis-l1-generation-recheck-bounded - name: APP_CACHE_REDIS_L1_INVALIDATION_QUEUE_CAPACITY - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 type: int @@ -2833,9 +2797,8 @@ env_keys: required_test: cache-contract:redis-l1-invalidation-queue-bounded - name: APP_CACHE_DEFAULT_TTL - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 # source: feature-cache-consistency-contract 2026-05-22 @@ -2852,9 +2815,8 @@ env_keys: required_test: cache-contract:default-ttl-bounded - name: APP_CACHE_NEGATIVE_TTL - # DEPRECATED 2026-08-10: the settings class that bound this property was removed - # with the previous Redis generation, so the key reached nothing. The row is kept - # (not deleted) so a deployment still setting it can be told what replaced it. + # 폐기 2026-08-10: 이 속성을 바인딩하던 settings class를 옛 Redis 세대와 함께 지워서 이 키는 어디에도 + # 닿지 않는다. 아직 이 키를 쓰는 배포에 무엇이 대신하는지 알려 주려고 행을 지우지 않고 둔다. deprecated_orphaned: true removal_deadline: 2026-11-30 # source: feature-cache-consistency-contract 2026-05-22 @@ -2870,15 +2832,15 @@ env_keys: compatibility_impact: additive required_test: cache-contract:negative-ttl-bounded - # === Messaging / Kafka (feature-domain-event-outbox-contract + integration-adapter-templates) === + # === 메시징 / Kafka (feature-domain-event-outbox-contract + integration-adapter-templates) === - name: APP_MESSAGING_BROKER - # source: messaging multi-broker redesign 2026-06-16 — single active broker selection - # (app.messaging.broker=), read by the vendored messaging platform. Replaces the - # former Kafka-binary APP_MESSAGING_KAFKA_ENABLED. The application bridge no longer reads it: - # the legacy KafkaSender seam that did was removed with the canonical outbox (2026-09-28). + # source: messaging multi-broker redesign 2026-06-16 — 활성 broker 하나를 고른다 + # (app.messaging.broker=). 들여온 메시징 플랫폼이 읽는다. 옛 Kafka 전용 APP_MESSAGING_KAFKA_ENABLED를 + # 대신한다. 애플리케이션 bridge는 이제 읽지 않는다: 읽던 옛 KafkaSender seam은 canonical outbox와 함께 + # 지웠다(2026-09-28). type: string - # The Kafka module's config/module-defaults/messaging.yml defaults it to kafka, the only registered broker. + # Kafka 모듈의 config/module-defaults/messaging.yml이 기본값을 등록된 유일한 broker인 kafka로 둔다. default: kafka allowed_values: null classification: public-config @@ -2891,10 +2853,10 @@ env_keys: - name: APP_MESSAGING_PRODUCER_ID # source: canonical messaging platform bridge 2026-09-18 - # Explicit logical producing-service identity for IntegrationEventPublishPort. - # Blank/absent = canonical platform bridge is not exposed; identity is never inferred. - # Every publication, the outbox relay's included, goes through that bridge, so with the - # messaging module present and on a blank value refuses startup (2026-09-28 canonical outbox). + # IntegrationEventPublishPort가 쓰는, 메시지를 내는 서비스의 논리 이름(명시값). + # 비었거나 없음 = canonical 플랫폼 bridge를 내놓지 않는다. 이름을 짐작하지 않는다. + # outbox relay를 포함해 모든 발행이 그 bridge를 거치므로, 메시징 모듈이 있고 켜진 상태에서 값이 비면 기동을 + # 거부한다(2026-09-28 canonical outbox). type: string default: null allowed_values: null @@ -2909,10 +2871,9 @@ env_keys: - name: APP_MESSAGING_KAFKA_BROKERS # source: feature-domain-event-outbox-contract — "Kafka는 optional integration adapter" - # (broker 활성화 시 endpoint 필요) - # Feeds app.messaging.brokers.kafka.bootstrap-servers (the messaging platform's Kafka - # transport) through the Kafka module's config/module-defaults/messaging.yml. - # spring.kafka.bootstrap-servers is not read. + # (broker를 켜면 endpoint가 필요하다) + # Kafka 모듈의 config/module-defaults/messaging.yml을 거쳐 app.messaging.brokers.kafka.bootstrap-servers + # (메시징 플랫폼의 Kafka transport)로 간다. spring.kafka.bootstrap-servers는 읽지 않는다. type: csv_list default: null allowed_values: null @@ -2924,10 +2885,10 @@ env_keys: compatibility_impact: behavior-change required_test: adapter-contract:kafka-brokers-when-enabled - # === Notification adapters (feature-integration-adapter-templates) === + # === 알림 adapter (feature-integration-adapter-templates) === - name: APP_NOTIFICATION_SLACK_WEBHOOK_ENABLED - # source: R0 Slack webhook provider gate; maps to app.notification.slack-webhook.enabled + # source: R0 Slack webhook provider 스위치. app.notification.slack-webhook.enabled로 이어진다 type: boolean default: false allowed_values: [true, false] @@ -2940,7 +2901,7 @@ env_keys: required_test: adapter-contract:notification-slack-provider-selection - name: APP_NOTIFICATION_GOOGLE_EMAIL_ENABLED - # source: R0 Google email provider gate; maps to app.notification.google-email.enabled + # source: R0 Google email provider 스위치. app.notification.google-email.enabled로 이어진다 type: boolean default: false allowed_values: [true, false] @@ -2952,22 +2913,20 @@ env_keys: compatibility_impact: behavior-change required_test: adapter-contract:notification-email-provider-selection - # === HTTP Client platform (app.httpclient.*) === + # === HTTP Client 플랫폼 (app.httpclient.*) === # - # Only the enabled key is registered here. The per-client surface is an indexed list whose - # element cannot be templated in application.yml without materialising a nameless client in every - # deployment, so it has no deployment-independent value for this registry to hold and is - # registered in docs/httpclient/env-fields.yaml instead. That manifest is derived from - # HttpClientPlatformSettings and enforced in both directions: a field with no entry fails - # HttpClientPlatformEnvManifestTest, and an APP_HTTPCLIENT_ variable with no field fails startup. + # 여기에는 enabled 키만 등록한다. client별 설정은 index가 붙은 목록이라, application.yml에 틀로 적으면 모든 + # 배포에 이름 없는 client가 생긴다. 그래서 배포와 상관없는 값이 없어 이 레지스트리에 둘 것이 없고, + # docs/httpclient/env-fields.yaml에 등록한다. 그 manifest는 HttpClientPlatformSettings에서 나오고 양쪽으로 + # 강제된다: 항목이 없는 필드는 HttpClientPlatformEnvManifestTest가 실패하고, 필드가 없는 APP_HTTPCLIENT_ + # 변수는 기동이 실패한다. - name: APP_HTTPCLIENT_ENABLED - # 2026-09-25 capability packaging: the module is on when present (its own config yml maps - # this key with default true); false is the explicit off. Absent from the build is the - # ordinary off state. - # While false the platform block is not bound at all: the auto-configuration that - # binds it is not processed, so no bean, connection pool, TLS context, credential, thread or - # gateway exists, and a malformed HTTP client setting cannot fail this deployment's startup. + # 2026-09-25 capability 포장: 모듈은 있으면 켜진다(모듈 자신의 설정 yml이 이 키를 기본 true로 잇는다). + # false가 명시적으로 끄는 값이다. 빌드에 모듈이 없는 것이 보통의 꺼진 상태다. + # false인 동안 플랫폼 블록을 전혀 바인딩하지 않는다: 바인딩하는 자동 설정을 처리하지 않으므로 bean, + # connection pool, TLS context, 자격 증명, thread, gateway가 생기지 않고, 잘못된 HTTP client 설정이 이 배포의 + # 기동을 실패시킬 수 없다. type: boolean default: true allowed_values: [true, false] @@ -2980,10 +2939,9 @@ env_keys: required_test: httpclient-platform:off-state-zero-side-effects-and-env-manifest-parity - name: APP_HTTPCLIENT_ROTATION_DRAIN_TIMEOUT - # How long a retired runtime generation may keep draining after a certificate rotation before - # its connection pool is closed underneath whatever is still in flight. Rotation replaces a - # generation rather than mutating material in place, because a pool holds sockets established - # under the previous identity; this value is how long the old identity is allowed to finish. + # 인증서를 교체한 뒤, 물러난 런타임 세대가 처리 중인 것을 마저 끝낼 수 있는 기간. 이 시간이 지나면 + # 그 connection pool을 닫는다. 교체는 자료를 제자리에서 바꾸지 않고 세대를 바꾼다. pool이 옛 신원으로 맺은 + # 소켓을 들고 있기 때문이다. 이 값이 옛 신원이 일을 끝낼 수 있는 시간이다. type: duration default: 30s classification: public-config @@ -2996,11 +2954,10 @@ env_keys: # === Fileserver HTTP platform (app.fileserver-platform.*) === - name: APP_FILESERVER_PLATFORM_ENABLED - # 2026-09-25 capability packaging: the module is on when present (its own config yml maps - # this key with default true); false is the explicit off. Absent from the build is the - # ordinary off state. - # While false the platform block is not bound at all: the auto-configuration that - # binds it is not processed, so no bean, route, thread, schema check or filesystem call exists. + # 2026-09-25 capability 포장: 모듈은 있으면 켜진다(모듈 자신의 설정 yml이 이 키를 기본 true로 잇는다). + # false가 명시적으로 끄는 값이다. 빌드에 모듈이 없는 것이 보통의 꺼진 상태다. + # false인 동안 플랫폼 블록을 전혀 바인딩하지 않는다: 바인딩하는 자동 설정을 처리하지 않으므로 bean, route, + # thread, schema 검사, 파일 시스템 호출이 생기지 않는다. type: boolean default: true allowed_values: [true, false] @@ -3013,8 +2970,8 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_INSTANCE_ID - # Writer-lease owner; must be unique per instance. The startup gate treats the default as - # single-instance and refuses a shared-metadata claim it cannot support. + # writer lease의 소유자. 인스턴스마다 달라야 한다. 기동 관문은 기본값을 단일 인스턴스로 보고, 지원할 수 + # 없는 공유 메타데이터 claim을 거부한다. type: string default: local-node allowed_values: null @@ -3027,7 +2984,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_DEFAULT_NAMESPACE - # Namespace applied to a request that does not name one. + # namespace를 적지 않은 요청에 쓰는 namespace. type: string default: default allowed_values: null @@ -3040,8 +2997,8 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_TARGET_NAMESPACES - # Namespaces copy and move may write into besides the default namespace, which is always - # allowed. Empty means the default namespace only; any other target is ACCESS_DENIED. + # copy와 move가 기본 namespace(늘 허용) 밖에 쓸 수 있는 namespace. 비면 기본 namespace만이고, 다른 + # 대상은 ACCESS_DENIED다. type: csv_list default: null allowed_values: null @@ -3054,8 +3011,8 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_STORAGE_ROOT - # Absolute path on its own volume. A relative root resolves against the process working - # directory, which differs between a container and a test, so it is refused. + # 자기 volume 위의 절대 경로. 상대 경로는 프로세스 실행 위치를 기준으로 풀리는데, 그 위치가 container와 + # 테스트에서 달라서 거부한다. type: string default: /var/lib/backend/files allowed_values: null @@ -3068,7 +3025,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_STORAGE_PUBLISH_MODE - # atomic-move-required fails startup when the probe cannot prove an atomic rename. + # atomic-move-required는 확인 과정이 원자적 이름 바꾸기를 증명하지 못하면 기동을 실패시킨다. type: string default: atomic-move-preferred allowed_values: [atomic-move-required, atomic-move-preferred, metadata-pointer] @@ -3081,7 +3038,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_STORAGE_BUFFER_SIZE - # Bounds every transfer allocation, so resident bytes never scale with file size. + # 모든 전송의 할당을 제한한다. 그래서 메모리에 머무는 바이트가 파일 크기에 따라 늘지 않는다. type: data_size default: 128KB allowed_values: null @@ -3094,8 +3051,8 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_STORAGE_FORBIDDEN_ROOT_ANCESTORS - # A storage root under a web root turns every upload into a published file; under a config - # root, into a configuration change. Both are refused at binding time. + # web root 아래의 저장소 root는 모든 업로드를 공개 파일로 만들고, config root 아래면 설정 변경으로 + # 만든다. 둘 다 바인딩할 때 거부한다. type: csv_list default: /app,/etc,/usr/share/nginx/html allowed_values: null @@ -3108,8 +3065,8 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_UPLOAD_MAX_FILE_SIZE - # Also drives spring.servlet.multipart.max-file-size. One placeholder for both: a smaller - # servlet ceiling rejects the upload before any Fileserver code, including its error mapping. + # spring.servlet.multipart.max-file-size도 이 값이 정한다. 둘에 자리표시자 하나다: servlet 상한이 더 + # 작으면 Fileserver 코드(오류 매핑 포함)에 닿기 전에 업로드를 거부한다. type: data_size default: 100MB allowed_values: null @@ -3135,7 +3092,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_UPLOAD_INITIAL_RESERVATION - # Quota reserved for an upload that does not declare its length. + # 길이를 밝히지 않은 업로드에 잡아 두는 할당량. type: data_size default: 8MB allowed_values: null @@ -3148,7 +3105,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_UPLOAD_MAX_PARTS - # Ceiling on parts in one multipart/batch request. + # multipart/batch 요청 하나의 part 수 상한. type: integer default: 16 allowed_values: null @@ -3161,7 +3118,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_UPLOAD_TTL - # Lifetime of an upload resource before it is reclaimable. + # 업로드 자원을 회수할 수 있게 되기까지의 수명. type: duration default: 1h allowed_values: null @@ -3174,7 +3131,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_UPLOAD_RESERVATION_TTL - # Lifetime of a quota reservation whose upload never completed. + # 업로드가 끝나지 않은 할당량 예약의 수명. type: duration default: 24h allowed_values: null @@ -3187,8 +3144,8 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_UPLOAD_LEASE_DURATION - # Writer lease. Renewed at one third of this while a transfer runs; a transfer that cannot - # renew is fenced out before its next physical write. + # writer lease. 전송하는 동안 이 값의 1/3마다 갱신한다. 갱신하지 못한 전송은 다음 실제 쓰기 전에 + # 막힌다(fenced). type: duration default: 30s allowed_values: null @@ -3201,7 +3158,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_UPLOAD_REQUIRE_CONTENT_LENGTH - # When true a raw upload without Content-Length is refused with 411. + # true면 Content-Length 없는 raw 업로드를 411로 거부한다. type: boolean default: false allowed_values: [true, false] @@ -3214,7 +3171,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_DOWNLOAD_CACHE_CONTROL - # Cache-Control emitted on every download response. + # 모든 다운로드 응답에 붙이는 Cache-Control. type: string default: private, no-store allowed_values: null @@ -3227,7 +3184,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_DOWNLOAD_INLINE_ALLOWED - # Inline rendering is off by default; scriptable content is forced to attachment regardless. + # inline 표시는 기본으로 꺼져 있다. script가 돌 수 있는 내용은 설정과 상관없이 attachment로 보낸다. type: boolean default: false allowed_values: [true, false] @@ -3240,7 +3197,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_DOWNLOAD_MAX_RANGES - # Multi-range is opt-in; above one the response is multipart/byteranges. + # 여러 범위 요청은 켜야 쓴다. 둘 이상이면 응답이 multipart/byteranges다. type: integer default: 1 allowed_values: null @@ -3253,8 +3210,8 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_DOWNLOAD_MAX_RANGE_BYTES - # Applies to the single-range profile too, so the ceiling is not inert in the default - # configuration that almost every deployment runs. + # 범위 하나 profile에도 적용한다. 그래서 거의 모든 배포가 쓰는 기본 설정에서도 상한이 실제로 + # 작동한다. type: data_size default: 100MB allowed_values: null @@ -3267,7 +3224,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_DOWNLOAD_ZERO_COPY_ENABLED - # Changes only where bytes are copied, never a header or a status. + # 바이트를 복사하는 곳만 바꾼다. 헤더나 상태 코드는 바꾸지 않는다. type: boolean default: true allowed_values: [true, false] @@ -3280,7 +3237,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_DOWNLOAD_ZERO_COPY_MINIMUM_BYTES - # Below this the syscall setup costs more than it saves. + # 이보다 작으면 syscall 준비 비용이 아끼는 것보다 크다. type: data_size default: 16MB allowed_values: null @@ -3293,7 +3250,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_TRANSFER_CORE_SIZE - # Bounded transfer pool; rejection becomes a retryable 429, never caller-runs. + # 크기가 정해진 전송 pool. 거절은 다시 시도할 수 있는 429가 되고, 호출자 스레드에서 돌리지 않는다. type: integer default: 8 allowed_values: null @@ -3306,7 +3263,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_TRANSFER_MAX_SIZE - # Upper bound of the transfer pool. + # 전송 pool의 상한. type: integer default: 32 allowed_values: null @@ -3319,7 +3276,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_TRANSFER_QUEUE_CAPACITY - # Bounded queue; an unbounded one trades a fast 429 for eventual heap exhaustion. + # 크기가 정해진 queue. 무한 queue는 빠른 429를 결국 heap 고갈로 바꾼다. type: integer default: 64 allowed_values: null @@ -3332,7 +3289,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_TRANSFER_AWAIT_SECONDS - # Shutdown drain and per-transfer caller wait. + # 종료 때 남은 일 정리 시간과 전송마다 호출자가 기다리는 시간. type: integer default: 300 allowed_values: null @@ -3345,8 +3302,8 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_SECURITY_ACCESS_POLICY - # No permissive default. `required` fails startup unless the deployment supplies a - # FileAccessPolicyPort bean; `unenforced` is refused under a production profile. + # 허용하는 기본값이 없다. `required`는 배포가 FileAccessPolicyPort bean을 주지 않으면 기동을 + # 실패시킨다. `unenforced`는 production profile에서 거부한다. type: string default: required allowed_values: [required, role-based, unenforced] @@ -3359,7 +3316,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_SECURITY_READ_ROLES - # Roles accepted for read operations under the role-based policy. + # role 기반 정책에서 읽기 연산에 받는 role. type: csv_list default: ROLE_FILE_READ allowed_values: null @@ -3372,7 +3329,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_SECURITY_WRITE_ROLES - # Roles accepted for write operations under the role-based policy. + # role 기반 정책에서 쓰기 연산에 받는 role. type: csv_list default: ROLE_FILE_WRITE allowed_values: null @@ -3385,8 +3342,8 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_SECURITY_ADMIN_ROLES - # Roles accepted for the management plane. Admin routes additionally require this role at the - # servlet chain, not only in application policy. + # 관리 기능(management plane)에 받는 role. admin route는 application 정책만이 아니라 servlet chain에서도 + # 이 role을 요구한다. type: csv_list default: ROLE_FILE_ADMIN allowed_values: null @@ -3399,7 +3356,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_VERIFICATION_TIMEOUT - # Whole-chain verification budget for one upload. + # 업로드 하나의 검증 사슬 전체 예산. type: duration default: 5s allowed_values: null @@ -3412,7 +3369,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_VERIFICATION_REQUIRE_MEDIA_TYPE_VERDICT - # When true a file whose type could not be determined is refused rather than published. + # true면 형식을 알아내지 못한 파일을 공개하지 않고 거부한다. type: boolean default: false allowed_values: [true, false] @@ -3425,8 +3382,8 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_VERIFICATION_INLINE_SAFE_PROFILE - # When true scriptable content is accepted instead of quarantined; only safe when downloads - # are never served inline from a trusted origin. + # true면 script가 돌 수 있는 내용을 격리하지 않고 받는다. 다운로드를 신뢰하는 origin에서 inline으로 + # 절대 내주지 않을 때만 안전하다. type: boolean default: false allowed_values: [true, false] @@ -3439,7 +3396,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_QUOTA_INSTANCE_UPLOAD_PERMITS - # Concurrent uploads admitted per instance. + # 인스턴스마다 받는 동시 업로드 수. type: integer default: 16 allowed_values: null @@ -3452,7 +3409,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_QUOTA_SCOPE_UPLOAD_PERMITS - # Concurrent uploads admitted per caller (principal). + # 호출자(principal)마다 받는 동시 업로드 수. type: integer default: 4 allowed_values: null @@ -3465,7 +3422,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_QUOTA_DIRECT_DOWNLOAD_PERMITS - # Concurrent direct downloads admitted per instance. + # 인스턴스마다 받는 동시 직접 다운로드 수. type: integer default: 64 allowed_values: null @@ -3478,7 +3435,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_QUOTA_SOFT_HIGH_WATER - # Storage fraction at which new uploads start being shed. + # 새 업로드를 덜어내기 시작하는 저장소 사용 비율. type: string default: 0.70 allowed_values: null @@ -3491,7 +3448,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_QUOTA_HARD_HIGH_WATER - # Storage fraction at which every upload is refused. + # 모든 업로드를 거부하는 저장소 사용 비율. type: string default: 0.85 allowed_values: null @@ -3504,8 +3461,8 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_QUOTA_NAMESPACE_LIMIT - # Most bytes one namespace may hold, live reservations plus committed usage. Empty means - # unlimited; a reservation past a set limit is refused with QUOTA_EXCEEDED (413). + # namespace 하나가 가질 수 있는 최대 바이트(살아 있는 예약과 확정된 사용량의 합). 비면 무제한이다. 정한 + # 상한을 넘는 예약은 QUOTA_EXCEEDED(413)로 거부한다. type: data_size default: null allowed_values: null @@ -3518,8 +3475,8 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_ADMIN_ENABLED - # Management plane, a separate decision from the data plane. Requires APP_FILESERVER_PLATFORM_ENABLED too: - # enabling it alone now does nothing instead of half-building a bean graph. + # 관리 기능(management plane). 데이터 기능과 따로 정한다. APP_FILESERVER_PLATFORM_ENABLED도 켜야 한다: + # 이 값만 켜면 이제 bean 그래프를 반쯤 만들지 않고 아무 일도 하지 않는다. type: boolean default: false allowed_values: [true, false] @@ -3532,8 +3489,8 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_ADMIN_ORPHAN_MINIMUM_AGE - # How long an unreferenced object must exist before a scan may name it; anything younger is - # assumed mid-commit rather than abandoned. + # 참조가 없는 객체가 scan에 이름이 오르기까지 있어야 하는 기간. 그보다 어린 것은 버려진 것이 아니라 + # 확정하는 중이라고 본다. type: duration default: 1h allowed_values: null @@ -3546,9 +3503,9 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_CLEANUP_ENABLED - # Background reclamation. On by default: without it cancelled/expired staging and rejected or - # deleted content stay on the volume until the hard high-water mark stops uploads. Turning it - # off logs a startup warning (another node or the admin plane must reclaim instead). + # 뒤에서 도는 회수. 기본으로 켜져 있다: 없으면 취소·만료된 staging과 거부·삭제된 내용이 volume에 남아, + # 결국 높은 수위(high-water mark)가 업로드를 막는다. 끄면 기동 때 경고를 남긴다(다른 노드나 관리 기능이 + # 대신 회수해야 한다). type: boolean default: true allowed_values: [true, false] @@ -3561,8 +3518,8 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_CLEANUP_INTERVAL - # Fixed delay between batches; sole owner of the schedule, with no @Scheduled placeholder - # carrying a second default. + # batch 사이의 고정 지연. 일정의 유일한 주인이다. 두 번째 기본값을 가진 @Scheduled 자리표시자를 두지 + # 않는다. type: duration default: 60s allowed_values: null @@ -3575,7 +3532,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_CLEANUP_MAX_ITEMS - # Item ceiling for one batch, so a backlog cannot monopolise the scheduler. + # batch 하나의 항목 수 상한. 밀린 일이 scheduler를 독차지하지 못하게 한다. type: integer default: 100 allowed_values: null @@ -3588,7 +3545,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_CLEANUP_MAX_BYTES - # Byte ceiling for one batch. + # batch 하나의 바이트 상한. type: data_size default: 1GB allowed_values: null @@ -3601,7 +3558,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_CLEANUP_RETRY_BACKOFF - # Delay before a failed cleanup item is retried. + # 실패한 정리 항목을 다시 시도하기 전 지연. type: duration default: 5m allowed_values: null @@ -3614,7 +3571,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_TUS_ENABLED - # tus 1.0. Requires APP_FILESERVER_PLATFORM_ENABLED too. + # tus 1.0. APP_FILESERVER_PLATFORM_ENABLED도 켜야 한다. type: boolean default: false allowed_values: [true, false] @@ -3627,7 +3584,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_HTTPBIS_DRAFT12_ENABLED - # Unratified draft whose contract can change without notice. Requires APP_FILESERVER_PLATFORM_ENABLED too. + # 승인되지 않은 초안이라 계약이 예고 없이 바뀔 수 있다. APP_FILESERVER_PLATFORM_ENABLED도 켜야 한다. type: boolean default: false allowed_values: [true, false] @@ -3640,8 +3597,8 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_NGINX_ENABLED - # Front-proxy delegation. Startup attests the internal mapping by exercising it; a mapping the - # proxy cannot resolve answers 200 with an empty body, so it fails closed instead. + # 앞단 proxy에 맡기기. 기동할 때 내부 매핑을 실제로 써 보고 확인한다. proxy가 풀지 못하는 매핑은 빈 + # 본문으로 200을 답하므로, 그대로 두지 않고 실패시킨다(fail closed). type: boolean default: false allowed_values: [true, false] @@ -3654,7 +3611,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_NGINX_INTERNAL_PREFIX - # Internal location the proxy resolves to the storage root. + # proxy가 저장소 root로 풀어 주는 내부 위치. type: string default: /__files/ allowed_values: null @@ -3667,7 +3624,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_NGINX_OBJECT_SUFFIX - # Suffix appended to the sharded object key in the internal URI. + # 내부 URI에서 shard로 나눈 객체 key 뒤에 붙이는 접미사. type: string default: .bin allowed_values: null @@ -3680,7 +3637,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_NGINX_MINIMUM_SIZE - # Below this the request is served by the application rather than delegated. + # 이보다 작은 요청은 맡기지 않고 애플리케이션이 직접 내준다. type: data_size default: 16MB allowed_values: null @@ -3693,7 +3650,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_OBSERVABILITY_METRICS_ENABLED - # When false neither the metrics port nor the fingerprint is created, and no key is required. + # false면 metrics port도 fingerprint도 만들지 않고 key도 요구하지 않는다. type: boolean default: true allowed_values: [true, false] @@ -3706,8 +3663,8 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_OBSERVABILITY_FINGERPRINT_KEY - # Keyed HMAC over file identifiers. An unkeyed digest of an enumerable identifier is - # reversible, so startup fails while metrics are on and this is blank. + # 파일 식별자에 거는 key 있는 HMAC. 셀 수 있는 식별자의 key 없는 digest는 되돌릴 수 있으므로, metrics가 + # 켜졌는데 이 값이 비면 기동이 실패한다. type: string default: null allowed_values: null @@ -3719,7 +3676,7 @@ env_keys: compatibility_impact: additive required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - # === File / Upload (feature-file-resource-handling-contract) === + # === 파일 / 업로드 (feature-file-resource-handling-contract) === - name: APP_ASYNC_EXECUTOR_CORE_SIZE # source: feature-background-job-async-contract 2026-05-22 @@ -3763,18 +3720,15 @@ env_keys: compatibility_impact: behavior-change required_test: async-contract:executor-queue-bounded - # === Notification delivery platform (NTF-025 — configuration surface) === - # The tree exists in application.yml as app.notification.platform, disabled by - # default. Every key carries an inline default so a deployment that leaves the platform off - # supplies nothing. Reference: docs/notification/configuration.md. + # === 알림 전달 플랫폼 (NTF-025 — 설정 표면) === + # application.yml에 app.notification.platform 트리가 있고 기본으로 꺼져 있다. 모든 키가 같은 줄에 기본값을 + # 가지므로, 플랫폼을 끈 배포는 아무것도 주지 않아도 된다. 참고: docs/notification/configuration-reference.md. - name: APP_PERSISTENCE_JPA_ENABLED - # source: five-adapter-runtime-remediation §5.1 — switch for relational persistence, shipped by - # the persistence-jpa module itself (config/module-defaults/persistence-jpa.yml). The module is - # selected by one build line and is on while present; false switches off this module's beans - # (entity scan, repositories, stores, startup guards). Removing the build line removes the - # capability and this key's only reader. The old app.jpa-platform.enabled gated three add-on - # beans while reading like this one. + # source: five-adapter-runtime-remediation §5.1 — 관계형 영속성 스위치. persistence-jpa 모듈이 직접 + # 가진다(config/module-defaults/persistence-jpa.yml). 모듈은 빌드 한 줄로 고르고, 있는 동안 켜진다. false면 + # 이 모듈의 bean(entity scan, repository, store, 기동 관문)을 끈다. 빌드 줄을 지우면 기능과 이 키를 읽는 유일한 + # 곳이 함께 사라진다. 옛 app.jpa-platform.enabled는 이 키처럼 읽혔지만 부가 bean 셋만 막았다. type: boolean default: true allowed_values: [true, false] @@ -3861,10 +3815,9 @@ env_keys: required_test: jpa-contract:hibernate-runtime-settings - name: APP_PERSISTENCE_MONGO_ENABLED - # 2026-09-25 capability packaging: the module is on when present (its own config yml maps - # this key with default true); false is the explicit off. Absent from the build is the - # ordinary off state. - # source: five-adapter-runtime-remediation §5.1 — on/off key for MongoDB persistence. + # 2026-09-25 capability 포장: 모듈은 있으면 켜진다(모듈 자신의 설정 yml이 이 키를 기본 true로 잇는다). + # false가 명시적으로 끄는 값이다. 빌드에 모듈이 없는 것이 보통의 꺼진 상태다. + # source: five-adapter-runtime-remediation §5.1 — MongoDB 영속성 켜고 끄기. type: boolean default: true allowed_values: [true, false] @@ -3876,9 +3829,8 @@ env_keys: compatibility_impact: behavior-change required_test: adapter-contract:persistence-mongo-disabled-safe - name: APP_PERSISTENCE_MONGO_ACTIVE_PROFILE - # source: five-adapter-runtime-remediation §5.1 — selects exactly one Mongo profile. The runtime - # builds one sync client and one pool; a profile present in the map but not selected has neither - # its secret resolved nor a client created. + # source: five-adapter-runtime-remediation §5.1 — Mongo profile을 정확히 하나 고른다. 런타임은 sync client + # 하나와 pool 하나를 만든다. map에 있지만 고르지 않은 profile은 비밀을 풀지도, client를 만들지도 않는다. type: string default: "" classification: public-config @@ -3890,15 +3842,15 @@ env_keys: compatibility_impact: behavior-change required_test: adapter-contract:persistence-mongo-active-profile - name: SPRING_MONGODB_URI - # source: persistence-mongo techlead review C1. Spring Boot 4 consumes this native key as - # spring.mongodb.uri. It is one of two valid connection sources; the alternate is the selected - # typed profile's uri-secret resolved through MongoCredentialResolver. + # source: persistence-mongo techlead review C1. Spring Boot 4는 이 자체 키를 spring.mongodb.uri로 쓴다. + # 유효한 연결 출처 둘 중 하나다. 다른 하나는 고른 typed profile의 uri-secret을 MongoCredentialResolver로 푼 + # 값이다. type: string default: null allowed_values: null classification: sensitive-config required: false - required_when: app.persistence-mongo.enabled=true AND no active-profile uri-secret + required_when: app.persistence-mongo.enabled=true이고 활성 profile의 uri-secret이 없을 때 reload_policy: restart-only owner_branch: persistence-mongo-runtime-remediation validation: mongodb_uri_when_selected_as_connection_source @@ -3906,11 +3858,10 @@ env_keys: required_test: adapter-contract:persistence-mongo-connection-source - name: APP_MESSAGING_ENABLED - # 2026-09-25 capability packaging: the module is on when present (its own config yml maps - # this key with default true); false is the explicit off. Absent from the build is the - # ordinary off state. - # source: five-adapter-runtime-remediation §5.1 — on/off key for broker publication. - # APP_MESSAGING_BROKER selects which transport and is no longer the de-facto switch. + # 2026-09-25 capability 포장: 모듈은 있으면 켜진다(모듈 자신의 설정 yml이 이 키를 기본 true로 잇는다). + # false가 명시적으로 끄는 값이다. 빌드에 모듈이 없는 것이 보통의 꺼진 상태다. + # source: five-adapter-runtime-remediation §5.1 — broker 발행 켜고 끄기. + # APP_MESSAGING_BROKER는 어느 transport인지만 고르고, 이제 사실상의 스위치가 아니다. type: boolean default: true allowed_values: [true, false] @@ -3921,15 +3872,14 @@ env_keys: validation: boolean compatibility_impact: behavior-change required_test: adapter-contract:messaging-disabled-safe - # === Optional WebSocket build-composition contract === - # These keys map directly to app.websocket.* when the websocket leaf is present in a chosen - # composition. The default bootJar does not contain that leaf; presence remains a build-time - # decision and these rows do not imply runtime membership. + # === 선택형 WebSocket 빌드 조립 계약 === + # 고른 조립에 websocket leaf가 있으면 이 키들이 app.websocket.*로 바로 이어진다. 기본 bootJar에는 그 leaf가 + # 없다. 있을지는 빌드할 때 정하고, 이 행들이 런타임에 들어 있다는 뜻은 아니다. - name: APP_WEBSOCKET_ENABLED - # 2026-09-25 capability packaging: the module is on when present (its own config yml maps - # this key with default true); false is the explicit off. Absent from the build is the - # ordinary off state. + # 2026-09-25 capability 포장: 모듈은 있으면 켜진다(모듈 자신의 설정 yml이 이 키를 + # 기본 true로 잇는다). false가 명시적으로 끄는 값이다. 빌드에 모듈이 없는 것이 + # 보통의 꺼진 상태다. property: app.websocket.enabled owner_module: adapter-inbound-websocket type: boolean @@ -4000,7 +3950,7 @@ env_keys: required_test: websocket-contract:canonical-property-namespace - name: APP_WEBSOCKET_MESSAGE_SIZE_LIMIT - # Spring's own default, now explicit (review 03-06); at most 2147483647 bytes. + # Spring 자체 기본값을 명시했다(review 03-06). 최대 2147483647 bytes. property: app.websocket.message-size-limit owner_module: adapter-inbound-websocket type: data_size @@ -4015,7 +3965,7 @@ env_keys: required_test: websocket-contract:canonical-property-namespace - name: APP_WEBSOCKET_SEND_BUFFER_SIZE_LIMIT - # Spring's own default, now explicit (review 03-06); at most 2147483647 bytes. + # Spring 자체 기본값을 명시했다(review 03-06). 최대 2147483647 bytes. property: app.websocket.send-buffer-size-limit owner_module: adapter-inbound-websocket type: data_size @@ -4030,7 +3980,7 @@ env_keys: required_test: websocket-contract:canonical-property-namespace - name: APP_WEBSOCKET_SEND_TIME_LIMIT - # Spring's own default, now explicit (review 03-06); at most 2147483647 ms. + # Spring 자체 기본값을 명시했다(review 03-06). 최대 2147483647 ms. property: app.websocket.send-time-limit owner_module: adapter-inbound-websocket type: duration @@ -4045,7 +3995,7 @@ env_keys: required_test: websocket-contract:canonical-property-namespace - name: APP_WEBSOCKET_TIME_TO_FIRST_MESSAGE - # Spring's own default, now explicit (review 03-06); at most 2147483647 ms. + # Spring 자체 기본값을 명시했다(review 03-06). 최대 2147483647 ms. property: app.websocket.time-to-first-message owner_module: adapter-inbound-websocket type: duration @@ -4060,7 +4010,8 @@ env_keys: required_test: websocket-contract:canonical-property-namespace - name: APP_WEBSOCKET_MAX_CONNECTIONS - # New per-node STOMP session ceiling (review 03-06); the next session is closed with 1013. 1000 x 512KB send buffer bounds worst-case outbound buffering near 512 MiB. + # 노드마다의 새 STOMP session 상한(review 03-06). 그 다음 session은 1013으로 닫는다. 1000 x 512KB 송신 + # 버퍼라 최악의 송신 버퍼링이 512 MiB 근처로 묶인다. property: app.websocket.max-connections owner_module: adapter-inbound-websocket type: integer @@ -4075,10 +4026,9 @@ env_keys: required_test: websocket-contract:canonical-property-namespace - name: APP_OBJECTSTORAGE_ENABLED - # 2026-11-03 RR-06-07: the explicit off the Compose smoke wrapper sets for every lane that is - # not about object storage. It bound by relaxed binding and was in no registry, so the env - # contract could not tell it from an unread name. The module is on when present; absent from - # the build is the ordinary off state. + # 2026-11-03 RR-06-07: Compose smoke wrapper가 객체 저장소와 상관없는 모든 lane에 거는 명시적 끄기 값. + # relaxed binding으로 바인딩되면서 어느 레지스트리에도 없어, env 계약이 읽히지 않는 이름과 구별하지 못했다. + # 모듈은 있으면 켜진다. 빌드에 모듈이 없는 것이 보통의 꺼진 상태다. property: app.object-storage.enabled owner_module: adapter-outbound-objectstorage type: boolean @@ -4092,9 +4042,9 @@ env_keys: compatibility_impact: none required_test: off-state-zero-side-effects-and-env-round-trip - name: APP_GRPC_SERVER_ENABLED - # 2026-11-03 RR-06-07: the explicit off for the gRPC server the Compose lanes set (it replaced - # CASKELETON_GRPC_ENABLED, which nothing read). The module is on when present; absent from the - # build is the ordinary off state. + # 2026-11-03 RR-06-07: Compose lane이 거는 gRPC 서버의 명시적 끄기 값(아무도 읽지 않던 + # CASKELETON_GRPC_ENABLED를 대신했다). 모듈은 있으면 켜진다. 빌드에 모듈이 없는 것이 보통의 꺼진 + # 상태다. property: app.grpc.server.enabled owner_module: adapter-inbound-grpc type: boolean @@ -4108,11 +4058,10 @@ env_keys: compatibility_impact: none required_test: off-state-zero-side-effects-and-env-round-trip - name: APP_GRAPHQL_ENABLED - # 2026-09-25 capability packaging: the module is on when present (its own config yml maps - # this key with default true); false is the explicit off. Absent from the build is the - # ordinary off state. - # source: five-adapter-runtime-remediation §5.1 — on/off key for the GraphQL transport. - # false publishes no /graphql route, including the one Spring GraphQL would publish by itself. + # 2026-09-25 capability 포장: 모듈은 있으면 켜진다(모듈 자신의 설정 yml이 이 키를 기본 true로 잇는다). + # false가 명시적으로 끄는 값이다. 빌드에 모듈이 없는 것이 보통의 꺼진 상태다. + # source: five-adapter-runtime-remediation §5.1 — GraphQL transport 켜고 끄기. + # false면 /graphql route를 내지 않는다. Spring GraphQL이 스스로 내는 route도 포함이다. type: boolean default: true allowed_values: [true, false] @@ -4124,10 +4073,9 @@ env_keys: compatibility_impact: behavior-change required_test: adapter-contract:graphql-disabled-safe - name: APP_GRAPHQL_DEPLOYMENT_MODE - # source: five-adapter-runtime-remediation §5.1 / GQL-INT-002 — replaces app.graphql.production - # and app.graphql.environment, which defaulted to production=false with - # environment=PRODUCTION_PUBLIC and let anonymous-principal and allow-by-default authorization - # read one axis while the other claimed production. + # source: five-adapter-runtime-remediation §5.1 / GQL-INT-002 — app.graphql.production과 + # app.graphql.environment를 대신한다. 둘의 기본값이 production=false와 environment=PRODUCTION_PUBLIC이라, + # 익명 principal과 기본 허용 권한 검사는 한 축을 읽고 다른 축은 production이라 주장했다. type: enum default: "" allowed_values: [LOCAL, DEV, PRODUCTION_INTERNAL, PRODUCTION_PUBLIC] @@ -4290,9 +4238,9 @@ env_keys: required_test: graphql-contract:wired-operator-settings - name: APP_OUTBOX_ENABLED - # source: five-adapter-runtime-remediation §6.1 JPA-INT-004 — the outbox capability switch. - # relay-enabled below only starts the scheduler; conflating the two meant a relay-off deployment - # still assembled outbox metrics over a store port a database-less runtime does not have. + # source: five-adapter-runtime-remediation §6.1 JPA-INT-004 — outbox 기능 스위치. + # 아래 relay-enabled는 scheduler만 시작한다. 둘을 섞으면 relay를 끈 배포도 DB 없는 런타임에는 없는 store + # port 위에 outbox metrics를 조립했다. type: boolean default: false allowed_values: [true, false] @@ -4304,10 +4252,9 @@ env_keys: compatibility_impact: behavior-change required_test: adapter-contract:outbox-capability-disabled-safe - name: APP_OUTBOX_RELAY_ENABLED - # source: five-adapter-runtime-remediation §6.3 MSG-INT-001 — starts the relay scheduler. - # Requires APP_OUTBOX_ENABLED, APP_PERSISTENCE_JPA_ENABLED and APP_MESSAGING_ENABLED with - # APP_MESSAGING_PRODUCER_ID; the shipped default was true beside a blank broker, which refused - # every startup. + # source: five-adapter-runtime-remediation §6.3 MSG-INT-001 — relay scheduler를 시작한다. + # APP_OUTBOX_ENABLED, APP_PERSISTENCE_JPA_ENABLED, APP_MESSAGING_ENABLED와 APP_MESSAGING_PRODUCER_ID가 + # 필요하다. 예전 기본값은 broker가 빈 채로 true라 모든 기동을 거부했다. type: boolean default: false allowed_values: [true, false] @@ -4319,9 +4266,9 @@ env_keys: compatibility_impact: behavior-change required_test: adapter-contract:outbox-relay-dependency - name: APP_NOTIFICATION_PLATFORM_ENABLED - # 2026-09-25 capability packaging: the notification-platform module is on when present (its - # config/module-defaults/notification.yml maps this key with default true); false is the - # explicit off and binds nothing at all. Absent from the build is the ordinary off state. + # 2026-09-25 capability 포장: notification-platform 모듈은 있으면 켜진다(모듈의 + # config/module-defaults/notification.yml이 이 키를 기본 true로 잇는다). false가 명시적으로 끄는 값이고 + # 아무것도 바인딩하지 않는다. 빌드에 모듈이 없는 것이 보통의 꺼진 상태다. # source: NTF-025. type: boolean default: true @@ -4335,9 +4282,8 @@ env_keys: required_test: adapter-contract:notification-platform-disabled-safe - name: APP_NOTIFICATION_PLATFORM_DEFAULT_LOCALE - # I-6b: the locale a submission that names none is rendered in. The accept use case applies - # it; the HTTP controller used to pick the host JVM's Locale.getDefault(), so the same request - # rendered differently per node. + # I-6b: locale을 적지 않은 제출을 그릴 locale. 접수 use case가 적용한다. 예전에는 HTTP controller가 host + # JVM의 Locale.getDefault()를 골라, 같은 요청이 노드마다 다르게 그려졌다. type: string default: ko-KR allowed_values: null @@ -4350,10 +4296,10 @@ env_keys: required_test: application-contract:notification-default-locale - name: APP_NOTIFICATION_PLATFORM_CONTACT_ENCRYPTION_KEY - # source: NTF-INT-007 — Encrypts recipient contact points at rest — addresses and phone numbers. - # Full row owned by secrets-classification.yaml. Bound by - # app.notification.platform.secrets.contact-encryption-key; the platform decodes it at startup and - # refuses to boot if it is blank, shorter than 32 bytes, or equal to another purpose's key. + # source: NTF-INT-007 — 저장된 수신자 연락처(주소와 전화번호)를 암호화한다. + # 행 전체는 secrets-classification.yaml이 가진다. 바인딩 위치: + # app.notification.platform.secrets.contact-encryption-key. 플랫폼이 기동할 때 값을 풀고, + # 비었거나 32바이트보다 짧거나 다른 용도의 key와 같으면 기동을 거부한다. type: string default: null allowed_values: null @@ -4366,10 +4312,10 @@ env_keys: required_test: adapter-contract:notification-secret-material-required - name: APP_NOTIFICATION_PLATFORM_CONTACT_LOOKUP_HMAC_KEY - # source: NTF-INT-007 — Blind index over contact points, so a lookup never needs the plaintext. - # Full row owned by secrets-classification.yaml. Bound by - # app.notification.platform.secrets.contact-lookup-hmac-key; the platform decodes it at startup and - # refuses to boot if it is blank, shorter than 32 bytes, or equal to another purpose's key. + # source: NTF-INT-007 — 연락처의 blind index. 조회에 평문이 필요 없게 한다. + # 행 전체는 secrets-classification.yaml이 가진다. 바인딩 위치: + # app.notification.platform.secrets.contact-lookup-hmac-key. 플랫폼이 기동할 때 값을 풀고, + # 비었거나 32바이트보다 짧거나 다른 용도의 key와 같으면 기동을 거부한다. type: string default: null allowed_values: null @@ -4382,10 +4328,10 @@ env_keys: required_test: adapter-contract:notification-secret-material-required - name: APP_NOTIFICATION_PLATFORM_CALLBACK_SIGNING_KEY - # source: NTF-INT-007 — Signs the callback URLs a provider posts delivery outcomes back to. - # Full row owned by secrets-classification.yaml. Bound by - # app.notification.platform.secrets.callback-signing-key; the platform decodes it at startup and - # refuses to boot if it is blank, shorter than 32 bytes, or equal to another purpose's key. + # source: NTF-INT-007 — provider가 전달 결과를 보내는 callback URL에 서명한다. + # 행 전체는 secrets-classification.yaml이 가진다. 바인딩 위치: + # app.notification.platform.secrets.callback-signing-key. 플랫폼이 기동할 때 값을 풀고, + # 비었거나 32바이트보다 짧거나 다른 용도의 key와 같으면 기동을 거부한다. type: string default: null allowed_values: null @@ -4398,10 +4344,10 @@ env_keys: required_test: adapter-contract:notification-secret-material-required - name: APP_NOTIFICATION_PLATFORM_PROVIDER_CREDENTIAL_KEY - # source: NTF-INT-007 — Encrypts stored provider credentials, which are themselves secrets. - # Full row owned by secrets-classification.yaml. Bound by - # app.notification.platform.secrets.provider-credential-key; the platform decodes it at startup and - # refuses to boot if it is blank, shorter than 32 bytes, or equal to another purpose's key. + # source: NTF-INT-007 — 저장된 provider 자격 증명(그 자체가 비밀)을 암호화한다. + # 행 전체는 secrets-classification.yaml이 가진다. 바인딩 위치: + # app.notification.platform.secrets.provider-credential-key. 플랫폼이 기동할 때 값을 풀고, + # 비었거나 32바이트보다 짧거나 다른 용도의 key와 같으면 기동을 거부한다. type: string default: null allowed_values: null @@ -4414,10 +4360,10 @@ env_keys: required_test: adapter-contract:notification-secret-material-required - name: APP_NOTIFICATION_PLATFORM_PAYLOAD_ENCRYPTION_KEY - # source: NTF-INT-007 — Encrypts notification variables and retained callback bodies at rest. - # Full row owned by secrets-classification.yaml. Bound by - # app.notification.platform.secrets.payload-encryption-key; the platform decodes it at startup and - # refuses to boot if it is blank, shorter than 32 bytes, or equal to another purpose's key. + # source: NTF-INT-007 — 저장된 알림 변수와 보관한 callback 본문을 암호화한다. + # 행 전체는 secrets-classification.yaml이 가진다. 바인딩 위치: + # app.notification.platform.secrets.payload-encryption-key. 플랫폼이 기동할 때 값을 풀고, + # 비었거나 32바이트보다 짧거나 다른 용도의 key와 같으면 기동을 거부한다. type: string default: null allowed_values: null @@ -4430,10 +4376,10 @@ env_keys: required_test: adapter-contract:notification-secret-material-required - name: APP_NOTIFICATION_PLATFORM_PROVIDER_REQUEST_LOOKUP_HMAC_KEY - # source: NTF-INT-007 — Keyed hash of provider request ids, which are provider-side identifiers. - # Full row owned by secrets-classification.yaml. Bound by - # app.notification.platform.secrets.provider-request-lookup-hmac-key; the platform decodes it at startup and - # refuses to boot if it is blank, shorter than 32 bytes, or equal to another purpose's key. + # source: NTF-INT-007 — provider 쪽 식별자인 provider request id의 key 있는 hash. + # 행 전체는 secrets-classification.yaml이 가진다. 바인딩 위치: + # app.notification.platform.secrets.provider-request-lookup-hmac-key. 플랫폼이 기동할 때 값을 풀고, + # 비었거나 32바이트보다 짧거나 다른 용도의 key와 같으면 기동을 거부한다. type: string default: null allowed_values: null @@ -4446,10 +4392,10 @@ env_keys: required_test: adapter-contract:notification-secret-material-required - name: APP_NOTIFICATION_PLATFORM_CALLBACK_FINGERPRINT_HMAC_KEY - # source: NTF-INT-007 — Keyed fingerprint of callback bodies, used to detect replays. - # Full row owned by secrets-classification.yaml. Bound by - # app.notification.platform.secrets.callback-fingerprint-hmac-key; the platform decodes it at startup and - # refuses to boot if it is blank, shorter than 32 bytes, or equal to another purpose's key. + # source: NTF-INT-007 — callback 본문의 key 있는 fingerprint. replay를 찾는 데 쓴다. + # 행 전체는 secrets-classification.yaml이 가진다. 바인딩 위치: + # app.notification.platform.secrets.callback-fingerprint-hmac-key. 플랫폼이 기동할 때 값을 풀고, + # 비었거나 32바이트보다 짧거나 다른 용도의 key와 같으면 기동을 거부한다. type: string default: null allowed_values: null @@ -4462,9 +4408,9 @@ env_keys: required_test: adapter-contract:notification-secret-material-required - name: APP_NOTIFICATION_PLATFORM_CONTACT_ENCRYPTION_KEY_ID - # source: NTF-INT-007 — the id written into every envelope the CONTACT_ENCRYPTION key produces. - # An identifier, not key material, so it is public-config; the material itself is the - # APP_NOTIFICATION_PLATFORM_CONTACT_ENCRYPTION_KEY row above. Bound into + # source: NTF-INT-007 — CONTACT_ENCRYPTION key가 만드는 모든 envelope에 적는 id. + # key 자료가 아니라 식별자라 public-config다. 자료 자체는 위의 + # APP_NOTIFICATION_PLATFORM_CONTACT_ENCRYPTION_KEY 행이다. 바인딩 위치: # app.notification.platform.secrets.active-key-ids.CONTACT_ENCRYPTION. type: string default: null @@ -4478,9 +4424,9 @@ env_keys: required_test: adapter-contract:notification-secret-material-required - name: APP_NOTIFICATION_PLATFORM_CONTACT_LOOKUP_HMAC_KEY_ID - # source: NTF-INT-007 — the id written into every envelope the CONTACT_LOOKUP_HMAC key produces. - # An identifier, not key material, so it is public-config; the material itself is the - # APP_NOTIFICATION_PLATFORM_CONTACT_LOOKUP_HMAC_KEY row above. Bound into + # source: NTF-INT-007 — CONTACT_LOOKUP_HMAC key가 만드는 모든 envelope에 적는 id. + # key 자료가 아니라 식별자라 public-config다. 자료 자체는 위의 + # APP_NOTIFICATION_PLATFORM_CONTACT_LOOKUP_HMAC_KEY 행이다. 바인딩 위치: # app.notification.platform.secrets.active-key-ids.CONTACT_LOOKUP_HMAC. type: string default: null @@ -4494,9 +4440,9 @@ env_keys: required_test: adapter-contract:notification-secret-material-required - name: APP_NOTIFICATION_PLATFORM_CALLBACK_SIGNING_KEY_ID - # source: NTF-INT-007 — the id written into every envelope the CALLBACK_SIGNING key produces. - # An identifier, not key material, so it is public-config; the material itself is the - # APP_NOTIFICATION_PLATFORM_CALLBACK_SIGNING_KEY row above. Bound into + # source: NTF-INT-007 — CALLBACK_SIGNING key가 만드는 모든 envelope에 적는 id. + # key 자료가 아니라 식별자라 public-config다. 자료 자체는 위의 + # APP_NOTIFICATION_PLATFORM_CALLBACK_SIGNING_KEY 행이다. 바인딩 위치: # app.notification.platform.secrets.active-key-ids.CALLBACK_SIGNING. type: string default: null @@ -4510,9 +4456,9 @@ env_keys: required_test: adapter-contract:notification-secret-material-required - name: APP_NOTIFICATION_PLATFORM_PROVIDER_CREDENTIAL_KEY_ID - # source: NTF-INT-007 — the id written into every envelope the PROVIDER_CREDENTIAL key produces. - # An identifier, not key material, so it is public-config; the material itself is the - # APP_NOTIFICATION_PLATFORM_PROVIDER_CREDENTIAL_KEY row above. Bound into + # source: NTF-INT-007 — PROVIDER_CREDENTIAL key가 만드는 모든 envelope에 적는 id. + # key 자료가 아니라 식별자라 public-config다. 자료 자체는 위의 + # APP_NOTIFICATION_PLATFORM_PROVIDER_CREDENTIAL_KEY 행이다. 바인딩 위치: # app.notification.platform.secrets.active-key-ids.PROVIDER_CREDENTIAL. type: string default: null @@ -4526,9 +4472,9 @@ env_keys: required_test: adapter-contract:notification-secret-material-required - name: APP_NOTIFICATION_PLATFORM_PAYLOAD_ENCRYPTION_KEY_ID - # source: NTF-INT-007 — the id written into every envelope the PAYLOAD_ENCRYPTION key produces. - # An identifier, not key material, so it is public-config; the material itself is the - # APP_NOTIFICATION_PLATFORM_PAYLOAD_ENCRYPTION_KEY row above. Bound into + # source: NTF-INT-007 — PAYLOAD_ENCRYPTION key가 만드는 모든 envelope에 적는 id. + # key 자료가 아니라 식별자라 public-config다. 자료 자체는 위의 + # APP_NOTIFICATION_PLATFORM_PAYLOAD_ENCRYPTION_KEY 행이다. 바인딩 위치: # app.notification.platform.secrets.active-key-ids.PAYLOAD_ENCRYPTION. type: string default: null @@ -4542,9 +4488,9 @@ env_keys: required_test: adapter-contract:notification-secret-material-required - name: APP_NOTIFICATION_PLATFORM_PROVIDER_REQUEST_LOOKUP_HMAC_KEY_ID - # source: NTF-INT-007 — the id written into every envelope the PROVIDER_REQUEST_LOOKUP_HMAC key produces. - # An identifier, not key material, so it is public-config; the material itself is the - # APP_NOTIFICATION_PLATFORM_PROVIDER_REQUEST_LOOKUP_HMAC_KEY row above. Bound into + # source: NTF-INT-007 — PROVIDER_REQUEST_LOOKUP_HMAC key가 만드는 모든 envelope에 적는 id. + # key 자료가 아니라 식별자라 public-config다. 자료 자체는 위의 + # APP_NOTIFICATION_PLATFORM_PROVIDER_REQUEST_LOOKUP_HMAC_KEY 행이다. 바인딩 위치: # app.notification.platform.secrets.active-key-ids.PROVIDER_REQUEST_LOOKUP_HMAC. type: string default: null @@ -4558,9 +4504,9 @@ env_keys: required_test: adapter-contract:notification-secret-material-required - name: APP_NOTIFICATION_PLATFORM_CALLBACK_FINGERPRINT_HMAC_KEY_ID - # source: NTF-INT-007 — the id written into every envelope the CALLBACK_FINGERPRINT_HMAC key produces. - # An identifier, not key material, so it is public-config; the material itself is the - # APP_NOTIFICATION_PLATFORM_CALLBACK_FINGERPRINT_HMAC_KEY row above. Bound into + # source: NTF-INT-007 — CALLBACK_FINGERPRINT_HMAC key가 만드는 모든 envelope에 적는 id. + # key 자료가 아니라 식별자라 public-config다. 자료 자체는 위의 + # APP_NOTIFICATION_PLATFORM_CALLBACK_FINGERPRINT_HMAC_KEY 행이다. 바인딩 위치: # app.notification.platform.secrets.active-key-ids.CALLBACK_FINGERPRINT_HMAC. type: string default: null @@ -4574,7 +4520,7 @@ env_keys: required_test: adapter-contract:notification-secret-material-required - name: APP_NOTIFICATION_PLATFORM_SES_ENABLED - # source: notification/fileserver H4-B — shipped SES dispatch assembler. + # source: notification/fileserver H4-B — 기본으로 들어 있는 SES 발송 조립기. type: boolean default: false allowed_values: [true, false] @@ -4587,7 +4533,7 @@ env_keys: required_test: adapter-contract:notification-ses-provider-assembled - name: APP_NOTIFICATION_PLATFORM_SES_PRIMARY - # source: notification/fileserver H4-B — shipped SES dispatch assembler. + # source: notification/fileserver H4-B — 기본으로 들어 있는 SES 발송 조립기. type: boolean default: false allowed_values: [true, false] @@ -4600,7 +4546,7 @@ env_keys: required_test: adapter-contract:notification-ses-provider-assembled - name: APP_NOTIFICATION_PLATFORM_SES_ENVIRONMENT - # source: notification/fileserver H4-B — shipped SES dispatch assembler. + # source: notification/fileserver H4-B — 기본으로 들어 있는 SES 발송 조립기. type: string default: PRODUCTION allowed_values: null @@ -4613,7 +4559,7 @@ env_keys: required_test: adapter-contract:notification-ses-provider-assembled - name: APP_NOTIFICATION_PLATFORM_SES_CREDENTIAL_KEY_ID - # source: notification/fileserver H4-B — shipped SES dispatch assembler. + # source: notification/fileserver H4-B — 기본으로 들어 있는 SES 발송 조립기. type: string default: null allowed_values: null @@ -4626,7 +4572,7 @@ env_keys: required_test: adapter-contract:notification-ses-provider-assembled - name: APP_NOTIFICATION_PLATFORM_SES_TIMEOUT - # source: notification/fileserver H4-B — shipped SES dispatch assembler. + # source: notification/fileserver H4-B — 기본으로 들어 있는 SES 발송 조립기. type: duration default: 10s allowed_values: null @@ -4639,7 +4585,7 @@ env_keys: required_test: adapter-contract:notification-ses-provider-assembled - name: APP_NOTIFICATION_PLATFORM_SES_MAX_CONCURRENCY - # source: notification/fileserver H4-B — shipped SES dispatch assembler. + # source: notification/fileserver H4-B — 기본으로 들어 있는 SES 발송 조립기. type: int default: 8 allowed_values: null @@ -4652,7 +4598,7 @@ env_keys: required_test: adapter-contract:notification-ses-provider-assembled - name: APP_NOTIFICATION_PLATFORM_SES_RATE_PER_SECOND - # source: notification/fileserver H4-B — shipped SES dispatch assembler. + # source: notification/fileserver H4-B — 기본으로 들어 있는 SES 발송 조립기. type: int default: 20 allowed_values: null @@ -4665,7 +4611,7 @@ env_keys: required_test: adapter-contract:notification-ses-provider-assembled - name: APP_NOTIFICATION_PLATFORM_SES_ENDPOINT - # source: notification/fileserver H4-B — shipped SES dispatch assembler. + # source: notification/fileserver H4-B — 기본으로 들어 있는 SES 발송 조립기. type: string default: https://email.us-east-1.amazonaws.com allowed_values: null @@ -4678,7 +4624,7 @@ env_keys: required_test: adapter-contract:notification-ses-provider-assembled - name: APP_NOTIFICATION_PLATFORM_SES_REGION - # source: notification/fileserver H4-B — shipped SES dispatch assembler. + # source: notification/fileserver H4-B — 기본으로 들어 있는 SES 발송 조립기. type: string default: us-east-1 allowed_values: null @@ -4691,7 +4637,7 @@ env_keys: required_test: adapter-contract:notification-ses-provider-assembled - name: APP_NOTIFICATION_PLATFORM_SES_SENDER_IDENTITY - # source: notification/fileserver H4-B — shipped SES dispatch assembler. + # source: notification/fileserver H4-B — 기본으로 들어 있는 SES 발송 조립기. type: string default: null allowed_values: null @@ -4704,7 +4650,7 @@ env_keys: required_test: adapter-contract:notification-ses-provider-assembled - name: APP_NOTIFICATION_PLATFORM_SES_ACCESS_KEY_ID - # source: notification/fileserver H4-B — shipped SES dispatch assembler. + # source: notification/fileserver H4-B — 기본으로 들어 있는 SES 발송 조립기. type: string default: null allowed_values: null @@ -4717,7 +4663,7 @@ env_keys: required_test: adapter-contract:notification-ses-provider-assembled - name: APP_NOTIFICATION_PLATFORM_SES_CONFIGURATION_SET - # source: notification/fileserver H4-B — shipped SES dispatch assembler. + # source: notification/fileserver H4-B — 기본으로 들어 있는 SES 발송 조립기. type: string default: null allowed_values: null @@ -4730,9 +4676,9 @@ env_keys: required_test: adapter-contract:notification-ses-provider-assembled - name: APP_NOTIFICATION_PLATFORM_SES_ALLOWED_TOPIC_ARNS - # source: 2026-09-24 module review Critical #10 — SNS topics whose SES event callbacks the - # shipped SES profile accepts. A valid SNS signature only proves AWS sent the message and - # anyone can own a topic, so binding fails when callbacks are enabled and this is empty. + # source: 2026-09-24 module review Critical #10 — 기본 SES profile이 받는 SES 이벤트 callback의 SNS topic. + # SNS 서명이 맞다는 것은 AWS가 보냈다는 것만 증명하고, topic은 누구나 가질 수 있다. 그래서 callback을 켰는데 + # 이 값이 비면 바인딩이 실패한다. type: csv default: "" allowed_values: null @@ -4745,7 +4691,7 @@ env_keys: required_test: adapter-contract:notification-ses-callback-topic-allowlist - name: APP_NOTIFICATION_PLATFORM_SMTP_ENABLED - # source: NTF-INT-001 — on/off key of the shipped SMTP provider profile; false means assembly skips it entirely. + # source: NTF-INT-001 — 기본 SMTP provider profile 켜고 끄기. false면 조립에서 통째로 뺀다. type: boolean default: false allowed_values: [true, false] @@ -4758,7 +4704,7 @@ env_keys: required_test: adapter-contract:notification-smtp-provider-assembled - name: APP_NOTIFICATION_PLATFORM_SMTP_PRIMARY - # source: NTF-INT-001 — whether this profile is the primary route for EMAIL; exactly one primary per channel. + # source: NTF-INT-001 — 이 profile이 EMAIL의 주 경로인지. 채널마다 주 경로는 정확히 하나다. type: boolean default: true allowed_values: [true, false] @@ -4771,7 +4717,7 @@ env_keys: required_test: adapter-contract:notification-smtp-provider-assembled - name: APP_NOTIFICATION_PLATFORM_SMTP_ENVIRONMENT - # source: NTF-INT-001 — the profile's declared environment, carried on every dispatch record. + # source: NTF-INT-001 — profile이 밝힌 환경. 모든 발송 기록에 실린다. type: string default: local allowed_values: null @@ -4784,7 +4730,7 @@ env_keys: required_test: adapter-contract:notification-smtp-provider-assembled - name: APP_NOTIFICATION_PLATFORM_SMTP_CREDENTIAL_PROFILE - # source: NTF-INT-001 — the credential profile the relay's credentials are resolved through. + # source: NTF-INT-001 — relay 자격 증명을 푸는 credential profile. type: string default: default allowed_values: null @@ -4797,7 +4743,7 @@ env_keys: required_test: adapter-contract:notification-smtp-provider-assembled - name: APP_NOTIFICATION_PLATFORM_SMTP_TIMEOUT - # source: NTF-INT-001 — per-attempt provider timeout for this profile. + # source: NTF-INT-001 — 이 profile의 시도마다 provider timeout. type: duration default: 10s allowed_values: null @@ -4810,7 +4756,7 @@ env_keys: required_test: adapter-contract:notification-smtp-provider-assembled - name: APP_NOTIFICATION_PLATFORM_SMTP_MAX_CONCURRENCY - # source: NTF-INT-001 — how many attempts this profile may have in flight. + # source: NTF-INT-001 — 이 profile이 동시에 처리할 수 있는 시도 수. type: int default: 4 allowed_values: null @@ -4823,7 +4769,7 @@ env_keys: required_test: adapter-contract:notification-smtp-provider-assembled - name: APP_NOTIFICATION_PLATFORM_SMTP_RATE_PER_SECOND - # source: NTF-INT-001 — the profile's attempt rate limit. + # source: NTF-INT-001 — profile의 시도 속도 제한. type: int default: 10 allowed_values: null @@ -4836,7 +4782,7 @@ env_keys: required_test: adapter-contract:notification-smtp-provider-assembled - name: APP_NOTIFICATION_PLATFORM_SMTP_SENDER_IDENTITY - # source: NTF-INT-001 — the envelope sender every message is sent as. + # source: NTF-INT-001 — 모든 메시지를 보내는 envelope 발신자. type: string default: no-reply@example.invalid allowed_values: null @@ -4849,7 +4795,7 @@ env_keys: required_test: adapter-contract:notification-smtp-provider-assembled - name: APP_NOTIFICATION_PLATFORM_SMTP_DISPATCH_CONCURRENCY - # source: NTF-INT-001 — size of the bounded executor SMTP sends run on. + # source: NTF-INT-001 — SMTP 발송이 도는, 크기가 정해진 executor의 크기. type: int default: 4 allowed_values: null @@ -4862,8 +4808,8 @@ env_keys: required_test: adapter-contract:notification-smtp-provider-assembled - name: SPRING_MAIL_HOST - # source: notification/fileserver techlead review H2 — native Spring Mail transport - # consumed by the JavaMailSender that the shipped SMTP assembler validates and uses. + # source: notification/fileserver techlead review H2 — Spring Mail 자체 transport 설정. 기본 SMTP 조립기가 + # 검증하고 쓰는 JavaMailSender가 읽는다. property: spring.mail.host owner_module: adapter-outbound-notification type: string @@ -4879,8 +4825,8 @@ env_keys: required_test: adapter-contract:notification-smtp-transport - name: SPRING_MAIL_PORT - # source: notification/fileserver techlead review H2 — native Spring Mail transport - # consumed by the JavaMailSender that the shipped SMTP assembler validates and uses. + # source: notification/fileserver techlead review H2 — Spring Mail 자체 transport 설정. 기본 SMTP 조립기가 + # 검증하고 쓰는 JavaMailSender가 읽는다. property: spring.mail.port owner_module: adapter-outbound-notification type: integer @@ -4896,8 +4842,8 @@ env_keys: required_test: adapter-contract:notification-smtp-transport - name: SPRING_MAIL_USERNAME - # source: notification/fileserver techlead review H2 — native Spring Mail transport - # consumed by the JavaMailSender that the shipped SMTP assembler validates and uses. + # source: notification/fileserver techlead review H2 — Spring Mail 자체 transport 설정. 기본 SMTP 조립기가 + # 검증하고 쓰는 JavaMailSender가 읽는다. property: spring.mail.username owner_module: adapter-outbound-notification type: string @@ -4913,8 +4859,8 @@ env_keys: required_test: adapter-contract:notification-smtp-transport - name: SPRING_MAIL_PASSWORD - # source: notification/fileserver techlead review H2 — native Spring Mail transport - # consumed by the JavaMailSender that the shipped SMTP assembler validates and uses. + # source: notification/fileserver techlead review H2 — Spring Mail 자체 transport 설정. 기본 SMTP 조립기가 + # 검증하고 쓰는 JavaMailSender가 읽는다. property: spring.mail.password owner_module: adapter-outbound-notification type: string @@ -4930,8 +4876,8 @@ env_keys: required_test: adapter-contract:notification-smtp-transport - name: SPRING_MAIL_PROPERTIES_MAIL_SMTP_STARTTLS_ENABLE - # source: notification/fileserver techlead review H2 — native Spring Mail transport - # consumed by the JavaMailSender that the shipped SMTP assembler validates and uses. + # source: notification/fileserver techlead review H2 — Spring Mail 자체 transport 설정. 기본 SMTP 조립기가 + # 검증하고 쓰는 JavaMailSender가 읽는다. property: spring.mail.properties.mail.smtp.starttls.enable owner_module: adapter-outbound-notification type: boolean @@ -4947,8 +4893,8 @@ env_keys: required_test: adapter-contract:notification-smtp-transport - name: SPRING_MAIL_PROPERTIES_MAIL_SMTP_STARTTLS_REQUIRED - # source: notification/fileserver techlead review H2 — native Spring Mail transport - # consumed by the JavaMailSender that the shipped SMTP assembler validates and uses. + # source: notification/fileserver techlead review H2 — Spring Mail 자체 transport 설정. 기본 SMTP 조립기가 + # 검증하고 쓰는 JavaMailSender가 읽는다. property: spring.mail.properties.mail.smtp.starttls.required owner_module: adapter-outbound-notification type: boolean @@ -4964,8 +4910,8 @@ env_keys: required_test: adapter-contract:notification-smtp-transport - name: SPRING_MAIL_PROPERTIES_MAIL_SMTP_CONNECTIONTIMEOUT - # source: notification/fileserver techlead review H2 — native Spring Mail transport - # consumed by the JavaMailSender that the shipped SMTP assembler validates and uses. + # source: notification/fileserver techlead review H2 — Spring Mail 자체 transport 설정. 기본 SMTP 조립기가 + # 검증하고 쓰는 JavaMailSender가 읽는다. property: spring.mail.properties.mail.smtp.connectiontimeout owner_module: adapter-outbound-notification type: integer @@ -4981,8 +4927,8 @@ env_keys: required_test: adapter-contract:notification-smtp-transport - name: SPRING_MAIL_PROPERTIES_MAIL_SMTP_TIMEOUT - # source: notification/fileserver techlead review H2 — native Spring Mail transport - # consumed by the JavaMailSender that the shipped SMTP assembler validates and uses. + # source: notification/fileserver techlead review H2 — Spring Mail 자체 transport 설정. 기본 SMTP 조립기가 + # 검증하고 쓰는 JavaMailSender가 읽는다. property: spring.mail.properties.mail.smtp.timeout owner_module: adapter-outbound-notification type: integer @@ -4998,8 +4944,8 @@ env_keys: required_test: adapter-contract:notification-smtp-transport - name: SPRING_MAIL_PROPERTIES_MAIL_SMTP_WRITETIMEOUT - # source: notification/fileserver techlead review H2 — native Spring Mail transport - # consumed by the JavaMailSender that the shipped SMTP assembler validates and uses. + # source: notification/fileserver techlead review H2 — Spring Mail 자체 transport 설정. 기본 SMTP 조립기가 + # 검증하고 쓰는 JavaMailSender가 읽는다. property: spring.mail.properties.mail.smtp.writetimeout owner_module: adapter-outbound-notification type: integer @@ -5015,9 +4961,9 @@ env_keys: required_test: adapter-contract:notification-smtp-transport - name: APP_OPENAPI_DOCS_ENABLED - # source: five-adapter-runtime-remediation §9 — whether /v3/api-docs is served; application-prod.yml pins it false. Stated rather than defaulted because - # SpringDoc warns on every startup until a deployment decides, and a warning on every start is - # one nobody reads. + # source: five-adapter-runtime-remediation §9 — /v3/api-docs를 내줄지. application-prod.yml이 false로 + # 고정한다. 기본값에 맡기지 않고 적는 이유: 배포가 정할 때까지 SpringDoc이 기동마다 경고하고, 기동마다 나는 + # 경고는 아무도 읽지 않는다. type: boolean default: true allowed_values: [true, false] @@ -5030,9 +4976,9 @@ env_keys: required_test: env-contract:openapi-exposure-decided - name: APP_OPENAPI_UI_ENABLED - # source: five-adapter-runtime-remediation §9 — whether the Swagger UI is served; application-prod.yml pins it false. Stated rather than defaulted because - # SpringDoc warns on every startup until a deployment decides, and a warning on every start is - # one nobody reads. + # source: five-adapter-runtime-remediation §9 — Swagger UI를 내줄지. application-prod.yml이 false로 고정한다. + # 기본값에 맡기지 않고 적는 이유: 배포가 정할 때까지 SpringDoc이 기동마다 경고하고, 기동마다 나는 경고는 + # 아무도 읽지 않는다. type: boolean default: true allowed_values: [true, false] @@ -5045,10 +4991,10 @@ env_keys: required_test: env-contract:openapi-exposure-decided - name: APP_NOTIFICATION_PLATFORM_MODE - # source: NTF-025 — SERVING refuses to start without a working provider; INGEST_ONLY stores and does not dispatch. - # The constant is INGEST_ONLY. This row said ACCEPT_ONLY, a name NotificationPlatformMode has - # never had, so an operator following the registry got a binding failure naming a value the - # documentation does not mention. NotificationModeSsotTest derives the list below from the enum. + # source: NTF-025 — SERVING은 동작하는 provider 없이 기동을 거부한다. INGEST_ONLY는 저장만 하고 보내지 않는다. + # 상수는 INGEST_ONLY다. 이 행은 ACCEPT_ONLY라 했는데, NotificationPlatformMode에 그런 이름은 없었다. 그래서 + # 레지스트리를 따른 운영자는 문서에 없는 값을 지목하는 바인딩 실패를 받았다. NotificationModeSsotTest가 아래 + # 목록을 enum에서 만든다. type: enum default: SERVING allowed_values: [SERVING, INGEST_ONLY] @@ -5061,7 +5007,7 @@ env_keys: required_test: adapter-contract:notification-platform-mode - name: APP_NOTIFICATION_PLATFORM_CLAIM_BATCH_SIZE - # source: NTF-025 — how many recipient deliveries one scheduler pass claims; 1..1000, refused outside that at binding + # source: NTF-025 — scheduler 한 번이 claim하는 수신자 전달 수. 1..1000이고 밖이면 바인딩에서 거부한다 type: integer default: 50 allowed_values: null @@ -5074,7 +5020,7 @@ env_keys: required_test: adapter-contract:notification-dispatch-bounds - name: APP_NOTIFICATION_PLATFORM_LEASE_DURATION - # source: NTF-025 — must outlast a provider call plus its timeout, or a live worker's delivery is claimed by a second one + # source: NTF-025 — provider 호출과 그 timeout보다 길어야 한다. 아니면 살아 있는 worker의 전달을 다른 worker가 claim한다 type: duration default: 2m allowed_values: null @@ -5087,7 +5033,7 @@ env_keys: required_test: adapter-contract:notification-lease-fencing - name: APP_NOTIFICATION_PLATFORM_POLL_INTERVAL - # source: NTF-025 — how often the scheduler asks for work when the last pass claimed nothing + # source: NTF-025 — 지난 차례에 claim한 것이 없을 때 scheduler가 일을 다시 묻는 간격 type: duration default: 1s allowed_values: null @@ -5100,7 +5046,7 @@ env_keys: required_test: adapter-contract:notification-dispatch-bounds - name: APP_NOTIFICATION_PLATFORM_MAX_CONCURRENCY - # source: NTF-025 — ceiling on in-flight provider calls across the whole process + # source: NTF-025 — 프로세스 전체에서 처리 중인 provider 호출 수 상한 type: integer default: 64 allowed_values: null @@ -5113,7 +5059,7 @@ env_keys: required_test: adapter-contract:notification-dispatch-bounds - name: APP_NOTIFICATION_PLATFORM_MAX_ADDITIONAL_ATTEMPTS - # source: NTF-025 — retries after the first attempt; 0 means one attempt and no retry + # source: NTF-025 — 첫 시도 뒤의 재시도 수. 0이면 한 번 시도하고 재시도하지 않는다 type: integer default: 4 allowed_values: null @@ -5126,7 +5072,7 @@ env_keys: required_test: adapter-contract:notification-retry-policy - name: APP_NOTIFICATION_PLATFORM_ESTIMATED_DISPATCH_DURATION - # source: NTF-025 — dispatch latency estimate used by lease/retry planning + # source: NTF-025 — lease·재시도 계획에 쓰는 발송 지연 추정값 type: duration default: 2s allowed_values: null @@ -5139,7 +5085,7 @@ env_keys: required_test: adapter-contract:notification-dispatch-bounds - name: APP_NOTIFICATION_PLATFORM_MAX_QUEUE_AGE - # source: NTF-025 — after this, a queued delivery expires rather than being sent late + # source: NTF-025 — 이 시간이 지나면 queue의 전달은 늦게 보내지 않고 만료된다 type: duration default: 24h allowed_values: null @@ -5152,7 +5098,7 @@ env_keys: required_test: adapter-contract:notification-expiry - name: APP_NOTIFICATION_PLATFORM_ALLOW_AMBIGUOUS_FALLBACK - # source: NTF-025 — an ambiguous attempt reached the provider with an unread outcome; falling back risks a duplicate send + # source: NTF-025 — 결과를 읽지 못한 애매한 시도가 provider에 닿았다. 다른 경로로 넘기면 두 번 보낼 위험이 있다 type: boolean default: false allowed_values: [true, false] @@ -5167,7 +5113,7 @@ env_keys: - name: APP_NOTIFICATION_PLATFORM_SHUTDOWN_GRACE - # source: NTF-025 — upper bound for worker drain during process termination + # source: NTF-025 — 프로세스 종료 때 worker 정리 시간의 상한 type: duration default: 20s allowed_values: null @@ -5180,7 +5126,7 @@ env_keys: required_test: adapter-contract:notification-shutdown-grace - name: APP_NOTIFICATION_PLATFORM_MAX_BACKLOG_DEPTH - # source: NTF-OBS-001 — readiness threshold for due and unclaimed deliveries + # source: NTF-OBS-001 — 기한이 됐는데 claim되지 않은 전달의 readiness 기준 type: integer default: 100000 allowed_values: null @@ -5193,7 +5139,7 @@ env_keys: required_test: adapter-contract:notification-serving-thresholds - name: APP_NOTIFICATION_PLATFORM_MAX_OLDEST_DUE_AGE - # source: NTF-OBS-001 — readiness threshold for the oldest due delivery + # source: NTF-OBS-001 — 기한이 된 가장 오래된 전달의 readiness 기준 type: duration default: 10m allowed_values: null @@ -5206,7 +5152,7 @@ env_keys: required_test: adapter-contract:notification-serving-thresholds - name: APP_NOTIFICATION_PLATFORM_MAX_STUCK_LEASES - # source: NTF-OBS-001 — readiness threshold for expired/stuck delivery leases + # source: NTF-OBS-001 — 만료되거나 멈춘 전달 lease의 readiness 기준 type: integer default: 50 allowed_values: null @@ -5219,7 +5165,7 @@ env_keys: required_test: adapter-contract:notification-serving-thresholds - name: APP_NOTIFICATION_PLATFORM_MAX_PENDING_PROJECTIONS - # source: NTF-OBS-001 — readiness threshold for unapplied provider-event projections + # source: NTF-OBS-001 — 적용되지 않은 provider 이벤트 projection의 readiness 기준 type: integer default: 50000 allowed_values: null @@ -5232,7 +5178,7 @@ env_keys: required_test: adapter-contract:notification-serving-thresholds - name: APP_NOTIFICATION_PLATFORM_MAX_FAILED_PROJECTIONS - # source: NTF-OBS-001 — readiness threshold for failed provider-event projections + # source: NTF-OBS-001 — 실패한 provider 이벤트 projection의 readiness 기준 type: integer default: 1000 allowed_values: null @@ -5245,7 +5191,7 @@ env_keys: required_test: adapter-contract:notification-serving-thresholds - name: APP_NOTIFICATION_PLATFORM_MAX_OLDEST_PENDING_PROJECTION_AGE - # source: NTF-OBS-001 — readiness threshold for the oldest pending projection + # source: NTF-OBS-001 — 가장 오래 기다린 projection의 readiness 기준 type: duration default: 15m allowed_values: null @@ -5258,7 +5204,7 @@ env_keys: required_test: adapter-contract:notification-serving-thresholds - name: APP_NOTIFICATION_PLATFORM_MAX_OLDEST_RECONCILIATION_AGE - # source: NTF-OBS-001 — readiness threshold for the oldest unresolved reconciliation + # source: NTF-OBS-001 — 가장 오래 풀리지 않은 대조(reconciliation)의 readiness 기준 type: duration default: 30m allowed_values: null @@ -5271,7 +5217,7 @@ env_keys: required_test: adapter-contract:notification-serving-thresholds - name: APP_NOTIFICATION_PLATFORM_CALLBACKS_ENABLED - # source: NTF-025 — whether the platform exposes provider callback endpoints + # source: NTF-025 — 플랫폼이 provider callback endpoint를 내놓을지 type: boolean default: false allowed_values: [true, false] @@ -5284,7 +5230,7 @@ env_keys: required_test: adapter-contract:notification-callback-ingestion - name: APP_NOTIFICATION_PLATFORM_CALLBACK_MAX_BODY_BYTES - # source: NTF-025 — ceiling is 65251 = ciphertext column minus the largest envelope (version, key-id length, 255-byte key id, AES-GCM nonce and tag); larger is refused at binding + # source: NTF-025 — 상한 65251 = 암호문 칸 크기에서 가장 큰 envelope(version, key-id 길이, 255바이트 key id, AES-GCM nonce와 tag)를 뺀 값. 더 크면 바인딩에서 거부한다 type: integer default: 65251 allowed_values: null @@ -5297,8 +5243,8 @@ env_keys: required_test: adapter-contract:notification-callback-body-bound - name: APP_NOTIFICATION_PLATFORM_CALLBACK_REPLAY_SKEW - # source: NTF-025 — how far a callback timestamp may differ from local time before it is treated as a replay - # review 05-20 — 1h covers SNS's whole HTTP/S retry period (capped at 3,600 s); a replay inside it is a ledger duplicate + # source: NTF-025 — callback 시각이 로컬 시각과 이만큼 넘게 다르면 replay로 본다 + # review 05-20 — 1h는 SNS의 HTTP/S 재시도 기간 전체(최대 3,600 s)를 덮는다. 그 안의 replay는 ledger 중복이다 type: duration default: 1h allowed_values: null diff --git a/docs/registries/error-codes.yaml b/docs/registries/error-codes.yaml index 821c32c1..134ffd8f 100644 --- a/docs/registries/error-codes.yaml +++ b/docs/registries/error-codes.yaml @@ -2,24 +2,24 @@ # Schema owner: feature-contract-registry-governance # Category enum owner: feature-operational-error-observability-foundation # Last updated: 2026-11-06 -# Scope: skeleton-wide OperationalError SSOT. Product/fork ApiErrorCode enums own local registries/contracts. +# 범위: 저장소 전체 OperationalError의 정본. 제품·fork의 ApiErrorCode enum은 자기 레지스트리·계약을 가진다. # -# Schema (per row): +# 행마다의 칸: # code: UPPER_SNAKE_CASE # category: VALIDATION | AUTH | AUTHZ | NOT_FOUND | CONFLICT | # RATE_LIMIT | TRANSIENT_DEPENDENCY | PERMANENT_DEPENDENCY | # DATA_INTEGRITY | INTERNAL -# http_status: int (async-only failures use 500 placeholder) +# http_status: int (비동기에서만 나는 실패는 자리표시로 500) # retryable: bool # retry_after_seconds: int | null (RATE_LIMIT/TRANSIENT 권고 backoff) # owner_layer: presentation | application | domain | infrastructure | crosscut # client_safe_message: = shared-contract ClientErrorMessages.of(category) — category별 한국어 문구 표 -# 하나(소유자 결정 11). no token / no principal raw / no internal path / no stack trace -# runbook_link: runbook://area/scenario OR null (client-error만 null 허용) +# 하나(소유자 결정 11). 토큰·principal 원문·내부 경로·stack trace를 담지 않는다 +# runbook_link: runbook://area/scenario 또는 null (client-error만 null 허용) # compatibility_impact: none | additive | behavior-change | breaking -# required_test: owning contract test identifier +# required_test: 이 행을 지키는 계약 테스트 식별자 # -# Runbook policy (operational-runbook-contract L80): +# runbook 규칙 (operational-runbook-contract L80): # retryable=false + category ∈ {AUTH, AUTHZ, RATE_LIMIT, INTERNAL, # TRANSIENT_DEPENDENCY, PERMANENT_DEPENDENCY} ⇒ runbook_link 필수. # VALIDATION/NOT_FOUND/CONFLICT/DATA_INTEGRITY는 client-error로 runbook 면제 가능. @@ -217,7 +217,7 @@ errors: required_test: contract-verification:container-runtime-oom # ============================================================ - # DB / Persistence (feature-persistence-failure-baseline / SQLState Matrix) + # DB / 영속성 (feature-persistence-failure-baseline / SQLState Matrix) # ============================================================ # source: feature-persistence-failure-baseline L85 — "08* | all | TRANSIENT_DEPENDENCY | DB_UNAVAILABLE | true" @@ -337,7 +337,7 @@ errors: compatibility_impact: none required_test: contract-verification:persistence-mapping - # source: review-followup P15 (S2-lead-4) — JPA OPTIMISTIC_CONFLICT (@Version check failed at flush/commit) + # source: review-followup P15 (S2-lead-4) — JPA OPTIMISTIC_CONFLICT (flush·commit 때 @Version 검사 실패) - code: DB_OPTIMISTIC_CONFLICT category: CONFLICT http_status: 409 @@ -350,7 +350,7 @@ errors: compatibility_impact: additive required_test: persistence-jpa:JpaPersistenceExceptionCodeTest - # source: review-followup P15 (S2-lead-4) — JPA COMPLETION_UNKNOWN (40003 / commit-phase connection loss) + # source: review-followup P15 (S2-lead-4) — JPA COMPLETION_UNKNOWN (40003 / commit 단계 연결 끊김) - code: DB_COMPLETION_UNKNOWN category: DATA_INTEGRITY http_status: 500 @@ -367,7 +367,7 @@ errors: # Rate limit / Idempotency (feature-rate-limit-idempotency-contract) # ============================================================ - # source: feature-rate-limit-idempotency-contract — rate limit response/log 기준 / Retry-After header 기준 (scope L29, L33) + # source: feature-rate-limit-idempotency-contract — rate limit 응답·로그 기준 / Retry-After 헤더 기준 (scope L29, L33) - code: RATE_LIMIT_EXCEEDED category: RATE_LIMIT http_status: 429 @@ -410,7 +410,7 @@ errors: compatibility_impact: none required_test: contract-verification:idempotency - # source: review-followup P15 (X2-P2-2a) — IdempotencyExecutor fail-closed refusal before the action + # source: review-followup P15 (X2-P2-2a) — IdempotencyExecutor가 동작 전에 닫힌 채 거절한다(fail-closed) - code: IDEMPOTENCY_UNAVAILABLE category: TRANSIENT_DEPENDENCY http_status: 503 @@ -438,7 +438,7 @@ errors: compatibility_impact: additive required_test: contract-verification:idempotency - # source: review-followup P15 (X2-P2-2a) — replay cannot decide whether an external effect happened + # source: review-followup P15 (X2-P2-2a) — replay가 외부 효과가 일어났는지 정할 수 없다 - code: IDEMPOTENCY_RECOVERY_REQUIRED category: DATA_INTEGRITY http_status: 500 @@ -452,18 +452,17 @@ errors: required_test: contract-verification:idempotency # ============================================================ - # File / Resource (feature-file-resource-handling-contract) + # 파일 / 자원 (feature-file-resource-handling-contract) # ============================================================ # source: feature-file-resource-handling-contract L69 — "spring.servlet.multipart.max-file-size 10MB ... Spring 단의 enforcement가 실패 시 envelope 응답 보장" / 테스트 계약 "oversized upload가 generic 500으로 처리되면 실패" # ============================================================ - # API contract transport-standard codes (feature-api-contract-baseline) + # API 계약의 전송 표준 코드 (feature-api-contract-baseline) # ============================================================ - # NOTE: feature-api-contract-baseline owns the transport-shape failure - # classification (D8 413/414, D9 406/415, D12 405, D15 412). These rows mirror - # dev.caskeleton.shared.error.OperationalError; the D11 status-mapping - # consistency test (owner: this branch, producer) fails the build when a code's - # registry http_status and the enum httpStatus() drift apart. + # 참고: 전송 모양 실패의 분류는 feature-api-contract-baseline이 가진다 + # (D8 413/414, D9 406/415, D12 405, D15 412). 이 행들은 dev.caskeleton.shared.error.OperationalError를 + # 그대로 옮긴 것이다. D11 상태 대응 일관성 테스트(소유: 이 branch, 생산자)가 코드의 레지스트리 http_status와 + # enum httpStatus()가 어긋나면 빌드를 실패시킨다. # source: feature-api-contract-baseline.md D12 — "405 Method Not Allowed + Allow header 의무" - code: METHOD_NOT_ALLOWED @@ -518,9 +517,8 @@ errors: required_test: contract-verification:api-contract-status-mapping # source: feature-api-contract-baseline.md D8 형제 — "URI 길이 실패 분류 (414)" - # NOTE: enforcement is Tomcat/gateway-owned (rejected before Spring dispatch); - # this row + code exist for status-mapping consistency. End-to-end 414 contract - # test is `planned` (gateway/Tomcat maxHttpHeaderSize 8KB boundary). + # 참고: 강제는 Tomcat·gateway가 한다(Spring dispatch 전에 거절). 이 행과 코드는 상태 대응 일관성을 위해 + # 있다. 끝에서 끝까지의 414 계약 테스트는 `planned`다 (gateway/Tomcat maxHttpHeaderSize 8KB 경계). - code: URI_TOO_LONG category: VALIDATION http_status: 414 @@ -560,14 +558,14 @@ errors: # (feature-operational-error-observability-foundation L110). 실제 도메인별 code는 # Phase D(도메인 feature 적용) 시 본 registry에 추가. - # source: feature-operational-error-observability-foundation L110 — "code: VALIDATION_EMAIL_FORMAT, // registry-registered code" (validation field error JSON shape example) + # source: feature-operational-error-observability-foundation L110 — "code: VALIDATION_EMAIL_FORMAT, // registry-registered code" (validation 필드 오류 JSON 모양 예) # ============================================================ - # Cache (feature-cache-consistency-contract) + # 캐시 (feature-cache-consistency-contract) # ============================================================ # source: feature-cache-consistency-contract — Decisionized Work Items "Redis unavailable | degrade only if declared | fail-fast for required cache | generic INTERNAL | unavailable mapping" / 테스트 "Redis unavailable이 degrade 가능 여부 없이 INTERNAL로 처리되면 실패" # ============================================================ - # Outbound HTTP (feature-outbound-http-client-baseline) + # 외부 HTTP 호출 (feature-outbound-http-client-baseline) # ============================================================ # source: feature-outbound-http-client-baseline L70 — "outbound HTTP timeout default = connect 2s / read 5s / global call 10s" + scope "timeout/connect/DNS failure 분류" / 테스트 "upstream timeout은 retryable dependency failure로 분류되어야 함" @@ -679,7 +677,7 @@ errors: required_test: contract-verification:outbox-dlq # ============================================================ - # Background job / Async (feature-background-job-async-contract) + # 백그라운드 작업 / 비동기 (feature-background-job-async-contract) # ============================================================ # source: feature-background-job-async-contract — Decisionized "saturation | bounded executor + rejection log" / L72 "saturation policy default = AbortPolicy" / 테스트 "executor rejection이 structured log 없이 발생하면 실패" @@ -722,7 +720,7 @@ errors: required_test: contract-verification:async-dlq # ============================================================ - # Distributed Lock (feature-distributed-lock-contract) + # 분산 lock (feature-distributed-lock-contract) # ============================================================ # source: feature-distributed-lock-contract D7 — "lock 획득 실패/timeout 의 error code = @@ -746,7 +744,7 @@ errors: required_test: contract-verification:lock-acquisition-timeout # ============================================================ - # Migration / Startup (feature-migration-startup-contract) + # Migration / 기동 (feature-migration-startup-contract) # ============================================================ # source: feature-migration-startup-contract L71 — "startup exit code 표준 = ... migration 실패=70 ..." + Decisionized "startup failure log | structured log with startup.phase, error.code, error.category" @@ -764,7 +762,7 @@ errors: # source: feature-migration-startup-contract L71 — "startup exit code 표준 = ... profile mismatch=71" / 테스트 "prod profile에서 local-only 설정이 켜지면 실패" # ============================================================ - # Management / Actuator (feature-management-actuator-security-contract) + # 관리 포트 / Actuator (feature-management-actuator-security-contract) # ============================================================ # source: feature-management-actuator-security-contract — Exposure Policy "env/configprops | forbidden" "heapdump/threaddump | forbidden unless break-glass runbook" "shutdown | forbidden" / 테스트 "prod에서 env/configprops endpoint가 노출되면 실패" @@ -781,9 +779,9 @@ errors: required_test: contract-verification:management-actuator # ============================================================ - # CURRENT CODE RECONCILIATION (2026-09-21) - # Skeleton-wide OperationalError entries that were live in code but absent from the Phase-B - # registry. Product-specific ApiErrorCode enums remain owned by their product modules. + # 지금 코드와 맞춤 (2026-09-21) + # 코드에는 있었지만 Phase-B 레지스트리에 없던 저장소 전체 OperationalError 항목. 제품별 ApiErrorCode enum은 + # 자기 제품 모듈이 가진다. # ============================================================ - code: VALIDATION_FAILED diff --git a/docs/registries/headers.yaml b/docs/registries/headers.yaml index e8c8a3fe..5530af1c 100644 --- a/docs/registries/headers.yaml +++ b/docs/registries/headers.yaml @@ -2,11 +2,11 @@ # Schema owner: feature-contract-registry-governance # Last updated: 2026-05-22 # -# Conventions: -# - HTTP header name: kebab-case (X-Request-Id, X-Correlation-Id) -# - W3C standard headers: lowercase (traceparent, tracestate) -# - mdc_key: snake_case (foundation SSOT) -# - envelope_meta_field: camelCase (envelope SSOT) +# 표기 규칙 +# - HTTP 헤더 이름: kebab-case (X-Request-Id, X-Correlation-Id) +# - W3C 표준 헤더: 소문자 (traceparent, tracestate) +# - mdc_key: snake_case (foundation이 정본) +# - envelope_meta_field: camelCase (envelope이 정본) headers: # source: feature-operational-error-observability-foundation.md L97 @@ -162,7 +162,7 @@ headers: required_test: contract-verification:envelope-headers # source: feature-security-operational-baseline.md L66 - # "JWT Resource Server를 baseline security model로 둠" (Bearer token via Authorization header) + # "JWT Resource Server를 baseline security model로 둠" (Authorization 헤더의 Bearer 토큰) - name: Authorization direction: inbound type: bearer-token @@ -176,7 +176,7 @@ headers: required_test: contract-verification:jwt-resource-server # source: feature-security-operational-baseline.md L83-90 (AuthN/AuthZ Decision Matrix) - # 401 응답 시 WWW-Authenticate (Bearer realm/error) — Spring Security JWT Resource Server 표준 challenge header + # 401 응답 시 WWW-Authenticate (Bearer realm/error) — Spring Security JWT Resource Server의 표준 challenge 헤더 - name: WWW-Authenticate direction: outbound type: string diff --git a/docs/registries/mdc-keys.yaml b/docs/registries/mdc-keys.yaml index 3d041296..fcf391c2 100644 --- a/docs/registries/mdc-keys.yaml +++ b/docs/registries/mdc-keys.yaml @@ -3,10 +3,10 @@ # MDC SSOT: feature-operational-error-observability-foundation # Last updated: 2026-05-22 # -# Conventions: -# - MDC key naming: snake_case (foundation L93 "snake_case 강제. camelCase / dot.case 금지.") +# 표기 규칙 +# - MDC key 이름: snake_case (foundation L93 "snake_case 강제. camelCase / dot.case 금지.") # - cardinality_safe_for_metric=true 인 key만 metric tag로 사용 가능 -# - foundation L93-102 표 "MDC Key Standard (final)" 6개가 core SSOT +# - foundation L93-102 표 "MDC Key Standard (final)"의 key들이 핵심 정본이다 mdc_keys: # source: feature-operational-error-observability-foundation.md L97 @@ -102,10 +102,10 @@ mdc_keys: compatibility_impact: none required_test: contract-verification:log-mdc-keys - # ── log type extensions (log-management-contract L101-109 "Log Type별 필수 필드") ── + # ── 로그 종류별 확장 (log-management-contract L101-109 "Log Type별 필수 필드") ── # source: feature-log-management-contract.md L105 "request | request_id, trace_id, method, uri_template, status, duration_ms" - # NOTE: application-port-usecase-contract / business 측 operation 식별자 (uri_template과 별도 application-set) + # 참고: application-port-usecase-contract / 업무 쪽 operation 식별자 (uri_template과 따로 application이 정한다) - key: operation type: string source: application_set @@ -134,7 +134,7 @@ mdc_keys: required_test: contract-verification:log-fields # source: feature-log-management-contract.md L105 "request | request_id, trace_id, method, uri_template, status, duration_ms" - # NOTE: metrics L86 "status_code | 7 (1xx-5xx + ok/other)" — bounded + # 참고: metrics L86 "status_code | 7 (1xx-5xx + ok/other)" — 값 개수가 정해져 있다 - key: status type: numeric source: inbound_filter @@ -163,7 +163,7 @@ mdc_keys: required_test: contract-verification:log-fields # source: feature-log-management-contract.md L106 "dependency | dependency_name, dependency_type, duration_ms, outcome, error_code" - # NOTE: metrics L88 "dependency_name | 50" — bounded + # 참고: metrics L88 "dependency_name | 50" — 값 개수가 정해져 있다 - key: dependency_name type: string source: application_set @@ -206,7 +206,7 @@ mdc_keys: required_test: contract-verification:log-fields # source: feature-log-management-contract.md L106 "dependency | ... error_code (실패 시)" - # NOTE: metrics L89 "error_code | 100 — error registry row 상한과 정합" — bounded + # 참고: metrics L89 "error_code | 100 — error registry row 상한과 정합" — 값 개수가 정해져 있다 - key: error_code type: string source: application_set diff --git a/docs/registries/metrics.yaml b/docs/registries/metrics.yaml index a3ba89d8..06f17143 100644 --- a/docs/registries/metrics.yaml +++ b/docs/registries/metrics.yaml @@ -3,17 +3,19 @@ # Owner branch: feature-metrics-alerting-contract # Last updated: 2026-05-22 # -# Notes -# - Naming: Micrometer dot.case + unit suffix (.seconds | .bytes | .total). -# - Tag cardinality bounds are SSOT of feature-metrics-alerting-contract "Cardinality Bounds" table. -# - High-cardinality tags forbidden globally: user_id, request_id, raw_url, raw_query, -# raw_header_value, ip_address. These MUST NOT appear in any row. -# - tenant_id label is bounded mapping table id OR cohort bucket only (ULID raw forbidden). -# - error_code tag cardinality_limit follows error-codes.yaml row count (max 100). +# 읽는 법 +# - 이름: Micrometer dot.case에 단위 접미사(.seconds | .bytes | .total)를 붙인다. +# - tag 값 개수(cardinality) 상한의 정본은 feature-metrics-alerting-contract의 "Cardinality Bounds" 표다. +# - 값 개수가 많은 tag는 어디서도 쓰지 않는다: user_id, request_id, raw_url, raw_query, +# raw_header_value, ip_address. 어떤 행에도 나오면 안 된다. +# - tenant_id label은 크기가 정해진 매핑 표의 id나 cohort bucket만 쓴다(ULID 원문 금지). +# - error_code tag의 cardinality_limit은 error-codes.yaml 행 수를 따른다(최대 100). +# - alert_severity_thresholds 값은 경보 조건을 사람이 읽는 글로 적은 것이다. 지표 이름·연산자· +# 기간(5m, 1h)은 원문 그대로 두고, 테스트는 키(p1·p2·p3)와 값이 비어 있지 않은지만 본다. metrics: - # === HTTP server (inbound) === + # === HTTP 서버 (inbound) === # source: feature-metrics-alerting-contract — Metric/Alert Defaults # "HTTP metric | http.server.requests with method/status/uri-template | raw URL or user id tag" - name: http.server.requests @@ -32,9 +34,9 @@ metrics: percentiles: [0.5, 0.9, 0.95, 0.99] histogram_buckets: slo_driven alert_severity_thresholds: - p1: "error_rate > 5% for 5m OR > 10% for 1m" - p2: "error_rate > 1% for 10m" - p3: "error_rate > 0.1% for 1h" + p1: "error_rate > 5%가 5m 동안, 또는 > 10%가 1m 동안" + p2: "error_rate > 1%가 10m 동안" + p3: "error_rate > 0.1%가 1h 동안" owner_branch: feature-metrics-alerting-contract log_field_mapping: [method, status, uri_template] compatibility_impact: additive @@ -55,15 +57,15 @@ metrics: percentiles: [0.5, 0.9, 0.95, 0.99] histogram_buckets: slo_driven alert_severity_thresholds: - p1: "p99 > 5s for 5m" - p2: "p99 > 1s for 10m" - p3: "p99 > 500ms for 30m" + p1: "p99 > 5s가 5m 동안" + p2: "p99 > 1s가 10m 동안" + p3: "p99 > 500ms가 30m 동안" owner_branch: feature-metrics-alerting-contract log_field_mapping: [method, uri_template, duration_ms] compatibility_impact: additive required_test: contract-verification:metrics-cardinality - # === HTTP client (outbound dependency) === + # === HTTP client (outbound 의존 대상) === # source: feature-metrics-alerting-contract — Metric/Alert Defaults # "dependency metric | dependency.client.requests with dependency.name/type/outcome | endpoint with secret tag" # source: feature-outbound-http-client-baseline — "circuit breaker metric은 dependency.name, dependency.type, outcome까지만 tag로 허용" @@ -82,16 +84,16 @@ metrics: percentiles: [0.5, 0.9, 0.95, 0.99] histogram_buckets: slo_driven alert_severity_thresholds: - p1: "required dep unavailable for 2m" - p2: "optional dep degraded for 5m" - p3: "spike alert (10x baseline)" + p1: "필수 의존 대상이 2m 동안 응답하지 않음" + p2: "선택 의존 대상이 5m 동안 저하됨" + p3: "급증 경보(기준선의 10배)" owner_branch: feature-metrics-alerting-contract log_field_mapping: [dependency_name, dependency_type, outcome, duration_ms] compatibility_impact: additive required_test: contract-verification:metrics-cardinality # source: feature-outbound-http-client-baseline — decisions - # "retry/circuit breaker 기본 라이브러리는 Resilience4j" + # "retry/circuit breaker 기본 라이브러리는 Resilience4j" # source: feature-metrics-alerting-contract — "retry/CB minimum: resilience4j.retry.calls{outcome}" - name: resilience4j.retry.calls type: counter @@ -105,7 +107,7 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p2: "retry exhaustion rate > 1% for 10m" + p2: "재시도 소진 비율 > 1%가 10m 동안" owner_branch: feature-outbound-http-client-baseline log_field_mapping: [dependency_name, outcome, retry_attempt] compatibility_impact: additive @@ -124,8 +126,8 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p1: "state == OPEN for required dependency for 2m" - p2: "state == OPEN for optional dependency for 5m" + p1: "필수 의존 대상의 state == OPEN이 2m 동안" + p2: "선택 의존 대상의 state == OPEN이 5m 동안" owner_branch: feature-outbound-http-client-baseline log_field_mapping: [dependency_name] compatibility_impact: additive @@ -144,7 +146,7 @@ metrics: percentiles: [0.5, 0.9, 0.95, 0.99] histogram_buckets: slo_driven alert_severity_thresholds: - p2: "CIRCUIT_OPEN rate > 1% for 10m" + p2: "CIRCUIT_OPEN 비율 > 1%가 10m 동안" owner_branch: feature-outbound-http-client-baseline log_field_mapping: [dependency_name, outcome, duration_ms] compatibility_impact: additive @@ -166,8 +168,8 @@ metrics: percentiles: [0.5, 0.9, 0.95, 0.99] histogram_buckets: slo_driven alert_severity_thresholds: - p1: "pool exhaustion (active == max) for 1m" - p2: "acquire p99 > 100ms for 5m" + p1: "pool 고갈(active == max)이 1m 동안" + p2: "acquire p99 > 100ms가 5m 동안" owner_branch: feature-persistence-failure-baseline log_field_mapping: [pool, outcome] compatibility_impact: additive @@ -183,7 +185,7 @@ metrics: percentiles: [0.5, 0.9, 0.95, 0.99] histogram_buckets: slo_driven alert_severity_thresholds: - p2: "usage p99 elevated > 10m" + p2: "usage p99가 10m 넘게 높음" owner_branch: feature-persistence-failure-baseline log_field_mapping: [pool] compatibility_impact: additive @@ -199,7 +201,7 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p1: "active == max for 1m" + p1: "active == max가 1m 동안" owner_branch: feature-persistence-failure-baseline log_field_mapping: [pool] compatibility_impact: additive @@ -219,13 +221,13 @@ metrics: percentiles: [0.5, 0.9, 0.95, 0.99] histogram_buckets: slo_driven alert_severity_thresholds: - p2: "p99 > 1s for 10m" + p2: "p99 > 1s가 10m 동안" owner_branch: feature-metrics-alerting-contract log_field_mapping: [operation, outcome, duration_ms] compatibility_impact: additive required_test: contract-verification:metrics-cardinality - # === Background job / async executor === + # === 백그라운드 작업 / 비동기 executor === # source: feature-background-job-async-contract — Decisionized Work Items "saturation policy" # "AbortPolicy default (core=10, max=50, queue=200)" - name: executor.saturation @@ -237,8 +239,8 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p2: "queue size > 80% capacity for 5m" - p1: "rejection rate > 0 for 1m" + p2: "queue 크기 > 용량의 80%가 5m 동안" + p1: "거절 비율 > 0이 1m 동안" owner_branch: feature-background-job-async-contract log_field_mapping: [executor_name] compatibility_impact: additive @@ -257,7 +259,7 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p1: "rejection_count > 0 for 1m" + p1: "rejection_count > 0이 1m 동안" owner_branch: feature-background-job-async-contract log_field_mapping: [executor_name, policy] compatibility_impact: additive @@ -276,7 +278,7 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p2: "EXHAUSTED rate > 1% for 10m" + p2: "EXHAUSTED 비율 > 1%가 10m 동안" owner_branch: feature-background-job-async-contract log_field_mapping: [job_name, outcome, retry_attempt] compatibility_impact: additive @@ -292,7 +294,7 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p1: "DLQ rate sustained > 0 for 5m" + p1: "DLQ 비율 > 0이 5m 동안 계속" owner_branch: feature-background-job-async-contract log_field_mapping: [job_name] compatibility_impact: additive @@ -313,18 +315,17 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p2: "timeout rate > 5% for 10m" + p2: "timeout 비율 > 5%가 10m 동안" owner_branch: feature-distributed-lock-contract log_field_mapping: [outcome] compatibility_impact: additive required_test: contract-verification:metrics-cardinality # source: feature-distributed-lock-contract §Edge / D5 (SI-LOCK-C5) — "lease 만료 후 unlock → - # ConcurrentModificationException — 삼킴 금지, 로그+metric 후 정상 흐름 복귀". Counts releases that - # found the lease already expired (the JdbcLock row was reclaimed by another instance before - # the holder called close()). A sustained nonzero rate means lease TTL is shorter than real - # critical-section duration — raise APP/lease TTL or shorten the protected work. Not an - # acquisition outcome, hence a separate counter from lock.acquisition. + # ConcurrentModificationException — 삼킴 금지, 로그+metric 후 정상 흐름 복귀". lease가 이미 만료된 뒤의 + # 해제를 센다(보유자가 close()를 부르기 전에 다른 인스턴스가 JdbcLock 행을 회수함). 0이 아닌 비율이 + # 이어지면 lease TTL이 실제 임계 구역 시간보다 짧다는 뜻이다 — APP/lease TTL을 늘리거나 보호하는 일을 + # 줄인다. 획득 결과가 아니라서 lock.acquisition과 다른 counter다. - name: lock.lease.expired type: counter unit: total @@ -332,13 +333,13 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p2: "lease-expired rate sustained > 0 for 10m" + p2: "lease-expired 비율 > 0이 10m 동안 계속" owner_branch: feature-distributed-lock-contract log_field_mapping: [] compatibility_impact: additive required_test: contract-verification:metrics-cardinality - # === Outbox publisher === + # === Outbox 발행기 === # source: feature-domain-event-outbox-contract — Outbox Defaults # "DB outbox table with eventId, aggregateId, eventType, payload, occurredAt, status, attemptCount, nextAttemptAt" - name: outbox.publisher.published.total @@ -349,20 +350,20 @@ metrics: cardinality_limit: 50 - name: outcome cardinality_limit: 5 - # The relay cycle outcomes (OutboxRelayResult.Outcome), not row statuses: IN_FLIGHT is a status - # and is never counted. STALE: the relay's claim was taken over before its result could be - # written (V17 lease fence). RELEASED: a stopping relay gave back a claim it had not used. + # 행 상태가 아니라 relay 한 바퀴의 결과(OutboxRelayResult.Outcome)다. IN_FLIGHT는 상태라 세지 않는다. + # STALE: relay의 claim을 결과를 쓰기 전에 다른 쪽이 넘겨받았다(V17 lease fence). RELEASED: 멈추는 relay가 + # 쓰지 않은 claim을 돌려줬다. allowed_values: [PUBLISHED, FAILED, DEAD, STALE, RELEASED] percentiles: null histogram_buckets: null alert_severity_thresholds: - p2: "FAILED rate > 1% for 10m, or STALE > 0 for 10m (in-flight timeout shorter than a relay stall)" + p2: "FAILED 비율 > 1%가 10m 동안, 또는 STALE > 0이 10m 동안(in-flight timeout이 relay 정지보다 짧다)" owner_branch: feature-domain-event-outbox-contract log_field_mapping: [event_type, outcome, event_id] compatibility_impact: additive required_test: contract-verification:metrics-cardinality - # source: feature-domain-event-outbox-contract — row status enum PENDING/IN_FLIGHT/PUBLISHED/FAILED/DEAD + # source: feature-domain-event-outbox-contract — 행 상태 enum PENDING/IN_FLIGHT/PUBLISHED/FAILED/DEAD - name: outbox.publisher.lag type: gauge unit: seconds @@ -372,15 +373,15 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p2: "lag > 60s for 10m" - p1: "lag > 300s for 5m" + p2: "lag > 60s가 10m 동안" + p1: "lag > 300s가 5m 동안" owner_branch: feature-domain-event-outbox-contract log_field_mapping: [event_type] compatibility_impact: additive required_test: contract-verification:metrics-cardinality # source: feature-domain-event-outbox-contract — row status enum + Outbox Defaults attemptCount - # PARKED: an operator held a row that was retried without end (re-review 2026-11-03 RR-05-03). + # PARKED: 끝없이 재시도되던 행을 운영자가 붙잡아 둠 (re-review 2026-11-03 RR-05-03). - name: outbox.pending.size type: gauge unit: total @@ -390,19 +391,19 @@ metrics: allowed_values: [PENDING, IN_FLIGHT, PUBLISHED, FAILED, DEAD, PARKED] percentiles: null histogram_buckets: null - # DEAD > 0: the claim moves a row it will not hand out to DEAD without a relay result, so - # outbox.publisher.published.total{outcome=DEAD} misses it (re-review round 2, RR-02-12). + # DEAD > 0: claim은 내주지 않을 행을 relay 결과 없이 DEAD로 옮기므로 + # outbox.publisher.published.total{outcome=DEAD}가 그것을 놓친다 (re-review round 2, RR-02-12). alert_severity_thresholds: p1: "DEAD > 0 (runbook://outbox/dead-letter)" - p2: "PENDING size growing for 10m" + p2: "PENDING 크기가 10m 동안 늘어남" owner_branch: feature-domain-event-outbox-contract log_field_mapping: [status] compatibility_impact: additive required_test: contract-verification:metrics-cardinality - # source: re-review 2026-11-03 RR-05-03 — a refusal for now and an unanswered publish are retried - # without end; these count the FAILED rows deferred at least 10 times (OutboxMetrics - # LONG_RETRY_DEFERRED_CLAIMS, the publish-failed runbook's §4.1 query) and age the oldest of them. + # source: re-review 2026-11-03 RR-05-03 — 지금의 거절과 답이 없는 발행은 끝없이 재시도된다. 이 둘은 + # 10번 이상 미뤄진 FAILED 행을 세고(OutboxMetrics LONG_RETRY_DEFERRED_CLAIMS, publish-failed runbook §4.1 + # 조회), 그중 가장 오래된 것의 나이를 잰다. - name: outbox.retry.long.size type: gauge unit: total @@ -410,7 +411,7 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p2: "> 0 for 10m (runbook://outbox/publish-failed §4.1)" + p2: "> 0이 10m 동안 (runbook://outbox/publish-failed §4.1)" owner_branch: feature-domain-event-outbox-contract log_field_mapping: [] compatibility_impact: additive @@ -429,7 +430,7 @@ metrics: compatibility_impact: additive required_test: contract-verification:metrics-cardinality - # === Cache === + # === 캐시 === # source: feature-cache-consistency-contract — Decisionized Work Items "cache pattern | cache-aside default" - name: cache.gets.total type: counter @@ -443,7 +444,7 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p3: "hit_ratio < baseline 0.5x for 1h" + p3: "hit_ratio < 기준선의 0.5배가 1h 동안" owner_branch: feature-cache-consistency-contract log_field_mapping: [cache_name, result] compatibility_impact: additive @@ -462,13 +463,13 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p2: "FAILURE rate > 0 for 5m" + p2: "FAILURE 비율 > 0이 5m 동안" owner_branch: feature-cache-consistency-contract log_field_mapping: [cache_name, outcome] compatibility_impact: additive required_test: contract-verification:metrics-cardinality - # source: redis-production-capability — optional bounded cache-only L1 + # source: redis-production-capability — 크기가 정해진 캐시 전용 L1 (선택) - name: cache.local.requests.total type: counter unit: total @@ -481,13 +482,13 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p3: "bypass or error rate above baseline for 15m" + p3: "bypass 또는 error 비율이 기준선보다 높은 상태가 15m 동안" owner_branch: redis-production-capability log_field_mapping: [cache_name, result] compatibility_impact: additive required_test: contract-verification:metrics-cardinality - # source: redis-production-capability — local stale-age bound + # source: redis-production-capability — 로컬 stale 나이 상한 - name: cache.local.entry.age.seconds type: timer unit: seconds @@ -497,13 +498,13 @@ metrics: percentiles: [0.5, 0.9, 0.95, 0.99] histogram_buckets: slo_driven alert_severity_thresholds: - p3: "p99 approaches configured local TTL for 30m" + p3: "p99가 설정한 로컬 TTL에 가까운 상태가 30m 동안" owner_branch: redis-production-capability log_field_mapping: [cache_name] compatibility_impact: additive required_test: contract-verification:metrics-cardinality - # source: redis-production-capability — bounded invalidation and generation reconciliation + # source: redis-production-capability — 크기가 정해진 무효화와 세대 대조(reconciliation) - name: cache.local.maintenance.total type: counter unit: total @@ -530,37 +531,36 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p2: "reconcile_error, subscriber_overflow, or sustained disconnects for 5m" + p2: "reconcile_error, subscriber_overflow, 또는 끊김이 5m 동안 계속" owner_branch: redis-production-capability log_field_mapping: [cache_name, event] compatibility_impact: additive required_test: contract-verification:metrics-cardinality - # === Redis connection lanes === - # source: review 2026-11-03 RR-04-02 — the cache's conditional writes got their own lane - # (CACHE_SCRIPT) so that cache fills cannot take the SCRIPT lane's connections from idempotency, - # rate limiting and leases. These meters show, per lane, whether that holds. Emitted by - # redis-runtime RedisLaneMetrics for every lane RedisRuntimeOwner pools, only when the context has - # a MeterRegistry. Every counter series is registered at zero at startup. + # === Redis 연결 lane === + # source: review 2026-11-03 RR-04-02 — 캐시의 조건부 쓰기는 자기 lane(CACHE_SCRIPT)을 받았다. 캐시 채우기가 + # idempotency·rate limiting·lease의 SCRIPT lane 연결을 가져가지 못하게 하려는 것이다. 이 meter들이 lane마다 + # 그것이 지켜지는지 보여 준다. redis-runtime RedisLaneMetrics가 RedisRuntimeOwner가 pool로 가진 모든 lane에 + # 대해, context에 MeterRegistry가 있을 때만 낸다. 모든 counter 계열은 기동 때 0으로 등록한다. - name: redis.lane.acquire.wait.seconds type: timer unit: seconds tags: - name: lane - # The lane's name: REGULAR, SCRIPT (redis-runtime), CACHE_SCRIPT (cache-redis), BLOCKING, - # TRANSACTION, ADMIN (redis-sdk), plus any lane a service composes as a RedisLaneContribution. + # lane 이름: REGULAR, SCRIPT (redis-runtime), CACHE_SCRIPT (cache-redis), BLOCKING, + # TRANSACTION, ADMIN (redis-sdk), 그리고 서비스가 RedisLaneContribution으로 조립한 lane. cardinality_limit: 12 - name: outcome cardinality_limit: 2 allowed_values: [admitted, refused] - # As RedisLaneMetrics registers it: a percentile histogram (publishPercentileHistogram, expected - # range 1ms..10s) and no client-side percentiles and no SLO boundaries. The p99 below is a - # histogram_quantile over the buckets (re-review 2026-11-04 RR-03-17). + # RedisLaneMetrics가 등록하는 모양: percentile histogram(publishPercentileHistogram, 예상 범위 + # 1ms..10s)이고, client 쪽 percentile과 SLO 경계는 없다. 아래 p99는 bucket 위의 histogram_quantile이다 + # (re-review 2026-11-04 RR-03-17). percentiles: null histogram_buckets: percentile_histogram alert_severity_thresholds: - p2: "SCRIPT admitted p99 > 100ms for 10m (the correctness lane is queueing)" - p3: "CACHE_SCRIPT admitted p99 > 100ms for 30m" + p2: "SCRIPT admitted p99 > 100ms가 10m 동안(정확성 lane이 줄을 서고 있다)" + p3: "CACHE_SCRIPT admitted p99 > 100ms가 30m 동안" owner_branch: redis-production-capability log_field_mapping: [lane, outcome] compatibility_impact: additive @@ -571,8 +571,8 @@ metrics: unit: total tags: - name: lane - # The lane's name: REGULAR, SCRIPT (redis-runtime), CACHE_SCRIPT (cache-redis), BLOCKING, - # TRANSACTION, ADMIN (redis-sdk), plus any lane a service composes as a RedisLaneContribution. + # lane 이름: REGULAR, SCRIPT (redis-runtime), CACHE_SCRIPT (cache-redis), BLOCKING, + # TRANSACTION, ADMIN (redis-sdk), 그리고 서비스가 RedisLaneContribution으로 조립한 lane. cardinality_limit: 12 - name: reason cardinality_limit: 4 @@ -580,8 +580,8 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p1: "SCRIPT or REGULAR saturated or connect_failed above zero for 2m while a correctness role is selected" - p2: "CACHE_SCRIPT saturated above baseline for 10m" + p1: "정확성 role을 고른 상태에서 SCRIPT 또는 REGULAR의 saturated나 connect_failed가 0보다 큰 상태가 2m 동안" + p2: "CACHE_SCRIPT saturated가 기준선보다 높은 상태가 10m 동안" owner_branch: redis-production-capability log_field_mapping: [lane, reason] compatibility_impact: additive @@ -592,13 +592,13 @@ metrics: unit: total tags: - name: lane - # The lane's name: REGULAR, SCRIPT (redis-runtime), CACHE_SCRIPT (cache-redis), BLOCKING, - # TRANSACTION, ADMIN (redis-sdk), plus any lane a service composes as a RedisLaneContribution. + # lane 이름: REGULAR, SCRIPT (redis-runtime), CACHE_SCRIPT (cache-redis), BLOCKING, + # TRANSACTION, ADMIN (redis-sdk), 그리고 서비스가 RedisLaneContribution으로 조립한 lane. cardinality_limit: 12 percentiles: null histogram_buckets: null alert_severity_thresholds: - p3: "opened rate after warm-up above baseline for 15m (reconnect churn against a slow Redis)" + p3: "warm-up 뒤 opened 비율이 기준선보다 높은 상태가 15m 동안(느린 Redis에 다시 연결하며 흔들림)" owner_branch: redis-production-capability log_field_mapping: [lane] compatibility_impact: additive @@ -609,8 +609,8 @@ metrics: unit: total tags: - name: lane - # The lane's name: REGULAR, SCRIPT (redis-runtime), CACHE_SCRIPT (cache-redis), BLOCKING, - # TRANSACTION, ADMIN (redis-sdk), plus any lane a service composes as a RedisLaneContribution. + # lane 이름: REGULAR, SCRIPT (redis-runtime), CACHE_SCRIPT (cache-redis), BLOCKING, + # TRANSACTION, ADMIN (redis-sdk), 그리고 서비스가 RedisLaneContribution으로 조립한 lane. cardinality_limit: 12 - name: reason cardinality_limit: 2 @@ -618,7 +618,7 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p3: "invalidated rate above baseline for 15m (timed-out or failed calls discarding connections)" + p3: "invalidated 비율이 기준선보다 높은 상태가 15m 동안(timeout·실패한 호출이 연결을 버림)" owner_branch: redis-production-capability log_field_mapping: [lane, reason] compatibility_impact: additive @@ -629,13 +629,13 @@ metrics: unit: total tags: - name: lane - # The lane's name: REGULAR, SCRIPT (redis-runtime), CACHE_SCRIPT (cache-redis), BLOCKING, - # TRANSACTION, ADMIN (redis-sdk), plus any lane a service composes as a RedisLaneContribution. + # lane 이름: REGULAR, SCRIPT (redis-runtime), CACHE_SCRIPT (cache-redis), BLOCKING, + # TRANSACTION, ADMIN (redis-sdk), 그리고 서비스가 RedisLaneContribution으로 조립한 lane. cardinality_limit: 12 percentiles: null histogram_buckets: null alert_severity_thresholds: - p2: "SCRIPT active == configured maximum-script-connections for 5m" + p2: "SCRIPT active == 설정한 maximum-script-connections가 5m 동안" owner_branch: redis-production-capability log_field_mapping: [lane] compatibility_impact: additive @@ -646,19 +646,19 @@ metrics: unit: total tags: - name: lane - # The lane's name: REGULAR, SCRIPT (redis-runtime), CACHE_SCRIPT (cache-redis), BLOCKING, - # TRANSACTION, ADMIN (redis-sdk), plus any lane a service composes as a RedisLaneContribution. + # lane 이름: REGULAR, SCRIPT (redis-runtime), CACHE_SCRIPT (cache-redis), BLOCKING, + # TRANSACTION, ADMIN (redis-sdk), 그리고 서비스가 RedisLaneContribution으로 조립한 lane. cardinality_limit: 12 percentiles: null histogram_buckets: null alert_severity_thresholds: - p2: "SCRIPT pending > 0 for 5m" + p2: "SCRIPT pending > 0이 5m 동안" owner_branch: redis-production-capability log_field_mapping: [lane] compatibility_impact: additive required_test: contract-verification:metrics-cardinality - # === Log appender === + # === 로그 appender === # source: feature-log-management-contract — Sampling Policy (final) # "async appender overflow default: drop oldest INFO/DEBUG with counter metric (log.appender.dropped.total)" - name: log.appender.dropped.total @@ -673,13 +673,13 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p2: "dropped > 0 sustained for 10m" + p2: "dropped > 0이 10m 동안 계속" owner_branch: feature-log-management-contract log_field_mapping: [appender, level] compatibility_impact: additive required_test: contract-verification:metrics-cardinality - # === Distributed tracing === + # === 분산 추적 === # source: feature-distributed-tracing-contract — decisions # "trace sampling rate default = prod 1%, dev/local 100%; shipped runtime profiles are local|dev|prod" - name: tracing.sampling.rate @@ -692,13 +692,13 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p3: "effective rate deviates from configured for 1h" + p3: "실제 비율이 설정값과 1h 동안 어긋남" owner_branch: feature-distributed-tracing-contract log_field_mapping: [profile] compatibility_impact: additive required_test: contract-verification:metrics-cardinality - # === JVM baseline === + # === JVM 기본 === # source: feature-metrics-alerting-contract — In scope "JVM/process metric" - name: jvm.memory.used type: gauge @@ -712,7 +712,7 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p2: "heap used / max > 0.85 for 10m" + p2: "heap used / max > 0.85가 10m 동안" owner_branch: feature-metrics-alerting-contract log_field_mapping: [area, id] compatibility_impact: additive @@ -730,7 +730,7 @@ metrics: percentiles: [0.5, 0.9, 0.95, 0.99] histogram_buckets: slo_driven alert_severity_thresholds: - p2: "p99 pause > 500ms for 10m" + p2: "p99 pause > 500ms가 10m 동안" owner_branch: feature-metrics-alerting-contract log_field_mapping: [action, cause] compatibility_impact: additive @@ -744,7 +744,7 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p3: "thread count > 2x baseline for 30m" + p3: "thread 수 > 기준선의 2배가 30m 동안" owner_branch: feature-metrics-alerting-contract log_field_mapping: [] compatibility_impact: additive @@ -758,7 +758,7 @@ metrics: percentiles: null histogram_buckets: null alert_severity_thresholds: - p1: "uptime reset unexpectedly < 60s (crash loop signal)" + p1: "uptime이 예상 밖으로 < 60s로 초기화됨(crash loop 신호)" owner_branch: feature-metrics-alerting-contract log_field_mapping: [] compatibility_impact: additive diff --git a/docs/registries/object-storage-readiness.yaml b/docs/registries/object-storage-readiness.yaml index b9d2d0ae..9efa7038 100644 --- a/docs/registries/object-storage-readiness.yaml +++ b/docs/registries/object-storage-readiness.yaml @@ -14,9 +14,9 @@ claims: required_tasks: - ":adapter:outbound:objectstorage:check" limitations: - - single-process control CAS only; no multi-node linearizability - - fsync and atomic move tests do not prove power-loss durability - - local development provider is forbidden in production profiles + - 한 프로세스 안의 control CAS만 보장한다. 여러 노드의 선형성(linearizability)은 없다 + - fsync·atomic move 시험은 전원이 꺼져도 남는다는 것을 증명하지 않는다 + - 로컬 개발용 제공자는 production profile에서 쓸 수 없다 - card_id: object-storage-managed-upload-multipart provider_type: filesystem-local-dev @@ -28,7 +28,7 @@ claims: required_tasks: - ":application-core:check" limitations: - - multipart publication protocol is not implemented + - multipart 게시 프로토콜은 구현하지 않았다 - card_id: object-storage-managed-download provider_type: filesystem-local-dev @@ -40,8 +40,8 @@ claims: required_tasks: - ":adapter:outbound:objectstorage:check" limitations: - - local functional full and range reads are not production-provider qualification - - no multi-node or power-loss durability claim + - 로컬의 전체·범위 읽기 기능 시험은 운영 제공자 qualification이 아니다 + - 여러 노드나 전원 손실에 대한 내구성은 주장하지 않는다 - card_id: object-storage-direct-upload-single provider_type: filesystem-local-dev @@ -53,7 +53,7 @@ claims: required_tasks: - ":application-core:check" limitations: - - direct grant provider and public inbound endpoint are not implemented + - 직접 grant 제공자와 공개 inbound endpoint는 구현하지 않았다 - card_id: object-storage-direct-upload-multipart provider_type: filesystem-local-dev @@ -65,7 +65,7 @@ claims: required_tasks: - ":application-core:check" limitations: - - direct multipart session and public inbound endpoint are not implemented + - 직접 multipart session과 공개 inbound endpoint는 구현하지 않았다 - card_id: object-storage-direct-download provider_type: filesystem-local-dev @@ -77,7 +77,7 @@ claims: required_tasks: - ":application-core:check" limitations: - - direct download grant and public inbound endpoint are not implemented + - 직접 download grant와 공개 inbound endpoint는 구현하지 않았다 - card_id: object-storage-quarantine-publication provider_type: filesystem-local-dev @@ -89,7 +89,7 @@ claims: required_tasks: - ":application-core:check" limitations: - - scanner handoff and verdict fencing are not implemented + - scanner 인계와 판정 fencing은 구현하지 않았다 - card_id: object-storage-retention provider_type: filesystem-local-dev @@ -101,8 +101,8 @@ claims: required_tasks: - ":application-core:check" limitations: - - retention and legal-hold provider enforcement are not implemented - - privileged purge composition remains intentionally empty + - 보존(retention)·법적 보존(legal hold)의 제공자 쪽 강제는 구현하지 않았다 + - 특권 purge 조립은 일부러 비워 두었다 - card_id: object-storage-reconciliation provider_type: filesystem-local-dev @@ -114,5 +114,5 @@ claims: required_tasks: - ":application-core:check" limitations: - - local create resolution is single-process functional evidence only - - production response-loss and multi-node reconciliation are not implemented + - 로컬 create 해소는 한 프로세스 안의 기능 증거일 뿐이다 + - 운영 환경의 응답 유실과 여러 노드 사이의 맞춤(reconciliation)은 구현하지 않았다 diff --git a/docs/registries/secrets-classification.yaml b/docs/registries/secrets-classification.yaml index bddb0aeb..af342bc9 100644 --- a/docs/registries/secrets-classification.yaml +++ b/docs/registries/secrets-classification.yaml @@ -3,8 +3,8 @@ # Owner branch: feature-secrets-config-source-contract # Last updated: 2026-05-22 # -# Conventions: -# - 3-tier classification (feature-secrets-config-source-contract 2026-05-22): +# 표기 규칙 +# - 분류는 세 등급이다 (feature-secrets-config-source-contract 2026-05-22): # public-config | sensitive-config | secret # - `secret` rows: prod_default 항상 null. dev fake 식별자는 `__LOCAL_DEV_` prefix # (feature-secrets-config-source-contract 2026-05-22: "dev/local sentinel value prefix = __LOCAL_DEV_"). @@ -15,22 +15,23 @@ # RR-07-04). 비밀값만 본다: 이 파일의 `secret` 행(SecretSourceValidator.CLASSIFIED_SECRETS, # SecretsClassificationRegistryTest가 1:1로 묶음), 모듈이 기여한 비밀, `secret://…/` 참조가 # 가리키는 변수. HOSTNAME·앱 이름 같은 비밀이 아닌 값은 보지 않는다 (review 2026-11-04 RR2-04-01). -# - Masking 기본 = `full_except_last_4` (feature-secrets-config-source-contract 2026-05-22: -# "full mask except last 4 chars for non-secret tokens"). 진짜 secret(password/private key)은 `full`. -# - Naming suffix는 보조 신호 (feature-secrets-config-source-contract: "_TOKEN, _KEY, _PASSWORD"). +# - 가림(masking) 기본 = `full_except_last_4` (feature-secrets-config-source-contract 2026-05-22: +# "full mask except last 4 chars for non-secret tokens" — 비밀이 아닌 토큰은 끝 4자만 남기고 가린다). +# 진짜 secret(password/private key)은 `full`. +# - 이름 접미사는 보조 신호다 (feature-secrets-config-source-contract: "_TOKEN, _KEY, _PASSWORD"). # - public-config 항목은 env-keys.yaml에서 직접 정의되며 본 파일에는 reference row만 둠. secrets: - # === Tier 3: secret (true secret — password/private-key/HMAC-salt) === + # === 3등급: secret (진짜 비밀 — password/private-key/HMAC-salt) === - name: APP_DATASOURCE_PASSWORD # source: feature-secrets-config-source-contract 2026-05-22 # "DB credential은 dual-bind 60s" + "__LOCAL_DEV_FAKE_DB_PASSWORD" 예시 classification: secret source: secret-manager - # Contributed by persistence-jpa (JpaStartupAutoConfiguration#jpaProductionSecrets) while the - # module is on; the composition root's guard no longer reads the module switch (P22-new-1). + # persistence-jpa가 모듈이 켜진 동안 기여한다(JpaStartupAutoConfiguration#jpaProductionSecrets). 조립 루트의 + # 관문은 이제 모듈 스위치를 읽지 않는다(P22-new-1). required_when: app.persistence-jpa.enabled=true rotation_policy: dual-bind-60s prod_default: null @@ -41,8 +42,8 @@ secrets: required_test: secrets-contract:db-password-no-leak-in-actuator - name: SPRING_MAIL_PASSWORD - # source: notification/fileserver techlead review H2 — credential consumed natively by Spring - # Mail and therefore intentionally retains the SPRING_* name rather than gaining an APP_* alias. + # source: notification/fileserver techlead review H2 — Spring Mail이 직접 읽는 자격 증명이라 APP_* 별칭을 두지 + # 않고 일부러 SPRING_* 이름을 유지한다. classification: secret source: secret-manager rotation_policy: restart-only @@ -56,13 +57,13 @@ secrets: - name: APP_CACHE_REDIS_PASSWORD # source: feature-secrets-config-source-contract 2026-05-22 - # 3-tier classification "secret" + feature-integration-adapter-templates "Redis | disabled optional module" - # (Redis enabled + auth 사용 시 secret으로 분류) + # 3등급 분류 "secret" + feature-integration-adapter-templates "Redis | disabled optional module" + # (Redis를 켜고 인증을 쓰면 secret으로 분류) classification: secret source: secret-manager rotation_policy: restart-only prod_default: null - # Required with app.redis.enabled=true and this role selected; checked by adapter-outbound-cache-redis RedisProductionSecrets. + # app.redis.enabled=true이고 이 role을 고르면 필요하다. adapter-outbound-cache-redis의 RedisProductionSecrets가 확인한다. required_when: app.capabilities.cache.bindings.default=redis dev_sentinel_prefix: __LOCAL_DEV_ owner_branch: feature-secrets-config-source-contract @@ -71,7 +72,7 @@ secrets: required_test: secrets-contract:redis-password-no-leak - name: APP_CACHE_REDIS_TRUST_PEM - # Public CA bundle content, but integrity-sensitive and supplied by the mounted environment. + # 공개 CA bundle 내용이지만 무결성이 중요하고, 마운트된 환경이 준다. classification: sensitive-config source: mounted-env rotation_policy: restart-only @@ -83,12 +84,12 @@ secrets: required_test: secrets-contract:redis-trust-reference-no-leak - name: APP_CACHE_REDIS_KEY_HMAC_SECRET - # Stable cache-key HMAC material. It is distinct from the Redis authentication credential. + # 바뀌지 않는 캐시 key HMAC 자료. Redis 인증 자격 증명과 다르다. classification: secret source: secret-manager rotation_policy: dual-read-restart-only prod_default: null - # Required with app.redis.enabled=true and this role selected; checked by adapter-outbound-cache-redis RedisProductionSecrets. + # app.redis.enabled=true이고 이 role을 고르면 필요하다. adapter-outbound-cache-redis의 RedisProductionSecrets가 확인한다. required_when: app.capabilities.cache.bindings.default=redis dev_sentinel_prefix: __LOCAL_DEV_ owner_branch: codex-phase-a-ci-recovery @@ -97,12 +98,12 @@ secrets: required_test: secrets-contract:redis-key-hmac-no-leak - name: APP_RATE_LIMIT_REDIS_PASSWORD - # Dedicated coordination-role Redis credential. It is never inherited from cache Redis. + # coordination role 전용 Redis 자격 증명. 캐시 Redis에서 물려받지 않는다. classification: secret source: secret-manager rotation_policy: restart-only prod_default: null - # Required with app.redis.enabled=true and this role selected; checked by adapter-outbound-cache-redis RedisProductionSecrets. + # app.redis.enabled=true이고 이 role을 고르면 필요하다. adapter-outbound-cache-redis의 RedisProductionSecrets가 확인한다. required_when: app.capabilities.rate-limit.provider=redis dev_sentinel_prefix: __LOCAL_DEV_ owner_branch: redis-distributed-rate-limit @@ -111,7 +112,7 @@ secrets: required_test: secrets-contract:rate-limit-redis-password-no-leak - name: APP_RATE_LIMIT_REDIS_TRUST_PEM - # Coordination-role CA bundle content; integrity-sensitive but not credential material. + # coordination role CA bundle 내용. 무결성이 중요하지만 자격 증명 자료는 아니다. classification: sensitive-config source: mounted-env rotation_policy: restart-only @@ -123,12 +124,12 @@ secrets: required_test: secrets-contract:rate-limit-redis-trust-reference-no-leak - name: APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET - # Stable private-key derivation material for rate-limit subjects and policy revisions. + # rate-limit 대상과 정책 개정에 쓰는, 바뀌지 않는 비공개 key 파생 자료. classification: secret source: secret-manager rotation_policy: dual-read-restart-only prod_default: null - # Required with app.redis.enabled=true and this role selected; checked by adapter-outbound-cache-redis RedisProductionSecrets. + # app.redis.enabled=true이고 이 role을 고르면 필요하다. adapter-outbound-cache-redis의 RedisProductionSecrets가 확인한다. required_when: app.capabilities.rate-limit.provider=redis dev_sentinel_prefix: __LOCAL_DEV_ owner_branch: redis-distributed-rate-limit @@ -137,12 +138,12 @@ secrets: required_test: secrets-contract:rate-limit-redis-key-hmac-no-leak - name: APP_SESSION_REDIS_PASSWORD - # Dedicated session-role ACL credential; never shared implicitly with cache or coordination. + # session role 전용 ACL 자격 증명. 캐시나 coordination과 몰래 함께 쓰지 않는다. classification: secret source: secret-manager rotation_policy: restart-only prod_default: null - # Required with app.redis.enabled=true and this role selected; checked by adapter-outbound-cache-redis RedisProductionSecrets. + # app.redis.enabled=true이고 이 role을 고르면 필요하다. adapter-outbound-cache-redis의 RedisProductionSecrets가 확인한다. required_when: app.security.auth-mode=redis-session dev_sentinel_prefix: __LOCAL_DEV_ owner_branch: redis-production-capability @@ -151,7 +152,7 @@ secrets: required_test: secrets-contract:session-redis-password-no-leak - name: APP_SESSION_REDIS_TRUST_PEM - # Session-role CA bundle content; integrity-sensitive but not credential material. + # session role CA bundle 내용. 무결성이 중요하지만 자격 증명 자료는 아니다. classification: sensitive-config source: mounted-env rotation_policy: restart-only @@ -163,12 +164,12 @@ secrets: required_test: secrets-contract:session-redis-trust-reference-no-leak - name: APP_SESSION_REDIS_KEY_HMAC_SECRET - # Stable private derivation material for pseudonymous Redis session keys. + # 가명 Redis session key에 쓰는, 바뀌지 않는 비공개 파생 자료. classification: secret source: secret-manager rotation_policy: dual-read-restart-only prod_default: null - # Required with app.redis.enabled=true and this role selected; checked by adapter-outbound-cache-redis RedisProductionSecrets. + # app.redis.enabled=true이고 이 role을 고르면 필요하다. adapter-outbound-cache-redis의 RedisProductionSecrets가 확인한다. required_when: app.security.auth-mode=redis-session dev_sentinel_prefix: __LOCAL_DEV_ owner_branch: redis-production-capability @@ -177,12 +178,12 @@ secrets: required_test: secrets-contract:session-redis-key-hmac-no-leak - name: APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET - # Owner-safe request-replay keys must not expose tenant/scope/request identifiers. + # owner-safe 요청 replay key가 tenant·scope·요청 식별자를 드러내면 안 된다. classification: secret source: secret-manager rotation_policy: cold-cutover-restart-only prod_default: null - # Required with app.redis.enabled=true and this role selected; checked by adapter-outbound-cache-redis RedisProductionSecrets. + # app.redis.enabled=true이고 이 role을 고르면 필요하다. adapter-outbound-cache-redis의 RedisProductionSecrets가 확인한다. required_when: app.capabilities.idempotency.provider=redis dev_sentinel_prefix: __LOCAL_DEV_ owner_branch: redis-production-capability-completion @@ -191,12 +192,12 @@ secrets: required_test: secrets-contract:idempotency-redis-key-hmac-no-leak - name: APP_LEASE_REDIS_KEY_HMAC_SECRET - # Efficiency-lease resource and owner scopes use a dedicated derivation key. + # 효율 lease의 자원·소유자 scope는 전용 파생 key를 쓴다. classification: secret source: secret-manager rotation_policy: cold-cutover-restart-only prod_default: null - # Required with app.redis.enabled=true and this role selected; checked by adapter-outbound-cache-redis RedisProductionSecrets. + # app.redis.enabled=true이고 이 role을 고르면 필요하다. adapter-outbound-cache-redis의 RedisProductionSecrets가 확인한다. required_when: app.capabilities.lease.provider=redis dev_sentinel_prefix: __LOCAL_DEV_ owner_branch: redis-production-capability-completion @@ -219,13 +220,12 @@ secrets: compatibility_impact: breaking required_test: secrets-contract:pseudonymization-salt-rotation - # === Tier 2: sensitive-config (token-bearing URL or id with exposure restriction) === + # === 2등급: sensitive-config (토큰이 든 URL이나 노출을 제한할 id) === - name: APP_NOTIFICATION_PLATFORM_CONTACT_ENCRYPTION_KEY - # Encrypts recipient contact points at rest — addresses and phone numbers. - # One of seven purpose-scoped keys. They must all differ: a single key reused across purposes - # means a compromise of any one of them is a compromise of all seven, and the platform enforces - # the distinction at startup rather than trusting the deployment to have noticed. + # 저장된 수신자 연락처(주소와 전화번호)를 암호화한다. + # purpose별 key 일곱 중 하나다. 모두 달라야 한다: 한 key를 여러 용도에 다시 쓰면 하나가 털릴 때 일곱이 모두 + # 털린다. 플랫폼은 배포가 알아챘으리라 믿지 않고 기동할 때 구별을 강제한다. classification: secret source: secret-manager rotation_policy: dual-read-restart-only @@ -238,10 +238,9 @@ secrets: required_test: secrets-contract:notification-contact-encryption-no-leak - name: APP_NOTIFICATION_PLATFORM_CONTACT_LOOKUP_HMAC_KEY - # Blind index over contact points, so a lookup never needs the plaintext. - # One of seven purpose-scoped keys. They must all differ: a single key reused across purposes - # means a compromise of any one of them is a compromise of all seven, and the platform enforces - # the distinction at startup rather than trusting the deployment to have noticed. + # 연락처의 blind index. 조회에 평문이 필요 없게 한다. + # purpose별 key 일곱 중 하나다. 모두 달라야 한다: 한 key를 여러 용도에 다시 쓰면 하나가 털릴 때 일곱이 모두 + # 털린다. 플랫폼은 배포가 알아챘으리라 믿지 않고 기동할 때 구별을 강제한다. classification: secret source: secret-manager rotation_policy: dual-read-restart-only @@ -254,10 +253,9 @@ secrets: required_test: secrets-contract:notification-contact-lookup-hmac-no-leak - name: APP_NOTIFICATION_PLATFORM_CALLBACK_SIGNING_KEY - # Signs the callback URLs a provider posts delivery outcomes back to. - # One of seven purpose-scoped keys. They must all differ: a single key reused across purposes - # means a compromise of any one of them is a compromise of all seven, and the platform enforces - # the distinction at startup rather than trusting the deployment to have noticed. + # provider가 전달 결과를 보내는 callback URL에 서명한다. + # purpose별 key 일곱 중 하나다. 모두 달라야 한다: 한 key를 여러 용도에 다시 쓰면 하나가 털릴 때 일곱이 모두 + # 털린다. 플랫폼은 배포가 알아챘으리라 믿지 않고 기동할 때 구별을 강제한다. classification: secret source: secret-manager rotation_policy: dual-read-restart-only @@ -270,10 +268,9 @@ secrets: required_test: secrets-contract:notification-callback-signing-no-leak - name: APP_NOTIFICATION_PLATFORM_PROVIDER_CREDENTIAL_KEY - # Encrypts stored provider credentials, which are themselves secrets. - # One of seven purpose-scoped keys. They must all differ: a single key reused across purposes - # means a compromise of any one of them is a compromise of all seven, and the platform enforces - # the distinction at startup rather than trusting the deployment to have noticed. + # 저장된 provider 자격 증명(그 자체가 비밀)을 암호화한다. + # purpose별 key 일곱 중 하나다. 모두 달라야 한다: 한 key를 여러 용도에 다시 쓰면 하나가 털릴 때 일곱이 모두 + # 털린다. 플랫폼은 배포가 알아챘으리라 믿지 않고 기동할 때 구별을 강제한다. classification: secret source: secret-manager rotation_policy: dual-read-restart-only @@ -286,10 +283,9 @@ secrets: required_test: secrets-contract:notification-provider-credential-no-leak - name: APP_NOTIFICATION_PLATFORM_PAYLOAD_ENCRYPTION_KEY - # Encrypts notification variables and retained callback bodies at rest. - # One of seven purpose-scoped keys. They must all differ: a single key reused across purposes - # means a compromise of any one of them is a compromise of all seven, and the platform enforces - # the distinction at startup rather than trusting the deployment to have noticed. + # 저장된 알림 변수와 보관한 callback 본문을 암호화한다. + # purpose별 key 일곱 중 하나다. 모두 달라야 한다: 한 key를 여러 용도에 다시 쓰면 하나가 털릴 때 일곱이 모두 + # 털린다. 플랫폼은 배포가 알아챘으리라 믿지 않고 기동할 때 구별을 강제한다. classification: secret source: secret-manager rotation_policy: dual-read-restart-only @@ -302,10 +298,9 @@ secrets: required_test: secrets-contract:notification-payload-encryption-no-leak - name: APP_NOTIFICATION_PLATFORM_PROVIDER_REQUEST_LOOKUP_HMAC_KEY - # Keyed hash of provider request ids, which are provider-side identifiers. - # One of seven purpose-scoped keys. They must all differ: a single key reused across purposes - # means a compromise of any one of them is a compromise of all seven, and the platform enforces - # the distinction at startup rather than trusting the deployment to have noticed. + # provider 쪽 식별자인 provider request id의 key 있는 hash. + # purpose별 key 일곱 중 하나다. 모두 달라야 한다: 한 key를 여러 용도에 다시 쓰면 하나가 털릴 때 일곱이 모두 + # 털린다. 플랫폼은 배포가 알아챘으리라 믿지 않고 기동할 때 구별을 강제한다. classification: secret source: secret-manager rotation_policy: dual-read-restart-only @@ -318,10 +313,9 @@ secrets: required_test: secrets-contract:notification-provider-request-lookup-hmac-no-leak - name: APP_NOTIFICATION_PLATFORM_CALLBACK_FINGERPRINT_HMAC_KEY - # Keyed fingerprint of callback bodies, used to detect replays. - # One of seven purpose-scoped keys. They must all differ: a single key reused across purposes - # means a compromise of any one of them is a compromise of all seven, and the platform enforces - # the distinction at startup rather than trusting the deployment to have noticed. + # callback 본문의 key 있는 fingerprint. replay를 찾는 데 쓴다. + # purpose별 key 일곱 중 하나다. 모두 달라야 한다: 한 key를 여러 용도에 다시 쓰면 하나가 털릴 때 일곱이 모두 + # 털린다. 플랫폼은 배포가 알아챘으리라 믿지 않고 기동할 때 구별을 강제한다. classification: secret source: secret-manager rotation_policy: dual-read-restart-only @@ -349,7 +343,7 @@ secrets: - name: APP_SECURITY_GOOGLE_OAUTH_CLIENT_ID # source: feature-secrets-config-source-contract 2026-05-22 - # "sensitive-config" tier (id이지만 노출 제한) + # "sensitive-config" 등급 (id이지만 노출 제한) # + feature-integration-adapter-templates "Google Email | disabled optional module" classification: sensitive-config source: mounted-env @@ -362,7 +356,7 @@ secrets: required_test: secrets-contract:google-oauth-client-id-masked - name: APP_DATASOURCE_USERNAME - # source: feature-secrets-config-source-contract 2026-05-22 — "sensitive-config" tier + # source: feature-secrets-config-source-contract 2026-05-22 — "sensitive-config" 등급 # (DB user는 password와 함께 노출되면 위험하므로 sensitive-config) classification: sensitive-config source: mounted-env @@ -375,8 +369,8 @@ secrets: required_test: secrets-contract:datasource-username-masked-in-actuator - name: SPRING_MONGODB_URI - # MongoDB URIs can carry username/password material and must never be logged as public config. - # Typed-profile deployments should prefer uri-secret so the URI itself never becomes env data. + # MongoDB URI에는 사용자 이름·비밀번호가 들어 있을 수 있어 public config로 로그에 남기면 안 된다. + # typed profile 배포는 URI 자체가 env 데이터가 되지 않게 uri-secret을 쓰는 편이 낫다. classification: sensitive-config source: mounted-env rotation_policy: restart-only @@ -400,10 +394,10 @@ secrets: compatibility_impact: breaking required_test: secrets-contract:datasource-url-masked-in-actuator - # === Tier 1: public-config (reference only — full row in env-keys.yaml) === + # === 1등급: public-config (참조만 — 행 전체는 env-keys.yaml에 있다) === - name: APP_PROFILE - # source: feature-env-driven-runtime-configuration — public-config tier reference + # source: feature-env-driven-runtime-configuration — public-config 등급 참조 classification: public-config source: application-yml owner_branch: feature-env-driven-runtime-configuration @@ -411,7 +405,7 @@ secrets: reference: env-keys.yaml#APP_PROFILE - name: APP_NAME - # source: feature-env-driven-runtime-configuration — public-config tier reference + # source: feature-env-driven-runtime-configuration — public-config 등급 참조 classification: public-config source: application-yml owner_branch: feature-env-driven-runtime-configuration @@ -419,7 +413,7 @@ secrets: reference: env-keys.yaml#APP_NAME - name: SERVER_PORT - # source: feature-env-driven-runtime-configuration — Spring native, public-config tier reference + # source: feature-env-driven-runtime-configuration — Spring 자체 키, public-config 등급 참조 classification: public-config source: application-yml owner_branch: feature-env-driven-runtime-configuration @@ -427,7 +421,7 @@ secrets: reference: env-keys.yaml#SERVER_PORT - name: SPRING_PROFILES_ACTIVE - # source: feature-env-driven-runtime-configuration — Spring native, public-config tier reference + # source: feature-env-driven-runtime-configuration — Spring 자체 키, public-config 등급 참조 classification: public-config source: application-yml owner_branch: feature-env-driven-runtime-configuration @@ -435,7 +429,7 @@ secrets: reference: env-keys.yaml#SPRING_PROFILES_ACTIVE - name: OTEL_EXPORTER_OTLP_ENDPOINT - # source: feature-distributed-tracing-contract — public-config tier reference + # source: feature-distributed-tracing-contract — public-config 등급 참조 classification: public-config source: application-yml owner_branch: feature-distributed-tracing-contract diff --git a/docs/runbooks/adapter-adapter-disabled.md b/docs/runbooks/adapter-adapter-disabled.md index 674e2299..3f88c52e 100644 --- a/docs/runbooks/adapter-adapter-disabled.md +++ b/docs/runbooks/adapter-adapter-disabled.md @@ -4,31 +4,35 @@ category: INTERNAL error_codes: [ADAPTER_DISABLED] severity: P2 owner: oncall -last_updated: 2026-06-15 -status: stub +last_updated: 2026-11-07 +status: 초안 --- # Runbook: ADAPTER_DISABLED (`runbook://adapter/adapter-disabled`) -## Symptoms +## 증상 -- HTTP 500 with `error.code=ADAPTER_DISABLED` -- Code invoked an optional adapter (Kafka/Redis/Slack/Email) that is disabled in this deployment +- HTTP 500, `error.code=ADAPTER_DISABLED`. +- 이 배포에서 꺼져 있거나 묶이지 않은 선택 어댑터의 경로를 코드가 호출했다. 지금 템플릿에서 이 코드를 내는 + 곳은 알림 라우터(`RoutingNotifier`)다. 채널과 route에 묶인 provider가 없을 때 낸다. -## Diagnosis +## 진단 -- Check adapter name in log (`adapter_name` field) -- Review deployment config — which optional adapters are enabled? +- ERROR 로그 `failure classified as ADAPTER_DISABLED (category=INTERNAL, retryable=false)`를 찾는다. 줄에 붙은 + 예외(`AdapterDisabledException`)의 메시지가 어댑터와 고칠 키를 알려 준다. + - 기본 메시지: `optional adapter '<이름>' is disabled (app..<이름>.enabled=false) …` + - 알림 라우터: `no notification route bound for channel=… route='…' — set app.notification.routes..=…` +- 배포 설정에서 어떤 선택 어댑터가 켜져 있는지 본다. -## Action +## 조치 -- Enable the adapter in deployment configuration (env flag) -- Or update application logic to skip disabled-adapter paths +- 배포 설정에서 그 어댑터를 켠다(환경 변수 스위치). 알림이면 메시지가 가리키는 route를 묶고 그 provider를 켠다. +- 아니면 꺼진 어댑터의 경로를 건너뛰도록 애플리케이션 로직을 고친다. -## Escalation +## 에스컬레이션 -- Escalate to deployment team if adapter should be enabled but isn't +- 켜져 있어야 할 어댑터가 꺼져 있으면 배포 담당 팀에 넘긴다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/auth-audience-mismatch.md b/docs/runbooks/auth-audience-mismatch.md index 5677e363..028422e6 100644 --- a/docs/runbooks/auth-audience-mismatch.md +++ b/docs/runbooks/auth-audience-mismatch.md @@ -5,31 +5,31 @@ error_codes: [AUTH_AUDIENCE_MISMATCH] severity: P2 owner: oncall last_updated: 2026-06-15 -status: stub +status: 초안 --- # Runbook: AUTH_AUDIENCE_MISMATCH (`runbook://auth/audience-mismatch`) -## Symptoms +## 증상 -- HTTP 401 with `error.code=AUTH_AUDIENCE_MISMATCH` -- Token `aud` claim does not include this service's expected audience +- HTTP 401, `error.code=AUTH_AUDIENCE_MISMATCH`. +- 토큰의 `aud` 클레임에 이 서비스가 기대하는 audience가 없다. -## Diagnosis +## 진단 -- Check token `aud` claim value -- Compare against configured `app.security.audience` (`APP_SECURITY_JWT_AUDIENCE`, comma-separated; - the token must name at least one) +- 토큰의 `aud` 클레임 값을 본다. +- 설정된 `app.security.audience`(`APP_SECURITY_JWT_AUDIENCE`, 쉼표로 구분)와 비교한다. 토큰은 그중 하나 이상을 + 담아야 한다. -## Action +## 조치 -- Verify client is requesting tokens scoped to the correct audience -- Update audience configuration if service identifier changed +- 클라이언트가 맞는 audience로 토큰을 요청하는지 확인한다. +- 서비스 식별자가 바뀌었으면 audience 설정을 고친다. -## Escalation +## 에스컬레이션 -- Escalate to auth-platform team if misconfiguration is system-wide +- 설정 오류가 시스템 전체에 걸쳐 있으면 인증 플랫폼 팀에 넘긴다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/auth-claim-mapping-failed.md b/docs/runbooks/auth-claim-mapping-failed.md index eaee6ca0..338e8430 100644 --- a/docs/runbooks/auth-claim-mapping-failed.md +++ b/docs/runbooks/auth-claim-mapping-failed.md @@ -5,30 +5,30 @@ error_codes: [AUTH_CLAIM_MAPPING_FAILED] severity: P2 owner: oncall last_updated: 2026-06-15 -status: stub +status: 초안 --- # Runbook: AUTH_CLAIM_MAPPING_FAILED (`runbook://auth/claim-mapping-failed`) -## Symptoms +## 증상 -- HTTP 401 with `error.code=AUTH_CLAIM_MAPPING_FAILED` -- Token validated but required claims (sub, roles, tenant) missing or unexpected type +- HTTP 401, `error.code=AUTH_CLAIM_MAPPING_FAILED`. +- 토큰 검증은 통과했지만 필요한 클레임(sub, roles, tenant)이 없거나 타입이 다르다. -## Diagnosis +## 진단 -- Inspect token payload claims via logs -- Check claim extractor configuration +- 로그에서 토큰 payload의 클레임을 본다. +- 클레임 추출 설정을 확인한다. -## Action +## 조치 -- Verify IdP token template includes required claims -- Update claim mapping configuration if IdP schema changed +- IdP 토큰 템플릿에 필요한 클레임이 들어 있는지 확인한다. +- IdP 스키마가 바뀌었으면 클레임 매핑 설정을 고친다. -## Escalation +## 에스컬레이션 -- Escalate to auth-platform team if IdP changed claim schema +- IdP가 클레임 스키마를 바꿨으면 인증 플랫폼 팀에 넘긴다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/auth-issuer-mismatch.md b/docs/runbooks/auth-issuer-mismatch.md index 1a173344..d77b97bd 100644 --- a/docs/runbooks/auth-issuer-mismatch.md +++ b/docs/runbooks/auth-issuer-mismatch.md @@ -5,30 +5,30 @@ error_codes: [AUTH_ISSUER_MISMATCH] severity: P2 owner: oncall last_updated: 2026-06-15 -status: stub +status: 초안 --- # Runbook: AUTH_ISSUER_MISMATCH (`runbook://auth/issuer-mismatch`) -## Symptoms +## 증상 -- HTTP 401 with `error.code=AUTH_ISSUER_MISMATCH` -- Token `iss` claim does not match configured expected issuer +- HTTP 401, `error.code=AUTH_ISSUER_MISMATCH`. +- 토큰의 `iss` 클레임이 설정된 발급자와 다르다. -## Diagnosis +## 진단 -- Compare token `iss` against `spring.security.oauth2.resourceserver.jwt.issuer-uri` -- Check if IdP environment changed +- 토큰의 `iss`를 `spring.security.oauth2.resourceserver.jwt.issuer-uri`와 비교한다. +- IdP 환경이 바뀌었는지 확인한다. -## Action +## 조치 -- Update issuer config if IdP migrated -- Reject tokens from unexpected issuers +- IdP를 옮겼으면 issuer 설정을 고친다. +- 예상하지 않은 발급자의 토큰은 계속 거부한다. -## Escalation +## 에스컬레이션 -- Escalate to platform-security if unexpected issuer detected +- 예상하지 않은 발급자를 찾으면 플랫폼 보안 팀에 넘긴다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/auth-jwks-unavailable.md b/docs/runbooks/auth-jwks-unavailable.md index b7c529e4..15197436 100644 --- a/docs/runbooks/auth-jwks-unavailable.md +++ b/docs/runbooks/auth-jwks-unavailable.md @@ -5,32 +5,32 @@ error_codes: [AUTH_JWKS_UNAVAILABLE] severity: P1 owner: oncall last_updated: 2026-11-06 -status: stub +status: 초안 --- # Runbook: AUTH_JWKS_UNAVAILABLE (`runbook://auth/jwks-unavailable`) -## Symptoms +## 증상 -- HTTP 503 with `error.code=AUTH_JWKS_UNAVAILABLE` -- ERROR log line `security failure: code=AUTH_JWKS_UNAVAILABLE category=TRANSIENT_DEPENDENCY method=… path=…` - (logger `AuthErrorResponseWriter`) -- All authentication failing; JWKS refresh attempts failing +- HTTP 503, `error.code=AUTH_JWKS_UNAVAILABLE`. +- ERROR 로그 줄 `security failure: code=AUTH_JWKS_UNAVAILABLE category=TRANSIENT_DEPENDENCY method=… path=…` + (logger `AuthErrorResponseWriter`). +- 인증이 모두 실패하고, JWKS 새로 고침도 실패한다. -## Diagnosis +## 진단 -- Check IdP JWKS endpoint health: `curl -sf https:///.well-known/jwks.json` -- Check network connectivity from app pods to IdP +- IdP의 JWKS 엔드포인트 상태를 본다: `curl -sf https:///.well-known/jwks.json` +- 앱 pod에서 IdP까지 네트워크가 닿는지 확인한다. -## Action +## 조치 -- Enable cached JWKS fallback if available -- Coordinate with IdP team for restoration +- 캐시된 JWKS로 버틸 수단이 있으면 쓴다. +- IdP 팀과 복구를 맞춘다. -## Escalation +## 에스컬레이션 -- P1 page: IdP team immediately if JWKS endpoint unreachable > 2 minutes +- P1 호출: JWKS 엔드포인트에 2분 넘게 닿지 않으면 IdP 팀을 바로 부른다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/auth-kid-unknown.md b/docs/runbooks/auth-kid-unknown.md index 1bb3ac15..d5949cfa 100644 --- a/docs/runbooks/auth-kid-unknown.md +++ b/docs/runbooks/auth-kid-unknown.md @@ -5,30 +5,30 @@ error_codes: [AUTH_KID_UNKNOWN] severity: P2 owner: oncall last_updated: 2026-06-15 -status: stub +status: 초안 --- # Runbook: AUTH_KID_UNKNOWN (`runbook://auth/kid-unknown`) -## Symptoms +## 증상 -- HTTP 401 with `error.code=AUTH_KID_UNKNOWN`, `retryable=true` -- Token `kid` header not present in cached JWKS +- HTTP 401, `error.code=AUTH_KID_UNKNOWN`, `retryable=true`. +- 토큰 헤더의 `kid`가 캐시된 JWKS에 없다. -## Diagnosis +## 진단 -- Check if IdP key rotation occurred recently -- Verify JWKS cache TTL and refresh timing +- 최근에 IdP 키 교체가 있었는지 확인한다. +- JWKS 캐시 TTL과 새로 고침 시점을 확인한다. -## Action +## 조치 -- Force JWKS cache refresh -- Confirm new key is published in IdP JWKS endpoint +- JWKS 캐시를 강제로 새로 고친다. +- 새 키가 IdP JWKS 엔드포인트에 게시됐는지 확인한다. -## Escalation +## 에스컬레이션 -- Escalate to IdP team if new kid not appearing in JWKS after 10 minutes +- 10분이 지나도 새 kid가 JWKS에 나타나지 않으면 IdP 팀에 넘긴다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/auth-public-path-misconfiguration.md b/docs/runbooks/auth-public-path-misconfiguration.md index 019a1976..164be247 100644 --- a/docs/runbooks/auth-public-path-misconfiguration.md +++ b/docs/runbooks/auth-public-path-misconfiguration.md @@ -4,33 +4,34 @@ category: INTERNAL error_codes: [INTERNAL_AUTH_MISCONFIGURATION] severity: P1 owner: oncall -last_updated: 2026-11-06 -status: stub +last_updated: 2026-11-07 +status: 초안 --- # Runbook: INTERNAL_AUTH_MISCONFIGURATION (`runbook://auth/public-path-misconfiguration`) -## Symptoms +## 증상 -- HTTP 500 with `error.code=INTERNAL_AUTH_MISCONFIGURATION` -- ERROR log line `security failure: code=INTERNAL_AUTH_MISCONFIGURATION category=INTERNAL method=… path=…` - (logger `AuthErrorResponseWriter`) -- Security filter misconfiguration detected at runtime +- HTTP 500, `error.code=INTERNAL_AUTH_MISCONFIGURATION`. +- ERROR 로그 줄 `security failure: code=INTERNAL_AUTH_MISCONFIGURATION category=INTERNAL method=… path=…` + (logger `AuthErrorResponseWriter`). +- 실행 중에 보안 필터 설정 오류가 드러났다. -## Diagnosis +## 진단 -- Check `verifyPublicPathSnapshot` output in CI -- Review recent changes to `SecurityConfig` or `application.yml` public path list +- CI의 `verifyPublicPathSnapshot` 결과를 본다. +- `SecurityConfig`와 공개 경로 목록(`config/security.yml`의 `public-paths`, `SECURITY_PUBLIC_PATHS`)의 최근 + 변경을 본다. -## Action +## 조치 -- Revert misconfigured public path change -- Run `./gradlew verifyPublicPathSnapshot` to compare snapshot +- 잘못된 공개 경로 변경을 되돌린다. +- `src/`에서 `./gradlew verifyPublicPathSnapshot`을 돌려 스냅숏과 비교한다. -## Escalation +## 에스컬레이션 -- P1 immediate: if auth bypass is possible due to misconfiguration +- P1 즉시: 설정 오류로 인증을 건너뛸 수 있으면. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/auth-token-expired.md b/docs/runbooks/auth-token-expired.md index 215e86de..acb5d48d 100644 --- a/docs/runbooks/auth-token-expired.md +++ b/docs/runbooks/auth-token-expired.md @@ -4,31 +4,31 @@ category: AUTH error_codes: [AUTH_TOKEN_EXPIRED] severity: P3 owner: oncall -last_updated: 2026-06-15 -status: stub +last_updated: 2026-11-07 +status: 초안 --- # Runbook: AUTH_TOKEN_EXPIRED (`runbook://auth/token-expired`) -## Symptoms +## 증상 -- HTTP 401 with `error.code=AUTH_TOKEN_EXPIRED` -- Spike may indicate clock skew or long-lived token usage +- HTTP 401, `error.code=AUTH_TOKEN_EXPIRED`. +- 급증하면 시계 차이(clock skew)나 오래 사는 토큰을 의심한다. -## Diagnosis +## 진단 -- Check `exp` claim vs server clock -- Check NTP sync on token-issuing host +- `exp` 클레임과 서버 시계를 비교한다. +- 토큰을 발급하는 호스트의 NTP 동기화를 확인한다. -## Action +## 조치 -- Client must refresh tokens before expiry -- Verify clock skew tolerance is configured (default 60s) +- 클라이언트는 만료 전에 토큰을 새로 받아야 한다. +- 시계 차이 허용값을 확인한다. 이 템플릿의 JWT 검증기는 60초를 허용한다(`JwtDecoderConfig`). -## Escalation +## 에스컬레이션 -- Escalate if spike is widespread or clock drift is confirmed +- 급증이 넓게 퍼졌거나 시계 어긋남이 확인되면 넘긴다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/auth-token-invalid-signature.md b/docs/runbooks/auth-token-invalid-signature.md index 02051f53..c0edd8eb 100644 --- a/docs/runbooks/auth-token-invalid-signature.md +++ b/docs/runbooks/auth-token-invalid-signature.md @@ -5,32 +5,32 @@ error_codes: [AUTH_TOKEN_INVALID_SIGNATURE] severity: P1 owner: oncall last_updated: 2026-11-06 -status: stub +status: 초안 --- # Runbook: AUTH_TOKEN_INVALID_SIGNATURE (`runbook://auth/token-invalid-signature`) -## Symptoms +## 증상 -- HTTP 401 with `error.code=AUTH_TOKEN_INVALID_SIGNATURE` -- WARN log line `security failure: code=AUTH_TOKEN_INVALID_SIGNATURE category=AUTH method=… path=…` - (logger `AuthErrorResponseWriter`). It is a WARN because the caller sent the token; search by - `code=`, not by level. A burst of these may indicate forged tokens or a wrong signing key +- HTTP 401, `error.code=AUTH_TOKEN_INVALID_SIGNATURE`. +- WARN 로그 줄 `security failure: code=AUTH_TOKEN_INVALID_SIGNATURE category=AUTH method=… path=…` + (logger `AuthErrorResponseWriter`). 토큰을 보낸 쪽이 호출자라서 WARN이다. 수준이 아니라 `code=`로 찾는다. + 한꺼번에 몰리면 위조 토큰이나 잘못된 서명 키를 의심한다. -## Diagnosis +## 진단 -- Check if JWKS endpoint returned a new key set -- Check for token forgery attempts in logs +- JWKS 엔드포인트가 새 키 묶음을 내놓았는지 확인한다. +- 로그에서 토큰 위조 시도를 찾는다. -## Action +## 조치 -- Verify JWKS key IDs match token headers -- Alert security team if forgery suspected +- JWKS의 키 ID가 토큰 헤더와 맞는지 확인한다. +- 위조가 의심되면 보안 팀에 알린다. -## Escalation +## 에스컬레이션 -- Immediate P1 escalation if forgery indicators present +- 위조 흔적이 있으면 바로 P1으로 올린다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/auth-token-malformed.md b/docs/runbooks/auth-token-malformed.md index 76a7d669..1ba219dd 100644 --- a/docs/runbooks/auth-token-malformed.md +++ b/docs/runbooks/auth-token-malformed.md @@ -5,30 +5,30 @@ error_codes: [AUTH_TOKEN_MALFORMED, INVALID_TOKEN] severity: P3 owner: oncall last_updated: 2026-06-15 -status: stub +status: 초안 --- # Runbook: AUTH_TOKEN_MALFORMED (`runbook://auth/token-malformed`) -## Symptoms +## 증상 -- HTTP 401 responses with `error.code=AUTH_TOKEN_MALFORMED` -- Token present but fails JWT parse (not 3-part, non-base64, etc.) +- HTTP 401 응답, `error.code=AUTH_TOKEN_MALFORMED`. +- 토큰은 있지만 JWT로 파싱되지 않는다(세 부분이 아님, base64가 아님 등). -## Diagnosis +## 진단 -- Inspect raw Authorization header value in logs -- Check if token generation tooling has a bug +- 로그에서 Authorization 헤더 원문을 본다. +- 토큰을 만드는 도구에 버그가 있는지 확인한다. -## Action +## 조치 -- Identify source of malformed tokens -- Fix or update client token generation +- 잘못된 토큰이 어디서 오는지 찾는다. +- 클라이언트의 토큰 생성을 고친다. -## Escalation +## 에스컬레이션 -- Escalate if spike suggests infrastructure issue +- 급증이 인프라 문제를 가리키면 넘긴다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/auth-token-missing.md b/docs/runbooks/auth-token-missing.md index b454f909..64cb8c13 100644 --- a/docs/runbooks/auth-token-missing.md +++ b/docs/runbooks/auth-token-missing.md @@ -5,30 +5,30 @@ error_codes: [AUTH_TOKEN_MISSING, UNAUTHENTICATED] severity: P3 owner: oncall last_updated: 2026-06-15 -status: stub +status: 초안 --- # Runbook: AUTH_TOKEN_MISSING (`runbook://auth/token-missing`) -## Symptoms +## 증상 -- HTTP 401 responses with `error.code=AUTH_TOKEN_MISSING` -- Client missing Authorization header or Bearer token +- HTTP 401 응답, `error.code=AUTH_TOKEN_MISSING`. +- 클라이언트가 Authorization 헤더나 Bearer 토큰을 보내지 않았다. -## Diagnosis +## 진단 -- Check request logs for missing Authorization header -- Verify client SDK configuration +- 요청 로그에서 Authorization 헤더가 빠졌는지 본다. +- 클라이언트 SDK 설정을 확인한다. -## Action +## 조치 -- Confirm API clients are sending Authorization header -- Check gateway/proxy configuration for header stripping +- API 클라이언트가 Authorization 헤더를 보내는지 확인한다. +- gateway·proxy가 헤더를 지우는지 설정을 확인한다. -## Escalation +## 에스컬레이션 -- Escalate if widespread or affecting critical workflows +- 넓게 퍼졌거나 중요한 업무 흐름에 영향이 있으면 넘긴다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/auth-token-rotation-failure.md b/docs/runbooks/auth-token-rotation-failure.md index 5bdc2417..90564407 100644 --- a/docs/runbooks/auth-token-rotation-failure.md +++ b/docs/runbooks/auth-token-rotation-failure.md @@ -5,7 +5,7 @@ error_codes: [AUTH_TOKEN_EXPIRED, AUTH_KID_UNKNOWN, AUTH_JWKS_UNAVAILABLE, AUTH_ severity: P1 owner: oncall last_updated: 2026-05-22 -status: stub +status: 초안 --- # Runbook: JWT key rotation 시 인증 실패 spike diff --git a/docs/runbooks/authz-cross-tenant-violation.md b/docs/runbooks/authz-cross-tenant-violation.md index b2a303c0..8aec86c6 100644 --- a/docs/runbooks/authz-cross-tenant-violation.md +++ b/docs/runbooks/authz-cross-tenant-violation.md @@ -5,7 +5,7 @@ error_codes: [AUTHZ_INSUFFICIENT_PERMISSION, AUTHZ_TENANT_MISMATCH] severity: P2 owner: oncall last_updated: 2026-05-22 -status: stub +status: 초안 --- # Runbook: cross-tenant 접근 시도 감지 diff --git a/docs/runbooks/authz-insufficient-permission.md b/docs/runbooks/authz-insufficient-permission.md index ac74bfe7..b7b40bdf 100644 --- a/docs/runbooks/authz-insufficient-permission.md +++ b/docs/runbooks/authz-insufficient-permission.md @@ -5,30 +5,30 @@ error_codes: [AUTHZ_INSUFFICIENT_PERMISSION, FORBIDDEN] severity: P3 owner: oncall last_updated: 2026-06-15 -status: stub +status: 초안 --- # Runbook: AUTHZ_INSUFFICIENT_PERMISSION (`runbook://authz/insufficient-permission`) -## Symptoms +## 증상 -- HTTP 403 with `error.code=AUTHZ_INSUFFICIENT_PERMISSION` -- Valid token but missing required role or permission +- HTTP 403, `error.code=AUTHZ_INSUFFICIENT_PERMISSION`. +- 토큰은 유효하지만 필요한 역할이나 권한이 없다. -## Diagnosis +## 진단 -- Check user's assigned roles in IdP -- Review endpoint's required permission annotation +- IdP에서 사용자에게 준 역할을 확인한다. +- 엔드포인트가 요구하는 권한 애너테이션을 확인한다. -## Action +## 조치 -- Grant correct role/permission to user -- Verify endpoint permission requirement is correct +- 사용자에게 맞는 역할·권한을 준다. +- 엔드포인트의 권한 요구가 맞는지 확인한다. -## Escalation +## 에스컬레이션 -- Escalate to access-management team if bulk users affected +- 여러 사용자가 한꺼번에 영향을 받으면 접근 관리 팀에 넘긴다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/authz-tenant-mismatch.md b/docs/runbooks/authz-tenant-mismatch.md index 47747cd9..7a9e7035 100644 --- a/docs/runbooks/authz-tenant-mismatch.md +++ b/docs/runbooks/authz-tenant-mismatch.md @@ -4,33 +4,33 @@ category: AUTHZ error_codes: [AUTHZ_TENANT_MISMATCH] severity: P1 owner: oncall -last_updated: 2026-11-06 -status: stub +last_updated: 2026-11-07 +status: 초안 --- # Runbook: AUTHZ_TENANT_MISMATCH (`runbook://authz/tenant-mismatch`) -## Symptoms +## 증상 -- HTTP 403 with `error.code=AUTHZ_TENANT_MISMATCH` -- The template does not emit this code; the service that decides cross-tenant access does. A 403 - carrier is answered without a log line (`ServerFailureLog`), so that service logs - `code=AUTHZ_TENANT_MISMATCH` where it decides, if this runbook is to find the attempt +- HTTP 403, `error.code=AUTHZ_TENANT_MISMATCH`. +- 템플릿은 이 코드를 내지 않는다. 다른 테넌트 접근을 판단하는 서비스가 낸다. 403 carrier는 로그 줄 없이 + 응답하므로(`ServerFailureLog`), 이 runbook으로 시도를 찾으려면 그 서비스가 판단하는 자리에서 + `code=AUTHZ_TENANT_MISMATCH`를 남겨야 한다. -## Diagnosis +## 진단 -- Extract `traceId`, check `X-Tenant-Id` vs token tenant claim -- Determine if this is misconfigured client or intentional attack +- `traceId`를 뽑고, 요청의 테넌트 헤더(서비스가 정한 이름, 예: `X-Tenant-Id`)와 토큰의 테넌트 클레임을 비교한다. +- 클라이언트 설정 오류인지 의도한 공격인지 가린다. -## Action +## 조치 -- Block repeat offenders at gateway level -- Alert security team for investigation +- 반복하는 호출자는 gateway에서 막는다. +- 보안 팀에 조사를 요청한다. -## Escalation +## 에스컬레이션 -- P1 if confirmed malicious cross-tenant access attempt +- 악의적인 다른 테넌트 접근 시도로 확인되면 P1. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/cache-stampede-lock-timeout.md b/docs/runbooks/cache-stampede-lock-timeout.md index f5e4f171..09643e5e 100644 --- a/docs/runbooks/cache-stampede-lock-timeout.md +++ b/docs/runbooks/cache-stampede-lock-timeout.md @@ -4,31 +4,32 @@ category: TRANSIENT_DEPENDENCY error_codes: [CACHE_STAMPEDE_LOCK_TIMEOUT] severity: P2 owner: oncall -last_updated: 2026-06-15 -status: stub +last_updated: 2026-11-07 +status: 초안 --- # Runbook: CACHE_STAMPEDE_LOCK_TIMEOUT (`runbook://cache/stampede-lock-timeout`) -## Symptoms +## 증상 -- HTTP 503 with `error.code=CACHE_STAMPEDE_LOCK_TIMEOUT` -- Multiple concurrent cache misses on same key; lock contention +- HTTP 503, `error.code=CACHE_STAMPEDE_LOCK_TIMEOUT`. +- 같은 키에 캐시 miss가 동시에 몰리고 락 경합이 생긴다. +- 지금 템플릿은 이 코드를 내지 않는다. `docs/registries/error-codes.yaml`에 이 코드의 행이 없다. 이 runbook은 캐시가 이 코드를 내게 될 때를 위한 초안이다. Redis 장애는 [redis-capability-incident.md](redis-capability-incident.md)를 먼저 본다. -## Diagnosis +## 진단 -- Check cache hit ratio metrics -- Identify cache keys with high miss rates +- 캐시 적중률 메트릭을 본다. +- miss 비율이 높은 캐시 키를 찾는다. -## Action +## 조치 -- Verify stampede lock TTL is configured appropriately -- Pre-warm cache for high-traffic keys on startup +- 스탬피드 락 TTL이 알맞게 설정됐는지 확인한다. +- 트래픽이 많은 키는 기동할 때 캐시를 미리 채운다. -## Escalation +## 에스컬레이션 -- Escalate if backend load spike accompanies stampede +- 스탬피드와 함께 백엔드 부하가 치솟으면 넘긴다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/cache-unavailable.md b/docs/runbooks/cache-unavailable.md index ebada52b..d2043c47 100644 --- a/docs/runbooks/cache-unavailable.md +++ b/docs/runbooks/cache-unavailable.md @@ -4,31 +4,32 @@ category: TRANSIENT_DEPENDENCY error_codes: [CACHE_UNAVAILABLE] severity: P1 owner: oncall -last_updated: 2026-06-15 -status: stub +last_updated: 2026-11-07 +status: 초안 --- # Runbook: CACHE_UNAVAILABLE (`runbook://cache/unavailable`) -## Symptoms +## 증상 -- HTTP 503 with `error.code=CACHE_UNAVAILABLE` -- Redis connection errors in logs +- HTTP 503, `error.code=CACHE_UNAVAILABLE`. +- 로그에 Redis 연결 오류가 있다. +- 지금 템플릿은 이 코드를 내지 않는다. `docs/registries/error-codes.yaml`에 이 코드의 행이 없다. 이 runbook은 캐시가 이 코드를 내게 될 때를 위한 초안이다. Redis 장애는 [redis-capability-incident.md](redis-capability-incident.md)를 먼저 본다. -## Diagnosis +## 진단 -- Check Redis cluster health -- Verify network connectivity from app to Redis +- Redis 클러스터 상태를 본다. +- 앱에서 Redis까지 네트워크가 닿는지 확인한다. -## Action +## 조치 -- Check Redis sentinel/cluster status -- Enable cache degradation path if configured for optional caches +- Redis sentinel·클러스터 상태를 확인한다. +- 선택 캐시에 degraded 경로(캐시 없이 원본에서 읽기)가 설정돼 있으면 켠다. -## Escalation +## 에스컬레이션 -- P1 if required cache is down and no degradation path exists +- 필수 캐시가 내려갔고 degraded 경로가 없으면 P1. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/db-deadlock.md b/docs/runbooks/db-deadlock.md index 6ba72674..d4db7a7d 100644 --- a/docs/runbooks/db-deadlock.md +++ b/docs/runbooks/db-deadlock.md @@ -5,30 +5,30 @@ error_codes: [DB_DEADLOCK] severity: P2 owner: oncall last_updated: 2026-06-15 -status: stub +status: 초안 --- # Runbook: DB_DEADLOCK (`runbook://db/deadlock`) -## Symptoms +## 증상 -- HTTP 409 with `error.code=DB_DEADLOCK` -- SQLState 40P01 in Postgres logs +- HTTP 409, `error.code=DB_DEADLOCK`. +- Postgres 로그에 SQLState 40P01이 있다. -## Diagnosis +## 진단 -- Check `pg_locks` and `pg_stat_activity` during deadlock -- Identify conflicting transaction lock order +- 교착이 생길 때 `pg_locks`와 `pg_stat_activity`를 본다. +- 충돌하는 트랜잭션의 락 순서를 찾는다. -## Action +## 조치 -- Client should retry (retryable=true) -- Fix lock ordering in code if recurring +- 클라이언트는 다시 시도한다(retryable=true). +- 반복되면 코드의 락 순서를 고친다. -## Escalation +## 에스컬레이션 -- Escalate to DBA if deadlock rate is sustained > 1% of transactions +- 교착 비율이 트랜잭션의 1%를 넘는 상태가 이어지면 DBA에 넘긴다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/db-idle-in-tx-timeout.md b/docs/runbooks/db-idle-in-tx-timeout.md index ade79237..cb19af4f 100644 --- a/docs/runbooks/db-idle-in-tx-timeout.md +++ b/docs/runbooks/db-idle-in-tx-timeout.md @@ -4,31 +4,33 @@ category: TRANSIENT_DEPENDENCY error_codes: [DB_IDLE_IN_TX_TIMEOUT] severity: P2 owner: oncall -last_updated: 2026-06-15 -status: stub +last_updated: 2026-11-07 +status: 초안 --- # Runbook: DB_IDLE_IN_TX_TIMEOUT (`runbook://db/idle-in-tx-timeout`) -## Symptoms +## 증상 -- HTTP 503 with `error.code=DB_IDLE_IN_TX_TIMEOUT` -- SQLState 25P03; transaction held open too long without activity +- HTTP 503, `error.code=DB_IDLE_IN_TX_TIMEOUT`. +- SQLState 25P03. 트랜잭션이 아무 일 없이 너무 오래 열려 있었다. -## Diagnosis +## 진단 -- Check `idle_in_transaction_session_timeout` Postgres setting -- Look for application-level long-running transaction holders +- Postgres의 `idle_in_transaction_session_timeout` 설정을 확인한다. 템플릿은 이 값을 설정하지 않는다. + DB나 역할에 걸린 값이다. +- 트랜잭션을 오래 쥐고 있는 애플리케이션 코드를 찾는다. 트랜잭션 안에서 외부 호출을 기다리는 코드가 흔한 + 원인이다. -## Action +## 조치 -- Reduce transaction scope in application code -- Verify `spring.jpa.properties.hibernate.connection.timeout` is bounded +- 애플리케이션 코드에서 트랜잭션 범위를 줄인다. +- 트랜잭션 시간 상한(`app.persistence-jpa.transaction.write-timeout`·`read-timeout`)이 정해져 있는지 확인한다. -## Escalation +## 에스컬레이션 -- Escalate to DBA if connection pool exhaustion results +- 그 결과로 커넥션 풀이 바닥나면 DBA에 넘긴다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/db-query-canceled.md b/docs/runbooks/db-query-canceled.md index 67ae9131..641833f2 100644 --- a/docs/runbooks/db-query-canceled.md +++ b/docs/runbooks/db-query-canceled.md @@ -4,31 +4,33 @@ category: TRANSIENT_DEPENDENCY error_codes: [DB_QUERY_CANCELED] severity: P2 owner: oncall -last_updated: 2026-06-15 -status: stub +last_updated: 2026-11-07 +status: 초안 --- # Runbook: DB_QUERY_CANCELED (`runbook://db/query-canceled`) -## Symptoms +## 증상 -- HTTP 503 with `error.code=DB_QUERY_CANCELED` -- SQLState 57014; query exceeds statement timeout +- HTTP 503, `error.code=DB_QUERY_CANCELED`. +- SQLState 57014. 쿼리가 문장 시간 상한을 넘었다. -## Diagnosis +## 진단 -- Check `statement_timeout` in Postgres -- Identify slow queries in `pg_stat_statements` +- Postgres의 `statement_timeout`을 확인한다. 템플릿은 트랜잭션 시간 상한 + (`app.persistence-jpa.transaction.write-timeout`·`read-timeout`)의 남은 시간을 문장마다 넘기므로, 그 상한을 + 넘긴 문장도 이 코드로 끝난다. +- `pg_stat_statements`에서 느린 쿼리를 찾는다. -## Action +## 조치 -- Optimize slow query or add index -- Adjust statement timeout if query is legitimately long +- 느린 쿼리를 고치거나 인덱스를 더한다. +- 정말 오래 걸려야 하는 쿼리면 시간 상한을 조정한다. -## Escalation +## 에스컬레이션 -- Escalate to DBA for query optimization if recurring +- 반복되면 쿼리 최적화를 DBA에 넘긴다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/db-serialization-failure.md b/docs/runbooks/db-serialization-failure.md index eb424eb6..77d3ba61 100644 --- a/docs/runbooks/db-serialization-failure.md +++ b/docs/runbooks/db-serialization-failure.md @@ -5,30 +5,30 @@ error_codes: [DB_SERIALIZATION_FAILURE] severity: P3 owner: oncall last_updated: 2026-06-15 -status: stub +status: 초안 --- # Runbook: DB_SERIALIZATION_FAILURE (`runbook://db/serialization-failure`) -## Symptoms +## 증상 -- HTTP 409 with `error.code=DB_SERIALIZATION_FAILURE` -- SQLState 40001; high concurrent transaction contention +- HTTP 409, `error.code=DB_SERIALIZATION_FAILURE`. +- SQLState 40001. 동시 트랜잭션 경합이 심하다. -## Diagnosis +## 진단 -- Check DB transaction isolation level -- Identify hot rows / hot tables under high concurrency +- DB 트랜잭션 격리 수준을 확인한다. +- 동시성이 높은 hot row·hot table을 찾는다. -## Action +## 조치 -- Client should retry with exponential backoff (retryable=true) -- Optimize transaction scope if spike is sustained +- 클라이언트는 지수 백오프로 다시 시도한다(retryable=true). +- 급증이 이어지면 트랜잭션 범위를 줄인다. -## Escalation +## 에스컬레이션 -- Escalate to DBA if sustained serialization failure rate > 5% +- 직렬화 실패 비율이 5%를 넘는 상태가 이어지면 DBA에 넘긴다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/db-unavailable.md b/docs/runbooks/db-unavailable.md index 8b532c10..60a957ae 100644 --- a/docs/runbooks/db-unavailable.md +++ b/docs/runbooks/db-unavailable.md @@ -5,30 +5,30 @@ error_codes: [DB_UNAVAILABLE] severity: P1 owner: oncall last_updated: 2026-06-15 -status: stub +status: 초안 --- # Runbook: DB_UNAVAILABLE (`runbook://db/unavailable`) -## Symptoms +## 증상 -- HTTP 503 with `error.code=DB_UNAVAILABLE` -- SQLState 08* connection errors in logs +- HTTP 503, `error.code=DB_UNAVAILABLE`. +- 로그에 SQLState 08* 연결 오류가 있다. -## Diagnosis +## 진단 -- Check DB server health and connection pool exhaustion -- Review network connectivity from app pods to DB +- DB 서버 상태와 커넥션 풀 고갈을 확인한다. +- 앱 pod에서 DB까지 네트워크가 닿는지 확인한다. -## Action +## 조치 -- Check DB primary health; failover to replica if available -- Drain connection pool and reconnect +- DB primary 상태를 확인한다. replica가 있으면 failover한다. +- 커넥션 풀을 비우고 다시 연결한다. -## Escalation +## 에스컬레이션 -- P1: immediate if DB primary is down +- P1: DB primary가 내려갔으면 즉시. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/dependency-4xx-client.md b/docs/runbooks/dependency-4xx-client.md index 19078807..81be84b1 100644 --- a/docs/runbooks/dependency-4xx-client.md +++ b/docs/runbooks/dependency-4xx-client.md @@ -5,30 +5,30 @@ error_codes: [DEPENDENCY_4XX_CLIENT] severity: P2 owner: oncall last_updated: 2026-06-15 -status: stub +status: 초안 --- # Runbook: DEPENDENCY_4XX_CLIENT (`runbook://dependency/4xx-client`) -## Symptoms +## 증상 -- HTTP 502 with `error.code=DEPENDENCY_4XX_CLIENT` -- Upstream returned 401/403/400 — credential, scope, or request format issue +- HTTP 502, `error.code=DEPENDENCY_4XX_CLIENT`. +- 업스트림이 401·403·400을 돌려줬다. 자격 증명, scope, 요청 형식 문제다. -## Diagnosis +## 진단 -- Check upstream response body in logs for error detail -- Verify API credentials and scopes are valid +- 로그에서 업스트림 응답 본문의 오류 내용을 본다. +- API 자격 증명과 scope가 유효한지 확인한다. -## Action +## 조치 -- Rotate credentials if expired -- Fix request format if API contract changed +- 자격 증명이 만료됐으면 교체한다. +- API 계약이 바뀌었으면 요청 형식을 고친다. -## Escalation +## 에스컬레이션 -- Escalate to upstream API owner if contract change is suspected +- 계약 변경이 의심되면 업스트림 API 소유자에게 넘긴다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/dependency-5xx-server.md b/docs/runbooks/dependency-5xx-server.md index 62d8c6a3..3affac0f 100644 --- a/docs/runbooks/dependency-5xx-server.md +++ b/docs/runbooks/dependency-5xx-server.md @@ -5,30 +5,30 @@ error_codes: [DEPENDENCY_5XX_SERVER] severity: P1 owner: oncall last_updated: 2026-06-15 -status: stub +status: 초안 --- # Runbook: DEPENDENCY_5XX_SERVER (`runbook://dependency/5xx-server`) -## Symptoms +## 증상 -- HTTP 502 with `error.code=DEPENDENCY_5XX_SERVER` -- Upstream returned 5xx; transient server-side failure +- HTTP 502, `error.code=DEPENDENCY_5XX_SERVER`. +- 업스트림이 5xx를 돌려줬다. 서버 쪽 일시 장애다. -## Diagnosis +## 진단 -- Check `dependency_name` tag for which upstream is failing -- Review upstream service status page +- `dependency_name` 태그로 어느 업스트림이 실패하는지 본다. +- 업스트림 서비스의 상태 페이지를 본다. -## Action +## 조치 -- Client should retry (retryable=true) -- Monitor upstream recovery +- 클라이언트는 다시 시도한다(retryable=true). +- 업스트림 회복을 지켜본다. -## Escalation +## 에스컬레이션 -- P1 if critical upstream is in sustained 5xx state +- 중요한 업스트림이 5xx 상태로 계속 머물면 P1. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/dependency-circuit-open.md b/docs/runbooks/dependency-circuit-open.md index 9fc3e084..16111f36 100644 --- a/docs/runbooks/dependency-circuit-open.md +++ b/docs/runbooks/dependency-circuit-open.md @@ -5,30 +5,30 @@ error_codes: [DEPENDENCY_CIRCUIT_OPEN] severity: P2 owner: oncall last_updated: 2026-06-15 -status: stub +status: 초안 --- # Runbook: DEPENDENCY_CIRCUIT_OPEN (`runbook://dependency/circuit-open`) -## Symptoms +## 증상 -- HTTP 503 with `error.code=DEPENDENCY_CIRCUIT_OPEN` -- Circuit breaker (Resilience4j) in OPEN state for a dependency +- HTTP 503, `error.code=DEPENDENCY_CIRCUIT_OPEN`. +- 어떤 의존성의 circuit breaker(Resilience4j)가 OPEN 상태다. -## Diagnosis +## 진단 -- Check Resilience4j circuit breaker metrics for the dependency -- Check upstream health; circuit opens after failure threshold breached +- 그 의존성의 Resilience4j circuit breaker 메트릭을 본다. +- 업스트림 상태를 확인한다. 실패가 임계를 넘으면 circuit이 열린다. -## Action +## 조치 -- Wait for circuit half-open probe (automatic after wait duration) -- Resolve upstream issue to allow circuit to close +- circuit의 half-open 시험을 기다린다(대기 시간이 지나면 자동으로 한다). +- 업스트림 문제를 풀어 circuit이 닫히게 한다. -## Escalation +## 에스컬레이션 -- P1 if circuit remains open > 5 minutes on a critical dependency +- 중요한 의존성의 circuit이 5분 넘게 열려 있으면 P1. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/dependency-connect-failed.md b/docs/runbooks/dependency-connect-failed.md index ee8aff29..259ca94f 100644 --- a/docs/runbooks/dependency-connect-failed.md +++ b/docs/runbooks/dependency-connect-failed.md @@ -5,30 +5,30 @@ error_codes: [DEPENDENCY_CONNECT_FAILED] severity: P1 owner: oncall last_updated: 2026-06-15 -status: stub +status: 초안 --- # Runbook: DEPENDENCY_CONNECT_FAILED (`runbook://dependency/connect-failed`) -## Symptoms +## 증상 -- HTTP 503 with `error.code=DEPENDENCY_CONNECT_FAILED` -- TCP connection refused or network unreachable to upstream +- HTTP 503, `error.code=DEPENDENCY_CONNECT_FAILED`. +- 업스트림으로 TCP 연결이 거부됐거나 네트워크에 닿지 않는다. -## Diagnosis +## 진단 -- Check `dependency_name` tag for which upstream is unreachable -- Verify network path and firewall rules +- `dependency_name` 태그로 어느 업스트림에 닿지 않는지 본다. +- 네트워크 경로와 방화벽 규칙을 확인한다. -## Action +## 조치 -- Check upstream service availability -- Verify service discovery / DNS resolution +- 업스트림 서비스가 살아 있는지 확인한다. +- service discovery와 DNS 조회를 확인한다. -## Escalation +## 에스컬레이션 -- P1 if upstream is a critical service dependency +- 업스트림이 중요한 서비스 의존성이면 P1. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/dependency-dns-failed.md b/docs/runbooks/dependency-dns-failed.md index de1dd9f1..e65820d2 100644 --- a/docs/runbooks/dependency-dns-failed.md +++ b/docs/runbooks/dependency-dns-failed.md @@ -5,30 +5,30 @@ error_codes: [DEPENDENCY_DNS_FAILED] severity: P1 owner: oncall last_updated: 2026-06-15 -status: stub +status: 초안 --- # Runbook: DEPENDENCY_DNS_FAILED (`runbook://dependency/dns-failed`) -## Symptoms +## 증상 -- HTTP 503 with `error.code=DEPENDENCY_DNS_FAILED` -- DNS resolution failure for upstream hostname +- HTTP 503, `error.code=DEPENDENCY_DNS_FAILED`. +- 업스트림 호스트 이름의 DNS 조회가 실패했다. -## Diagnosis +## 진단 -- Test DNS resolution from app pod: `nslookup ` -- Check cluster DNS (CoreDNS) health +- 앱 pod에서 DNS 조회를 시험한다: `nslookup ` +- 클러스터 DNS(CoreDNS) 상태를 확인한다. -## Action +## 조치 -- Verify upstream hostname configuration -- Check CoreDNS / cluster DNS health +- 업스트림 호스트 이름 설정을 확인한다. +- CoreDNS·클러스터 DNS 상태를 확인한다. -## Escalation +## 에스컬레이션 -- P1 if cluster DNS is degraded +- 클러스터 DNS가 나빠졌으면 P1. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/dependency-timeout.md b/docs/runbooks/dependency-timeout.md index 6d5a98f6..693cc116 100644 --- a/docs/runbooks/dependency-timeout.md +++ b/docs/runbooks/dependency-timeout.md @@ -4,31 +4,32 @@ category: TRANSIENT_DEPENDENCY error_codes: [DEPENDENCY_TIMEOUT] severity: P1 owner: oncall -last_updated: 2026-06-15 -status: stub +last_updated: 2026-11-07 +status: 초안 --- # Runbook: DEPENDENCY_TIMEOUT (`runbook://dependency/timeout`) -## Symptoms +## 증상 -- HTTP 504 with `error.code=DEPENDENCY_TIMEOUT` -- Upstream service did not respond within configured timeout (default: global 10s) +- HTTP 504, `error.code=DEPENDENCY_TIMEOUT`. +- 업스트림 서비스가 설정된 시간 안에 답하지 않았다. 호출 전체의 상한은 HTTP 클라이언트 profile의 + `timeout.total-call`이다(기본값은 `docs/httpclient/configuration-reference.md`). -## Diagnosis +## 진단 -- Check `dependency_name` in log for which upstream is timing out -- Review upstream service latency metrics +- 로그의 `dependency_name`으로 어느 업스트림이 시간을 넘기는지 본다. +- 업스트림 서비스의 지연 메트릭을 본다. -## Action +## 조치 -- Check upstream service health -- Verify timeout settings match SLA expectations +- 업스트림 서비스 상태를 확인한다. +- 시간 상한 설정이 SLA 기대와 맞는지 확인한다. -## Escalation +## 에스컬레이션 -- P1 if critical upstream is timing out at scale +- 중요한 업스트림이 대규모로 시간을 넘기면 P1. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/dependency-unavailable.md b/docs/runbooks/dependency-unavailable.md index bd491f8f..a8d21080 100644 --- a/docs/runbooks/dependency-unavailable.md +++ b/docs/runbooks/dependency-unavailable.md @@ -5,7 +5,7 @@ error_codes: [DEPENDENCY_TIMEOUT, DEPENDENCY_CONNECT_FAILED, DEPENDENCY_DNS_FAIL severity: P1 owner: oncall last_updated: 2026-05-22 -status: stub +status: 초안 --- # Runbook: 외부 의존성 unavailable diff --git a/docs/runbooks/file-download-streaming-failure.md b/docs/runbooks/file-download-streaming-failure.md index c1275456..743573d6 100644 --- a/docs/runbooks/file-download-streaming-failure.md +++ b/docs/runbooks/file-download-streaming-failure.md @@ -4,31 +4,33 @@ category: TRANSIENT_DEPENDENCY error_codes: [DOWNLOAD_STREAMING_FAILURE] severity: P2 owner: oncall -last_updated: 2026-06-15 -status: stub +last_updated: 2026-11-07 +status: 초안 --- # Runbook: DOWNLOAD_STREAMING_FAILURE (`runbook://file/download-streaming-failure`) -## Symptoms +## 증상 -- HTTP 503 with `error.code=DOWNLOAD_STREAMING_FAILURE` -- Streaming response truncated; backpressure or timeout (60s / 100MB limit) +- HTTP 503, `error.code=DOWNLOAD_STREAMING_FAILURE`. +- 스트리밍 응답이 잘렸다. backpressure나 시간 초과(60초 / 100MB 한도)다. +- 지금 템플릿은 이 코드를 내지 않는다. `docs/registries/error-codes.yaml`에 이 코드의 행이 없다. 파일 서버 + 다운로드 장애는 [`docs/fileserver/operations.md`](../fileserver/operations.md)를 먼저 본다. -## Diagnosis +## 진단 -- Check streaming response timeout configuration -- Review download size vs 100MB limit +- 스트리밍 응답 시간 상한 설정을 확인한다. +- 다운로드 크기를 100MB 한도와 비교한다. -## Action +## 조치 -- Verify storage backend is reachable -- Check for network congestion on download path +- 저장소 백엔드에 닿는지 확인한다. +- 다운로드 경로의 네트워크 혼잡을 확인한다. -## Escalation +## 에스컬레이션 -- Escalate to infra if storage backend is degraded +- 저장소 백엔드가 나빠졌으면 인프라 팀에 넘긴다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/grpc-advanced-capabilities.md b/docs/runbooks/grpc-advanced-capabilities.md index bc3a50d3..1382eade 100644 --- a/docs/runbooks/grpc-advanced-capabilities.md +++ b/docs/runbooks/grpc-advanced-capabilities.md @@ -1,94 +1,88 @@ # Runbook: gRPC advanced capabilities -Scope: the `:grpc-advanced:*` family. Everything here is off by default and stays off until a -deployment names it. Nothing in this family ships in a runtime composition today. +범위: `:grpc-advanced:*` family. 여기 있는 것은 모두 기본으로 꺼져 있고, 배포가 이름을 대기 전까지 꺼진 채로 +있다. 지금 이 family의 어떤 것도 런타임 조립에 들어가지 않는다. -Flags are `app.grpc.advanced..enabled`. `GrpcAdvancedCapability` owns the list of -capability names; `GrpcAdvancedSupportMatrix` owns their current grades. +스위치는 `app.grpc.advanced..enabled`다. capability 이름 목록과 기본 등급은 +`GrpcAdvancedCapability`(`defaultGrade()`)가 가진다. 근거가 있는 배포는 `GrpcAdvancedFeatureFlags.withGrade`로 +등급을 바꾼다. --- -## A capability refuses to start +## capability가 뜨기를 거부한다 -`GrpcAdvancedModuleGuard` gives three different refusals, and the remedy differs: +`GrpcAdvancedModuleGuard`는 세 가지로 거부하고, 고치는 법이 다르다. -| Message contains | Meaning | Remedy | +| 메시지에 있는 말 | 뜻 | 고치는 법 | | --- | --- | --- | -| "its feature flag is not set" | Nobody enabled it | Set the property named in the message | -| "tracked rather than implemented" | Grade is `WATCH` | Nothing to do here; the capability is not implemented | -| "uncharacterised failure modes" | Grade is `EXPERIMENTAL` and this is production | Record a production approval, or run it outside production | +| "its feature flag is not set" | 아무도 켜지 않았다 | 메시지가 이름 댄 속성을 설정한다 | +| "tracked rather than implemented" | 등급이 `WATCH`다 | 여기서 할 일은 없다. 그 capability는 구현되지 않았다 | +| "uncharacterised failure modes" | 등급이 `EXPERIMENTAL`이고 여기는 운영이다 | 운영 승인을 기록하거나, 운영 밖에서 돌린다 | -The refusal message always names the property key, so the first case is a configuration line rather -than a support question. +거부 메시지는 늘 속성 키를 이름 댄다. 그래서 첫 경우는 지원 문의가 아니라 설정 한 줄이다. --- -## xDS: the control plane went away +## xDS: control plane이 사라졌다 -**What you are seeing.** The control plane is unreachable and clients are still routing. +**보이는 것.** control plane에 닿지 않는데 클라이언트는 아직 라우팅한다. -**What it means.** `GrpcXdsFailurePolicy` serves the last-known-good snapshot, up to its staleness -bound. +**뜻.** `GrpcXdsFailurePolicy`가 마지막으로 정상이던 snapshot을 오래됨 상한까지 내준다. -**What to do.** +**할 일.** -1. Check the snapshot's age. `SERVE_LAST_KNOWN_GOOD` is the healthy degraded state. -2. `STALE_BEYOND_BOUND` means the snapshot is older than the policy allows and is no longer trusted. - Beyond that bound, a decommissioned backend would otherwise keep receiving traffic indefinitely. -3. `NO_SNAPSHOT_YET` on a starting instance means it never reached the control plane. It fails after - the initial fetch timeout rather than starting with no routing. +1. snapshot의 나이를 본다. `SERVE_LAST_KNOWN_GOOD`는 정상적인 degraded 상태다. +2. `STALE_BEYOND_BOUND`는 snapshot이 정책이 허용하는 것보다 오래돼서 더는 믿지 않는다는 뜻이다. 그 상한이 + 없으면 내린 backend가 트래픽을 끝없이 받는다. +3. 뜨는 인스턴스의 `NO_SNAPSHOT_YET`은 control plane에 한 번도 닿지 못했다는 뜻이다. 라우팅 없이 뜨지 않고, 첫 + fetch 시간 상한이 지나면 실패한다. -**Do not** add application-level retry policy while xDS is enabled. `GrpcXdsProfile` refuses an -`APPLICATION` retry owner, because retry defined in two places has a winner that depends on -resolution order rather than on a decision. +xDS가 켜진 동안 애플리케이션 수준의 재시도 정책을 **더하지 않는다**. `GrpcXdsProfile`이 `APPLICATION` 재시도 +소유자를 거부한다. 두 곳에 정의한 재시도는 결정이 아니라 해석 순서가 이기는 쪽을 정하기 때문이다. --- -## gRPC-Web: a browser call hangs and then fails with no status +## gRPC-Web: 브라우저 호출이 멈췄다가 상태 없이 실패한다 -**Almost always the proxy.** A gRPC status arrives as a trailer, and a browser cannot read a trailer -the proxy did not expose. Check that the proxy's CORS `expose_headers` includes `grpc-status` and -`grpc-message`; `GrpcWebProxyContract.violations` reports exactly this, and the reference -configuration in `envoy/envoy.yaml` shows it in place. +**거의 언제나 proxy다.** gRPC 상태는 trailer로 오고, 브라우저는 proxy가 노출하지 않은 trailer를 읽지 못한다. +proxy의 CORS `expose_headers`에 `grpc-status`와 `grpc-message`가 있는지 확인한다. +`GrpcWebProxyContract.violations`가 정확히 이것을 보고하고, 참조 설정 +`src/platforms/grpc-advanced/grpc-advanced-compat/src/test/resources/envoy/envoy.yaml`에 그것이 들어 있다. -**If the method is client- or bidirectional-streaming**, it cannot work over gRPC-Web at all — a -browser has no way to send a stream of messages. `GrpcWebRpcSupport.require` refuses such a method. +**메서드가 client streaming이나 bidirectional streaming이면** gRPC-Web으로는 아예 되지 않는다. 브라우저는 +메시지 stream을 보낼 방법이 없다. `GrpcWebRpcSupport.require`가 그런 메서드를 거부한다. --- -## Servlet: a transport setting appears to be ignored +## Servlet: 전송 설정이 무시되는 것 같다 -It is ignored. The container owns the socket, so keepalive tuning, maximum connection age and -flow-control window tuning belong to it. This repository has no Servlet transport code that would -refuse them, so configure them on the container. +무시된다. 소켓은 컨테이너가 가지므로 keepalive 조정, 최대 연결 수명, flow-control window 조정은 컨테이너의 +몫이다. 이 저장소에는 그것을 거부할 Servlet 전송 코드가 없으니 컨테이너에서 설정한다. -A Servlet run never substitutes for Netty certification. +Servlet 실행은 Netty 인증을 대신하지 않는다. --- -## Hedging: backend load doubled +## Hedging: backend 부하가 두 배가 됐다 -**Expected, within a bound.** Hedging trades duplicate load for tail latency. -`GrpcHedgingResult` records both `duplicateBackendCalls` and `cancelledLoserAttempts`; a dashboard -showing only the latency improvement makes the trade look free. +**상한 안이면 예상한 일이다.** hedging은 중복 부하를 내고 꼬리 지연을 줄인다. `GrpcHedgingResult`는 +`duplicateBackendCalls`와 `cancelledLoserAttempts`를 둘 다 기록한다. 지연 개선만 보여 주는 대시보드는 그 교환을 +공짜처럼 보이게 한다. -**What to check.** `GrpcHedgingBudget` caps hedges as a fraction of completed calls. If duplicate -load is above that fraction, the budget is not being consumed — which means something is issuing -hedges outside the coordinator. +**확인할 것.** `GrpcHedgingBudget`은 hedge를 끝난 호출의 비율로 제한한다. 중복 부하가 그 비율을 넘으면 예산이 +쓰이지 않고 있다는 뜻이다. coordinator 밖에서 무언가가 hedge를 보내고 있다. -**Hedging is refused** for anything but a read-only unary method. A hedged mutation runs twice by -design, and an idempotency key does not help: the second attempt duplicates a success in progress -rather than retrying a failure. +읽기 전용 unary 메서드가 아니면 **hedging을 거부한다**. hedge된 변경은 설계상 두 번 돈다. 멱등 키도 소용없다. +두 번째 시도는 실패를 다시 시도하는 것이 아니라 진행 중인 성공을 중복한다. --- -## Promoting a capability +## capability 승격 -Promotion to `ADVANCED_STABLE` needs compatibility evidence, a security review, fault evidence, -performance evidence, an ADR, a runbook, a real-environment test and seven days of soak. A Stable -default needs thirty. Promotions are independent: promoting one capability changes no other's -grade. This is a review checklist; the in-code `GrpcAdvancedPromotionGate` that restated it was -removed (review 2026-09-24 S5-lead-4) because nothing but its own test called it. +`ADVANCED_STABLE`로 올리려면 호환성 증거, 보안 리뷰, 장애 증거, 성능 증거, ADR, runbook, 실제 환경 시험, 7일 +soak이 필요하다. Stable 기본값은 30일이 필요하다. 승격은 서로 독립이다. 한 capability를 올려도 다른 것의 등급은 +바뀌지 않는다. 이것은 리뷰 점검 목록이다. 이것을 코드로 다시 적은 `GrpcAdvancedPromotionGate`는 자기 테스트 +말고는 부르는 곳이 없어 지웠다(리뷰 2026-09-24 S5-lead-4). -Before citing a suite as evidence, check that it ran against the real infrastructure it needs (proxy, -container, control plane or toolchain). A suite that ran without it passed and established nothing. +어떤 suite를 증거로 들기 전에, 그 suite가 필요한 실제 인프라(proxy, 컨테이너, control plane, toolchain)에 대고 +돌았는지 확인한다. 인프라 없이 돈 suite는 통과했지만 아무것도 증명하지 않았다. diff --git a/docs/runbooks/grpc-platform-operations.md b/docs/runbooks/grpc-platform-operations.md index aa896ec7..44f2bf31 100644 --- a/docs/runbooks/grpc-platform-operations.md +++ b/docs/runbooks/grpc-platform-operations.md @@ -1,179 +1,160 @@ # Runbook: gRPC platform operations -Scope: the `:grpc:*` family. All of it is build-only today — every leaf's `runtime_memberships` is -empty — so nothing here fires in production yet. It is written now because the states it covers are -the ones an on-call cannot work out from first principles at three in the morning, and shipping the -behaviour before the runbook means the first person to meet one is doing that. +범위: `:grpc:*` family. 지금은 모두 빌드만 된다. registry에서 이 family의 leaf는 모두 `"build": "optional-grpc"` +(주 빌드 밖, `-p platforms/optional-build`로 돈다)이고 어느 조립에도 들어가지 않으므로, 여기 있는 것은 아직 운영에서 +일어나지 않는다. 그래도 지금 쓰는 이유가 있다. 여기서 다루는 상태는 당번이 새벽 세 시에 처음부터 따져서는 알아낼 +수 없는 것들이고, runbook보다 동작을 먼저 내보내면 그것을 처음 만난 사람이 그 따지기를 하게 된다. -Configuration lives under `app.grpc.platform.*` and is bound by `GrpcPlatformProperties`. -The platform does not start unless `app.grpc.platform.enabled=true`. +설정은 `app.grpc.platform.*` 아래에 있고 `GrpcPlatformProperties`가 묶는다. 플랫폼은 +`app.grpc.platform.enabled=true`가 아니면 뜨지 않는다. --- -## COMPLETION_UNKNOWN on a mutation +## 상태를 바꾸는 호출의 COMPLETION_UNKNOWN -**What you are seeing.** A client received `DEADLINE_EXCEEDED`, `UNAVAILABLE` or `INTERNAL` on a -state-changing call, and the response trailer `completion-outcome` reads `COMPLETION_UNKNOWN`. +**보이는 것.** 클라이언트가 상태를 바꾸는 호출에서 `DEADLINE_EXCEEDED`, `UNAVAILABLE`, `INTERNAL`을 받았고, 응답 +trailer `completion-outcome`이 `COMPLETION_UNKNOWN`이다. -**What it means.** The server may have committed. This is not a failure and not a success; the status -code cannot distinguish them, which is why the outcome is carried separately. +**뜻.** 서버가 커밋했을 수 있다. 실패도 성공도 아니다. 상태 코드로는 둘을 가릴 수 없어서 결과를 따로 싣는다. -**What not to do.** Do not re-issue the call. Do not tell the caller it failed. Both are wrong half -the time, and which half is not knowable from the status. +**하지 말 것.** 호출을 다시 보내지 않는다. 호출자에게 실패했다고 말하지 않는다. 둘 다 절반은 틀리고, 어느 절반인지 +상태 코드로는 알 수 없다. -**What to do.** +**할 일.** -1. Take the `error-execution-id` from the trailers. It is the only link between what the client saw - and what the server did. -2. If the method is `IDEMPOTENCY_KEY_REQUIRED`, query the operation ledger with the caller - fingerprint, the full method name and the caller's key. `GrpcOperationStatusQuery` returns one of - `IN_PROGRESS`, `COMMITTED`, `FAILED_TERMINAL`, `NOT_FOUND` or `UNKNOWN`. -3. `COMMITTED` means return the stored outcome reference, not a freshly computed answer — the resource - may have changed since, and a new answer would describe the state at reconciliation time rather - than the state the caller's own call produced. -4. `NOT_FOUND` means the operation never started and is safe to re-issue. `FAILED_TERMINAL` means the - same. -5. `UNKNOWN` means the ledger could not be consulted. Nothing may be concluded. The case is queued by - `GrpcCompletionReconciler` and retried later. -6. If the method is not keyed, there is no ledger row. Resolve it against the business resource, or - escalate to the service owner. This is the case the keyed profile exists to avoid. +1. trailer에서 `error-execution-id`를 꺼낸다. 클라이언트가 본 것과 서버가 한 것을 잇는 유일한 고리다. +2. 메서드가 `IDEMPOTENCY_KEY_REQUIRED`면 호출자 fingerprint, 전체 메서드 이름, 호출자의 키로 operation ledger를 + 조회한다. `GrpcOperationStatusQuery`는 `IN_PROGRESS`, `COMMITTED`, `FAILED_TERMINAL`, `NOT_FOUND`, `UNKNOWN` + 중 하나를 돌려준다. +3. `COMMITTED`면 새로 계산한 답이 아니라 저장된 결과 참조를 돌려준다. 그 뒤에 자원이 바뀌었을 수 있고, 새 답은 + 호출자 자신의 호출이 만든 상태가 아니라 맞춰 보는 시점의 상태를 설명한다. +4. `NOT_FOUND`는 operation이 시작하지 않았다는 뜻이라 다시 보내도 안전하다. `FAILED_TERMINAL`도 같다. +5. `UNKNOWN`은 ledger를 조회하지 못했다는 뜻이다. 아무것도 결론 낼 수 없다. `GrpcCompletionReconciler`가 그 + 건을 대기열에 넣고 나중에 다시 시도한다. +6. 메서드에 키가 없으면 ledger 행이 없다. 업무 자원으로 맞춰 보거나 서비스 소유자에게 넘긴다. 키 있는 profile은 + 이 경우를 피하려고 있다. -7. `IN_PROGRESS` means a claim exists and has not finished. If its owner died, the claim is not - stuck forever: once it is older than the claim TTL (`app.grpc.platform.operation-ledger-claim-ttl`, - default 5m), the next retry of the same request takes it over and runs again, - and a later reconciler pass sees that attempt's `COMMITTED` or `FAILED_TERMINAL`. Until a retry - arrives, the case stays pending. The re-run is safe only when the ledger commit is recorded in the - mutation's own transaction; if this service commits them separately, check the business resource - before letting the retry through. An owner that was only slow cannot spoil the takeover: its claim - attempt (`claim_attempt`) is behind, so its late commit is refused and its late failure ignored. - A log line saying an operation "is no longer held by attempt N" is that refusal, not an outage. +7. `IN_PROGRESS`는 claim이 있고 끝나지 않았다는 뜻이다. 그 소유자가 죽었어도 claim이 영원히 묶이지는 않는다. + claim TTL(`app.grpc.platform.operation-ledger-claim-ttl`, 기본 5m)보다 오래되면, 같은 요청의 다음 재시도가 + 그것을 넘겨받아 다시 돌리고, 뒤의 reconciler 단계가 그 시도의 `COMMITTED`나 `FAILED_TERMINAL`을 본다. + 재시도가 오기 전까지 그 건은 대기로 남는다. 다시 돌리는 것은 ledger 커밋이 변경 자신의 트랜잭션 안에서 기록될 + 때만 안전하다. 이 서비스가 둘을 따로 커밋하면 재시도를 들이기 전에 업무 자원을 확인한다. 느리기만 했던 + 소유자는 넘겨받기를 망치지 못한다. 그 claim 시도(`claim_attempt`)가 뒤처졌으므로 늦은 커밋은 거부되고 늦은 + 실패는 무시된다. operation이 "is no longer held by attempt N"이라는 로그 줄이 그 거부다. 장애가 아니다. -**Escalate when** the reconciler's pending list grows across passes. That means the ledger is -unreachable rather than slow. A case pending as `IN_PROGRESS` for longer than the claim TTL with no -retry arriving is a caller that gave up; it needs the business resource checked, not a ledger fix. +**넘길 때는** reconciler의 대기 목록이 단계를 거듭하며 커질 때다. ledger가 느린 게 아니라 닿지 않는다는 뜻이다. +claim TTL보다 오래 `IN_PROGRESS`로 대기 중인데 재시도가 오지 않는 건은 호출자가 포기한 것이다. ledger를 고칠 일이 +아니라 업무 자원을 확인할 일이다. --- -## The operation ledger table keeps growing +## operation ledger 테이블이 계속 커진다 -**What you are seeing.** `grpc_operation_ledger` grows without bound, or a retry of an old key runs -the mutation again instead of replaying. +**보이는 것.** `grpc_operation_ledger`가 끝없이 커지거나, 오래된 키의 재시도가 replay 대신 변경을 다시 돌린다. -**What it means.** Finished rows (`COMMITTED`, `FAILED_TERMINAL`) are deleted only when something -calls `GrpcOperationLedgerRetention.purgeExpired(now)`; the starter assembles that bean -(`app.grpc.platform.operation-ledger-enabled=true`) but does not schedule it. A growing table means -the service's scheduler is not calling it. A retry that re-ran after the retention -(`app.grpc.platform.operation-ledger-retention`, default 24h) is the trade the retention makes: its -record was purged, so it was a new operation. +**뜻.** 끝난 행(`COMMITTED`, `FAILED_TERMINAL`)은 누군가 `GrpcOperationLedgerRetention.purgeExpired(now)`를 불러야만 +지워진다. starter는 그 bean을 조립하지만(`app.grpc.platform.operation-ledger-enabled=true`) 일정을 걸지는 않는다. +테이블이 커지면 서비스의 scheduler가 그것을 부르지 않는 것이다. 보존 기간 +(`app.grpc.platform.operation-ledger-retention`, 기본 24h)이 지난 뒤 다시 돈 재시도는 보존 기간이 감수하는 +교환이다. 기록이 지워졌으므로 새 operation이었다. -**What to do.** +**할 일.** -1. Check that the service schedules `purgeExpired`. Each call deletes in batches of 500 until a batch - comes back short, never touching `IN_PROGRESS` rows. -2. For a large backlog, call it repeatedly; each batch is a short transaction that skips rows another - transaction holds. -3. If retried keys re-run after the retention, raise the retention above the callers' retry window - rather than skipping the purge. +1. 서비스가 `purgeExpired`에 일정을 걸었는지 확인한다. 한 번 부르면 500행씩 지우다가 덜 찬 묶음이 나오면 멈추고, + `IN_PROGRESS` 행은 건드리지 않는다. +2. 밀린 양이 많으면 여러 번 부른다. 묶음마다 짧은 트랜잭션이고, 다른 트랜잭션이 쥔 행은 건너뛴다. +3. 다시 보낸 키가 보존 기간 뒤에 다시 돌면, purge를 건너뛰지 말고 보존 기간을 호출자의 재시도 창보다 길게 한다. -**Escalate when** old `IN_PROGRESS` rows accumulate. Those are not purged by design; each is an -abandoned claim no retry has taken over (see `IN_PROGRESS` above). +**넘길 때는** 오래된 `IN_PROGRESS` 행이 쌓일 때다. 그 행은 설계상 지워지지 않는다. 하나하나가 어느 재시도도 +넘겨받지 않은 버려진 claim이다(위의 `IN_PROGRESS`). --- -## A stream ended with FULL_RESYNC_REQUIRED +## stream이 FULL_RESYNC_REQUIRED로 끝났다 -**What you are seeing.** A client's resume was refused and it was told to resynchronise. +**보이는 것.** 클라이언트의 resume이 거부되고 다시 동기화하라는 답을 받았다. -**What it means.** The server can no longer replay from the client's cursor. Either the snapshot -version moved, or the cursor predates retained history. +**뜻.** 서버가 클라이언트의 cursor부터 더는 replay할 수 없다. snapshot 버전이 움직였거나, cursor가 보존된 이력보다 +앞선다. -**What to do.** Nothing on the server. The client is expected to discard its position and start a new -stream from a fresh snapshot. A client that instead retries the same token will keep receiving the -same answer. +**할 일.** 서버에서는 없다. 클라이언트가 자기 위치를 버리고 새 snapshot에서 새 stream을 시작해야 한다. 대신 같은 +token으로 다시 시도하는 클라이언트는 같은 답을 계속 받는다. -**Escalate when** it is happening to many clients at once. That usually means history retention was -reduced, or snapshots are rotating faster than clients reconnect. +**넘길 때는** 많은 클라이언트에 한꺼번에 일어날 때다. 보통 이력 보존이 줄었거나, 클라이언트가 다시 붙는 것보다 +snapshot이 빨리 돈다는 뜻이다. --- -## A stream ended with SLOW_CONSUMER +## stream이 SLOW_CONSUMER로 끝났다 -**What you are seeing.** Streams terminating with `SLOW_CONSUMER`, and -`grpc.stream.flow_control_stalls` rising. +**보이는 것.** stream이 `SLOW_CONSUMER`로 끝나고 `grpc.stream.flow_control_stalls`가 오른다. -**What it means.** The consumer could not keep up with the bounded queue. The stream was terminated -rather than silently dropping messages, because a client cannot detect drops — the sequence numbers -it sees are the ones it was sent. +**뜻.** 소비자가 상한 있는 큐를 따라가지 못했다. 메시지를 조용히 버리는 대신 stream을 끝냈다. 클라이언트는 버려진 +것을 알아챌 수 없다. 클라이언트가 보는 순번은 보내진 것뿐이다. -**What to do.** +**할 일.** -1. Check whether the consumer is slow or the producer is fast. `grpc.stream.messages` against - `grpc.stream.lifetime` tells you the rate. -2. If the consumer is slow, the fix is on the consumer. Raising the queue bound moves the failure - later and makes it larger. -3. A resume is not available after this ending: the messages that overflowed the queue are gone, so - continuing from the last delivered sequence would silently skip them. The client resynchronises. +1. 소비자가 느린지 생산자가 빠른지 확인한다. `grpc.stream.messages`를 `grpc.stream.lifetime`과 견주면 속도가 + 나온다. +2. 소비자가 느리면 고칠 곳은 소비자다. 큐 상한을 올리면 실패가 뒤로 밀리고 커질 뿐이다. +3. 이렇게 끝난 뒤에는 resume을 쓸 수 없다. 큐를 넘친 메시지는 사라졌으므로, 마지막으로 전달한 순번부터 이어 가면 + 그것을 조용히 건너뛴다. 클라이언트는 다시 동기화한다. --- -## RESOURCE_EXHAUSTED under load +## 부하에서 RESOURCE_EXHAUSTED -**What you are seeing.** Calls refused with `RESOURCE_EXHAUSTED` and `GrpcAdmissionController` -reporting rejections. +**보이는 것.** 호출이 `RESOURCE_EXHAUSTED`로 거부되고 `GrpcAdmissionController`가 거부를 보고한다. -**What it means.** The server is at its concurrency and queue bounds and is shedding rather than -queueing. This is the designed behaviour: accepting work whose callers have already given up spends -capacity on nothing. +**뜻.** 서버가 동시성과 큐 상한에 닿아서 줄을 세우지 않고 덜어 낸다. 설계한 동작이다. 호출자가 이미 포기한 일을 +받으면 아무것도 아닌 데 용량을 쓴다. -**What to do.** +**할 일.** -1. Read `grpc.rpc.duration` and `grpc.rpc.queue_wait` separately. Queue time rising with duration flat - means the bottleneck is admission, not the work. -2. Check which saturation counter is moving — executor, channel or flow control. They look identical - in a latency graph and have different fixes. -3. Raising `app.grpc.platform.executor-queue-capacity` defers the problem; it does not remove - it. `GrpcExecutorProfile` refuses a queue above ten thousand for that reason. +1. `grpc.rpc.duration`과 `grpc.rpc.queue_wait`를 따로 읽는다. duration은 그대로인데 큐 시간이 오르면 병목은 일이 + 아니라 admission이다. +2. 어느 포화 counter가 움직이는지 확인한다. executor, channel, flow control이다. 지연 그래프에서는 똑같이 보이지만 + 고치는 법이 다르다. +3. `app.grpc.platform.executor-queue-capacity`를 올리면 문제를 미룰 뿐 없애지 않는다. 그래서 `GrpcExecutorProfile`이 + 1만이 넘는 큐를 거부한다. --- -## A rollout is producing errors at every deploy +## 배포할 때마다 rollout이 오류를 낸다 -**What you are seeing.** A burst of `UNAVAILABLE` or `CANCELLED` each time an instance goes away. +**보이는 것.** 인스턴스가 빠질 때마다 `UNAVAILABLE`이나 `CANCELLED`가 몰린다. -**What it means.** The drain sequence is not completing, or is running out of order. +**뜻.** drain 순서가 끝나지 않거나, 순서가 어긋나서 돈다. -**What to do.** +**할 일.** -1. `GrpcDrainResult` records what each drain achieved: completed and cancelled unary calls, signalled - and cancelled streams, and which phases ran. A drain that routinely force-cancels is the cause. -2. The order matters. Readiness flips first and nothing is refused during that window, because there - is a gap between an instance reporting unready and routing acting on it. Refusing during that gap - turns a clean rollout into a burst of errors at every deploy. -3. For long streams, check the Kubernetes profile's `streamReconnectBudget` and - `readinessDrainGrace`. A stream is pinned to one pod for its whole life, so every rollout ends it; - a profile with long streams and no reconnect budget has not decided what clients do next. +1. `GrpcDrainResult`가 각 drain이 해낸 것을 기록한다. 끝난 unary 호출과 취소된 unary 호출, 신호를 받은 stream과 + 취소된 stream, 돈 단계다. 늘 강제 취소하는 drain이 원인이다. +2. 순서가 중요하다. readiness가 먼저 뒤집히고, 그 사이에는 아무것도 거부하지 않는다. 인스턴스가 unready를 보고한 + 뒤 라우팅이 그것을 따르기까지 틈이 있기 때문이다. 그 틈에 거부하면 깨끗한 rollout이 배포마다 오류 묶음이 된다. +3. 긴 stream이면 Kubernetes profile의 `streamReconnectBudget`과 `readinessDrainGrace`를 확인한다. stream은 일생 + 내내 한 pod에 묶이므로 rollout마다 끝난다. 긴 stream이 있는데 다시 붙는 예산이 없는 profile은 클라이언트가 다음에 + 할 일을 정하지 않은 것이다. --- -## Verifying a deployment's configuration +## 배포의 설정 확인 -`GrpcPlatformSnapshotService` produces a secret-free snapshot for a caller on the admin network -holding an admin role. Both gates are required. +`GrpcPlatformSnapshotService`는 관리 네트워크에 있고 관리 역할을 가진 호출자에게 secret 없는 snapshot을 만든다. +두 관문이 모두 필요하다. -`GrpcPlatformSnapshotService.driftAgainstRelease` compares a running snapshot with the release -manifest and reports schema version, method policy hash and per-channel profile differences. An -instance running a configuration the release did not ship is behind a whole class of incidents that -are otherwise diagnosed by reading logs. +`GrpcPlatformSnapshotService.driftAgainstRelease`는 실행 중인 snapshot을 릴리스 manifest와 비교해 스키마 버전, +메서드 정책 해시, channel별 profile 차이를 보고한다. 릴리스가 내보내지 않은 설정으로 도는 인스턴스는, 그렇지 않으면 +로그를 읽어야만 진단되는 장애 한 부류의 원인이다. -The snapshot carries hashes and names only. A field whose name looks like a credential is refused at -construction rather than redacted. +snapshot에는 해시와 이름만 실린다. 자격 증명처럼 보이는 이름의 칸은 가리지 않고 만들 때 거부한다. --- -## Things that are deliberately off +## 일부러 꺼 둔 것 -- **Reflection in production.** `GrpcReflectionMode.defaultFor` returns `DISABLED` for `STAGE` and - `PROD`. Reflection publishes the whole schema to anyone who can open a connection. -- **Every advanced capability.** See `docs/runbooks/grpc-advanced-capabilities.md`. -- **The platform itself.** `app.grpc.platform.enabled` defaults to false, and every `:grpc:*` - leaf is build-only in the registry. +- **운영의 reflection.** `GrpcReflectionMode.defaultFor`는 `STAGE`와 `PROD`에 `DISABLED`를 돌려준다. reflection은 + 연결을 열 수 있는 누구에게나 스키마 전체를 공개한다. +- **모든 advanced capability.** `docs/runbooks/grpc-advanced-capabilities.md`를 본다. +- **플랫폼 자체.** `app.grpc.platform.enabled`의 기본값은 false이고, registry에서 모든 `:grpc:*` leaf는 + `"build": "optional-grpc"`라 기본 조립에 들어가지 않는다. diff --git a/docs/runbooks/idempotency-unavailable.md b/docs/runbooks/idempotency-unavailable.md index 8afacfac..72da6af8 100644 --- a/docs/runbooks/idempotency-unavailable.md +++ b/docs/runbooks/idempotency-unavailable.md @@ -4,68 +4,58 @@ category: TRANSIENT_DEPENDENCY error_codes: [IDEMPOTENCY_UNAVAILABLE, IDEMPOTENCY_COMPLETION_UNKNOWN, IDEMPOTENCY_RECOVERY_REQUIRED] severity: P2 owner: oncall -last_updated: 2026-11-05 -status: active +last_updated: 2026-11-07 +status: 운영 --- # Runbook: IDEMPOTENCY_UNAVAILABLE (`runbook://idempotency/unavailable`) -## Symptoms +## 증상 -- HTTP 503 (`error.code=IDEMPOTENCY_UNAVAILABLE`, `retryable=true`) on endpoints that take an - `Idempotency-Key`; the same code on the gRPC `error-code` trailer (`UNAVAILABLE`). -- `IdempotencyExecutor` refused to run the action because the replay store (JPA or Redis, whichever - `app.idempotency` selects) did not answer. Nothing was executed: the refusal happens before the - action, so a client retry is safe. -- The same 503 when the store refused to start a claim whose processing lease had already run out - — the request spent longer than the lease between its claim and the start of its action (a - stalled process, a slow store call). The ERROR line, `failure classified as - IDEMPOTENCY_UNAVAILABLE (…)`, has the exception attached, and the exception's message reads `the - claim's processing lease ran out before the action started; nothing ran: ` — in prod JSON - logs that is in `stack_trace`, not `message`. The store may be healthy. - Nothing ran here either, and the next request with the key takes the claim over and runs it. -- HTTP 503 `IDEMPOTENCY_COMPLETION_UNKNOWN` (`retryable=true`) is the same outage hitting after the - action ran: the store did not answer while the result was being recorded. When the use case called - the executor inside its write transaction, that transaction's database writes rolled back with the - exception; an action that committed a transaction of its own kept its writes, and anything outside - a transaction (an outbound call, a message) may have happened. This is not "nothing was executed". - Clients resend with the same key. -- HTTP 500 `IDEMPOTENCY_RECOVERY_REQUIRED` (`retryable=false`) means the opposite case: the store - cannot tell whether an earlier attempt's effect already happened. Two records produce it: - - `ABANDONED`: the action threw, or reported its effect unknown. Final until the record expires. - - `EXECUTING` past its processing lease (`APP_IDEMPOTENCY_PROCESSING_LEASE`, 30s): the attempt - crashed, or is still running longer than the lease. The executor never renews the lease, so a - slow but healthy request lands here too. The server never runs it again and does not touch the - record. If the attempt is still running and finishes, its result is recorded, the first request - gets its normal answer, and later requests with the key get that result replayed; a failure it - reports is recorded the same way. So this 500 can stop on its own (owner decision 2026-11-04). - This is the Redis store's case. The PostgreSQL store, called inside the use case's write - transaction as the template calls it, never shows another request an unfinished record: that - request waits for the first transaction to end, and gets the replay if it committed or a fresh - run if it rolled back (`docs/web/http-contract.md` §2). +- `Idempotency-Key`를 받는 엔드포인트에서 HTTP 503(`error.code=IDEMPOTENCY_UNAVAILABLE`, `retryable=true`). + gRPC는 `error-code` trailer에 같은 코드가 온다(`UNAVAILABLE`). +- replay 저장소(`app.idempotency`가 고른 JPA나 Redis)가 답하지 않아서 `IdempotencyExecutor`가 action 실행을 + 거절했다. 아무것도 실행되지 않았다. 거절은 action 전에 일어나므로 클라이언트가 다시 시도해도 안전하다. +- 처리 lease가 이미 끝난 claim을 저장소가 시작하지 않을 때도 같은 503이다. 요청이 claim과 action 시작 사이에 + lease보다 오래 걸렸다(멈춘 프로세스, 느린 저장소 호출). ERROR 줄 `failure classified as + IDEMPOTENCY_UNAVAILABLE (…)`에 예외가 붙고, 예외 메시지는 `the claim's processing lease ran out before the + action started; nothing ran: `다. prod JSON 로그에서는 `message`가 아니라 `stack_trace`에 있다. + 저장소는 멀쩡할 수 있다. 이때도 아무것도 실행되지 않았고, 그 키로 오는 다음 요청이 claim을 넘겨받아 실행한다. +- HTTP 503 `IDEMPOTENCY_COMPLETION_UNKNOWN`(`retryable=true`)은 같은 장애가 action이 실행된 뒤에 닥친 것이다. + 결과를 기록하는 동안 저장소가 답하지 않았다. use case가 자기 쓰기 트랜잭션 안에서 executor를 불렀으면, 그 + 트랜잭션의 DB 쓰기는 예외와 함께 롤백됐다. 자기 트랜잭션을 따로 커밋한 action은 쓰기가 남았고, 트랜잭션 밖의 + 일(외부 호출, 메시지)은 일어났을 수 있다. 「아무것도 실행되지 않았다」가 아니다. 클라이언트는 같은 키로 다시 + 보낸다. +- HTTP 500 `IDEMPOTENCY_RECOVERY_REQUIRED`(`retryable=false`)는 반대 경우다. 앞선 시도의 효과가 이미 일어났는지 + 저장소가 가릴 수 없다. 두 기록이 이 코드를 낸다. + - `ABANDONED`: action이 예외를 던졌거나 효과를 모른다고 보고했다. 기록이 만료될 때까지 바뀌지 않는다. + - 처리 lease(`APP_IDEMPOTENCY_PROCESSING_LEASE`, 30s)가 지난 `EXECUTING`: 시도가 죽었거나, lease보다 오래 아직 + 돌고 있다. executor는 lease를 늘리지 않으므로 느리지만 멀쩡한 요청도 여기에 온다. 서버는 그 요청을 다시 + 실행하지 않고 기록도 건드리지 않는다. 시도가 아직 돌다가 끝나면 그 결과가 기록되고, 첫 요청은 보통의 응답을 + 받고, 그 키로 오는 뒤의 요청은 그 결과를 replay로 받는다. 시도가 보고한 실패도 같은 식으로 기록된다. 그래서 + 이 500은 저절로 멈출 수 있다(소유자 결정 2026-11-04). + 이것은 Redis 저장소의 경우다. PostgreSQL 저장소는 템플릿이 부르는 대로 use case의 쓰기 트랜잭션 안에서 + 불리면, 끝나지 않은 기록을 다른 요청에 보이지 않는다. 그 요청은 첫 트랜잭션이 끝나기를 기다렸다가, 커밋됐으면 + replay를, 롤백됐으면 새 실행을 받는다(`docs/web/http-contract.md` §2). -## Diagnosis +## 진단 -- Check the health of the idempotency store the service uses (`/actuator/health` component of the - JPA datasource or Redis, depending on the selected provider). -- Look for connection-pool saturation or timeouts on that store in the same time window; the - executor reports saturation as unavailable rather than guessing. -- For `IDEMPOTENCY_RECOVERY_REQUIRED`, find the scope in the server's ERROR log of the failed request. - Every transport writes the same line, `failure classified as IDEMPOTENCY_RECOVERY_REQUIRED - (category=DATA_INTEGRITY, retryable=false)`, with the exception attached - (shared-contract `ServerFailureLog`), and adds its own correlation: - - web: no suffix; the line carries the request's `X-Request-Id` (MDC `request_id`). - - gRPC: ` (method=/)`; MDC `request_id` too when the service closed the call on - its callback thread. - - GraphQL: ` (executionId=)`, the `executionId` the client got in the error's `extensions`. - - STOMP (`@MessageMapping`): no suffix; MDC `request_id` is the frame's. +- 서비스가 쓰는 멱등성 저장소의 상태를 본다(고른 provider에 따라 JPA datasource나 Redis의 `/actuator/health` + 구성 요소). +- 같은 시간대에 그 저장소의 커넥션 풀 포화나 시간 초과를 찾는다. executor는 포화를 추측하지 않고 사용 불가로 + 보고한다. +- `IDEMPOTENCY_RECOVERY_REQUIRED`는 실패한 요청의 서버 ERROR 로그에서 scope를 찾는다. 모든 전송 계층이 같은 줄 + `failure classified as IDEMPOTENCY_RECOVERY_REQUIRED (category=DATA_INTEGRITY, retryable=false)`에 예외를 + 붙여 쓰고(shared-contract `ServerFailureLog`), 자기 상관 정보를 덧붙인다. + - web: 덧붙이는 것이 없다. 줄에 요청의 `X-Request-Id`(MDC `request_id`)가 실린다. + - gRPC: ` (method=/)`. 서비스가 callback 스레드에서 호출을 닫았으면 MDC `request_id`도 있다. + - GraphQL: ` (executionId=)`. 클라이언트가 오류의 `extensions`에서 받은 `executionId`다. + - STOMP(`@MessageMapping`): 덧붙이는 것이 없다. MDC `request_id`는 그 frame의 것이다. - The exception message ends with - `::v::`, for example - `claim requires reconciliation: CHARGE_CARD::v1::3f9a…` (64 hex characters). Then look at the - record in the store the service uses (`APP_IDEMPOTENCY_PROVIDER`). There is no tool for this; these - are the commands. - - Redis. The key, for example `prod:order:shared:idem:v1:d1:CHARGE_CARD:3f9a…`, is + 예외 메시지는 `::v::`로 끝난다. 예: + `claim requires reconciliation: CHARGE_CARD::v1::3f9a…`(16진수 64자). 그다음 서비스가 쓰는 저장소 + (`APP_IDEMPOTENCY_PROVIDER`)에서 기록을 본다. 이것을 해 주는 도구는 없다. 아래가 그 명령이다. + - Redis. 키는 예를 들어 `prod:order:shared:idem:v1:d1:CHARGE_CARD:3f9a…`이고, 모양은 다음과 같다. ``` @@ -77,11 +67,10 @@ status: active PTTL ``` - `state` `ABANDONED` is final. `state` `EXECUTING` with a `leaseUntil` (lease end, epoch - milliseconds, server clock) earlier than the server's `TIME` (first value × 1000) is an attempt - past its lease that may still be running. `PTTL` is how long the record still lives, in - milliseconds. - - PostgreSQL, in the application's schema: + `state` `ABANDONED`는 바뀌지 않는다. `state` `EXECUTING`이면서 `leaseUntil`(lease 끝, epoch 밀리초, 서버 + 시계)이 서버의 `TIME`(첫 값 × 1000)보다 이르면, lease가 지났지만 아직 돌고 있을 수 있는 시도다. `PTTL`은 + 기록이 앞으로 살아 있을 시간(밀리초)이다. + - PostgreSQL. 애플리케이션의 스키마에서: ```sql SELECT status, attempt, failure_disposition, last_transition_kind, @@ -91,48 +80,44 @@ status: active AND scope_hash = ''; ``` - `status` `ABANDONED` with `last_transition_kind` `FAIL_ABANDONED` means the action threw or - reported its effect unknown. `status` `EXECUTING` with `processing_lease_until` before - `clock_timestamp()` is an attempt past its lease that may still be running. (`ABANDONED` with - `EXPIRED_EXECUTION` is a lease that ran out under a version before 2026-11-04, which abandoned - such rows; it goes away when the row expires.) `expires_at` is when the reaper deletes the row. + `status` `ABANDONED`에 `last_transition_kind` `FAIL_ABANDONED`면 action이 예외를 던졌거나 효과를 모른다고 + 보고했다. `status` `EXECUTING`에 `processing_lease_until`이 `clock_timestamp()`보다 이르면, lease가 지났지만 + 아직 돌고 있을 수 있는 시도다. `expires_at`은 reaper가 행을 지우는 시각이다. -## Action + > 이력: `ABANDONED`에 `EXPIRED_EXECUTION`은 2026-11-04 전 버전에서 lease가 끝난 행이다. 그 버전은 그런 행을 + > 버렸다. 행이 만료되면 사라진다. -- `IDEMPOTENCY_UNAVAILABLE`: restore the store; clients retry with the same key and backoff. When - the exception message says the claim's processing lease ran out before the action started, the - store is not the cause: find what held those requests between claim and start (thread dumps, GC - pauses, the store's latency in that window). Nothing to repair; the next same-key request runs. -- `IDEMPOTENCY_COMPLETION_UNKNOWN`: restore the store, then check the effects outside the - transaction for the failed requests (the ERROR log line names the code). A same-key resend replays - a result that was in fact recorded, gets `IDEMPOTENT_IN_FLIGHT` while the attempt's lease lasts, - and `IDEMPOTENCY_RECOVERY_REQUIRED` after it — handle that one as below. -- `IDEMPOTENCY_RECOVERY_REQUIRED`: do not ask the client to retry blindly. If the record is - `EXECUTING` past its lease, first wait for the attempt: look the record up again after the - longest time the action can take. It changes by itself when the attempt finishes — `COMPLETED` - (resends replay it, nothing to do), `ABANDONED`, or `FAILED_RETRYABLE` (the attempt proved it had - no effect, and the next request with the key runs it). A crashed attempt, or one whose request - already ended with `IDEMPOTENCY_COMPLETION_UNKNOWN`, never changes it; that record stays - `EXECUTING` until it expires. Business data checked while the attempt still runs can say "no - effect" a moment before the effect lands. Then confirm from business data (the order, the - payment, the downstream system) whether the effect exists. There is no way to complete the record - by hand — the stored response is the action's own result. - - The effect exists: tell the client it was applied. Leave the record; a resend with the key keeps - getting this 500 until the record expires (Redis `PTTL`, PostgreSQL `expires_at`). - - The effect does not exist: the client sends the request again under a new key. To let the same - key run again instead, delete the record — only while it is `ABANDONED`, because any other state - belongs to a request that may still be running or to a stored result. Do not delete an - `EXECUTING` record, even past its lease: if its attempt is still alive, its late result finds no - record (`ABSENT`) — the result is lost, the first request gets this 500 after its work took - effect, and the next request with the key runs the work a second time. Leave it to expire. - - Redis: check and delete in one step, as the account the service's registered scripts run as - (`APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE`, or the application account when it - is unset). Checking with `HMGET` and then sending `DEL` is two commands: a record that expires - between them and is claimed again by a new request is deleted while that request runs, and - the next request with the key runs the work a second time (re-review 2026-11-04 RR4-03-02). - The program below deletes the key only while its `state` is `ABANDONED`. The application - accounts are denied `EVAL` (`compose/redis/acl/README.md`), so load it and run it by the - digest `SCRIPT LOAD` prints, as the service runs its own scripts: +## 조치 + +- `IDEMPOTENCY_UNAVAILABLE`: 저장소를 되살린다. 클라이언트는 같은 키로 백오프하며 다시 시도한다. 예외 메시지가 + action 시작 전에 claim의 처리 lease가 끝났다고 하면 저장소가 원인이 아니다. claim과 시작 사이에 그 요청들을 + 붙잡은 것을 찾는다(스레드 덤프, GC 멈춤, 그 시간대의 저장소 지연). 고칠 것은 없다. 같은 키의 다음 요청이 + 실행된다. +- `IDEMPOTENCY_COMPLETION_UNKNOWN`: 저장소를 되살린 뒤, 실패한 요청들의 트랜잭션 밖 효과를 확인한다(ERROR 로그 + 줄이 코드를 알려 준다). 같은 키로 다시 보내면, 실제로 기록된 결과는 replay로 받고, 시도의 lease가 남은 동안은 + `IDEMPOTENT_IN_FLIGHT`를, 그 뒤에는 `IDEMPOTENCY_RECOVERY_REQUIRED`를 받는다. 마지막 것은 아래처럼 다룬다. +- `IDEMPOTENCY_RECOVERY_REQUIRED`: 클라이언트에게 그냥 다시 시도하라고 하지 않는다. 기록이 lease가 지난 + `EXECUTING`이면 먼저 시도를 기다린다. action이 걸릴 수 있는 가장 긴 시간이 지난 뒤 기록을 다시 본다. 시도가 + 끝나면 기록은 저절로 바뀐다. `COMPLETED`(다시 보내면 replay된다, 할 일 없음), `ABANDONED`, `FAILED_RETRYABLE` + (시도가 효과가 없었음을 증명했고, 그 키의 다음 요청이 실행한다) 중 하나다. 죽은 시도, 또는 요청이 이미 + `IDEMPOTENCY_COMPLETION_UNKNOWN`으로 끝난 시도는 기록을 바꾸지 않는다. 그 기록은 만료될 때까지 `EXECUTING`으로 + 남는다. 시도가 아직 도는 동안 확인한 업무 데이터는 효과가 들어가기 직전에 「효과 없음」으로 보일 수 있다. + 그다음 업무 데이터(주문, 결제, 하위 시스템)로 효과가 있는지 확인한다. 기록을 손으로 완료할 방법은 없다. 저장된 + 응답은 action 자신의 결과다. + - 효과가 있다: 클라이언트에게 적용됐다고 알린다. 기록은 그대로 둔다. 그 키로 다시 보내면 기록이 만료될 때까지 + (Redis `PTTL`, PostgreSQL `expires_at`) 이 500을 계속 받는다. + - 효과가 없다: 클라이언트가 새 키로 요청을 다시 보낸다. 같은 키로 다시 돌리게 하려면 기록을 지운다. 단 + `ABANDONED`일 때만 지운다. 다른 상태는 아직 돌고 있을 수 있는 요청이나 저장된 결과의 것이다. `EXECUTING` + 기록은 lease가 지났어도 지우지 않는다. 그 시도가 아직 살아 있으면 늦게 온 결과가 기록을 찾지 못하고 + (`ABSENT`) 결과가 사라진다. 첫 요청은 일이 적용된 뒤에 이 500을 받고, 그 키의 다음 요청이 일을 한 번 더 + 한다. 만료되게 둔다. + - Redis: 확인과 삭제를 한 단계로, 서비스에 등록된 스크립트가 도는 계정으로 한다 + (`APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE`, 비어 있으면 애플리케이션 계정). `HMGET`으로 + 확인하고 `DEL`을 보내면 명령이 둘이다. 그 사이에 만료되어 새 요청이 다시 claim한 기록은 그 요청이 도는 + 동안 지워지고, 그 키의 다음 요청이 일을 한 번 더 한다(2026-11-04 재확인 리뷰 RR4-03-02). 아래 프로그램은 + `state`가 `ABANDONED`일 때만 키를 지운다. 애플리케이션 계정은 `EVAL`이 막혀 있으므로 + (`compose/redis/acl/README.md`), 서비스가 자기 스크립트를 돌리는 것처럼 불러 올리고 `SCRIPT LOAD`가 찍은 + digest로 돌린다. ``` @@ -140,11 +125,10 @@ status: active EVALSHA 1 ``` - `1` deleted the record; the key is new. `0` deleted nothing: the record is no longer - `ABANDONED` (or is gone) — look again before doing anything else. `NOSCRIPT` means the node - that holds the key (a cluster) has not loaded the program: run `SCRIPT LOAD` on that node and - `EVALSHA` again; nothing was deleted. A record that is about to expire needs nothing; once it - is gone the key is new. + `1`이면 기록을 지웠고 키는 새것이다. `0`이면 아무것도 지우지 않았다. 기록이 더는 `ABANDONED`가 아니다 + (또는 없다). 다른 일을 하기 전에 다시 본다. `NOSCRIPT`는 키를 가진 노드(클러스터)가 프로그램을 불러 올리지 + 않았다는 뜻이다. 그 노드에서 `SCRIPT LOAD`를 돌리고 `EVALSHA`를 다시 한다. 아무것도 지워지지 않았다. 곧 + 만료될 기록은 할 일이 없다. 사라지면 키는 새것이다. - PostgreSQL: ```sql @@ -154,12 +138,12 @@ status: active AND status = 'ABANDONED'; ``` - Without either step the key is released when the record expires. A record whose attempt never - finished lives for the processing lease plus `APP_IDEMPOTENCY_TTL` from its claim; one the action - marked failed lives for `APP_IDEMPOTENCY_FAILURE_RETENTION` (not shorter than `APP_IDEMPOTENCY_TTL`) - from the failure (`docs/web/http-contract.md`, "서버가 기억하는 기간"). + 어느 단계도 하지 않으면 기록이 만료될 때 키가 풀린다. 시도가 끝나지 않은 기록은 claim부터 처리 lease에 + `APP_IDEMPOTENCY_TTL`을 더한 만큼 산다. action이 실패로 표시한 기록은 실패부터 + `APP_IDEMPOTENCY_FAILURE_RETENTION`(`APP_IDEMPOTENCY_TTL`보다 짧지 않다)만큼 산다 + (`docs/web/http-contract.md` 「서버가 기억하는 기간」). -## Escalation +## 에스컬레이션 -- P2 → P1 when the store stays unavailable for more than 10 minutes on a write path. -- Page the owner of the idempotency store (database or Redis on-call). +- 쓰기 경로에서 저장소가 10분 넘게 사용 불가로 남으면 P2 → P1. +- 멱등성 저장소 소유자(DB나 Redis 당번)를 부른다. diff --git a/docs/runbooks/internal-error-spike.md b/docs/runbooks/internal-error-spike.md index 0f90c325..83e6d561 100644 --- a/docs/runbooks/internal-error-spike.md +++ b/docs/runbooks/internal-error-spike.md @@ -5,7 +5,7 @@ error_codes: [INTERNAL_ERROR, INTERNAL_AUTH_MISCONFIGURATION, JVM_OOM] severity: P1 owner: oncall last_updated: 2026-05-22 -status: stub +status: 초안 --- # Runbook: 5xx Internal error spike diff --git a/docs/runbooks/job-dead-letter.md b/docs/runbooks/job-dead-letter.md index 0dfdd840..38faf6c3 100644 --- a/docs/runbooks/job-dead-letter.md +++ b/docs/runbooks/job-dead-letter.md @@ -5,7 +5,7 @@ error_codes: [JOB_DEAD_LETTER] severity: P1 owner: oncall last_updated: 2026-06-13 -status: stub +status: 초안 --- # Runbook: background job dead letter (`runbook://job/dead-letter`) diff --git a/docs/runbooks/job-executor-rejected.md b/docs/runbooks/job-executor-rejected.md index c13db0d7..ea9fa91d 100644 --- a/docs/runbooks/job-executor-rejected.md +++ b/docs/runbooks/job-executor-rejected.md @@ -5,7 +5,7 @@ error_codes: [JOB_EXECUTOR_REJECTED] severity: P1 owner: oncall last_updated: 2026-06-13 -status: stub +status: 초안 --- # Runbook: async executor rejected (`runbook://job/executor-rejected`) diff --git a/docs/runbooks/job-timeout.md b/docs/runbooks/job-timeout.md index 30947cd7..dafd084b 100644 --- a/docs/runbooks/job-timeout.md +++ b/docs/runbooks/job-timeout.md @@ -5,7 +5,7 @@ error_codes: [JOB_TIMEOUT] severity: P2 owner: oncall last_updated: 2026-11-03 -status: stub +status: 초안 --- # Runbook: background job timeout (`runbook://job/timeout`) diff --git a/docs/runbooks/lock-acquisition-timeout.md b/docs/runbooks/lock-acquisition-timeout.md index 2f3f8bf4..4230ae9c 100644 --- a/docs/runbooks/lock-acquisition-timeout.md +++ b/docs/runbooks/lock-acquisition-timeout.md @@ -5,34 +5,34 @@ error_codes: [LOCK_ACQUISITION_TIMEOUT] severity: P2 owner: oncall last_updated: 2026-11-07 -status: stub +status: 초안 --- # Runbook: LOCK_ACQUISITION_TIMEOUT (`runbook://lock/acquisition-timeout`) -## Symptoms +## 증상 -- HTTP 409 with `error.code=LOCK_ACQUISITION_TIMEOUT` and `Retry-After: 1`; GraphQL extension - `code=LOCK_ACQUISITION_TIMEOUT`, gRPC trailer `error-code: LOCK_ACQUISITION_TIMEOUT` (`ABORTED`), all - `retryable=true`. -- No server log line. A 4xx answer is not an incident, so no transport logs it, and the lock adapters - do not log a timeout either. The exception's message (lock key, wait time) reaches no log and no - client, so which lock timed out is recorded nowhere. Read the metric and the lock table below. -- Before 2026-11-07 the template answered this as 500 `INTERNAL_ERROR` with an "unhandled exception" - ERROR line (the exception was not an `ApiErrorCarrier`). A service on an older template sees that - instead. -- Distributed lock wait exceeded configured timeout; high contention on a resource +- HTTP 409, `error.code=LOCK_ACQUISITION_TIMEOUT`, `Retry-After: 1`. GraphQL은 extension + `code=LOCK_ACQUISITION_TIMEOUT`, gRPC는 trailer `error-code: LOCK_ACQUISITION_TIMEOUT`(`ABORTED`)이고, 모두 + `retryable=true`다. +- 서버 로그 줄이 없다. 4xx 응답은 장애가 아니라서 어느 전송 계층도 로그를 남기지 않고, 락 어댑터도 시간 초과를 + 로그에 쓰지 않는다. 예외 메시지(락 키, 대기 시간)는 어느 로그에도 클라이언트에도 닿지 않으므로 어느 락이 + 시간을 넘겼는지는 어디에도 기록되지 않는다. 아래의 메트릭과 락 테이블을 읽는다. +- 분산 락 대기가 설정된 시간 상한을 넘었다. 한 자원에 경합이 심하다. -## Diagnosis +> 이력: 2026-11-07 전의 템플릿은 이 경우를 500 `INTERNAL_ERROR`와 "unhandled exception" ERROR 줄로 +> 응답했다(예외가 `ApiErrorCarrier`가 아니었다). 옛 템플릿을 쓰는 서비스에서는 그것이 보인다. -1. Contention rate. With `APP_MULTI_INSTANCE_ENABLED=true` the JDBC lock is metered: compare - `lock.acquisition{outcome="timeout"}` with `lock.acquisition{outcome="acquired"}`. The counter has - no lock name and no wait time — a key is never a metric tag (`docs/registries/metrics.yaml`). The - in-process lock (`APP_MULTI_INSTANCE_ENABLED=false`, the default) has no metric and keeps nothing in - the database; the steps below apply only to the JDBC lock. -2. Who holds locks now. `INT_LOCK` has one row per held lock. `CLIENT_ID` is the holding instance's - lock repository id, and the times are UTC. A row whose `EXPIRED_AFTER` has passed is a dead lease: - the next acquisition of that key takes it over. The oldest live rows are the long holders. +## 진단 + +1. 경합 비율. `APP_MULTI_INSTANCE_ENABLED=true`이면 JDBC 락에 메트릭이 붙는다. + `lock.acquisition{outcome="timeout"}`을 `lock.acquisition{outcome="acquired"}`와 비교한다. 이 counter에는 + 락 이름도 대기 시간도 없다. 키는 메트릭 태그가 되지 않는다(`docs/registries/metrics.yaml`). 프로세스 안 락 + (`APP_MULTI_INSTANCE_ENABLED=false`, 기본값)은 메트릭이 없고 DB에 아무것도 남기지 않는다. 아래 단계는 JDBC + 락에만 해당한다. +2. 지금 누가 락을 쥐고 있나. `INT_LOCK`에는 쥔 락마다 한 행이 있다. `CLIENT_ID`는 쥔 인스턴스의 락 저장소 id이고, + 시각은 UTC다. `EXPIRED_AFTER`가 지난 행은 죽은 lease다. 그 키를 다음에 잡는 쪽이 넘겨받는다. 가장 오래된 + 살아 있는 행이 오래 쥔 쪽이다. ```sql @@ -41,10 +41,9 @@ FROM int_lock ORDER BY created_date; ``` -3. The holder of one lock whose key you know from the code (for example `orders/42`). `LOCK_KEY` is - not the key: Spring Integration stores the key's name-based UUID (`UUID.nameUUIDFromBytes` of the - key's UTF-8 bytes), so a key cannot be read back from the table. This computes the UUID from the - key and finds its row: +3. 코드에서 키를 아는 락 하나(예: `orders/42`)를 누가 쥐고 있나. `LOCK_KEY`는 키 자체가 아니다. Spring + Integration은 키의 이름 기반 UUID(키의 UTF-8 바이트에 `UUID.nameUUIDFromBytes`)를 저장하므로 테이블에서 키를 + 거꾸로 읽을 수 없다. 아래 쿼리는 키에서 UUID를 계산해 그 행을 찾는다. ```sql @@ -56,18 +55,18 @@ WHERE lock_key = ( FROM md5('') AS h); ``` -`:adapter:outbound:persistence-jpa:postgresqlDistributedLockIntegrationTest` runs both blocks, read -from this file, against real PostgreSQL while locks are held. +`:adapter:outbound:persistence-jpa:postgresqlDistributedLockIntegrationTest`가 두 블록을 이 파일에서 읽어, +락을 쥔 상태의 실제 PostgreSQL에 돌린다. -## Action +## 조치 -- Client should retry with backoff (retryable=true) -- Optimize critical section holding time if lock contention is systemic +- 클라이언트는 백오프하며 다시 시도한다(retryable=true). +- 락 경합이 구조적이면 임계 구역을 쥐는 시간을 줄인다. -## Escalation +## 에스컬레이션 -- Escalate if lock holder appears stuck (potential deadlock in distributed lock) +- 락 보유자가 멈춘 것으로 보이면 넘긴다(분산 락의 교착 가능성). --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/management-actuator-forbidden.md b/docs/runbooks/management-actuator-forbidden.md index 3aa96f73..d3115fb4 100644 --- a/docs/runbooks/management-actuator-forbidden.md +++ b/docs/runbooks/management-actuator-forbidden.md @@ -4,31 +4,33 @@ category: AUTHZ error_codes: [ACTUATOR_FORBIDDEN] severity: P2 owner: oncall -last_updated: 2026-06-15 -status: stub +last_updated: 2026-11-07 +status: 초안 --- # Runbook: ACTUATOR_FORBIDDEN (`runbook://management/actuator-forbidden`) -## Symptoms +## 증상 -- HTTP 403 with `error.code=ACTUATOR_FORBIDDEN` -- Attempt to access restricted actuator endpoint (env/configprops/heapdump/shutdown) +- HTTP 403, `error.code=ACTUATOR_FORBIDDEN`. +- 제한된 actuator 엔드포인트(env·configprops·heapdump·shutdown)에 접근하려 했다. -## Diagnosis +## 진단 -- Identify which actuator endpoint was accessed -- Check caller identity (internal tooling vs external) +- 어느 actuator 엔드포인트에 접근했는지 찾는다. +- 호출자가 누구인지(내부 도구인지 외부인지) 확인한다. -## Action +## 조치 -- Verify management port is not exposed externally -- For heapdump/threaddump: follow break-glass runbook procedure +- management 포트가 밖으로 노출되지 않았는지 확인한다. +- heapdump·threaddump는 노출 목록에서 빠져 있다(`config/observability.yml`의 + `management.endpoints.web.exposure.exclude`). 꼭 필요하면 운영 조직의 break-glass 절차를 따른다. 이 저장소에는 + 그 절차 문서가 없다. -## Escalation +## 에스컬레이션 -- P1 if forbidden actuator access appears to be external attack +- 금지된 actuator 접근이 외부 공격으로 보이면 P1. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/migration-failed.md b/docs/runbooks/migration-failed.md index 601f96a6..4f96a60e 100644 --- a/docs/runbooks/migration-failed.md +++ b/docs/runbooks/migration-failed.md @@ -5,27 +5,25 @@ error_codes: [MIGRATION_FAILED] severity: P1 owner: oncall last_updated: 2026-11-07 -status: active +status: 운영 --- # Runbook: MIGRATION_FAILED (`runbook://migration/failed`) -## Symptoms +## 증상 -- Container exits with code 70 (migration failure exit) -- Structured log with `error.code=MIGRATION_FAILED`, `startup.phase=migration` -- App refuses to start (fail-fast) -- JPA capability adapter refuses activation because its - `capability_schema_registry.lifecycle_state` is not `ACTIVE` +- 컨테이너가 코드 70으로 끝난다(마이그레이션 실패 종료). +- 구조화 로그 `error.code=MIGRATION_FAILED`, `startup.phase=migration`. +- 앱이 뜨기를 거부한다(fail-fast). +- JPA capability 어댑터가 활성화를 거부한다. 그 `capability_schema_registry.lifecycle_state`가 `ACTIVE`가 아니다. -## Diagnosis +## 진단 -1. Stop rollout and keep the failed revision out of readiness. Do not route traffic to a partially - migrated instance. -2. Identify the exact stream from `src/adapter/outbound/persistence-jpa/release/readiness-cards.yaml`. Each stream has an - independent `location` and `history-table`; do not infer ownership from a broad - `classpath:db/migration` scan. -3. From a privileged migration session, capture the stream state before changing anything: +1. rollout을 멈추고, 실패한 revision을 readiness 밖에 둔다. 마이그레이션이 반쯤 된 인스턴스로 트래픽을 보내지 + 않는다. +2. `src/adapter/outbound/persistence-jpa/release/readiness-cards.yaml`에서 정확한 stream을 찾는다. stream마다 + `location`과 `history-table`이 따로 있다. 넓은 `classpath:db/migration` 스캔으로 소유를 짐작하지 않는다. +3. 권한 있는 마이그레이션 세션에서, 무엇이든 바꾸기 전에 stream 상태를 남긴다. ```sql select installed_rank, version, description, success @@ -37,15 +35,14 @@ status: active where capability_id = ''; ``` -4. Check whether any owned relation was created without a successful history entry. Compare only - against the owned tables in the reviewed migration; do not drop unrelated relations. -5. Classify the failure: - - lock/statement timeout: remove the blocker or reduce rollout concurrency, then rerun. A - migration that locks a table already in use gives up after its own `SET LOCAL lock_timeout` - (5 s; SQLState `55P03` `lock_not_available`) and rolls back whole, so the history ends one - version below it. The blocker is a transaction that touched the table and is still open — - often an idle-in-transaction session. Find it by the lock it holds on that table (`` - is the table the failing statement locks; for a `REFERENCES`, also the table it references): +4. 성공한 이력 행 없이 만들어진 소유 relation이 있는지 확인한다. 검토한 마이그레이션의 소유 테이블과만 + 비교한다. 상관없는 relation은 지우지 않는다. +5. 실패를 분류한다(Classify the failure). + - 락·문장 시간 초과: 막는 쪽을 없애거나 rollout 동시성을 줄이고 다시 돌린다. 이미 쓰는 테이블을 잠그는 + 마이그레이션은 자기 `SET LOCAL lock_timeout`(5 s, SQLState `55P03` `lock_not_available`)이 지나면 포기하고 + 통째로 롤백한다. 그래서 이력은 그 버전 바로 아래에서 끝난다. 막는 쪽은 그 테이블을 건드린 뒤 아직 열려 있는 + 트랜잭션이다. 흔히 idle-in-transaction 세션이다. 그 테이블에 쥔 락으로 찾는다(`
`은 실패한 문장이 + 잠그는 테이블이다. `REFERENCES`면 참조하는 테이블도 본다). ```sql SELECT DISTINCT a.pid, a.state, a.xact_start, a.query @@ -54,74 +51,65 @@ status: active ORDER BY a.xact_start; ``` - `query` is only that session's last statement, not the one that touched the table, so do not - look for the table name in it. Listing every long transaction instead names unrelated ones - (reports, batches) beside the blocker. End the blocker, then rerun - (`docs/jpa/migration-guide.md` "Bound the lock wait"); - - SQL/data precondition: create a new forward migration that makes the precondition explicit; - a duplicate outbox order key stopping V21 (`ux_outbox_event_aggregate_order`) is the known - case — clean it up with `outbox-dead-letter.md` §8 and rerun, the migration stays as it is; - - checksum mismatch: compare the deployed artifact with the already applied script before - considering repair; - - a concurrent index migration failed (`CREATE [UNIQUE] INDEX CONCURRENTLY`, `DROP INDEX - CONCURRENTLY` or `REINDEX … CONCURRENTLY` that Flyway ran outside a transaction): a duplicate - value for a unique index, a deadlock, `statement_timeout` or a statement cancelled while it - waited for an open transaction. Outside a transaction nothing rolled back: the migration left - an invalid index and a history row with `success = false` for that version, and every later - deploy fails validation ("Detected failed migration to version …") until the row is gone. - Dropping the index alone does not clear it. Follow "Recover a failed concurrent index - migration" below; - - connection/TLS failure: fix transport or credentials without changing Flyway history. + `query`는 그 세션의 마지막 문장일 뿐 테이블을 건드린 문장이 아니므로, 거기서 테이블 이름을 찾지 않는다. + 대신 긴 트랜잭션을 모두 나열하면 막는 쪽 옆에 상관없는 것(리포트, 배치)도 나온다. 막는 쪽을 끝낸 뒤 다시 + 돌린다(`docs/jpa/migration-guide.md` "Bound the lock wait"). + - SQL·데이터 전제 조건: 전제 조건을 드러내는 새 forward 마이그레이션을 만든다. 중복된 outbox 순서 키가 + V21(`ux_outbox_event_aggregate_order`)을 막는 것이 알려진 경우다. `outbox-dead-letter.md` §8로 정리하고 다시 + 돌린다. 마이그레이션은 그대로 둔다. + - checksum 불일치: repair를 생각하기 전에 배포한 산출물과 이미 적용된 스크립트를 비교한다. + - 동시 인덱스 마이그레이션 실패(Flyway가 트랜잭션 밖에서 돌린 `CREATE [UNIQUE] INDEX CONCURRENTLY`, + `DROP INDEX CONCURRENTLY`, `REINDEX … CONCURRENTLY`): unique 인덱스의 중복 값, 교착, `statement_timeout`, + 또는 열린 트랜잭션을 기다리다 취소된 문장이다. 트랜잭션 밖이라 아무것도 롤백되지 않았다. 마이그레이션은 + 무효 인덱스와, 그 버전의 `success = false` 이력 행을 남겼다. 그 행이 사라질 때까지 뒤의 배포는 모두 검증에서 + 실패한다("Detected failed migration to version …"). 인덱스만 지워서는 풀리지 않는다. 아래 「실패한 동시 + 인덱스 마이그레이션 복구」를 따른다. + - 연결·TLS 실패: Flyway 이력을 바꾸지 않고 전송이나 자격 증명을 고친다. -## Action +## 조치 -1. Prefer forward recovery. Fix the environmental blocker or add a new immutable migration, then - rerun the same owned stream with its exact history table. -2. For an optional stream that never installed successfully, keep the capability marker absent and - the runtime adapter disabled until migration succeeds. -3. After a successful migration, validate: - - the history contains only successful expected versions; - - `core_epoch` and `feature_revision` match the readiness registry; - - the marker is `INSTALLED_INACTIVE`; - - owned objects and constraints exist. -4. Change the marker to `ACTIVE` only after the compatible application revision is deployed and its - readiness check succeeds. Disabling or rolling back application code changes the marker to - `INSTALLED_INACTIVE`; it does not drop history or owned data. -5. Re-run the readiness lanes before promoting (every card's scenarios, no skips): +1. forward 복구를 먼저 쓴다. 환경 쪽 막힘을 고치거나 바뀌지 않는 새 마이그레이션을 더한 뒤, 같은 소유 stream을 + 그 정확한 이력 테이블로 다시 돌린다. +2. 한 번도 성공적으로 설치되지 않은 선택 stream은 마이그레이션이 성공할 때까지 capability 표시를 두지 않고 런타임 + 어댑터를 꺼 둔다. +3. 마이그레이션이 성공하면 확인한다. + - 이력에 기대한 버전의 성공 행만 있다. + - `core_epoch`와 `feature_revision`이 readiness registry와 같다. + - 표시가 `INSTALLED_INACTIVE`다. + - 소유 객체와 제약이 있다. +4. 맞는 애플리케이션 revision이 배포되고 그 readiness 검사가 성공한 뒤에만 표시를 `ACTIVE`로 바꾼다. + 애플리케이션 코드를 끄거나 되돌리면 표시가 `INSTALLED_INACTIVE`로 바뀐다. 이력이나 소유 데이터는 지우지 않는다. +5. 승격 전에 readiness lane을 다시 돌린다(모든 card의 시나리오, 건너뜀 없음). ```bash cd src ./gradlew :adapter:outbound:persistence-jpa:integrationTestLaneCheck --console=plain ``` -6. Record the failed revision, stream/history table, root cause, recovery migration, elapsed time - and verification artifact in the incident. +6. 실패한 revision, stream·이력 테이블, 근본 원인, 복구 마이그레이션, 걸린 시간, 검증 산출물을 장애 기록에 남긴다. -Do not: +하지 않을 것: -- edit an already applied migration; -- delete or rewrite Flyway history to make validation green. The one exception is the failed row - of a failed concurrent index migration, deleted as "Recover a failed concurrent index migration" - below says — that row and nothing else; -- run `flyway repair` before checksum provenance is proven and reviewed; -- use `clean`, destructive rollback, or schema-wide restore as the first response; -- mark a capability `ACTIVE` before its migration and adapter readiness succeed. +- 이미 적용된 마이그레이션을 고친다. +- 검증을 통과시키려고 Flyway 이력을 지우거나 다시 쓴다. 예외는 하나다. 실패한 동시 인덱스 마이그레이션의 실패 + 행을 아래 「실패한 동시 인덱스 마이그레이션 복구」대로 지운다. 그 행 말고는 아무것도 지우지 않는다. +- checksum의 출처가 증명되고 검토되기 전에 `flyway repair`를 돌린다. +- 첫 대응으로 `clean`, 파괴적 롤백, 스키마 전체 복원을 쓴다. +- 마이그레이션과 어댑터 readiness가 성공하기 전에 capability를 `ACTIVE`로 표시한다. -If commit outcome was indeterminate during the failure, reconcile by the application -`OperationId`/idempotency reference before retrying business work. Never blind-retry a commit whose -result is unknown. +장애 중에 커밋 결과를 알 수 없었으면, 업무 작업을 다시 하기 전에 애플리케이션의 `OperationId`·멱등성 참조로 +맞춘다. 결과를 모르는 커밋을 그냥 다시 시도하지 않는다. -## Recover a failed concurrent index migration +## 실패한 동시 인덱스 마이그레이션 복구 (Recover a failed concurrent index migration) -The one case where this runbook changes Flyway history (owner decision, 2026-11-06). It applies to a -migration that holds a single concurrent index statement which Flyway ran outside a transaction — -with the `executeInTransaction=false` the guide asks for, or on its own for `CREATE`/`DROP INDEX -CONCURRENTLY` (`docs/jpa/migration-guide.md` "Concurrent index builds") — and whose row for this -version in the stream's history table says `success = false`. A migration that mixed other -statements in has already committed them: reconstruct that state with the database owner instead. +이 runbook이 Flyway 이력을 바꾸는 유일한 경우다(소유자 결정, 2026-11-06). Flyway가 트랜잭션 밖에서 돌린 동시 +인덱스 문장 하나만 담은 마이그레이션에 쓴다. 가이드가 요구하는 `executeInTransaction=false`로 돌렸거나, +`CREATE`/`DROP INDEX CONCURRENTLY`라서 Flyway가 알아서 그렇게 돌린 경우다(`docs/jpa/migration-guide.md` +"Concurrent index builds"). 그리고 stream 이력 테이블의 이 버전 행이 `success = false`여야 한다. 다른 문장을 섞은 +마이그레이션은 그 문장을 이미 커밋했다. 그 상태는 DB 소유자와 함께 다시 맞춘다. -1. Confirm no build is still running. An index that is still being built looks invalid in the - catalog too, and dropping it races the build. This query returns no rows when none is: +1. 아직 도는 빌드가 없는지 확인한다. 아직 만드는 중인 인덱스도 카탈로그에서는 무효로 보이고, 그것을 지우면 + 빌드와 경합한다. 도는 빌드가 없으면 이 쿼리는 행을 돌려주지 않는다. ```sql @@ -130,29 +118,26 @@ FROM pg_stat_progress_create_index WHERE datname = current_database(); ``` -2. Remove the cause. For a unique index, clean up the duplicate rows with the data owner (a forward - fix, never by editing the migration). For a deadlock, a timeout or a cancelled statement, end or - wait out the transaction that held it: a build or a rebuild waits for every transaction older - than itself, a drop for every transaction that holds a lock on its table. Do this before step 3, - whose `DROP INDEX CONCURRENTLY` waits for the same transactions. -3. Drop the invalid index a failed build or rebuild left: the index a `CREATE [UNIQUE] INDEX - CONCURRENTLY` names, or the copy a `REINDEX … CONCURRENTLY` made, named after the index with - `_ccnew` (or `_ccold`) on the end (`docs/jpa/runbooks.md` "An invalid index exists" lists them). - Run it on its own, not inside `BEGIN`: `CONCURRENTLY` refuses a transaction block. - **Skip this step when the failed statement is `DROP INDEX CONCURRENTLY`.** The invalid index it - left is the index the migration drops, and the deploy in step 5 runs the same statement, which - drops it. Dropped by hand first, that statement fails with `42704` ("index … does not exist") - and leaves a new failed row. +2. 원인을 없앤다. unique 인덱스면 데이터 소유자와 중복 행을 정리한다(forward 수정이다. 마이그레이션을 고치지 + 않는다). 교착, 시간 초과, 취소된 문장이면 그것을 쥔 트랜잭션을 끝내거나 끝나기를 기다린다. 빌드와 재빌드는 + 자기보다 오래된 트랜잭션을 모두 기다리고, 삭제는 그 테이블에 락을 쥔 트랜잭션을 모두 기다린다. 3단계 전에 + 한다. 3단계의 `DROP INDEX CONCURRENTLY`도 같은 트랜잭션을 기다린다. +3. 실패한 빌드나 재빌드가 남긴 무효 인덱스를 지운다. `CREATE [UNIQUE] INDEX CONCURRENTLY`가 이름 붙인 인덱스, + 또는 `REINDEX … CONCURRENTLY`가 만든 사본이다. 사본은 인덱스 이름 끝에 `_ccnew`(또는 `_ccold`)가 붙는다 + (`docs/jpa/runbooks.md` "An invalid index exists"가 그 목록을 준다). `BEGIN` 안이 아니라 따로 돌린다. + `CONCURRENTLY`는 트랜잭션 블록을 거부한다. + **실패한 문장이 `DROP INDEX CONCURRENTLY`면 이 단계를 건너뛴다.** 그것이 남긴 무효 인덱스는 마이그레이션이 + 지우는 인덱스이고, 5단계의 배포가 같은 문장을 돌려 그것을 지운다. 먼저 손으로 지우면 그 문장이 `42704` + ("index … does not exist")로 실패하고 새 실패 행을 남긴다. ```sql DROP INDEX CONCURRENTLY IF EXISTS ; ``` -4. Delete that version's failed row from the stream's history table, and nothing else. `` - is the `version` column of the failed row as the Diagnosis query shows it (`22.1` for - `V22_1__…`). It must delete exactly one row; if it deletes none, this is not the failure this - section is for, so classify it again. +4. stream 이력 테이블에서 그 버전의 실패 행을 지운다. 그 밖에는 아무것도 지우지 않는다. ``은 진단 + 쿼리가 보여 주는 실패 행의 `version` 칸이다(`V22_1__…`이면 `22.1`). 정확히 한 행을 지워야 한다. 한 행도 지우지 + 않으면 이 절이 다루는 실패가 아니므로 다시 분류한다. ```sql @@ -160,28 +145,24 @@ DELETE FROM WHERE version = '' AND NOT success; ``` -5. Deploy again. Flyway runs the same migration from the start: it builds the index, rebuilds it, - or drops the index the failed drop left. +5. 다시 배포한다. Flyway가 같은 마이그레이션을 처음부터 돌린다. 인덱스를 만들거나, 다시 만들거나, 실패한 + 삭제가 남긴 인덱스를 지운다. -The failed row is the record of a version that never applied, so deleting it leaves the order and -the checksum of every applied version as they were. Do not use `flyway repair` for this: it also -rewrites the checksums and descriptions of the remaining rows to match the scripts on disk, which -removes the evidence a checksum mismatch carries. `:adapter:outbound:persistence-jpa:postgresqlConcurrentIndexMigrationIntegrationTest` -runs the three SQL blocks above, read from this file, against real PostgreSQL for each statement -this section covers: a unique build that fails on a duplicate, and a rebuild and a drop cancelled -while they wait for an open transaction. Steps 1–4 run in order, step 3 for the build and the -rebuild only, and the next deploy applies the version with no invalid index left and the earlier -version's checksum unchanged. +실패 행은 한 번도 적용되지 않은 버전의 기록이다. 그래서 지워도 적용된 모든 버전의 순서와 checksum은 그대로다. +이 일에 `flyway repair`를 쓰지 않는다. repair는 남은 행의 checksum과 description도 디스크의 스크립트에 맞춰 다시 +쓰므로, checksum 불일치가 담은 증거를 지운다. +`:adapter:outbound:persistence-jpa:postgresqlConcurrentIndexMigrationIntegrationTest`가 위의 SQL 블록 셋을 이 +파일에서 읽어, 이 절이 다루는 문장마다 실제 PostgreSQL에 돌린다. 중복으로 실패하는 unique 빌드, 열린 트랜잭션을 +기다리다 취소된 재빌드와 삭제다. 1~4단계를 차례로 돌리고(3단계는 빌드와 재빌드만), 다음 배포가 무효 인덱스 없이 +그 버전을 적용하며 앞 버전의 checksum은 바뀌지 않는다. -## Escalation +## 에스컬레이션 -- P1 immediate: the required application revision cannot become ready. -- Escalate to the database owner before Flyway history repair, destructive DDL, point-in-time - recovery, or primary failover. -- R3 restore/PITR and failover rehearsal requires a target-like backup topology; local - Testcontainers evidence is not a substitute. +- P1 즉시: 필요한 애플리케이션 revision이 ready가 되지 못한다. +- Flyway 이력 repair, 파괴적 DDL, 시점 복구(PITR), primary failover 전에 DB 소유자에게 넘긴다. +- R3 복원·PITR과 failover 예행연습에는 대상과 비슷한 백업 구성이 필요하다. 로컬 Testcontainers 증거로 대신하지 + 않는다. --- -This runbook is forward-only. The reviewed migration artifact and the readiness lanes' JUnit -results from CI are the audit sources. +이 runbook은 forward 방향만 다룬다. 감사 근거는 검토한 마이그레이션 산출물과 CI의 readiness lane JUnit 결과다. diff --git a/docs/runbooks/outbox-dead-letter.md b/docs/runbooks/outbox-dead-letter.md index 4799c29c..c42fdda9 100644 --- a/docs/runbooks/outbox-dead-letter.md +++ b/docs/runbooks/outbox-dead-letter.md @@ -5,7 +5,7 @@ error_codes: [OUTBOX_DEAD_LETTER] severity: P1 owner: oncall last_updated: 2026-11-04 -status: stub +status: 초안 --- # Runbook: outbox dead letter (`runbook://outbox/dead-letter`) diff --git a/docs/runbooks/outbox-publish-failed.md b/docs/runbooks/outbox-publish-failed.md index b676e14e..fd6d7491 100644 --- a/docs/runbooks/outbox-publish-failed.md +++ b/docs/runbooks/outbox-publish-failed.md @@ -5,7 +5,7 @@ error_codes: [OUTBOX_PUBLISH_FAILED] severity: P2 owner: oncall last_updated: 2026-11-04 -status: stub +status: 초안 --- # Runbook: outbox publish 일시 실패 (`runbook://outbox/publish-failed`) diff --git a/docs/runbooks/rate-limit-exceeded.md b/docs/runbooks/rate-limit-exceeded.md index e3be402d..225512a1 100644 --- a/docs/runbooks/rate-limit-exceeded.md +++ b/docs/runbooks/rate-limit-exceeded.md @@ -5,7 +5,7 @@ error_codes: [RATE_LIMIT_EXCEEDED, IDEMPOTENT_IN_FLIGHT] severity: P3 owner: oncall last_updated: 2026-05-22 -status: stub +status: 초안 --- # Runbook: Rate limit 초과 spike diff --git a/docs/runbooks/redis-capability-incident.md b/docs/runbooks/redis-capability-incident.md index 481bb7fd..2af8035f 100644 --- a/docs/runbooks/redis-capability-incident.md +++ b/docs/runbooks/redis-capability-incident.md @@ -5,7 +5,7 @@ error_codes: [] severity: P1 owner: oncall last_updated: 2026-07-29 -status: active +status: 운영 --- # Runbook: Redis capability incident (`runbook://redis/capability-incident`) diff --git a/docs/runbooks/runtime-jvm-oom.md b/docs/runbooks/runtime-jvm-oom.md index b8210da6..b3666efb 100644 --- a/docs/runbooks/runtime-jvm-oom.md +++ b/docs/runbooks/runtime-jvm-oom.md @@ -4,33 +4,38 @@ category: INTERNAL error_codes: [JVM_OOM] severity: P1 owner: oncall -last_updated: 2026-06-15 -status: stub +last_updated: 2026-11-07 +status: 초안 --- # Runbook: JVM_OOM (`runbook://runtime/jvm-oom`) -## Symptoms +## 증상 -- Container exits with code 137 (ExitOnOutOfMemoryError triggered) -- Structured log entry with `error.code=JVM_OOM` before exit +- 컨테이너가 코드 3으로 끝나고, stderr 마지막 줄이 `Terminating due to java.lang.OutOfMemoryError: <종류>`다 + (예: `Java heap space`). 이미지의 `JAVA_TOOL_OPTIONS`가 `-XX:+ExitOnOutOfMemoryError`를 켜기 때문이다(`src/Dockerfile`). +- 앱은 끝나기 전에 `error.code=JVM_OOM` 로그를 남기지 않는다. 이 코드를 로그에 쓰는 코드가 없다. +- 코드 137(SIGKILL)과 `OOMKilled: true`는 이 runbook의 일이 아니다. 프로세스 전체 메모리가 컨테이너 한계를 넘어 커널이 + 죽인 것이다. 힙과 그 밖의 네이티브 메모리(스레드 스택, 라이브러리의 네이티브 할당 등)를 합친 크기를 보고, + `-XX:MaxRAMPercentage`가 힙 밖에 남긴 몫이 모자라는지 본다. JVM이 손쓸 틈 없이 죽으므로 힙 덤프도 없다. -## Diagnosis +## 진단 -- Check heap dump if `-XX:HeapDumpOnOutOfMemoryError` is configured -- Review memory usage trends before crash -- Check for memory leaks: large cache growth, unbounded lists, session accumulation +- 힙 덤프를 본다. 이미지의 `JAVA_TOOL_OPTIONS`가 `-XX:+HeapDumpOnOutOfMemoryError`와 + `-XX:HeapDumpPath=/var/tmp/heap`을 켠다(`src/Dockerfile`). +- 죽기 전 메모리 사용 추세를 본다. +- 메모리 누수를 찾는다: 커지기만 하는 캐시, 상한 없는 목록, 쌓이는 세션. -## Action +## 조치 -- Restart container immediately (k8s will auto-restart with liveness probe) -- If recurring: increase heap `-Xmx` or fix memory leak +- 컨테이너를 바로 다시 띄운다(k8s는 liveness probe로 알아서 다시 띄운다). +- 반복되면 힙(`-Xmx`, 이미지는 `-XX:MaxRAMPercentage`)을 늘리거나 누수를 고친다. -## Escalation +## 에스컬레이션 -- P1: immediate if multiple pods crashing simultaneously -- Page SRE / infra team for heap analysis +- P1: 여러 pod가 동시에 죽으면 즉시. +- 힙 분석은 SRE·인프라 팀을 부른다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/startup-profile-mismatch.md b/docs/runbooks/startup-profile-mismatch.md index 6fa27e8b..a5d0ea2c 100644 --- a/docs/runbooks/startup-profile-mismatch.md +++ b/docs/runbooks/startup-profile-mismatch.md @@ -5,31 +5,31 @@ error_codes: [PROFILE_MISMATCH] severity: P1 owner: oncall last_updated: 2026-06-15 -status: stub +status: 초안 --- # Runbook: PROFILE_MISMATCH (`runbook://startup/profile-mismatch`) -## Symptoms +## 증상 -- Container exits with code 71 (profile mismatch exit) -- Structured log with `error.code=PROFILE_MISMATCH`, `startup.phase=profile-check` -- Production profile active with local-only settings enabled +- 컨테이너가 코드 71로 끝난다(프로파일 불일치 종료). +- 구조화 로그 `error.code=PROFILE_MISMATCH`, `startup.phase=profile-check`. +- 운영 프로파일이 켜져 있는데 로컬 전용 설정이 켜져 있다. -## Diagnosis +## 진단 -- Check active Spring profiles (`spring.profiles.active`) -- Identify which local-only setting is incorrectly enabled in prod profile +- 켜진 Spring 프로파일(`spring.profiles.active`)을 확인한다. +- 운영 프로파일에서 잘못 켜진 로컬 전용 설정을 찾는다. -## Action +## 조치 -- Remove local-only setting from production deployment config -- Ensure prod profile does not inherit local/dev profile settings +- 운영 배포 설정에서 로컬 전용 설정을 지운다. +- 운영 프로파일이 local·dev 프로파일 설정을 물려받지 않게 한다. -## Escalation +## 에스컬레이션 -- P1: security risk if local settings expose debug endpoints in production +- P1: 로컬 설정이 운영에서 디버그 엔드포인트를 열면 보안 위험이다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/startup-required-adapter-disabled.md b/docs/runbooks/startup-required-adapter-disabled.md index 341aa0cb..8862119a 100644 --- a/docs/runbooks/startup-required-adapter-disabled.md +++ b/docs/runbooks/startup-required-adapter-disabled.md @@ -4,31 +4,31 @@ category: INTERNAL error_codes: [REQUIRED_ADAPTER_DISABLED] severity: P1 owner: oncall -last_updated: 2026-06-15 -status: stub +last_updated: 2026-11-07 +status: 초안 --- # Runbook: REQUIRED_ADAPTER_DISABLED (`runbook://startup/required-adapter-disabled`) -## Symptoms +## 증상 -- Container exits with code 72 (required adapter disabled exit) -- Structured log with `error.code=REQUIRED_ADAPTER_DISABLED`, `startup.phase=adapter-check` +- 컨테이너가 코드 72로 끝난다(필수 어댑터 비활성화 종료). +- 구조화 로그 `error.code=REQUIRED_ADAPTER_DISABLED`, `startup.phase=adapter-enablement`. -## Diagnosis +## 진단 -- Identify which adapter is disabled but required -- Check adapter enable flags in environment config +- 필수인데 꺼진 어댑터를 찾는다. +- 환경 설정의 어댑터 스위치를 확인한다. -## Action +## 조치 -- Enable required adapter in deployment configuration -- If adapter is intentionally disabled, update the required/optional designation +- 배포 설정에서 필수 어댑터를 켠다. +- 일부러 끈 어댑터면 필수·선택 지정을 고친다. -## Escalation +## 에스컬레이션 -- P1: app cannot start; coordinate with deployment team +- P1: 앱이 뜨지 못한다. 배포 팀과 맞춘다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/startup-validation-failed.md b/docs/runbooks/startup-validation-failed.md index fbeb5e8a..06a1ff90 100644 --- a/docs/runbooks/startup-validation-failed.md +++ b/docs/runbooks/startup-validation-failed.md @@ -5,30 +5,30 @@ error_codes: [STARTUP_VALIDATION_FAILED] severity: P1 owner: oncall last_updated: 2026-06-15 -status: stub +status: 초안 --- # Runbook: STARTUP_VALIDATION_FAILED (`runbook://startup/validation-failed`) -## Symptoms +## 증상 -- Container exits with code 78 (env validation failure exit) -- Structured log with `error.code=STARTUP_VALIDATION_FAILED`, `startup.phase=env-validation` +- 컨테이너가 코드 78로 끝난다(환경 변수 검증 실패 종료). +- 구조화 로그 `error.code=STARTUP_VALIDATION_FAILED`, `startup.phase=env-validation`. -## Diagnosis +## 진단 -- Check which required env variable is missing or malformed -- Review container environment and secrets injection +- 빠졌거나 형식이 틀린 필수 환경 변수를 찾는다. +- 컨테이너 환경과 secret 주입을 확인한다. -## Action +## 조치 -- Supply missing environment variables to deployment -- Verify secrets are correctly mounted / injected +- 빠진 환경 변수를 배포에 넣는다. +- secret이 제대로 마운트·주입됐는지 확인한다. -## Escalation +## 에스컬레이션 -- P1: app cannot start; coordinate with deployment/secrets team +- P1: 앱이 뜨지 못한다. 배포·secret 담당 팀과 맞춘다. --- -> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9) +> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다. diff --git a/docs/runbooks/template.md b/docs/runbooks/template.md index 5759c600..48954a8a 100644 --- a/docs/runbooks/template.md +++ b/docs/runbooks/template.md @@ -5,40 +5,39 @@ error_codes: [, ] severity: owner: oncall last_updated: -status: +status: <초안|운영> --- # Runbook: (`runbook://<area>/<scenario>`) -## Symptoms +## 증상 -- What observable signals trigger this runbook? -- Alert name, metric thresholds, log patterns +- 이 runbook을 펴게 하는 관측 신호는 무엇인가? +- alert 이름, 메트릭 임계값, 로그 패턴 -## Diagnosis +## 진단 -- Step-by-step diagnostic commands and queries -- Log queries (Loki/CloudWatch) -- Metric panels to check -- Trace investigation approach +- 차례로 따라 하는 진단 명령과 쿼리 +- 로그 쿼리(Loki·CloudWatch) +- 볼 메트릭 패널 +- trace 조사 방법 -## Action +## 조치 -- Immediate mitigation steps -- Configuration changes -- Manual intervention procedures +- 바로 하는 완화 +- 설정 변경 +- 손으로 하는 개입 절차 -## Escalation +## 에스컬레이션 -- Conditions for severity upgrade (e.g., P2 → P1) -- Who to page and when -- Fallback procedures if on-call cannot resolve +- 심각도를 올리는 조건(예: P2 → P1) +- 언제 누구를 부르나 +- 당번이 풀지 못할 때의 대안 --- -> **Note**: This is the canonical runbook template. -> Copy this file, rename it to match the `runbook://area/scenario` pattern (→ `area-scenario.md`), -> fill in the frontmatter fields, replace section bodies with operational content, -> then set `status: active`. `LEGACY_STUB_DEBT` in `RunbookCoverageContractTest` is temporary -> containment for existing debt only; do not add a new stub there. Complete the runbook or adopt -> the future owned, expiring debt ledger. +> **안내**: 이 파일이 runbook의 기준 양식이다. +> 이 파일을 복사하고, `runbook://area/scenario` 꼴에 맞춰 이름을 바꾸고(→ `area-scenario.md`), 머리말 칸을 채우고, +> 절 본문을 운영 내용으로 바꾼 뒤 `status: 운영`으로 둔다. 본문을 아직 쓰지 못한 runbook은 `status: 초안`이다. +> `RunbookCoverageContractTest`의 `LEGACY_STUB_DEBT`는 이미 있는 초안만 잠시 담아 두는 목록이다. 새 초안을 거기에 +> 더하지 않는다. runbook을 끝내거나, 앞으로 생길 소유자·기한 있는 부채 장부를 쓴다. diff --git a/docs/storage-capability-boundary.md b/docs/storage-capability-boundary.md index 130fe99c..9eb6a39a 100644 --- a/docs/storage-capability-boundary.md +++ b/docs/storage-capability-boundary.md @@ -1,32 +1,27 @@ -# Fileserver vs Object Storage +# 파일 서버와 Object Storage -These capabilities overlap at the byte-storage level but own different serving boundaries. They are -not interchangeable providers for one port. +두 capability는 바이트 저장 수준에서 겹치지만 가진 서빙 경계가 다르다. port 하나의 바꿔 끼울 수 있는 provider가 아니다. -| Question | Fileserver HTTP platform | Object Storage | +| 질문 | 파일 서버 HTTP 플랫폼 | Object Storage | |---|---|---| -| Who serves bytes to the client? | This application, through Fileserver HTTP routes | This application, streaming through the semantic transfer port (no direct/presigned transfer exists) | -| Primary application contract | Upload/download/lifecycle HTTP workflow and Fileserver application ports | Provider-neutral managed and staged object-storage ports | -| Storage semantics | Application-owned staging, verification, publication, range/conditional delivery, upload leases | Managed and staged object publication plus remote-store versioning semantics | -| Local filesystem role | Certified backing store for the application-owned Fileserver platform | `filesystem-local-dev` development/provider implementation | -| Remote S3-style semantics | Not its purpose | First-class capability | +| 누가 클라이언트에 바이트를 주나? | 이 애플리케이션이 파일 서버 HTTP route로 준다 | 이 애플리케이션이 의미 수준 transfer port로 stream한다(직접·presigned 전송은 없다) | +| 주된 애플리케이션 계약 | upload/download/lifecycle HTTP 흐름과 파일 서버 애플리케이션 port | provider 중립의 managed·staged object storage port | +| 저장 의미 | 애플리케이션이 가진 staging, 검증, 게시, range·조건부 전달, upload lease | managed·staged 객체 게시와 원격 저장소의 versioning 의미 | +| 로컬 파일 시스템의 역할 | 애플리케이션이 가진 파일 서버 플랫폼의 인증된 backing store | `filesystem-local-dev` 개발용 provider 구현 | +| 원격 S3 방식의 의미 | 목적이 아니다 | 일급 capability | -## Decision rule +## 고르는 규칙 -Use **Fileserver** when the service itself owns upload/download HTTP behavior: authentication, range -and conditional requests, verification/quarantine, resumable upload state, lifecycle/admin routes, -and optional delegated serving such as X-Accel-Redirect. +서비스 자신이 upload/download HTTP 동작을 가질 때 **파일 서버**를 쓴다. 인증, range와 조건부 요청, 검증·격리, 이어 올리는 +upload 상태, lifecycle·관리 route, X-Accel-Redirect 같은 선택적 위임 서빙이다. -Use **Object Storage** when the application needs an object-storage abstraction whose provider owns -the storage semantics, especially S3-compatible managed objects. Direct/presigned transfer and -multipart upload are not implemented: their unassembled code was removed (see -`docs/capability-status.md` 「제거된 코드」). +애플리케이션이 저장 의미를 provider가 가지는 object storage 추상, 특히 S3 호환 managed 객체가 필요할 때 **Object Storage**를 +쓴다. 직접·presigned 전송과 multipart upload는 구현하지 않았다. 조립되지 않던 그 코드는 지웠다(`docs/capability-status.md` +「제거된 코드」). -Do not enable both as two independent sources of truth for the same logical object. If a product -needs both, one capability must own the logical object/control record and the other must be an -explicit transport/provider integration behind that owner; duplicating metadata, retention state, or -publication state across both is not a supported composition. +같은 논리 객체에 대해 둘을 서로 독립된 정본 둘로 켜지 않는다. 제품에 둘 다 필요하면 한 capability가 논리 객체·제어 기록을 +가지고, 다른 하나는 그 소유자 뒤의 명시적 전송·provider 통합이어야 한다. 둘에 메타데이터, 보존 상태, 게시 상태를 겹쳐 두는 것은 +지원하는 조립이 아니다. -Readiness remains independent: `docs/fileserver/support-matrix.md` certifies Fileserver behavior; -`docs/registries/object-storage-readiness.yaml` certifies Object Storage behavior. Evidence from one -does not upgrade the other. +readiness는 따로 남는다. `docs/fileserver/support-matrix.md`가 파일 서버 동작을, `docs/registries/object-storage-readiness.yaml`이 +Object Storage 동작을 인증한다. 한쪽의 증거가 다른 쪽을 올려 주지 않는다. diff --git a/docs/upgrade/2026-11-docs-records.md b/docs/upgrade/2026-11-docs-records.md index 0357e710..0cfd0ccf 100644 --- a/docs/upgrade/2026-11-docs-records.md +++ b/docs/upgrade/2026-11-docs-records.md @@ -1,12 +1,13 @@ # 업그레이드 안내 — 2026-11 기록 문서 위치 -- 범위: 템플릿 `docs/`의 설계서·계획서·납품 패키지·증거·학습 문서를 옮긴 변경 하나 +- 범위: 템플릿 `docs/`의 설계서·계획서·납품 패키지·증거·학습 문서를 옮긴 변경(1단계, 2·3절)과, 살아 있는 문서·ADR을 + 한국어로 옮기고 알림 결정 기록을 `docs/adr/`로 옮긴 변경(2단계, 2·4절) - 근거: `docs/README.md` 「설계와 기록」, design-docs `conventions/docs-system.md` ## 1. 누가 읽나 -이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스가 읽는다. 코드·설정·빌드는 바뀌지 않았다. -문서 경로만 바뀌었다. +이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스가 읽는다. 1단계에서는 코드·설정·빌드가 +바뀌지 않았고 문서 경로만 바뀌었다. 2단계에서는 문서를 읽는 테스트의 기대 문구가 한국어로 바뀌었다(4절). ## 2. 옮긴 경로 @@ -20,13 +21,44 @@ | `docs/websocket-superpowers-package/` | `docs/history/packages/websocket-superpowers-package/` | | `docs/evidence/` | `docs/history/evidence/` | | `docs/study/` | `docs/history/study/` | +| `docs/notification/adr/NOTIF-ADR-*.md` | `docs/adr/NOTIF-ADR-*.md` (2단계. `docs/notification/adr/` 폴더는 없어졌다) | `docs/superpowers/plans/2026-09-25-review-followup-tools/__pycache__/`의 `.pyc`는 실행 산출물이라 지웠다. ## 3. 할 일 1. 서비스 문서·코드 주석이 위 「전」 경로를 가리키면 「지금」 경로로 바꾼다. - `git grep -n -e docs/superpowers -e superpowers-package -e docs/evidence -e docs/study`로 찾는다. + `git grep -n -e docs/superpowers -e superpowers-package -e docs/evidence -e docs/study -e notification/adr`로 찾는다. 2. 서비스가 이 기록을 지웠다면 merge에서 「삭제 대 이름 바꿈」 충돌이 난다. 지운 쪽을 고르면 된다. -3. 옮긴 기록 파일과 ADR 맨 위에 한국어 머리 블록(상태·작성일·요약·현재 정본)을 달았다. 본문은 원문 그대로다. +3. 옮긴 기록 파일과 ADR 맨 위에 한국어 머리 블록(상태·작성일·요약·현재 정본)을 달았다. 본문은 원문 그대로다 + (ADR 본문만 2단계에서 한국어로 옮겼다. 4절). 서비스가 그 파일을 고쳤다면 맨 위 몇 줄에서 충돌이 날 수 있다. 형식은 `docs/README.md` 「기록 문서의 머리 블록」이다. + +## 4. 2단계 — 문서 번역 (2026-11-07) + +살아 있는 문서(README, `CLAUDE.md`, 모듈 문서, 영역 운영 문서, 레지스트리 설명 칸, runbook)와 ADR 본문을 한국어로 +옮겼다. 뜻은 바꾸지 않았다. 다만 코드와 다른 주장은 옮기면서 코드에 맞췄다(무엇을 고쳤는지는 각 `docs(...)` 커밋 +본문). 문서 검사에 `map`·`readme` 두 검사가 더해졌고, 예외 목록과 그 기준선(`FROZEN`)은 비었다(`docs/README.md` +「문서 검사」). + +### 할 일 + +| # | 할 일 | 안 하면 | 해당 서비스 | +|---|---|---|---| +| 1 | 템플릿 문서를 고친 적이 있으면, merge 충돌이 난 파일에서 자기 변경을 한국어판 위에 다시 얹는다 | 영어판이 남거나 충돌이 풀리지 않는다 | 템플릿 문서를 고친 서비스 | +| 2 | 자기 runbook(`docs/runbooks/*.md`) 머리말의 `status`를 `초안` 또는 `운영`으로 바꾼다(옛 `stub` → `초안`, `active` → `운영`) | `mainCheck`의 `:app-bootstrap:documentContractTest`(`RunbookCoverageContractTest`)가 실패한다. 두 값 밖의 `status`도 실패다 | `docs/runbooks/`에 자기 runbook을 둔 서비스 | +| 3 | 루트 `README.md`를 자기 것으로 고쳐 썼으면 `## 시작하기` 절과 「첫 실행 진입점은 하나다.」 문장을 둔다 | `:app-bootstrap:documentContractTest`(`DeveloperExperienceContractTest`)가 실패한다 | 루트 README를 바꾼 서비스 | +| 4 | `docs-check` workflow를 유지하면, 자기 문서 폴더를 `docs/README.md` 「문서 지도」 표에 더하고 루트 README가 정해진 `##` 절을 정해진 순서로 갖게 한다(`scripts/check-docs.py`의 `README_SECTIONS`) | `check-docs.py`의 `map`·`readme` 검사가 실패한다 | `docs-check`를 유지하는 서비스 | +| 5 | 아래 문서를 자기 것으로 고쳤으면, 그 문서를 읽는 테스트가 찾는 한국어 제목·칸 이름을 지킨다 | 그 테스트가 실패한다 | 해당 문서를 고친 서비스 | + +5번의 문서와 테스트: + +| 문서 | 테스트가 찾는 것 | 테스트 | +| --- | --- | --- | +| `docs/notification/support-matrix.md` | 등급 칸 이름 `등급`(옛 `Grade`), 절 「## 지원하지 않는 것」 | `NotificationEvidenceVerifier`, `NotificationReleaseGateTest` | +| `docs/fileserver/operations.md`, `docs/fileserver/support-matrix.md` | runbook 절 제목(「## 저장소 가득 참」 등)과 「## 주장하지 않는 것」 | `FileserverDocumentationCoverageTest` | +| `docs/jpa/support-matrix.md`, `docs/jpa/repository-adaptation.md` | 「운영 보장이 아니」, 「PostgreSQL 계약 증거」, 「알려진 빈틈」 | `JpaDocumentationContractTest` | +| `src/application-core/CLAUDE.md` | 패키지 소유 표 둘(application·domain)의 첫 머리 칸 `패키지 (…)` | `TemplatePackageOwnershipDocumentTest` | + +- 다른 문서가 영어 절 제목으로 가리키던 절은 `## 한국어 제목 (English title)` 꼴로 영어 제목을 괄호에 남겼다. + 서비스 문서·코드 주석의 영어 절 제목 인용은 그대로 찾아진다. diff --git a/docs/web/advanced-capabilities.md b/docs/web/advanced-capabilities.md index da72f415..58ffd654 100644 --- a/docs/web/advanced-capabilities.md +++ b/docs/web/advanced-capabilities.md @@ -1,78 +1,71 @@ -# Web Advanced: support matrix +# Web Advanced: 지원 매트릭스 -The Advanced capabilities live in their own leaf, `adapter:inbound:web-advanced` -(`src/adapter/inbound/web-advanced`, package `dev.caskeleton.adapter.inbound.web.advanced`). No -default composition carries it: `app-bootstrap`은 이 leaf에 의존하지 않는다. A -service that wants one of these capabilities adds the leaf as `implementation` in its own adapter -leaf and calls the types directly. +Advanced capability는 따로 된 leaf `adapter:inbound:web-advanced`(`src/adapter/inbound/web-advanced`, package +`dev.caskeleton.adapter.inbound.web.advanced`)에 있다. 이 leaf를 가진 기본 조립은 없다. `app-bootstrap`은 이 leaf에 +의존하지 않는다. 이 capability 중 하나가 필요한 서비스는 자기 어댑터 leaf에 이 leaf를 `implementation`으로 더하고 +타입을 직접 부른다. -Three capabilities have a runtime switch, published through the leaf's own -`META-INF/spring/...AutoConfiguration.imports`. Everything else is a library: no property, no bean, -nothing happens until service code calls it. +실행 중 스위치가 있는 capability는 셋이고, leaf 자신의 `META-INF/spring/...AutoConfiguration.imports`로 등록한다. +나머지는 모두 라이브러리다. 속성도 bean도 없고, 서비스 코드가 부르기 전에는 아무 일도 일어나지 않는다. -| Capability | How it is turned on | What it adds | Tests | +| Capability | 켜는 법 | 더하는 것 | 테스트 | | --- | --- | --- | --- | -| MVC virtual threads | `app.web.advanced.mvc-virtual-threads.enabled=true` (+ admission limit and budgets) | A different scheduling model for **every** request | `MvcAdvancedConfigurationTest`, `VirtualThreadAdmissionTest` | -| NDJSON streaming | `app.web.advanced.ndjson.enabled=true` | Long-lived connections | `MvcStreamingWiringTest`, `WebStreamCoreTest`, `WebStreamDrainTest`, `WebStreamingSoakIT` | -| JSON text sequences (RFC 7464) | `app.web.advanced.json-sequence.enabled=true` | Long-lived connections | as NDJSON | -| JSON Merge Patch (RFC 7396) | library — `JsonMergePatchApplier` | Partial documents | `JsonMergePatchApplierTest` | -| JSON Patch (RFC 6902) | library — `JsonPatchApplier` | Arbitrary pointers | `JsonPatchApplierTest` | -| CBOR / XML codecs | library — `WebCborMapperFactory`, `WebXmlMapperFactory`; the backend jar is the service's choice | A second decoder | `WebCodecMapperTest`, `WebCodecSecurityTest` | -| OpenAPI 3.2 | library — `WebOpenApi32Generator` | A parallel description artifact | `WebOpenApi32GeneratorTest` | -| Stream replay from messaging | library — `MessagingReplayBridge` | Resume after reconnect | `MessagingReplayBridgeTest` | +| MVC virtual thread | `app.web.advanced.mvc-virtual-threads.enabled=true`(+ 허가 상한과 예산) | **모든** 요청에 대한 다른 스케줄링 모델 | `MvcAdvancedConfigurationTest`, `VirtualThreadAdmissionTest` | +| NDJSON 스트리밍 | `app.web.advanced.ndjson.enabled=true` | 오래 사는 connection | `MvcStreamingWiringTest`, `WebStreamCoreTest`, `WebStreamDrainTest`, `WebStreamingSoakIT` | +| JSON text sequence(RFC 7464) | `app.web.advanced.json-sequence.enabled=true` | 오래 사는 connection | NDJSON과 같다 | +| JSON Merge Patch(RFC 7396) | 라이브러리 — `JsonMergePatchApplier` | 부분 문서 | `JsonMergePatchApplierTest` | +| JSON Patch(RFC 6902) | 라이브러리 — `JsonPatchApplier` | 임의의 pointer | `JsonPatchApplierTest` | +| CBOR / XML codec | 라이브러리 — `WebCborMapperFactory`, `WebXmlMapperFactory`. backend jar는 서비스가 고른다 | 두 번째 decoder | `WebCodecMapperTest`, `WebCodecSecurityTest` | +| OpenAPI 3.2 | 라이브러리 — `WebOpenApi32Generator` | 나란히 만드는 설명 산출물 | `WebOpenApi32GeneratorTest` | +| messaging에서 stream 다시 보내기 | 라이브러리 — `MessagingReplayBridge` | 다시 연결한 뒤 이어 받기 | `MessagingReplayBridgeTest` | -The same leaf also holds the web library packages the servlet production path never reaches: -`http` (URI and method policy), `versioning`, `operation`, `budget`, `contract`, `security` -(security-context bridge), `idempotency` (`JsonIdempotentResponseCodec`) and `admin/route`. +같은 leaf에 servlet 운영 경로가 닿지 않는 web 라이브러리 package도 있다: `http`(URI와 method 정책), `versioning`, +`operation`, `budget`, `contract`, `security`(security context 다리), `idempotency`(`JsonIdempotentResponseCodec`), +`admin/route`. -`./gradlew :adapter:inbound:web-advanced:test` runs all of it. `webAdvancedTest` is the tagged -subset and fails when the tag selects nothing. +`./gradlew :adapter:inbound:web-advanced:test`가 전부 돌린다. `webAdvancedTest`는 tag를 단 부분집합이고, tag가 아무 +것도 고르지 않으면 실패한다. -## Removed on 2026-09-25 +## 2026-09-25에 지운 것 -- The promotion/release gate (`WebAdvancedPromotionGate`, `WebAdvancedReleaseManifest`, - `WebAdvancedFeature`) and the OpenAPI 3.2 promotion report (`OpenApi32CompatibilityReport`, - `OpenApiToolchainMatrix`). They were checks on this repository's release process kept in - production code, and only their own tests called them. The feature catalog also named flags that - no code reads (`…json-merge-patch.enabled`, `…sse.enabled`, `…cbor.enabled` and others). -- `advanced.blockingbridge`: the accounting half of the WebFlux blocking bridge, whose adapter went - with the WebFlux twin. -- `functional` (`FunctionalRouteRegistry`, `WebFunctionalHandlerAdapter`): it built a WebFlux - `RouterFunction`, which nothing serves in a servlet-only template (D4). `spring-webflux` left the - leaf with it. -- Packages that re-implemented what the production web path already does another way, and the - `webNginxProxyTest` lane that certified only one of them: - - `proxy` + `http.External*` — production uses `server.forward-headers-strategy` +- 승격/릴리스 게이트(`WebAdvancedPromotionGate`, `WebAdvancedReleaseManifest`, `WebAdvancedFeature`)와 OpenAPI 3.2 + 승격 보고서(`OpenApi32CompatibilityReport`, `OpenApiToolchainMatrix`). 이 저장소의 릴리스 절차를 검사하는 것이 + production 코드에 있었고, 자기 테스트만 그것을 불렀다. 기능 목록은 어떤 코드도 읽지 않는 flag(`…json-merge-patch.enabled`, + `…sse.enabled`, `…cbor.enabled` 등)도 적었다. +- `advanced.blockingbridge`: WebFlux blocking 다리의 회계 쪽 절반. 어댑터 쪽은 WebFlux 쌍과 함께 사라졌다. +- `functional`(`FunctionalRouteRegistry`, `WebFunctionalHandlerAdapter`): WebFlux `RouterFunction`을 만들었는데, + servlet만 쓰는 템플릿(D4)에서는 아무것도 그것을 내보내지 않는다. `spring-webflux`도 함께 leaf를 떠났다. +- 운영 web 경로가 이미 다른 방식으로 하는 일을 다시 구현한 package들, 그리고 그중 하나만 인증하던 `webNginxProxyTest` + lane: + - `proxy` + `http.External*` — 운영은 `server.forward-headers-strategy`를 쓴다 (`app-bootstrap/src/main/resources/config/server.yml`). - - `security` CORS/CSRF profiles — production uses `CorsSettings` and `SecurityConfig`. - - `cache` — production uses `CacheControlFilter`. - - `json` (`WebObjectMapperFactory`) — production uses Boot's `JsonMapper`; the streaming encoder - now writes with that bean. - - `openapi.WebOpenApiCustomizer` (+ `WebOpenApiProfile`, `CursorSchemaContributor`) — - production customizes springdoc through `OpenApiContractConfig`. + - `security` CORS/CSRF profile — 운영은 `CorsSettings`와 `SecurityConfig`를 쓴다. + - `cache` — 운영은 `CacheControlFilter`를 쓴다. + - `json`(`WebObjectMapperFactory`) — 운영은 Boot의 `JsonMapper`를 쓴다. 스트리밍 encoder도 이제 그 bean으로 쓴다. + - `openapi.WebOpenApiCustomizer`(+ `WebOpenApiProfile`, `CursorSchemaContributor`) — 운영은 + `OpenApiContractConfig`로 springdoc을 손본다. -Recovery paths are in `docs/capability-status.md` (the removed-code table). +되살리는 길은 `docs/capability-status.md`(제거된 코드 표)에 있다. -## What is refused, and why the row is here +## 거부하는 것과 그 행이 여기 있는 이유 -| Refused | Reason | +| 거부 | 이유 | | --- | --- | -| Virtual threads without an admission limit | The pool size *was* the admission policy. Removing it accepts every arrival and queues them on downstream budgets that did not grow. | -| A merge patch outside its field allowlist | A merge patch is partial, so no DTO's absent fields say "not permitted". Without an allowlist the writable set grows every time somebody adds a field. | -| A JSON Patch pointer above its allowed prefix | Replacing a parent deletes every sibling, so permission on a child cannot grant it. | -| A `move` whose source is unauthorized | Checking only the destination lets a caller relocate data out of a field they may not touch. | -| XML with a DTD or an external entity | Billion-laughs and XXE. Neither errors when it fires; the parse succeeds and the document contains something it should not. | -| A non-JSON representation without all three gates | The enabled set the service passes to `RepresentationNegotiationPolicy`, route `produces`, and client allowlist. An `Accept` header is not evidence the route was tested against that codec. | -| Compression-style silent fallback on a 406 | A client that asked only for CBOR and gets JSON parses the bytes as CBOR and fails somewhere far away. | -| Changing HTTP status after commit | The body becomes half stream, half JSON, and the 200 is cached. | -| Unbounded buffering for a slow consumer | It moves the client's slowness into the server's heap. | +| 허가 상한 없는 virtual thread | pool 크기가 *곧* 허가 정책이었다. 그것을 없애면 오는 요청을 다 받고, 늘지 않은 하류 예산에 줄 세운다. | +| 필드 허용 목록 밖의 merge patch | merge patch는 부분이라, 어떤 DTO의 빠진 필드도 「허락 안 함」을 뜻하지 않는다. 허용 목록이 없으면 누가 필드를 더할 때마다 쓸 수 있는 집합이 커진다. | +| 허락한 접두사보다 위의 JSON Patch pointer | 부모를 바꾸면 모든 형제가 지워진다. 그래서 자식에 대한 권한이 부모 권한을 줄 수 없다. | +| 출처가 허락되지 않은 `move` | 목적지만 검사하면 호출자가 건드릴 수 없는 필드의 데이터를 옮겨 낼 수 있다. | +| DTD나 외부 entity가 있는 XML | Billion-laughs와 XXE. 둘 다 터져도 오류가 나지 않는다. 파싱은 성공하고 문서에 있으면 안 되는 것이 들어 있다. | +| 세 관문을 다 지나지 않은 JSON 아닌 표현 | 서비스가 `RepresentationNegotiationPolicy`에 넘기는 켜진 집합, route의 `produces`, client 허용 목록. `Accept` 헤더는 그 route가 그 codec으로 시험됐다는 증거가 아니다. | +| 406에서 압축처럼 조용히 물러서기 | CBOR만 요청한 client가 JSON을 받으면 그 바이트를 CBOR로 파싱하다 먼 곳에서 실패한다. | +| commit 뒤 HTTP 상태 바꾸기 | 본문이 반은 stream, 반은 JSON이 되고, 200이 cache된다. | +| 느린 소비자를 위한 상한 없는 버퍼링 | client의 느림을 서버의 heap으로 옮긴다. | -## Turning it off +## 끄기 -Removing the dependency removes the capability. With the dependency present, the three switches -default to off; `WebAdvancedRollbackIT` asserts that no Advanced bean exists with no flag set and -with each flag explicitly `false`. +의존성을 빼면 capability가 사라진다. 의존성이 있어도 스위치 셋은 기본으로 꺼져 있다. `WebAdvancedRollbackIT`가 +flag를 하나도 주지 않았을 때와 각 flag를 명시적으로 `false`로 줬을 때 Advanced bean이 하나도 없음을 단언한다. -See `docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md`, -`ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md`, and -`ADR-WEB-ADV-003-openapi-32-remains-experimental.md`. +`docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md`, +`ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md`, +`ADR-WEB-ADV-003-openapi-32-remains-experimental.md`를 본다. diff --git a/docs/web/http-contract.md b/docs/web/http-contract.md index 67cb9f91..1f66a154 100644 --- a/docs/web/http-contract.md +++ b/docs/web/http-contract.md @@ -206,5 +206,5 @@ CORS가 켜져 있으면(`app.cors.enabled=true`) cross-origin 실제 응답의 `docs/registries/error-codes.yaml`, 이 문서 2절을 같은 변경에서 고친다. 공유 코드의 `retryable`은 gRPC trailer(`error-retryable`)와 GraphQL extension(`retryable`)에도 그대로 나가므로 그 둘의 README와 매핑 테스트(`GrpcStatusMapperTest`, `GraphQlWireErrorMapperTest`)도 같이 본다. -- 짝 프론트의 백엔드 계약 문서(`clean-architecture-frontend-template` - `docs/architecture/backend-api-and-server-state-contract.md` §4.1·§6)는 이 문서를 가리켜야 한다. +- 짝 프론트 repo `clean-architecture-frontend-template`의 백엔드 계약 문서(「backend API와 server state + 계약」 §4.1·§6)는 이 문서를 가리켜야 한다. 그 문서는 다른 repo에 있어서 여기서 경로로 가리키지 않는다. diff --git a/docs/web/openapi-32-compatibility.md b/docs/web/openapi-32-compatibility.md index 1f042656..a6a477d6 100644 --- a/docs/web/openapi-32-compatibility.md +++ b/docs/web/openapi-32-compatibility.md @@ -1,32 +1,27 @@ -# OpenAPI 3.2: the experimental lane +# OpenAPI 3.2: 실험 lane -## Why it is a lane rather than an upgrade +## 업그레이드가 아니라 lane인 이유 -Generating 3.2 is cheap. Adopting it is not, and the two get conflated because the generated -document looks fine. +3.2를 만드는 것은 싸다. 받아들이는 것은 싸지 않다. 만든 문서가 멀쩡해 보여서 둘이 섞인다. -The value of an API description is entirely in what consumes it. A document in a version a client -generator does not fully understand does not fail — it produces a client that compiles and is wrong, -which is worse than no document at all. +API 설명의 가치는 전부 그것을 소비하는 쪽에 있다. client generator가 다 이해하지 못하는 버전의 문서는 실패하지 +않는다. 컴파일되는데 틀린 client를 만든다. 문서가 아예 없는 것보다 나쁘다. -So 3.1.2 stays the release artifact and 3.2 is generated beside it. +그래서 3.1.2가 릴리스 산출물로 남고, 3.2는 그 옆에서 만든다. -## The invariant +## 불변식 -**Generating 3.2 must not change the 3.1 snapshot.** Both come from the same model, so a contributor -that mutates it on the way to 3.2 changes the artifact that is actually shipped — silently, and only -when 3.2 is generated. +**3.2를 만드는 것이 3.1 snapshot을 바꾸면 안 된다.** 둘은 같은 모델에서 나온다. 그래서 3.2로 가는 길에 모델을 +바꾸는 기여자는 실제로 내보내는 산출물을 바꾼다. 조용히, 그리고 3.2를 만들 때만. -Nothing in this repository checks it any more. `OpenApi32CompatibilityReport` and -`OpenApiToolchainMatrix` — the promotion report that hashed the snapshot and recorded which parser, -linter, generator and client compile had read the 3.2 output — were removed on 2026-09-25: they -lived in production code and only their own tests called them. A service that generates 3.2 with -`WebOpenApi32Generator` (library, `adapter:inbound:web-advanced`) owns that check in its own build. +이 저장소에는 그것을 검사하는 것이 더는 없다. snapshot을 hash하고 어떤 parser, linter, generator, client 컴파일이 +3.2 출력을 읽었는지 기록하던 승격 보고서 `OpenApi32CompatibilityReport`와 `OpenApiToolchainMatrix`는 2026-09-25에 +지웠다. production 코드에 있었고 자기 테스트만 그것을 불렀다. `WebOpenApi32Generator`(라이브러리, +`adapter:inbound:web-advanced`)로 3.2를 만드는 서비스는 그 검사를 자기 빌드에서 가진다. -Promotion stays a judgement, recorded in -`docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md`. +승격은 판단으로 남고, `docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md`에 기록한다. -## Running it +## 돌리기 -No workflow in this repository generates 3.2. `OpenApiVersionLane.STABLE_3_1` is the release -artifact; `WebOpenApi32GeneratorTest` covers the generator. +이 저장소의 어떤 workflow도 3.2를 만들지 않는다. `OpenApiVersionLane.STABLE_3_1`이 릴리스 산출물이고, +`WebOpenApi32GeneratorTest`가 generator를 다룬다. diff --git a/docs/web/patch-contract.md b/docs/web/patch-contract.md index 8fffa985..5cb64725 100644 --- a/docs/web/patch-contract.md +++ b/docs/web/patch-contract.md @@ -1,60 +1,50 @@ -# Web patch: the client contract +# Web patch: client 계약 -Two patch formats, and they are not interchangeable. Both appliers are library code in -`adapter:inbound:web-advanced` (opt-in): a service adds the leaf and calls `JsonMergePatchApplier` -or `JsonPatchApplier` from its controller. +patch 형식은 둘이고, 서로 바꿔 쓸 수 없다. 두 applier 모두 `adapter:inbound:web-advanced`(골라 쓰는 leaf)의 라이브러리 +코드다. 서비스가 그 leaf를 더하고 자기 controller에서 `JsonMergePatchApplier`나 `JsonPatchApplier`를 부른다. -## Choosing one +## 하나 고르기 -A route accepts exactly one, and sending the other is a 415 rather than a best-effort guess. The -reason is that a mismatch is silent in the worst direction: +route는 정확히 하나만 받고, 다른 것을 보내면 최선의 짐작 대신 415다. 어긋남이 가장 나쁜 방향으로 조용하기 때문이다. -- `{"a": null}` as a **merge patch** deletes `a`. As a **JSON Patch** it is not a patch at all — it - is an object where an array was required. -- A JSON Patch array read as a merge patch is a document whose fields are array indices. It merges - nothing and reports success. +- `{"a": null}`은 **merge patch**로는 `a`를 지운다. **JSON Patch**로는 patch가 아예 아니다. 배열이 필요한 곳의 객체다. +- JSON Patch 배열을 merge patch로 읽으면 필드가 배열 index인 문서다. 아무것도 합치지 않고 성공을 보고한다. | | Merge patch | JSON Patch | | --- | --- | --- | | Media type | `application/merge-patch+json` | `application/json-patch+json` | | RFC | 7396 | 6902 | -| Shape | A partial document | An ordered array of operations | -| Delete | `"field": null` | `{"op":"remove","path":"/field"}` | -| Arrays | Replaced whole | Addressable per index | -| Preconditions | `If-Match` only | `If-Match`, plus per-field `test` | +| 모양 | 부분 문서 | 순서 있는 연산 배열 | +| 삭제 | `"field": null` | `{"op":"remove","path":"/field"}` | +| 배열 | 통째로 바꾼다 | index마다 가리킬 수 있다 | +| 선행 조건 | `If-Match`만 | `If-Match`, 그리고 필드별 `test` | -Use merge patch for "change these fields". Use JSON Patch when you need array element edits or a -precondition on one field that `If-Match` cannot express. +「이 필드들을 바꿔라」에는 merge patch를 쓴다. 배열 원소를 고치거나, `If-Match`로 표현할 수 없는 필드 하나의 선행 +조건이 필요하면 JSON Patch를 쓴다. -## What is refused +## 거부하는 것 -**Fields outside the allowlist.** The server declares which fields a merge patch may modify and -which pointers a JSON Patch may address. Anything else is refused, and *every* refused path is -named — you will not discover them one round trip at a time. +**허용 목록 밖의 필드.** 서버가 merge patch가 바꿀 수 있는 필드와 JSON Patch가 가리킬 수 있는 pointer를 선언한다. +그 밖의 것은 거부하고, 거부한 경로는 *모두* 이름을 댄다. 왕복 한 번에 하나씩 알게 되지 않는다. -The allowlist is checked **before** anything is applied. A refusal tells you nothing about the -current values, which is deliberate: deciding afterwards whether a refused field "actually changed -anything" would answer a question about data you may not read. +허용 목록은 무엇이든 적용하기 **전에** 검사한다. 거부는 지금 값에 대해 아무것도 알려 주지 않는다. 일부러 그렇다. +거부한 필드가 「실제로 무언가를 바꿨는지」를 나중에 따지면 읽어서는 안 되는 데이터에 대한 질문에 답하게 된다. -**Pointer permission does not travel upwards.** Permission on `/profile` covers -`/profile/displayName`; permission on `/profile/displayName` does not cover `/profile`, because -replacing the parent deletes every sibling. +**pointer 권한은 위로 올라가지 않는다.** `/profile`에 대한 권한은 `/profile/displayName`을 덮는다. +`/profile/displayName`에 대한 권한은 `/profile`을 덮지 않는다. 부모를 바꾸면 모든 형제가 지워지기 때문이다. -**A `move` needs permission on both ends.** Checking only the destination would let you relocate -data out of a field you may not touch. +**`move`는 양쪽 끝의 권한이 필요하다.** 목적지만 검사하면 건드릴 수 없는 필드의 데이터를 옮겨 낼 수 있다. -**Limits.** At most 100 operations, pointer depth at most 16, merge-patch nesting depth at most 32. -The first two multiply — each operation walks its pointer over a document the server deep-copied -first. +**한도.** 연산은 최대 100개, pointer 깊이는 최대 16, merge patch 중첩 깊이는 최대 32. 앞의 둘은 곱해진다. 연산마다 +서버가 먼저 깊이 복사한 문서 위로 pointer를 따라 걷는다. -## Atomicity +## 원자성 -A JSON Patch document applies entirely or not at all. Every operation runs against a working copy; -the resource is not touched until all of them have succeeded and the result has passed full -validation. +JSON Patch 문서는 전부 적용되거나 하나도 적용되지 않는다. 모든 연산은 작업 사본에서 돈다. 모든 연산이 성공하고 +결과가 전체 검증을 통과하기 전에는 자원을 건드리지 않는다. -This is what makes `test` useful. A client putting a `test` first is relying on nothing after it -having happened when the test fails, and that reliance holds: +그래서 `test`가 쓸모 있다. `test`를 맨 앞에 둔 client는 test가 실패하면 그 뒤의 어떤 것도 일어나지 않았다고 믿고, +그 믿음은 지켜진다. ```json [ @@ -63,18 +53,16 @@ having happened when the test fails, and that reliance holds: ] ``` -A failed `test` is **409**, not 400: the document was well-formed and permitted, and the resource -simply was not in the state you expected. Re-read and retry. The response names the pointer that -failed and does not return the server's value — returning it would make `test` a read primitive for -fields you may not read. +실패한 `test`는 400이 아니라 **409**다. 문서는 형식이 맞고 허락됐지만, 자원이 기대한 상태가 아니었을 뿐이다. 다시 +읽고 재시도한다. 응답은 실패한 pointer의 이름을 대고 서버의 값은 돌려주지 않는다. 돌려주면 `test`가 읽어서는 안 되는 +필드를 읽는 도구가 된다. -## Validation +## 검증 -The patched result is validated as a whole document, not field by field. A patch whose individual -fields are all valid can produce an object that is not — two fields that must agree, a state -transition that is not allowed — and validating only what changed sees none of it. +patch를 적용한 결과는 필드 하나씩이 아니라 문서 전체로 검증한다. 필드 하나하나는 모두 유효한 patch가 유효하지 않은 +객체를 만들 수 있다. 서로 맞아야 하는 두 필드, 허락되지 않은 상태 전이 같은 것이다. 바뀐 것만 검증하면 그중 아무것도 +보지 못한다. -## Preconditions +## 선행 조건 -Patch routes require `If-Match`. A partial update against a resource that moved underneath you -applies your changes to a version you never saw. +patch route는 `If-Match`를 요구한다. 그 사이에 바뀐 자원에 대한 부분 갱신은 본 적 없는 버전에 변경을 적용한다. diff --git a/docs/web/repository-adaptation.md b/docs/web/repository-adaptation.md index 8e233558..7f841345 100644 --- a/docs/web/repository-adaptation.md +++ b/docs/web/repository-adaptation.md @@ -1,284 +1,257 @@ -# Web platform — repository adaptation +# Web 플랫폼 — 저장소 적응 -The inbound HTTP API execution platform design -(`docs/history/packages/web-superpowers-package/docs/superpowers/specs/2026-08-13-web-inbound-http-api-execution-platform-design.md`) -was written against a standalone repository. Four of its assumptions do not hold here, and this -document records what each became and why, so a reader comparing the design to the tree is not left -guessing whether a difference is a decision or a mistake. +inbound HTTP API 실행 플랫폼 설계서 +(`docs/history/packages/web-superpowers-package/docs/superpowers/specs/2026-08-13-web-inbound-http-api-execution-platform-design.md`)는 +따로 선 저장소를 전제로 썼다. 그 가정 중 넷이 여기서는 맞지 않는다. 이 문서는 각각이 무엇이 됐고 왜 그런지 적는다. +설계와 트리를 비교하는 사람이 차이가 결정인지 실수인지 짐작하지 않게 하려는 것이다. -> **2026-09-25 (D4, Wave 2 W2-3).** The template is servlet (Spring MVC) on virtual threads. The -> WebFlux twin, the second-generation problem-document/budget/throttle/admission platform, the -> durable-operation HTTP projection and the in-leaf module-boundary check were removed. HTTP errors -> are the `Envelope` written by `GlobalExceptionHandler`. What was removed, and the commit it last -> existed in, is listed in `docs/capability-status.md` ("제거된 코드"). +> **2026-09-25 (D4, Wave 2 W2-3).** 템플릿은 virtual thread 위의 servlet(Spring MVC)이다. WebFlux 쌍, 2세대 +> problem-document/budget/throttle/admission 플랫폼, 지속 작업 HTTP 투영, leaf 안의 모듈 경계 검사를 지웠다. HTTP +> 오류는 `GlobalExceptionHandler`가 쓰는 `Envelope`다. 무엇을 지웠고 마지막으로 있던 commit이 무엇인지는 +> `docs/capability-status.md`(「제거된 코드」)에 있다. -## 1. Twenty-three Gradle modules became sub-packages of one leaf +## 1. Gradle 모듈 스물셋이 leaf의 하위 package가 됐다 -The design lays the platform out as `modules/web/web-core-api`, `web-contract`, `web-mvc` and so on. -This repository's `src/config/architecture/modules.json` is a fail-closed registry that owns the leaf -list, and adding twenty-three leaves to it is an architecture decision the design cannot make on the -repository's behalf. The JPA and GraphQL platforms reached the same fork and resolved it the same -way, so this is the established answer rather than a new one. +설계는 플랫폼을 `modules/web/web-core-api`, `web-contract`, `web-mvc` 같은 식으로 배치한다. 이 저장소의 +`src/config/architecture/modules.json`은 leaf 목록을 가진, 닫힌 쪽으로 실패하는 registry다. leaf 스물셋을 더하는 +것은 설계가 저장소 대신 내릴 수 없는 아키텍처 결정이다. JPA와 GraphQL 플랫폼도 같은 갈림길에서 같은 답을 냈다. +그래서 이것은 새 답이 아니라 이미 정한 답이다. -A Gradle dependency gate cannot see inside a leaf. The in-leaf module map that used to check the -package edges (`WebStableModule`) was removed with the second-generation platform; the ArchUnit -rules in `testkit/arch` (`WebArchitectureRules`) are what remains. +설계 모듈은 지금 web leaf(`adapter:inbound:web`)와 Advanced leaf(`adapter:inbound:web-advanced`)의 package로 +나뉘어 있다. Gradle 의존성 게이트는 leaf 안을 보지 못한다. package edge를 검사하던 leaf 안의 모듈 지도 +(`WebStableModule`)는 2세대 플랫폼과 함께 지웠다. 남은 것은 web leaf testFixtures의 `testkit/arch`에 있는 ArchUnit +규칙(`WebArchitectureRules`)이다. -| Design module | Package under `dev.caskeleton.adapter.inbound.web` | Status | +| 설계 모듈 | 지금 있는 곳(package는 `dev.caskeleton.adapter.inbound.web` 아래) | 상태 | | --- | --- | --- | -| `web-core-api` | `core` | planned (Task 2+) | -| `web-contract` | `contract` | planned | -| `web-error` | `error` | present | -| `web-pagination` | `pagination` | present | -| `web-idempotency` | `idempotency` | present | -| `web-idempotency-jpa` | `idempotency.jpa` | planned | -| `web-idempotency-redis` | `idempotency.redis` | planned | -| `web-versioning` | `versioning` | planned | -| `web-security-integration` | `auth`, `authz` | present | -| `web-observability` | `observability` | present | -| `web-openapi` | `openapi` | planned | -| `web-mvc` | `mvc` | planned | -| `web-webflux` | — | removed (D4: servlet only) | -| `web-admin` | `admin` | planned | -| `web-operation-jpa` | `operation.jpa` | planned | -| `web-operation-messaging` | `operation.messaging` | planned | -| `web-spring-boot-starter-mvc` | `autoconfigure.mvc` | planned | -| `web-spring-boot-starter-webflux` | — | removed (D4: servlet only) | -| `web-testkit-*` | `testkit`, `testkit.mvc` | present | -| — | `conditional`, `http`, `filter`, `envelope`, `config`, `controller`, `ratelimit`, `settings` | present, pre-dates the design | -| — | `fileserver.*`, `notification.*` | present, feature integrations rather than platform modules | +| `web-core-api` | web leaf `core` | 있음 | +| `web-contract` | web-advanced leaf `advanced.contract` | 있음(라이브러리) | +| `web-error` | web leaf `error` | 있음 | +| `web-pagination` | web leaf `pagination` | 있음 | +| `web-idempotency` | web-advanced leaf `advanced.idempotency`. 저장소 SPI는 `application-core`(6절) | 있음 | +| `web-idempotency-jpa` | web 쪽에는 없다. `persistence-jpa`의 `PostgreSqlIdempotencyStore`(6절) | 다른 곳에 있음 | +| `web-idempotency-redis` | web 쪽에는 없다. `cache-redis`의 `RedisIdempotencyStoreAdapter`(6절) | 다른 곳에 있음 | +| `web-versioning` | web-advanced leaf `advanced.versioning` | 있음(라이브러리) | +| `web-security-integration` | web leaf `auth`, `authz` | 있음 | +| `web-observability` | web leaf `observability` | 있음 | +| `web-openapi` | web leaf `config`의 `OpenApiContractConfig`(springdoc, 3.1), web-advanced leaf `advanced.openapi`(3.2 생성기) | 있음 | +| `web-mvc` | web leaf `mvc` | 있음 | +| `web-webflux` | — | 지움(D4: servlet만) | +| `web-admin` | web-advanced leaf `advanced.admin` | 있음(라이브러리) | +| `web-operation-jpa` | web 쪽에는 없다. `persistence-jpa`의 `operation`(7절) | 다른 곳에 있음 | +| `web-operation-messaging` | — | 없음 | +| `web-spring-boot-starter-mvc` | web leaf `mvc.autoconfigure`(`WebAdapterAutoConfiguration`) | 있음 | +| `web-spring-boot-starter-webflux` | — | 지움(D4: servlet만) | +| `web-testkit-*` | web leaf testFixtures의 `testkit`(`arch`, `fault`, `mvc`, `order`, `performance`) | 있음 | +| — | web leaf `conditional`, `http`, `filter`, `envelope`, `config`, `controller`, `ratelimit`, `settings` | 있음, 설계보다 먼저 있었다 | +| — | web leaf `operation`(지속 작업 HTTP 면, 7절) | 있음 | +| — | 파일서버·알림 HTTP 면 | 따로 된 leaf `adapter:inbound:web-fileserver`, `adapter:inbound:web-notification` | ## 2. Root package -The design uses `io.backend.skeleton.web`. This repository's package root is -`dev.caskeleton.adapter.inbound.web`, and the registry, the ArchUnit rules and the composition root's -component scan are all written against it. +설계는 `io.backend.skeleton.web`을 쓴다. 이 저장소의 package root는 `dev.caskeleton.adapter.inbound.web`이고, +registry, ArchUnit 규칙, 조립 루트의 component scan이 모두 그것을 기준으로 쓰였다. ## 3. Gradle DSL -The design's snippets are Kotlin DSL. Every build file in this repository is Groovy DSL, and -`src/build-logic` carries the shared convention plugins the leaf inherits. The build logic is -translated, not copied. +설계의 조각은 Kotlin DSL이다. 이 저장소의 빌드 파일은 모두 Groovy DSL이고, `src/build-logic`이 leaf가 물려받는 공용 +convention plugin을 가진다. 빌드 로직은 복사하지 않고 옮겨 썼다. -## 4. Spring Boot baseline +## 4. Spring Boot 기준 -The design names "Spring Boot 4.1 BOM". This repository's baseline is **4.0.8** — see -`.vscode/settings.json` for why the 4.1 minor line is a planned migration rather than a currency -fix. Where the design depends on a 4.1-only API the difference is recorded at the call site rather -than silently absorbed. +설계는 「Spring Boot 4.1 BOM」을 든다. 이 저장소의 기준은 Spring Boot 4.0 계열이다(정확한 버전은 +`src/gradle/libs.versions.toml`의 `springBoot`). 설계가 4.1에만 있는 API에 기대는 곳은 그 차이를 조용히 흡수하지 않고 +호출하는 자리에 적는다. -## 5. Sample application +## 5. 샘플 애플리케이션 설계의 `examples/web-platform-sample`에 해당하는 모듈은 없다. 그 역할을 하던 샘플 leaf는 2026-11-07에 지웠고, 그 안의 OpenAPI 드리프트 검사와 실서버 계약 lane도 함께 사라졌다. 예시는 `docs/manual/`과 `scripts/new-feature.sh` 출력이 맡는다. -## 6. Idempotency: the design's store SPI is already owned by `application-core` +## 6. 멱등성: 설계의 저장소 SPI는 이미 `application-core`가 가진다 -The design gives `web-idempotency` its own `IdempotencyStore`, `IdempotencyRecord`, -`IdempotencyState`, `IdempotencyScope` and `RequestFingerprint`. This repository already has the -equivalents in `application-core/idempotency` — `IdempotencyStorePort`, `IdempotencyState`, -`IdempotencyScopeDigest` and `RequestFingerprint` — with two provider stores behind the port: -PostgreSQL (`PostgreSqlIdempotencyStore` in `persistence-jpa`) and Redis -(`RedisIdempotencyStoreAdapter` in `cache-redis`), selected by -`app.capabilities.idempotency.provider`. That is what the design's Tasks 39 and 40 ask for, -built in the direction the registry permits. +설계는 `web-idempotency`에 자기 `IdempotencyStore`, `IdempotencyRecord`, `IdempotencyState`, `IdempotencyScope`, +`RequestFingerprint`를 준다. 이 저장소에는 이미 `application-core/idempotency`에 같은 것들이 있다: +`IdempotencyStorePort`, `IdempotencyState`, `IdempotencyScopeDigest`, `RequestFingerprint`. port 뒤에는 provider +저장소가 둘 있다. PostgreSQL(`persistence-jpa`의 `PostgreSqlIdempotencyStore`)과 Redis(`cache-redis`의 +`RedisIdempotencyStoreAdapter`)이고, `app.capabilities.idempotency.provider`로 고른다. 설계의 Task 39와 40이 요구하는 +것이 이것이고, registry가 허락하는 방향으로 만들었다. -Implementing the design's SPI literally would have required -`adapter-outbound-persistence-jpa → adapter-inbound-web`, an edge the registry forbids and one that -points the wrong way regardless: the store is an application concern that two transports could -share, not something the HTTP layer owns. +설계의 SPI를 글자 그대로 구현하려면 `adapter-outbound-persistence-jpa → adapter-inbound-web` edge가 필요했다. +registry가 금하는 edge이고, 어쨌든 방향이 틀렸다. 저장소는 두 transport가 함께 쓸 수 있는 애플리케이션 관심사이지, +HTTP 계층이 가질 것이 아니다. -So the web leaf keeps only the part that is genuinely HTTP: JSON encoding of a replayed -application result. Claiming, scope, fingerprint construction and replay policy remain at the -application use-case boundary. +그래서 web 쪽에는 정말 HTTP인 부분만 남는다: 다시 보내는 애플리케이션 결과의 JSON 인코딩이고, +`adapter:inbound:web-advanced`에 있다. 잡기, 범위, fingerprint 만들기, 다시 보내기 정책은 애플리케이션 use case +경계에 남는다. -| Design concern | Here | +| 설계 관심사 | 여기 | | --- | --- | | store / record / scope / claim / replay | `application-core/idempotency` | -| request fingerprint policy | application use case, because only the use case knows which fields define the same work | -| `Idempotency-Key` extraction | concrete inbound endpoint that opts into idempotency | -| replay JSON encoding | `adapter-inbound-web-advanced/idempotency/JsonIdempotentResponseCodec` | +| 요청 fingerprint 정책 | 애플리케이션 use case. 어떤 필드가 같은 일을 정하는지는 use case만 안다 | +| `Idempotency-Key` 꺼내기 | 멱등성을 골라 쓰는 구체 inbound endpoint | +| 다시 보내기 JSON 인코딩 | `adapter-inbound-web-advanced/idempotency/JsonIdempotentResponseCodec` | -This avoids two authorities for “same request”. The HTTP adapter does not run its own database -replay policy; it translates the transport input into the application idempotency context and lets -the use case own duplicate execution. +이렇게 하면 「같은 요청」을 정하는 권한이 둘이 되지 않는다. HTTP 어댑터는 자기 DB 다시 보내기 정책을 돌리지 않는다. +transport 입력을 애플리케이션 멱등성 context로 옮기고, 중복 실행은 use case가 갖게 한다. -## 7. Durable operations: the design's `web-operation-jpa` cannot exist here +## 7. 지속 작업: 설계의 `web-operation-jpa`는 여기 있을 수 없다 -The design gives the web platform its own persistence module — `modules/web/web-operation-jpa` — -holding a JPA store for long-running operations, with the port -(`DurableOperationStore`) in `web-core-api` beside `WebProblem`. +설계는 web 플랫폼에 자기 persistence 모듈 `modules/web/web-operation-jpa`를 준다. 오래 도는 작업을 위한 JPA 저장소를 +담고, port(`DurableOperationStore`)는 `web-core-api`에 `WebProblem` 옆에 둔다. -`src/config/architecture/modules.json` forbids both halves of that: +`src/config/architecture/modules.json`은 그 두 절반을 모두 금한다. -- `:adapter:inbound:web` may depend only on `domain-core`, `application-core` and - `shared-contract`, so the web leaf cannot take a JPA dependency. -- `:adapter:outbound:persistence-jpa` is an outbound adapter and cannot depend on an inbound one, - so a JPA store cannot see a web type. +- `:adapter:inbound:web`은 registry가 허락한 leaf에만 의존할 수 있다(`domain-core`, `application-core`, + `shared-contract`, `adapter-outbound-support`). 그래서 web leaf는 JPA 의존성을 가질 수 없다. +- `:adapter:outbound:persistence-jpa`는 outbound 어댑터라 inbound 어댑터에 의존할 수 없다. 그래서 JPA 저장소는 web + 타입을 볼 수 없다. -This is the same shape as §6 and takes the same resolution — the one the repository already used -for idempotency, where `IdempotencyStorePort` lives in `application-core` and -`PostgreSqlIdempotencyStore` in `persistence-jpa`: +6절과 같은 모양이고 같은 해결을 쓴다. 저장소가 멱등성에 이미 쓴 해결이다. 거기서 `IdempotencyStorePort`는 +`application-core`에, `PostgreSqlIdempotencyStore`는 `persistence-jpa`에 있다. -| Design type | Here | +| 설계 타입 | 여기 | | --- | --- | | `DurableOperationStore` | `application-core/operation/DurableOperationStorePort` | | `OperationSubmission` | `application-core/operation/DurableOperationSubmission` | -| the stored operation | `application-core/operation/DurableOperation` | -| the lease | `application-core/operation/OperationLease` | -| the stored failure | `application-core/operation/OperationFailure` — a code and an already-safe message, never an exception | +| 저장한 작업 | `application-core/operation/DurableOperation` | +| lease | `application-core/operation/OperationLease` | +| 저장한 실패 | `application-core/operation/OperationFailure` — code와 이미 안전한 메시지. 예외가 아니다 | | `JpaDurableOperationStore`, `JpaOperationEntity`, `V002__web_operation.sql` | `persistence-jpa/operation/*`, `db/migration/postgresql/V11__durable_operation.sql` | -| `OperationResource`, `OperationStatus`, `OperationProgress`, `OperationId` | removed 2026-09-25 — the web `operationasync` projection and `/api/v1/operations` controller had no production wiring and published failures only as `WebProblem` | +| `OperationResource`, `OperationStatus`, `OperationProgress`, `OperationId` | 2026-09-25에 지움 — web `operationasync` 투영과 `/api/v1/operations` controller는 운영 연결이 없었고 실패를 `WebProblem`으로만 내보냈다 | -The split is not only a registry workaround; it puts each half where its invariants belong. A -problem document is an HTTP concept and has no business being persisted, so the stored failure is a -code plus a safe message. +이 나눔은 registry 우회만이 아니다. 각 절반을 그 불변식이 속한 곳에 둔다. problem document는 HTTP 개념이고 저장될 +이유가 없다. 그래서 저장한 실패는 code와 안전한 메시지다. -The HTTP surface was added back on 2026-09-25 (owner decision 15) as a thin transport over the -application use cases: `adapter:inbound:web` `operation/DurableOperationController` — -`POST /operations` (202 + `Location`), `GET /operations/{id}`, `DELETE /operations/{id}` (202), -answers in the `Envelope` contract, and a caller's operation that is not theirs is the same 404 -(`OPERATION_NOT_FOUND`) as one that does not exist. The controller and the three use cases are -assembled by `composition:durable-operation` (`DurableOperationAutoConfiguration`), which turns on only -when the operation store and the outbox append port exist (the JPA module with -`app.outbox.enabled=true`). Submit and cancel need `operation:submit` / `operation:cancel` -(that module's `config/module-defaults/durable-operation.yml` grants both to the `operation-submit` -role). +HTTP 면은 2026-09-25에 애플리케이션 use case 위의 얇은 transport로 다시 더했다(소유자 결정 15). +`adapter:inbound:web` `operation/DurableOperationController`다. -The state machine is enforced three times on purpose: in `DurableOperation`'s constructor, in the -`CHECK` constraints of `V11__durable_operation.sql`, and in the `WHERE` clause of every statement -that changes a row. The constructor catches application bugs, the constraints catch any other -writer, and the predicates make each transition atomic — a worker whose lease lapsed while it was -still working cannot record a result over the worker that took over, because its `UPDATE` matches -no row and it learns that from the affected count. +- `POST /operations`(202 + `Location`), `GET /operations/{id}`, `DELETE /operations/{id}`(202). +- `Envelope` 계약으로 답한다. +- 호출자의 것이 아닌 작업은 없는 작업과 같은 404(`OPERATION_NOT_FOUND`)다. -## 8. Budget enforcement: what the edge stops and what the application stops +controller와 use case 셋은 `composition:durable-operation`(`DurableOperationAutoConfiguration`)이 조립한다. 작업 +저장소와 outbox append port가 있을 때만 켜진다(JPA 모듈과 `app.outbox.enabled=true`). 제출과 취소에는 +`operation:submit` / `operation:cancel`이 필요하다(그 모듈의 `config/module-defaults/durable-operation.yml`이 둘 다 +`operation-submit` role에 준다). -> **Removed 2026-09-25.** The servlet budget filter (`WebMvcBudgetFilter`) and its problem mapping -> were deleted with the second-generation platform. The shipped application no longer enforces the -> application column below; the `budget` catalog (`WebRequestBudget`, `WebBudgetCatalog`) remains as -> library code in `adapter:inbound:web-advanced`, and its unused meter (`WebBudgetMeter` and its -> outcome/violation types) was removed. The edge column still applies. +상태 기계는 일부러 세 번 강제한다: `DurableOperation`의 생성자, `V11__durable_operation.sql`의 `CHECK` 제약, 행을 바꾸는 +모든 문의 `WHERE` 절. 생성자는 애플리케이션 결함을 잡고, 제약은 다른 쓰는 쪽을 잡고, 조건은 전이마다 원자적으로 +만든다. 일하는 동안 lease가 끝난 worker는 이어받은 worker 위에 결과를 기록할 수 없다. 그 `UPDATE`가 행에 맞지 않고, +worker는 바뀐 행 수로 그것을 안다. -The design (Task 49) requires that the difference between an edge proxy's limits and the -application's own be written down rather than discovered during an incident. Two limits on the same -dimension always exist, they are never equal, and which one fires decides what the caller sees. +## 8. 예산 강제: edge가 막는 것과 애플리케이션이 막는 것 -| Dimension | Edge (nginx) | Application | Who answers when crossed | +> **2026-09-25에 지움.** servlet 예산 filter(`WebMvcBudgetFilter`)와 그 problem 대응은 2세대 플랫폼과 함께 지웠다. +> 내보내는 애플리케이션은 더는 아래 애플리케이션 칸을 강제하지 않는다. `budget` 목록(`WebRequestBudget`, +> `WebBudgetCatalog`)은 `adapter:inbound:web-advanced`에 라이브러리 코드로 남고, 쓰이지 않던 meter(`WebBudgetMeter`와 +> 그 결과/위반 타입)는 지웠다. edge 칸은 여전히 맞다. + +설계(Task 49)는 edge proxy의 한도와 애플리케이션 자체 한도의 차이를 장애 중에 발견하지 말고 적어 두라고 요구한다. +같은 차원에 한도는 늘 둘 있고, 둘은 결코 같지 않으며, 어느 쪽이 걸리는지가 호출자가 보는 것을 정한다. + +| 차원 | Edge (nginx) | 애플리케이션 | 넘으면 누가 답하나 | | --- | --- | --- | --- | -| Request line / URI | `large_client_header_buffers` (default 8k) | `maxUriBytes` | Edge first — nginx answers 414 with its own HTML | -| Request headers | `large_client_header_buffers` | `maxHeaderBytes` | Edge first — nginx 400, no problem document | -| Request body | `client_max_body_size` (default 1m) | `maxBodyBytes` (platform ceiling 8 MiB) | Whichever is smaller; nginx answers 413 with HTML | -| Query parameter count | not enforced | `maxQueryParameters` | Application, always | -| JSON depth / array size | not enforced | `maxJsonDepth`, `maxArrayElements` | Application, always | -| Execution time | `proxy_read_timeout` (default 60s) | `maxExecutionTime` (ceiling 2 min) | Edge first if the platform's is larger | -| Response size | not enforced | `maxResponseBytes` (ceiling 32 MiB) | Application, always | +| 요청 줄 / URI | `large_client_header_buffers`(기본 8k) | `maxUriBytes` | edge가 먼저 — nginx가 자기 HTML로 414 | +| 요청 헤더 | `large_client_header_buffers` | `maxHeaderBytes` | edge가 먼저 — nginx 400, problem document 없음 | +| 요청 본문 | `client_max_body_size`(기본 1m) | `maxBodyBytes`(플랫폼 상한 8 MiB) | 더 작은 쪽. nginx는 HTML로 413 | +| query parameter 수 | 강제하지 않음 | `maxQueryParameters` | 늘 애플리케이션 | +| JSON 깊이 / 배열 크기 | 강제하지 않음 | `maxJsonDepth`, `maxArrayElements` | 늘 애플리케이션 | +| 실행 시간 | `proxy_read_timeout`(기본 60s) | `maxExecutionTime`(상한 2분) | 플랫폼 쪽이 더 크면 edge가 먼저 | +| 응답 크기 | 강제하지 않음 | `maxResponseBytes`(상한 32 MiB) | 늘 애플리케이션 | -Two consequences worth stating, because both are counterintuitive: +둘 다 직관과 반대라서 적어 둘 만한 결과가 둘 있다. -**An edge limit below the application's means clients never see the application's error body.** -nginx answers its own HTML error page, so a client that branches on `error.code` gets a body it -cannot parse. -Where a dimension matters to clients, the edge limit must be set *above* the application's so the -application is the one that refuses. +**edge 한도가 애플리케이션 한도보다 낮으면 client는 애플리케이션의 오류 본문을 절대 보지 못한다.** nginx가 자기 +HTML 오류 쪽을 답하므로, `error.code`로 분기하는 client는 파싱할 수 없는 본문을 받는다. client에게 중요한 차원이면 +edge 한도를 애플리케이션보다 *높게* 두어 애플리케이션이 거부하게 한다. -**An edge limit above the application's is not redundant.** It is the only thing standing between -the process and a body large enough to matter before the application's own meter has counted it. -Both belong; only their ordering is a decision. +**edge 한도가 애플리케이션보다 높아도 쓸데없지 않다.** 애플리케이션의 meter가 세기 전에 문제가 될 만큼 큰 본문과 +프로세스 사이에 서 있는 것은 그것뿐이다. 둘 다 있어야 하고, 정할 것은 순서뿐이다. -## 9. The Nginx lane (removed 2026-09-25) +## 9. Nginx lane (2026-09-25에 지움) -The `webNginxProxyTest` lane ran the forwarded-header library (`proxy`, `http.External*`) behind a -Testcontainers `nginx:1.27-alpine`. That library was a second way of doing what the shipped path -does with `server.forward-headers-strategy`, so the library and its lane were removed together -(`docs/capability-status.md`, "제거된 코드"). +`webNginxProxyTest` lane은 forwarded header 라이브러리(`proxy`, `http.External*`)를 Testcontainers +`nginx:1.27-alpine` 뒤에서 돌렸다. 그 라이브러리는 내보내는 경로가 `server.forward-headers-strategy`로 하는 일을 다른 +방식으로 하는 것이었다. 그래서 라이브러리와 lane을 함께 지웠다(`docs/capability-status.md`, 「제거된 코드」). -One finding from that lane still applies to any Nginx in front of this service. Nginx's -inheritance rule for array directives is *replacement*: a single `proxy_set_header` inside a -`location` discards every `proxy_set_header` inherited from `server`. Setting the forwarded headers -once at `server` level and adding only `X-Forwarded-Prefix` per `location` therefore sends none of -the others, and the application falls back to the upstream's own `Host`. Keep the forwarded headers -in one included file and `include` it in every `location`. +그 lane에서 얻은 발견 하나는 이 서비스 앞의 어떤 Nginx에도 여전히 맞다. Nginx의 배열 지시어 상속 규칙은 +*교체*다. `location` 안의 `proxy_set_header` 하나가 `server`에서 물려받은 `proxy_set_header`를 모두 버린다. 그래서 +forwarded header를 `server` 수준에 한 번 두고 `location`마다 `X-Forwarded-Prefix`만 더하면 나머지는 하나도 보내지 +않고, 애플리케이션은 upstream 자신의 `Host`로 물러선다. forwarded header는 include 파일 하나에 두고 모든 +`location`에서 `include`한다. -## Advanced capabilities +## Advanced capability -The Advanced expansion plan asks for eleven Gradle modules under `modules/web-advanced/`. They are -packages under `advanced.**` in this leaf, for the reason the Stable platform is one leaf: -`src/config/architecture/modules.json` is fail-closed and owns the leaf list, and eleven entries to -satisfy a directory layout is a registry change rather than an architecture one. +Advanced 확장 계획서는 `modules/web-advanced/` 아래에 Gradle 모듈 열하나를 요구한다. 여기서는 따로 된 leaf +`adapter:inbound:web-advanced`의 `advanced.**` package다. Stable 플랫폼이 leaf 하나인 것과 같은 이유다. +`src/config/architecture/modules.json`이 닫힌 쪽으로 실패하고 leaf 목록을 가진다. 폴더 배치를 맞추려고 항목 열하나를 +더하는 것은 아키텍처 변경이 아니라 registry 변경이다. -What the design wanted from the separation is enforced instead by two machine checks: +설계가 나눔으로 얻으려던 것은 대신 registry가 강제한다. registry는 `adapter-inbound-web-advanced → +adapter-inbound-web` 방향만 허락한다. 그래서 Stable 클래스가 Advanced 타입을 이름 대면 Gradle 의존성 게이트 +(`verifyCleanArchitectureDependencies`)가 빌드를 실패시킨다. feature flag는 bean을 만들지 정할 뿐 컴파일 시점 edge에는 +아무것도 하지 않는다. 그런 edge 하나면 Advanced 없이는 Stable을 빌드할 수 없다. -- **`WEB-ARCH-ADV`** in `WebArchitectureRules.stableDoesNotDependOnAdvanced()` fails the build when a - Stable class names an Advanced type. A feature flag decides whether a bean is created; it does - nothing about a compile-time edge, and one such edge makes Stable unbuildable without Advanced. +`advanced.patch`와 `advanced.codec`은 framework에 묶이고, 묶일 수밖에 없었다. 앞의 것은 Jackson의 tree 모델 때문이다. +merge patch의 「null은 지움」은 Java 객체로 표현할 수 없어서 applier가 node 위에서 일한다. 뒤의 것은 +`XMLInputFactory` 때문이다. `advanced.stream.encoding`을 `advanced.stream`에서 떼어 낸 것도 같은 이유다. framing은 +직렬화하고, 직렬화는 Jackson에 묶인다. -`advanced.patch` and `advanced.codec` bind to a framework and had to: Jackson's tree model is the -reason for the first — a merge patch's null-means-delete has no representation in a Java object, so -the applier works on nodes — and `XMLInputFactory` is the reason for the second. -`advanced.stream.encoding` is separated from `advanced.stream` for the same reason: framing -serializes, and serializing binds to Jackson. +### 복사하지 않고 고친 것 -### What was adapted rather than copied +**`WebStreamErrorPolicy`의 factory 메서드는 `startOver` / `resumeFromPosition` / `nothingToDo`다.** 설계의 이름은 +record 자신의 accessor와 겹쳤고, Java가 그것을 거부한다. -**`WebStreamErrorPolicy`'s factory methods are `startOver` / `resumeFromPosition` / `nothingToDo`.** -The design's names collided with the record's own accessors, which Java rejects. +**codec backend는 compile 전용이고, 그 이유를 알아내는 데 조립 루트 하나가 깨졌다.** `WebCborMapperFactory`와 +`WebXmlMapperFactory`를 구현했고, 실패 모드를 지닌 부분도 함께 구현했다. -**The codec backends are compile-only, and finding out why cost a broken composition root.** -`WebCborMapperFactory` and `WebXmlMapperFactory` are implemented, along with the parts that carry -the failure modes: `SecureXmlInputFactory` (the DTD and external-entity defaults, both of which -produce no error when they fire), `CodecBudget` (per representation, because a megabyte of CBOR can -declare an array of a billion elements in a handful of bytes), and `RepresentationNegotiationPolicy` -(three gates, because an `Accept` header is not evidence the route was tested against that codec). +- `SecureXmlInputFactory`: DTD와 외부 entity 기본값. 둘 다 터져도 오류를 내지 않는다. +- `CodecBudget`: 표현마다 둔다. CBOR 1메가바이트는 몇 바이트로 원소 10억 개짜리 배열을 선언할 수 있다. +- `RepresentationNegotiationPolicy`: 관문 셋. `Accept` 헤더는 그 route가 그 codec으로 시험됐다는 증거가 아니다. -`jackson-dataformat-cbor` and `jackson-dataformat-xml` were declared `implementation` first, so that -a missing backend could not surface as a `NoClassDefFoundError` at the first request that negotiated -one. That reasoning was wrong about what the jars do. Spring Boot's Jackson auto-configuration -registers an `xmlMapper` and a `cborMapper` bean the moment each backend is on the runtime -classpath, and Spring registers an XML message converter with it. Two things followed, and only the -first was noisy: +처음에는 `jackson-dataformat-cbor`와 `jackson-dataformat-xml`을 `implementation`으로 선언했다. backend가 없을 때 그것을 +협상한 첫 요청에서 `NoClassDefFoundError`로 드러나지 않게 하려는 것이었다. jar가 하는 일에 대해 그 판단은 틀렸다. +Spring Boot의 Jackson auto-configuration은 각 backend가 런타임 classpath에 올라오는 순간 `xmlMapper`와 `cborMapper` +bean을 등록하고, Spring은 그것으로 XML 메시지 변환기를 등록한다. 두 가지가 뒤따랐고, 시끄러운 것은 첫째뿐이었다. -- The composition root held three `ObjectMapper` beans — `webStrictObjectMapper`, `xmlMapper`, - `cborMapper` — so every `@Autowired ObjectMapper` became ambiguous and the application would not - start. Six `app-bootstrap` tests failed with `UnsatisfiedDependencyException`. -- Every deployment silently began accepting `application/xml` request bodies. An XXE surface, - acquired by adding a dependency, on a capability that is supposed to be off unless a deployment - names it. +- 조립 루트가 `ObjectMapper` bean 셋(`webStrictObjectMapper`, `xmlMapper`, `cborMapper`)을 가졌다. 그래서 모든 + `@Autowired ObjectMapper`가 모호해지고 애플리케이션이 시작하지 않았다. `app-bootstrap` 테스트 여섯 개가 + `UnsatisfiedDependencyException`으로 실패했다. +- 모든 배포가 조용히 `application/xml` 요청 본문을 받기 시작했다. 배포가 이름을 대지 않으면 꺼져 있어야 하는 + capability에서, 의존성 하나를 더해서 얻은 XXE 면이다. -So both are `compileOnly` plus `testImplementation`: the factories compile, their tests run against -real backends, and the runtime classpath belongs to the deployment that enables the capability. -`WebRepresentation.available()` turns an absent backend into a sentence naming the missing -coordinate. `RepresentationBackendScopeTest` reads `build.gradle` and fails if either coordinate -returns to `implementation`, because nothing else catches it — the codec's own tests pass either -way, and the failure only appears in whatever composes this leaf. +그래서 둘 다 `compileOnly`와 `testImplementation`이다. factory는 컴파일되고, 그 테스트는 실제 backend로 돌고, 런타임 +classpath는 capability를 켜는 배포의 몫이다. `WebRepresentation.available()`은 없는 backend를 빠진 좌표를 이름 댄 +문장으로 바꾼다. `RepresentationBackendScopeTest`는 `build.gradle`을 읽고 둘 중 하나라도 `implementation`으로 +돌아가면 실패한다. 다른 어떤 것도 그것을 잡지 못하기 때문이다. codec 자체 테스트는 어느 쪽이든 통과하고, 실패는 +이 leaf를 조립하는 곳에서만 나타난다. -**The framing and the writer are separate.** `NdjsonFraming` and `JsonSequenceFraming` hold the -contract; `MvcStreamWriter` is what puts it on a response. There is no MVC SSE writer: this -repository's `NO_SSE_EMITTER` ArchUnit rule forbids `SseEmitter` outright, and the only SSE writer -was the WebFlux one removed on 2026-09-25. So the servlet stack streams NDJSON and JSON-seq, and SSE -is framing-only — nothing serves it until a servlet writer exists. +**framing과 writer는 따로다.** `NdjsonFraming`과 `JsonSequenceFraming`이 계약을 가지고, `MvcStreamWriter`가 그것을 +응답에 싣는다. MVC SSE writer는 없다. 이 저장소의 `NO_SSE_EMITTER` ArchUnit 규칙이 `SseEmitter`를 아예 금하고, 유일한 +SSE writer는 2026-09-25에 지운 WebFlux 것이었다. 그래서 servlet stack은 NDJSON과 JSON-seq를 스트리밍하고, SSE는 +framing만 있다. servlet writer가 생기기 전에는 아무것도 SSE를 내보내지 않는다. -**`MessagingReplayBridge` is `WebStreamReplaySource`, an interface this module implements nowhere.** -The design's requirement is that the web module store no durable event history; an implementation -here would be the thing it forbids. +**`MessagingReplayBridge`는 이 모듈이 어디서도 구현하지 않는 interface인 `WebStreamReplaySource`다.** 설계의 요구는 +web 모듈이 지속되는 이벤트 이력을 저장하지 않는 것이다. 여기서 구현하면 그것이 금하는 바로 그것이 된다. -### What the execution layer had to get right +### 실행 계층이 맞혀야 했던 것 -On the servlet stack there is no disconnect event at all: the first sign a client is gone is a write that throws, which is why the heartbeat is the probe rather than a -courtesy and why a failed beat is recorded as disconnect evidence. +servlet stack에는 연결 끊김 이벤트가 아예 없다. client가 사라졌다는 첫 신호는 예외를 던지는 쓰기다. 그래서 +heartbeat는 예의가 아니라 탐침이고, 실패한 heartbeat는 연결 끊김 증거로 기록한다. -### Verification +### 확인 ```bash cd src -./gradlew :adapter:inbound:web:test # the shipped web leaf -./gradlew :adapter:inbound:web:systemTest # Tomcat, real socket -./gradlew :adapter:inbound:web:webJettyCompatTest # Jetty, real socket -./gradlew :adapter:inbound:web-advanced:test # the opt-in Advanced leaf -./gradlew :adapter:inbound:web-advanced:webAdvancedTest # the tagged Advanced lane +./gradlew :adapter:inbound:web:test # 내보내는 web leaf +./gradlew :adapter:inbound:web:systemTest # Tomcat, 실제 socket +./gradlew :adapter:inbound:web:webJettyCompatTest # Jetty, 실제 socket +./gradlew :adapter:inbound:web-advanced:test # 골라 쓰는 Advanced leaf +./gradlew :adapter:inbound:web-advanced:webAdvancedTest # tag를 단 Advanced lane ``` -See `docs/web/advanced-capabilities.md`, `docs/web/streaming-contract.md`, -`docs/web/patch-contract.md`, `docs/web/virtual-thread-profile.md`, -`docs/web/openapi-32-compatibility.md`, and `docs/adr/ADR-WEB-ADV-00{1,2,3}-*.md`. +`docs/web/advanced-capabilities.md`, `docs/web/streaming-contract.md`, `docs/web/patch-contract.md`, +`docs/web/virtual-thread-profile.md`, `docs/web/openapi-32-compatibility.md`, `docs/adr/ADR-WEB-ADV-00{1,2,3}-*.md`를 +본다. diff --git a/docs/web/runbook.md b/docs/web/runbook.md index dde6316c..da66560b 100644 --- a/docs/web/runbook.md +++ b/docs/web/runbook.md @@ -1,104 +1,98 @@ -# Web platform runbook +# Web 플랫폼 runbook -What an operator needs when the HTTP boundary misbehaves. Organised by what you observe, because -that is what you have at 3am — not by which module owns it. +HTTP 경계가 이상할 때 운영자에게 필요한 것이다. 어느 모듈이 가졌는지가 아니라 무엇을 보았는지로 나눴다. 새벽 +3시에 손에 있는 것이 그것이기 때문이다. -## Reading a `429` +## `429` 읽기 -`RateLimitInterceptor` answers `429 RATE_LIMIT_EXCEEDED` with `Retry-After` when the edge rate -limit refuses a caller. `RATE_LIMIT_UNAVAILABLE` means the rate-limit store could not be reached, -not that the caller exceeded anything — look at the store, not the caller. +`RateLimitInterceptor`는 edge 속도 제한이 호출자를 거부하면 `Retry-After`와 함께 `429 RATE_LIMIT_EXCEEDED`로 답한다. +`RATE_LIMIT_UNAVAILABLE`은 호출자가 무언가를 넘었다는 뜻이 아니라 속도 제한 저장소에 닿지 못했다는 뜻이다. 호출자가 +아니라 저장소를 본다. -## Errors that are not the `Envelope` +## `Envelope`가 아닌 오류 -Every HTTP error the application writes is the `Envelope` from `GlobalExceptionHandler` -(`spring.mvc.problemdetails.enabled=false`), with an `error.code` a client branches on. +애플리케이션이 쓰는 모든 HTTP 오류는 `GlobalExceptionHandler`가 쓰는 `Envelope`이고 +(`spring.mvc.problemdetails.enabled=false`), client가 분기하는 `error.code`를 가진다. -- **How to confirm quickly:** send a request that must fail validation and check the body has - `error.code`. A body without it (Spring's `ProblemDetail`, or the container's error page) means - the handler is not installed or the response came from the edge. +- **빨리 확인하는 법:** 검증에 실패해야 하는 요청을 보내고 본문에 `error.code`가 있는지 본다. 없으면(Spring의 + `ProblemDetail`이나 container의 오류 쪽) handler가 설치되지 않았거나 응답이 edge에서 왔다. -## A response is truncated or the connection dies mid-document +## 응답이 잘리거나 문서 중간에 connection이 끊긴다 -Two different causes, distinguished by the status the client did receive. +원인은 둘이고, client가 받은 상태로 구분한다. -- **Client got a status, then nothing** — the response failed after commit. The status cannot be - retracted, so the connection ends mid-document. -- **Client got nothing from the application** — the proxy refused it. `client_max_body_size` in - nginx answers with its own HTML rather than the `Envelope`. See `repository-adaptation.md` §8. +- **client가 상태를 받고 그다음 아무것도 없다** — 응답이 commit 뒤에 실패했다. 상태는 되돌릴 수 없으므로 문서 중간에 + connection이 끝난다. +- **client가 애플리케이션에서 아무것도 받지 못했다** — proxy가 거부했다. nginx의 `client_max_body_size`는 `Envelope`가 + 아니라 자기 HTML로 답한다. `repository-adaptation.md` §8을 본다. -## A retried write happened twice +## 재시도한 쓰기가 두 번 일어났다 -The idempotency key is the control, and there are exactly three ways it fails to apply. +통제 수단은 멱등 key이고, 그것이 적용되지 않는 길은 정확히 셋이다. -1. **The client did not send one.** The endpoint does not require the key, so it ran unguarded. - Require it if a duplicate is unacceptable. -2. **The client sent a different body.** Answered `422 IDEMPOTENT_REQUEST_MISMATCH`, never a - replay — replaying would hand back a receipt for a request the caller never made. -3. **The record expired.** TTL is per-operation with a 72h cap. A retry after expiry is a new - request by definition. +1. **client가 key를 보내지 않았다.** endpoint가 key를 요구하지 않으니 보호 없이 돌았다. 중복을 받아들일 수 없으면 key를 + 요구한다. +2. **client가 다른 본문을 보냈다.** `422 IDEMPOTENT_REQUEST_MISMATCH`로 답하고 절대 다시 보내지 않는다. 다시 보내면 + 호출자가 한 적 없는 요청의 영수증을 돌려주게 된다. +3. **기록이 만료됐다.** TTL은 연산마다 정하고 상한은 72h다. 만료 뒤의 재시도는 정의상 새 요청이다. -A `409 IDEMPOTENT_IN_FLIGHT` (retryable=true, `Retry-After: 2`) is not a failure: an earlier -attempt is still running and its result is unknown. The caller resends with the **same** -`Idempotency-Key` after `Retry-After`; a new key is a new request and is how a write ends up -applied twice. The four idempotency answers are in `http-contract.md` §2. +`409 IDEMPOTENT_IN_FLIGHT`(retryable=true, `Retry-After: 2`)는 실패가 아니다. 앞 시도가 아직 돌고 있고 그 결과를 +모른다. 호출자는 `Retry-After` 뒤에 **같은** `Idempotency-Key`로 다시 보낸다. 새 key는 새 요청이고, 쓰기가 두 번 +적용되는 길이 그것이다. 멱등성 답 넷은 `http-contract.md` §2에 있다. -## Rolling deploy stalls with instances half-drained +## rolling 배포가 인스턴스를 반쯤 비운 채 멈춘다 -`shutDownGracefully` waits for in-flight work, and an open-but-idle keep-alive connection can count -as in-flight. Calling `stop()` while that wait is in progress hangs. +`shutDownGracefully`는 진행 중인 일을 기다리고, 열려 있지만 노는 keep-alive connection이 진행 중으로 셀 수 있다. 그 +기다림 중에 `stop()`을 부르면 멈춘다. -- **Symptom:** an instance neither serving nor exiting, no error in its log. -- **Cause:** an unbounded graceful wait. `GracefulShutdownProbe` bounds it at a stated grace period - and stops the server regardless once it elapses; a deployment must do the same. -- **Setting:** `spring.lifecycle.timeout-per-shutdown-phase`. Without a bound the deploy waits for - a connection that may never go idle. +- **증상:** 요청을 받지도 않고 끝나지도 않는 인스턴스. 로그에 오류가 없다. +- **원인:** 상한 없는 graceful 기다림. `GracefulShutdownProbe`는 정한 유예 시간으로 그것을 제한하고, 시간이 지나면 + 어쨌든 서버를 멈춘다. 배포도 같게 해야 한다. +- **설정:** `spring.lifecycle.timeout-per-shutdown-phase`. 상한이 없으면 배포는 영영 놀지 않을 수도 있는 connection을 + 기다린다. -## Metrics stopped arriving, or the bill jumped +## metric이 오지 않거나 청구액이 뛰었다 -Almost always a high-cardinality tag — typically a `routeTemplate` carrying a *resolved* path, which -is one series per resource. +거의 늘 가짓수가 많은 tag다. 흔히 *풀린* 경로를 담은 `routeTemplate`이고, 자원마다 시계열 하나가 된다. -- **Check:** the tag values in the metrics backend for `routeTemplate`. Braces mean templates; - identifiers mean the resolved path leaked through. -- **Never tags:** the URL, the query string, any identifier, the tenant, a key, a token, a cookie, - a body. A tag value reaches the metrics backend unredacted and usually a third-party SaaS with it. +- **확인:** metric 저장소에서 `routeTemplate`의 tag 값을 본다. 중괄호가 있으면 template이고, 식별자가 있으면 풀린 + 경로가 새어 나갔다. +- **절대 tag로 쓰지 않는 것:** URL, query string, 식별자, tenant, key, token, cookie, 본문. tag 값은 가려지지 않은 채 + metric 저장소에 닿고, 보통 그와 함께 외부 SaaS에도 닿는다. -## Cross-origin requests fail only in the browser +## 브라우저에서만 cross-origin 요청이 실패한다 -The API answers correctly and the browser refuses the response. CORS is `CorsSettings` -(`app.cors.*`) applied by `SecurityConfig`. Startup refuses two settings: +API는 맞게 답하는데 브라우저가 응답을 거부한다. CORS는 `SecurityConfig`가 적용하는 `CorsSettings`(`app.cors.*`)다. +시작 단계는 두 설정을 거부한다. -- `APP_SECURITY_CORS_ENABLED=true` with no origin. -- `*` in `APP_SECURITY_CORS_ORIGINS` with `APP_SECURITY_CORS_ALLOW_CREDENTIALS=true` — no browser - honours it. +- origin 없이 `APP_SECURITY_CORS_ENABLED=true`. +- `APP_SECURITY_CORS_ALLOW_CREDENTIALS=true`와 함께 `APP_SECURITY_CORS_ORIGINS`의 `*` — 어떤 브라우저도 받아들이지 + 않는다. -Two more start fine and still fail in the browser: +다음 둘은 시작은 되지만 브라우저에서 여전히 실패한다. -- `https://*.example.com` in the origin list — it is compared as a literal and matches nothing. -- An origin with a path (`https://app.example.com/ui`) — an origin is scheme, host and port only. +- origin 목록의 `https://*.example.com` — 글자 그대로 비교하므로 아무것에도 맞지 않는다. +- 경로가 있는 origin(`https://app.example.com/ui`) — origin은 scheme, host, port뿐이다. -The response arrives but a header reads as `null` in browser code (`Retry-After`, `X-Request-Id`, -`Location`, a tus `Upload-Offset`): the header is not in `Access-Control-Expose-Headers`. The exposed -list is `CorsExposedHeaders.PLATFORM` plus each module's `CorsExposedHeaders` bean -(`docs/web/http-contract.md` §3); a header a service adds needs its own bean. A proxy that strips or -rewrites `Access-Control-Expose-Headers` has the same symptom. +응답은 오는데 브라우저 코드에서 헤더가 `null`로 읽힌다(`Retry-After`, `X-Request-Id`, `Location`, tus +`Upload-Offset`): 그 헤더가 `Access-Control-Expose-Headers`에 없다. 노출 목록은 `CorsExposedHeaders.PLATFORM`과 모듈마다의 +`CorsExposedHeaders` bean이다(`docs/web/http-contract.md` §3). 서비스가 더한 헤더에는 자기 bean이 필요하다. +`Access-Control-Expose-Headers`를 지우거나 고쳐 쓰는 proxy도 같은 증상을 낸다. -A preflight answered `401` means CORS ran after authentication. Preflights carry no credentials by -design; the order is asserted by `WebPipelineOrderContract`. +preflight가 `401`로 답하면 CORS가 인증 뒤에 돈 것이다. preflight는 설계상 credential을 싣지 않는다. 순서는 +`WebPipelineOrderContract`가 단언한다. -## Two access-log lines for one request +## 요청 하나에 접근 로그 줄이 둘 -An async request passes through the servlet filter chain twice — once for the initial request and -again on the ASYNC redispatch. A completion recorded without checking `isAsyncStarted()` is written -both times, and every latency percentile computed from that data is wrong while looking plausible. -`WebPipelineOrderContract` asserts exactly one observation per logical request on every container. +async 요청은 servlet filter chain을 두 번 지난다. 처음 요청 때 한 번, ASYNC 재전달 때 또 한 번이다. +`isAsyncStarted()`를 확인하지 않고 기록한 완료는 두 번 쓰이고, 그 데이터로 계산한 모든 지연 백분위수는 그럴듯해 +보이면서 틀린다. `WebPipelineOrderContract`가 모든 container에서 논리 요청마다 관측이 정확히 하나임을 단언한다. -## Verification commands +## 확인 명령 ```bash cd src -./gradlew :adapter:inbound:web:test # unit, boundary, architecture -./gradlew :adapter:inbound:web:systemTest # Tomcat, real socket -./gradlew :adapter:inbound:web:webJettyCompatTest # second servlet container +./gradlew :adapter:inbound:web:test # 단위, 경계, 아키텍처 +./gradlew :adapter:inbound:web:systemTest # Tomcat, 실제 socket +./gradlew :adapter:inbound:web:webJettyCompatTest # 두 번째 servlet container ``` diff --git a/docs/web/streaming-contract.md b/docs/web/streaming-contract.md index 5bd6ab7a..b2ccb6a8 100644 --- a/docs/web/streaming-contract.md +++ b/docs/web/streaming-contract.md @@ -1,84 +1,75 @@ -# Web streaming: the client contract +# Web 스트리밍: client 계약 -What a client must implement to consume NDJSON or `application/json-seq` from this platform. SSE -framing exists, but since the WebFlux twin was removed (2026-09-25) nothing on the servlet stack -writes it. +이 플랫폼의 NDJSON이나 `application/json-seq`를 받으려면 client가 무엇을 구현해야 하는지 적는다. SSE framing은 있지만, +WebFlux 쌍을 지운 뒤(2026-09-25) servlet stack에서는 아무것도 그것을 쓰지 않는다. -The writers ship in `adapter:inbound:web-advanced` (opt-in, switched by -`app.web.advanced.ndjson.enabled` / `app.web.advanced.json-sequence.enabled`); no default -composition carries them. +writer는 `adapter:inbound:web-advanced`(골라 쓰는 leaf, `app.web.advanced.ndjson.enabled` / +`app.web.advanced.json-sequence.enabled`로 켠다)에 있다. 기본 조립에는 없다. -## Three outcomes, not two +## 끝은 둘이 아니라 셋이다 -After the first byte the HTTP status is 200 and cannot change. So the status tells you nothing about -whether the stream succeeded, and a closed connection is ambiguous. There are three endings: +첫 바이트 뒤에는 HTTP 상태가 200이고 바뀔 수 없다. 그래서 상태는 stream이 성공했는지 아무것도 말해 주지 않고, 닫힌 +connection은 결과를 알 수 없다. 끝은 셋이다. -1. **A `Complete` envelope.** The stream finished. `lastSequence` is the final position. -2. **A `Failure` record.** Something failed after commit. Carries an error code and a client-safe - message. The status is still 200. -3. **Neither.** The connection closed mid-stream. The server records this as `ABRUPT_CLOSE`; from - the client's side it is indistinguishable from a completed stream *unless the client is looking - for the terminal envelope*. +1. **`Complete` envelope.** stream이 끝났다. `lastSequence`가 마지막 위치다. +2. **`Failure` 기록.** commit 뒤에 무언가 실패했다. 오류 code와 client에게 보여도 되는 메시지를 담는다. 상태는 여전히 + 200이다. +3. **둘 다 아님.** stream 중간에 connection이 닫혔다. 서버는 이것을 `ABRUPT_CLOSE`로 기록한다. client 쪽에서는 *끝 + envelope를 찾지 않는 한* 끝난 stream과 구분할 수 없다. -**A client that treats a closed connection as completion will silently truncate data.** No server -change can fix that for it. Looking for the terminal envelope is the contract. +**닫힌 connection을 완료로 보는 client는 데이터를 조용히 잘라 먹는다.** 어떤 서버 변경도 그것을 대신 고칠 수 없다. +끝 envelope를 찾는 것이 계약이다. -## Positions +## 위치 -Every `Item` carries a `sequence`, counting from 1. Positions are strictly increasing, and the -server enforces it — a repeat or a regression is a server-side error, not something a client has to -tolerate. +모든 `Item`은 1부터 세는 `sequence`를 가진다. 위치는 엄격히 증가하고, 서버가 그것을 강제한다. 반복이나 후퇴는 client가 +견뎌야 할 것이 아니라 서버 쪽 오류다. -Zero is never a valid position. A stream whose first item claimed 0 and one whose sequence was never -set would look identical. +0은 절대 유효한 위치가 아니다. 첫 항목이 0을 주장한 stream과 sequence를 아예 정하지 않은 stream이 똑같아 보이기 +때문이다. -## Resuming +## 이어 받기 -Where a route supports it, send the last position you applied as `Last-Event-ID`. +route가 지원하면 마지막으로 적용한 위치를 `Last-Event-ID`로 보낸다. -- If the source still holds it, delivery continues from the next position. -- If it does not, the response is a **resnapshot-required** error, not a partial stream. Resuming - from the oldest retained position would give you contiguous positions with a hole in the middle, - and nothing in the data would say so. +- source가 아직 그 위치를 가지고 있으면 다음 위치부터 이어서 보낸다. +- 가지고 있지 않으면 응답은 부분 stream이 아니라 **resnapshot-required** 오류다. 남아 있는 가장 오래된 위치부터 이어 + 주면 위치는 이어지는데 가운데에 구멍이 생기고, 데이터 어디에도 그 사실이 드러나지 않는다. -A resnapshot means re-reading the resource from its normal endpoint and starting a fresh stream. -Clients that cannot do that cheaply should not use the resume path. +resnapshot은 자원을 보통 endpoint에서 다시 읽고 새 stream을 시작한다는 뜻이다. 그것을 싸게 할 수 없는 client는 이어 +받기 경로를 쓰지 않는다. ## Framing -| Format | Media type | Framing | Truncation behaviour | +| 형식 | Media type | Framing | 잘렸을 때 | | --- | --- | --- | --- | -| SSE | `text/event-stream` | `data:` lines, blank-line separated | Partial event at the end | -| NDJSON | `application/x-ndjson` | One JSON value, then `\n` | The truncated line has no newline, and the delimiter is what was lost | -| JSON-seq | `application/json-seq` | `0x1E`, value, `\n` | The next `0x1E` unambiguously starts the next record | +| SSE | `text/event-stream` | `data:` 줄, 빈 줄로 구분 | 끝에 반쪽 event | +| NDJSON | `application/x-ndjson` | JSON 값 하나, 그다음 `\n` | 잘린 줄에는 줄바꿈이 없고, 잃은 것이 바로 구분자다 | +| JSON-seq | `application/json-seq` | `0x1E`, 값, `\n` | 다음 `0x1E`가 모호함 없이 다음 기록의 시작이다 | -Prefer JSON-seq where truncation matters. Its separator comes *first*, so a parser resynchronises at -the next record rather than trying to parse the truncation joined to what follows. For a long-lived -stream, truncation is the normal way it ends. +잘림이 중요하면 JSON-seq를 쓴다. 구분자가 *먼저* 오므로, parser는 잘린 것과 뒤따르는 것을 이어 파싱하려 하지 않고 다음 +기록에서 다시 맞춘다. 오래 사는 stream에서는 잘림이 보통의 끝이다. -Records never contain a raw newline. The server refuses to write one, because for NDJSON the -consumer's line split is the only record boundary there is. +기록에는 날것의 줄바꿈이 절대 없다. 서버가 그것을 쓰기를 거부한다. NDJSON에서는 소비자의 줄 나누기가 유일한 기록 +경계이기 때문이다. -## Heartbeats and timeouts +## Heartbeat와 시간 초과 -The server writes a keepalive every `heartbeatInterval`. A client that sees nothing for longer than -that should assume the connection is dead — a silent connection and a disconnected one are the same -thing at the socket, and the heartbeat is what separates them. +서버는 `heartbeatInterval`마다 keepalive를 쓴다. 그보다 오래 아무것도 보지 못한 client는 connection이 죽었다고 봐야 +한다. socket에서는 조용한 connection과 끊긴 connection이 같고, heartbeat가 둘을 가른다. -Streams are closed at `idleTimeout` (nothing produced) and at `maxStreamAge` (regardless of -activity). Both are normal endings, and both send a terminal envelope where the connection permits. +stream은 `idleTimeout`(만든 것이 없음)과 `maxStreamAge`(활동과 상관없음)에 닫힌다. 둘 다 보통의 끝이고, connection이 +허락하면 둘 다 끝 envelope를 보낸다. -## Slow consumers +## 느린 소비자 -The server buffers at most `maxBufferedItems` for a consumer that is behind. Past that it closes the -connection rather than growing the buffer. A client that cannot keep up should reconnect with a -resume cursor, not expect the server to hold its backlog. +서버는 뒤처진 소비자를 위해 최대 `maxBufferedItems`까지만 버퍼링한다. 그것을 넘으면 버퍼를 키우지 않고 connection을 +닫는다. 따라가지 못하는 client는 서버가 밀린 것을 쥐고 있기를 기대하지 말고, 이어 받기 cursor로 다시 연결한다. -## Shutdown +## 종료 -During a rolling deploy, open streams receive a reconnect request before the node stops accepting. -Reconnect promptly — the node force-closes anything still open at its drain deadline, and that -arrives as an abrupt close. +rolling 배포 중에는 노드가 받기를 멈추기 전에 열린 stream이 다시 연결하라는 요청을 받는다. 바로 다시 연결한다. 노드는 +drain 기한에 아직 열린 것을 강제로 닫고, 그것은 갑작스러운 닫힘으로 도착한다. -Do not reconnect immediately on an abrupt close without backoff and jitter. If a node's streams are -all cut at once, every client reconnecting at once is what keeps the replacement down. +갑작스러운 닫힘에 backoff와 jitter 없이 바로 다시 연결하지 않는다. 노드의 stream이 한꺼번에 끊겼을 때 모든 client가 +한꺼번에 다시 연결하면 그것이 교체 노드를 쓰러뜨린다. diff --git a/docs/web/virtual-thread-profile.md b/docs/web/virtual-thread-profile.md index ed3b9b5c..599927db 100644 --- a/docs/web/virtual-thread-profile.md +++ b/docs/web/virtual-thread-profile.md @@ -1,23 +1,20 @@ -# The virtual-thread MVC profile +# Virtual thread MVC profile -## What it changes, and what it does not +## 바꾸는 것과 바꾸지 않는 것 -Virtual threads remove the cost of a thread waiting. They do not remove the reason the waiting was -bounded. +virtual thread는 스레드가 기다리는 비용을 없앤다. 기다림에 상한을 둔 이유는 없애지 않는다. -A platform-thread MVC deployment has an implicit concurrency limit — the thread pool. Nobody wrote -it down as an admission policy, but it is what has been protecting the database pool, the outbound -HTTP bulkhead and every downstream service from the full arrival rate. +platform 스레드 MVC 배포에는 숨은 동시성 상한이 있다. 스레드 pool이다. 아무도 그것을 허가 정책으로 적지 않았지만, +DB pool, 외부 HTTP bulkhead, 모든 하류 서비스를 전체 도착률로부터 지켜 온 것이 그것이다. -Switching to virtual threads deletes that limit and deletes nothing that depended on it. The result -is not a slow system. It is a system that accepts ten thousand concurrent requests, queues all of -them on a twenty-connection pool, and times out every one — having done no useful work. The load -that used to be shed at the front door is shed at the back, after the cost of accepting it. +virtual thread로 바꾸면 그 상한이 사라지고, 그것에 기대던 것은 하나도 사라지지 않는다. 결과는 느린 시스템이 아니다. +동시 요청 만 개를 받아 connection 스무 개짜리 pool에 모두 줄 세우고, 쓸모 있는 일은 하나도 못 한 채 모두 시간 초과를 +내는 시스템이다. 예전에 앞문에서 버리던 부하를 받는 비용을 치른 뒤 뒷문에서 버린다. -## Enabling it +## 켜기 -The profile ships in `adapter:inbound:web-advanced`, which no default composition carries. Add -that leaf to the service, then two settings — the profile refuses to be constructed with only one: +profile은 기본 조립에 없는 `adapter:inbound:web-advanced`에 있다. 서비스에 그 leaf를 더하고, 설정 둘을 준다. profile은 +하나만 주면 만들어지기를 거부한다. ```yaml app: @@ -25,54 +22,48 @@ app: advanced: mvc-virtual-threads: enabled: true - admission-limit: 100 # required - database-pool-size: 20 # stated, and unchanged - outbound-bulkhead: 20 # stated, and unchanged + admission-limit: 100 # 필수 + database-pool-size: 20 # 밝혀 둔다. 바뀌지 않는다 + outbound-bulkhead: 20 # 밝혀 둔다. 바뀌지 않는다 ``` -The downstream numbers are carried in the profile because the whole point is that they did not grow. -`VirtualThreadProfile.admissionFitsDownstreamBudgets()` reports when the admission limit exceeds -them. It does not refuse — a deployment can legitimately admit more than its pool when the work is -not all database-bound — but it makes the choice a choice. +하류 숫자를 profile에 싣는 것은, 핵심이 바로 그 숫자가 늘지 않았다는 데 있기 때문이다. +`VirtualThreadProfile.admissionFitsDownstreamBudgets()`가 허가 상한이 그것을 넘으면 보고한다. 거부하지는 않는다. 일이 +모두 DB에 묶이지 않았으면 배포가 pool보다 많이 허가하는 것도 정당하다. 다만 그 선택을 선택으로 만든다. -## The limit bounds use cases, not threads +## 상한은 스레드가 아니라 use case를 제한한다 -`VirtualThreadAdmissionGuard` is a fair semaphore, not a pool. Bounding the threads would put the -waiting back and throw away what virtual threads bought. Ten thousand virtual threads may exist -while a hundred hold permits and the rest are refused at the door. +`VirtualThreadAdmissionGuard`는 pool이 아니라 공정한 semaphore다. 스레드를 제한하면 기다림을 되돌려 놓고 virtual +thread로 얻은 것을 버리게 된다. virtual thread 만 개가 있어도 백 개만 허가를 쥐고 나머지는 문 앞에서 거부된다. -A refusal is a **503 with `Retry-After`**, and it is the outcome the limit exists to produce. A -request refused in a millisecond is strictly better for the client than the same request accepted -and timed out thirty seconds later behind a full pool. +거부는 **`Retry-After`가 붙은 503**이고, 상한이 만들려는 결과가 바로 그것이다. 1밀리초 만에 거부된 요청이, 받아들여진 뒤 +가득 찬 pool 뒤에서 30초 뒤에 시간 초과가 난 같은 요청보다 client에게 확실히 낫다. -The semaphore is fair on purpose. An unfair one is faster and lets newer arrivals overtake waiting -ones, which the overtaken client experiences as a random timeout. +semaphore는 일부러 공정하다. 불공정한 것이 빠르지만, 새로 온 요청이 기다리던 요청을 앞지르게 두고, 앞지름당한 +client는 그것을 무작위 시간 초과로 겪는다. -## What to watch +## 볼 것 -| Signal | Why | +| 신호 | 이유 | | --- | --- | -| `jdk.VirtualThreadPinned` JFR events | A `synchronized` block held across a blocking call pins the carrier thread. The carrier pool is bounded by CPU count, so enough pinned carriers is a deadlock — and a thread dump does not obviously show it. | -| Carrier pool queue depth | The same problem, from the other side. | -| Admission rejections | They should rise under load. If they do not, the limit is not being applied. | -| Downstream wait time | The signal that admission is admitting more than the pools serve. | +| `jdk.VirtualThreadPinned` JFR event | blocking 호출을 가로질러 쥔 `synchronized` 블록은 carrier 스레드를 고정한다. carrier pool은 CPU 수로 제한되므로 고정된 carrier가 충분하면 deadlock이다. thread dump로는 잘 보이지 않는다. | +| carrier pool 큐 깊이 | 같은 문제를 반대쪽에서 본 것이다. | +| 허가 거부 | 부하가 오르면 같이 올라야 한다. 오르지 않으면 상한이 적용되지 않고 있다. | +| 하류 대기 시간 | 허가가 pool이 받을 수 있는 것보다 많이 허가하고 있다는 신호다. | -`VirtualThreadProfile.requiredObservations()` is the same list, in code. +`VirtualThreadProfile.requiredObservations()`가 코드로 된 같은 목록이다. -## Testing it +## 시험하기 -`VirtualThreadAdmissionGuard.peakActive()` exists so a load test can assert the limit was applied. -It is invisible from throughput — a load test that only measures throughput passes with the guard -removed, which is precisely the failure this profile guards against. +`VirtualThreadAdmissionGuard.peakActive()`는 부하 시험이 상한이 적용됐음을 단언할 수 있게 하려고 있다. 처리량으로는 보이지 +않는다. 처리량만 재는 부하 시험은 guard를 빼도 통과한다. 이 profile이 막으려는 실패가 바로 그것이다. -The test that matters asserts two things together: peak concurrency at or below the limit, **and** -more threads created than the limit. Without the second, the test would pass on a deployment that -never used virtual threads at all. +중요한 시험은 두 가지를 함께 단언한다. 최대 동시성이 상한 이하이고, **그리고** 만든 스레드가 상한보다 많다. 둘째가 +없으면 virtual thread를 아예 쓰지 않은 배포에서도 시험이 통과한다. -## Rolling back +## 되돌리기 -Set `enabled: false`, or drop the leaf. The rollback test asserts that Stable behaviour is then -identical — if it is not, the feature was never optional and every deployment has it. +`enabled: false`로 두거나 leaf를 뺀다. 되돌리기 시험은 그때 Stable 동작이 같은지 단언한다. 같지 않으면 그 기능은 처음부터 +선택 사항이 아니었고 모든 배포가 그것을 가지고 있다. -This is the only web Advanced capability that affects requests which do not use them, which is why -its rollback test is the one that matters most. +이것은 쓰지 않는 요청에도 영향을 주는 유일한 web Advanced capability다. 그래서 되돌리기 시험이 가장 중요하다. diff --git a/docs/websocket/runbook.md b/docs/websocket/runbook.md index ac0e70e1..8505a365 100644 --- a/docs/websocket/runbook.md +++ b/docs/websocket/runbook.md @@ -1,83 +1,73 @@ # WebSocket handler runbook -> **Scope:** the shipped compositions do not assemble a WebSocket runtime. This runbook applies to -> a service that registered `PlatformWebSocketHandler` itself (see -> `src/adapter/inbound/websocket/README.md`, "라이브러리 API"). The STOMP channel's rules are in the -> leaf `CLAUDE.md`. +> **범위:** 내보내는 조립은 WebSocket 런타임을 조립하지 않는다. 이 runbook은 `PlatformWebSocketHandler`를 스스로 등록한 +> 서비스에 적용한다(`src/adapter/inbound/websocket/README.md` 「라이브러리 API」). STOMP channel의 규칙은 leaf +> `CLAUDE.md`에 있다. -Organised by what you observe, because that is what you have during an incident. +무엇을 보았는지로 나눴다. 장애 중에 손에 있는 것이 그것이기 때문이다. -## Clients report 1006 — "closed abnormally, no reason" +## client가 1006을 보고한다 — 「비정상 종료, 이유 없음」 -1006 is indistinguishable from a network failure and drives every client into its most aggressive -reconnect path. +1006은 네트워크 장애와 구분할 수 없고, 모든 client를 가장 공격적인 재연결 경로로 몰아넣는다. -- **During a deploy** — the handler did not close its connections. It closes them with - **1001 going away** from `SmartLifecycle.stop()`; a container's own graceful shutdown does not, - because it waits for in-flight *requests* and an established WebSocket is not a request. Check - the handler is a Spring bean (otherwise Spring never calls `stop()`). `TomcatWebSocketShutdownIT` - shows the order: with the handler's phase below the web server's, the client sees 1006. -- **Behind a proxy** — the upgrade is mishandled, so the close frame never becomes a close frame. - See the next section. -- **Neither** — something threw while closing. A close reason longer than 123 bytes makes the - container throw mid-close; the handler truncates for that reason. +- **배포 중** — handler가 connection을 닫지 않았다. handler는 `SmartLifecycle.stop()`에서 **1001 going away**로 닫는다. + container 자체의 graceful 종료는 닫지 않는다. 진행 중인 *요청*을 기다리는데, 맺어진 WebSocket은 요청이 아니기 + 때문이다. handler가 Spring bean인지 확인한다(아니면 Spring이 `stop()`을 부르지 않는다). `TomcatWebSocketShutdownIT`가 + 순서를 보여 준다. handler의 phase가 web 서버보다 낮으면 client는 1006을 본다. +- **proxy 뒤** — upgrade를 잘못 다뤄서 close frame이 close frame이 되지 못한다. 다음 절을 본다. +- **둘 다 아님** — 닫는 중에 무언가 예외를 던졌다. 123바이트보다 긴 close 이유는 container가 닫는 도중에 예외를 던지게 + 한다. 그래서 handler가 이유를 자른다. -## Connections work locally and not behind the load balancer +## 로컬에서는 되는데 load balancer 뒤에서는 안 된다 -Three nginx directives, each producing a different failure: +nginx 지시어 셋이고, 각각 다른 실패를 낸다. -| Missing | Symptom | +| 빠진 것 | 증상 | | --- | --- | -| `proxy_http_version 1.1` | Handshake answered 400, or simply not upgraded. HTTP/1.0 has no Upgrade mechanism. | -| `Upgrade` / `Connection` forwarded | Upstream sees an ordinary GET and answers 404 or 200 for a route that works when tested directly. They are hop-by-hop headers, so a proxy is *required* to drop them. | -| `proxy_read_timeout` raised | Every connection quieter than 60s is killed with no close frame. A WebSocket is idle by nature. | +| `proxy_http_version 1.1` | handshake가 400으로 답하거나 그냥 upgrade되지 않는다. HTTP/1.0에는 Upgrade 방식이 없다. | +| `Upgrade` / `Connection` 전달 | upstream이 보통 GET을 보고, 직접 시험하면 되는 route에 404나 200으로 답한다. hop-by-hop 헤더라서 proxy는 이것을 *반드시* 버린다. | +| `proxy_read_timeout` 올리기 | 60초보다 조용한 connection은 close frame 없이 모두 죽는다. WebSocket은 원래 놀고 있다. | -`websocketNginxTest` asserts these against a real Nginx, and carries a deliberately broken -configuration (`nginx-no-upgrade.conf`) so it proves its own assertions can fail. +`websocketNginxTest`가 실제 Nginx에 대해 이것을 단언하고, 일부러 망가뜨린 설정(`nginx-no-upgrade.conf`)을 지녀서 자기 +단언이 실패할 수 있음을 증명한다. -## Connections vanish with no close frame and no error +## close frame도 오류도 없이 connection이 사라진다 -Almost always an intermediary's idle timeout, not the application. TCP does not report a departed -peer — a closed laptop lid, a phone switching to cellular and a NAT forgetting its mapping all -produce no FIN. The handler has no heartbeat or idle timer; set the container idle timeout -(`ServletServerContainerFactoryBean.setMaxSessionIdleTimeout`) and the proxy read timeout, and have -clients ping below the smallest of them. +거의 늘 애플리케이션이 아니라 중간 장비의 idle timeout이다. TCP는 떠난 상대를 알려 주지 않는다. 닫힌 노트북 덮개, +셀룰러로 넘어가는 휴대폰, mapping을 잊은 NAT 모두 FIN을 만들지 않는다. handler에는 heartbeat나 idle timer가 없다. +container idle timeout(`ServletServerContainerFactoryBean.setMaxSessionIdleTimeout`)과 proxy read timeout을 정하고, +client가 그중 가장 작은 것보다 짧게 ping하게 한다. -## Clients are closed with 1009 +## client가 1009로 닫힌다 -The message exceeded a bound. Two places enforce one: the container's text buffer (Tomcat default -8 KiB) closes before the handler sees the message, and the handler closes when the message exceeds -`WebSocketConnectionBudget.maxMessageBytes` (UTF-8 bytes). Set the container buffer to the same -value so the answer does not depend on which one fired first. +메시지가 상한을 넘었다. 상한을 강제하는 곳은 둘이다. container의 text buffer(Tomcat 기본 8 KiB)는 handler가 메시지를 +보기 전에 닫고, handler는 메시지가 `WebSocketConnectionBudget.maxMessageBytes`(UTF-8 바이트)를 넘으면 닫는다. container +buffer를 같은 값으로 둬서 답이 어느 쪽이 먼저 걸렸는지에 달리지 않게 한다. -## Clients are closed with 1013 +## client가 1013으로 닫힌다 -A reply could not be queued: the connection's outbound buffer (`maxBufferedOutboundBytes`) or the -node-wide `GlobalBufferBudget` is full, which means the peer reads more slowly than the service -answers. Closing is deliberate — a client that reconnects has lost nothing, while one that silently -missed a reply is wrong and does not know it. +답을 큐에 넣지 못했다. connection의 송신 버퍼(`maxBufferedOutboundBytes`)나 노드 전체의 `GlobalBufferBudget`이 가득 +찼다. 상대가 서비스가 답하는 것보다 느리게 읽는다는 뜻이다. 닫는 것은 일부러다. 다시 연결하는 client는 잃은 것이 없고, +조용히 답을 놓친 client는 틀렸는데 그것을 모른다. -## Memory grows and nothing is failing +## 메모리가 늘고 아무것도 실패하지 않는다 -A slow consumer. It does not error — it reads more slowly than the server writes and the difference -accumulates. Arranging it requires no tooling: reading slowly is enough. +느린 소비자다. 오류를 내지 않는다. 서버가 쓰는 것보다 느리게 읽고 그 차이가 쌓인다. 재현에 도구가 필요 없다. 느리게 +읽기만 하면 된다. -- **Bounds:** per connection (`maxBufferedOutboundBytes`) *and* node-wide (`GlobalBufferBudget`). - The second is not redundant — a megabyte each is fine at a hundred connections and is the whole - heap at fifty thousand. -- **Drops:** `OutboundQueue.snapshot().droppedCount()` counts droppable and conflatable messages - the queue shed. Connection counts and buffered bytes look healthy while data is being shed; the - drop count is the only number that says so. -- **If drops are zero and memory still grows:** check that the queue lock and the socket lock are - separate. When they were one lock, a stalled peer blocked every producer, the queue never filled, - and the shedding bound never fired. +- **상한:** connection마다(`maxBufferedOutboundBytes`) *그리고* 노드 전체(`GlobalBufferBudget`). 둘째는 쓸데없지 않다. + connection마다 1메가바이트는 connection 백 개에서는 괜찮고 오만 개에서는 heap 전체다. +- **버림:** `OutboundQueue.snapshot().droppedCount()`가 큐가 버린 droppable·conflatable 메시지를 센다. 데이터를 버리는 + 동안에도 connection 수와 버퍼 바이트는 멀쩡해 보인다. 그렇다고 말해 주는 숫자는 버린 수뿐이다. +- **버린 수가 0인데도 메모리가 늘면:** 큐 lock과 socket lock이 따로인지 본다. 하나였을 때는 멈춘 상대가 모든 생산자를 + 막아서 큐가 차지 않았고, 버리는 상한도 걸리지 않았다. -## Verification +## 확인 ```bash cd src -./gradlew :adapter:inbound:websocket:test # queue, writer, budget, handler -./gradlew :adapter:inbound:websocket:systemTest # real Tomcat, incl. context close → 1001 -./gradlew :adapter:inbound:websocket:websocketJettyTest # second servlet container -./gradlew :adapter:inbound:websocket:websocketNginxTest # real Nginx; needs Docker, fails without it +./gradlew :adapter:inbound:websocket:test # 큐, writer, 예산, handler +./gradlew :adapter:inbound:websocket:systemTest # 실제 Tomcat, context 닫기 → 1001 포함 +./gradlew :adapter:inbound:websocket:websocketJettyTest # 두 번째 servlet container +./gradlew :adapter:inbound:websocket:websocketNginxTest # 실제 Nginx. Docker가 필요하고 없으면 실패한다 ``` diff --git a/docs/work/evidence.md b/docs/work/evidence.md index 7fc6ff72..96aaecf8 100644 --- a/docs/work/evidence.md +++ b/docs/work/evidence.md @@ -318,6 +318,16 @@ - 줄바꿈 검사: 한 줄에서 안 걸려도 다음 줄과 이었을 때 줄 경계를 넘는 ID(`(review` ↵ `2026-11-01 07-10)`)를 잡는다. 이번에 2줄(web·persistence-mongo)이 이 꼴이었다. persistence-fileserver·cache-redis의 갈린 괄호는 둘째 줄의 `RR-` 접두어가 따로 잡혔다. - 오탐 시험(`docs-writing.md` 4절 12단계): 잡아야 할 문장 10개는 모두 잡혔다. 잡지 말아야 할 문장 8개 중 하나가 걸렸다: 일부러 만든 "line 10-12 (b)"(콜론 없는 줄 범위 뒤 대안 표시)다. repo에는 그 꼴이 없어 그대로 뒀다. `docs/reviews/**` 밖 전체에 돌리면 새로 125줄이 걸린다. 모두 검사 대상 밖(모듈 README, ADR, `docs/httpclient/` 등)의 실제 ID이고, 검사 대상 안의 오탐은 0이다. +문서 2단계 통합(2026-11-07)에서 걷어낸 것: 번역한 진입 문서에 단독 번호(`07-08`처럼 짝 하나)로 남은 이력 ID 넷이다. +검사 패턴은 단독 번호를 일부러 잡지 않는다(범위나 절 번호와 구별할 수 없다). 줄 번호는 커밋 `9c4ca9f3`의 줄이다. + +| 원래 위치 | 원래 괄호 | 지금 본문 | 근거 | +| --- | --- | --- | --- | +| `src/adapter/outbound/persistence-jpa/CLAUDE.md:156` | "(07-08)" | "2026-11-01 성숙도 리뷰 뒤로. 기본 조립 루트가 고르지 않은 capability의 설정을 알면 안 된다" | `1101/07-08`(기본 조립 루트가 아직 선택 capability를 안다, `07-bootstrap-composition-config.md`) | +| `src/app-bootstrap/CLAUDE.md:63` | "07-08" | "2026-11-01 성숙도 리뷰 뒤로 bootstrap 밖" | 같은 `1101/07-08`. 그 수정 표가 `DurableOperationConfig`를 `composition:*` 모듈로 옮겼다 | +| `src/platforms/grpc/CLAUDE.md:145` | "(11-M9)" | "2026-09-18 리뷰가 찾은 문제" | `docs/reviews/2026-09-18-techlead-review/11-grpc-platform.md` M9(starter가 JPA를 무조건 끌고 온다) | +| `src/platforms/messaging/CLAUDE.md:55` | "06-01 수정" | "다시 시도하면 될 거부를 relay가 즉시 DEAD로 보내던 결함의 수정(2026-11-01 성숙도 리뷰 뒤)" | `1101/06-01`(`06-messaging.md`) | + ## 11. cold-read 시험 2회차 빈틈 처리 (2026-11-07) 2026-11-07 round7 수정과 통합, round8 확인 리뷰를 시험으로 돌렸다. 이력 없는 세션 9개가 1회차 수정을 넣은 매뉴얼(기준 `73d39212`, 통합과 리뷰는 `83a12f66`)로 일했다. 9개 모두 일은 끝냈고, 매뉴얼에서 답을 못 찾은 곳이 52건 나왔다(1회차 35건). 코드 수정 과제에서 같은 질문이 되풀이됐다. 아래는 공유 노트(`~/.config/Claude/side-session-notes/local_fcd89c34-c754-4c5b-a38f-fa322834286f/`)의 「매뉴얼에서 답을 못 찾은 곳」과 시험 기록(design-docs `delegation-loop/trials/2026-11-07-*.md`)의 「질문」 표를 한 줄씩 처리한 결과다. 기준 커밋 `83948d58`. diff --git a/docs/work/operate.md b/docs/work/operate.md index 9487fe83..0fa9b782 100644 --- a/docs/work/operate.md +++ b/docs/work/operate.md @@ -137,5 +137,5 @@ ssh desktop 'cd ~/workspace/<작업 이름> && git add -A && git write-tree' - desktop 기존 checkout에서 브랜치를 바꿔 다른 세션의 작업을 방해한다. 자기 worktree를 만든다. - 짧게 끝난 실행을 통과로 적는다. 캐시 재사용인지, 태스크가 실제로 돌았는지 로그로 확인한다. -- 빌드 캐시에서 가져온 테스트 결과를 지금 이 환경에서 통과한 증거로 쓴다. 기준 상태를 확인하거나 시간·환경에 민감한 테스트를 볼 때는 그 태스크를 `--rerun`으로 다시 돌린다. `--rerun`은 바로 앞 태스크 하나에만 걸린다. 태스크마다 붙인다(`:a:test --rerun :b:test --rerun`). `ci` 같은 집계 태스크는 새 worktree에서 `--no-build-cache`로 돌린다([reference/gates.md](reference/gates.md) 3절). +- 빌드 캐시에서 가져온 테스트 결과를 지금 이 환경에서 통과한 증거로 쓴다. 기준 상태를 확인하거나 시간·환경에 민감한 테스트를 볼 때는 그 태스크를 `--rerun`으로 다시 돌린다. `--rerun`은 바로 앞 태스크 하나에만 걸린다. 태스크마다 붙인다(`:domain-core:test --rerun :application-core:test --rerun`). `ci` 같은 집계 태스크는 새 worktree에서 `--no-build-cache`로 돌린다([reference/gates.md](reference/gates.md) 3절). - 커밋하고 push한 뒤 desktop에서 돌려, 결과를 커밋 본문에 못 넣는다. push 전에 패치로 검증한다(4.1절). diff --git a/scripts/check-docs-exceptions.txt b/scripts/check-docs-exceptions.txt index 1bff4f87..a5ba76cd 100644 --- a/scripts/check-docs-exceptions.txt +++ b/scripts/check-docs-exceptions.txt @@ -2,218 +2,12 @@ # # - 이 목록에 새 줄을 더하면 검사가 실패한다. 줄마다 check-docs.py의 FROZEN에 지문이 있어야 한다. # - 번역하거나 고쳐서 더는 걸리지 않는 줄은 지운다. 남겨 두면 검사가 실패한다. +# - 줄을 지우면 같은 변경에서 FROZEN에서 그 지문도 뺀다. 남겨 두면 검사가 실패한다. +# - 2026-11-07 번역 단계에서 모든 줄을 지웠다. FROZEN도 비어 있어 어떤 줄을 더해도 실패한다. # - 형식: <검사><탭><경로>[<탭><걸린 값>]. 「#」으로 시작하는 줄과 빈 줄은 읽지 않는다. -# 언어: 아직 한국어로 옮기지 않은 살아 있는 문서와 ADR. 다음 단계(살아 있는 문서 번역, ADR 번역)에서 지운다. -language .github/dependency-vulnerability-policy.md -language .github/pull_request_template.md -language compose/keycloak/README.md -language compose/redis/acl/README.md -language docs/adr/ADR-BUILD-001-one-convention-for-shared-test-code.md -language docs/adr/ADR-GQL-001-graphql-context-and-storage-ownership.md -language docs/adr/ADR-GRPC-001-platform-family-and-registry-shape.md -language docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md -language docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md -language docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md -language docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md -language docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md -language docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md -language docs/adr/ADR-JPA-001-domain-owns-persistence-model.md -language docs/adr/ADR-JPA-002-full-transaction-retry.md -language docs/adr/ADR-JPA-003-completion-unknown.md -language docs/adr/ADR-JPA-004-flyway-schema-source-of-truth.md -language docs/adr/ADR-JPA-005-postgresql-real-contract.md -language docs/adr/ADR-JPA-006-canonical-technical-audit.md -language docs/adr/ADR-MONGO-001-platform-boundary.md -language docs/adr/ADR-MONGO-002-bson-representation.md -language docs/adr/ADR-MONGO-003-transaction-retry.md -language docs/adr/ADR-MONGO-004-index-schema-admin-plane.md -language docs/adr/ADR-MONGO-ADV-001-capability-promotion.md -language docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md -language docs/adr/ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md -language docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md -language docs/adr/ADR-WS-001-platform-as-packages-and-its-boundaries.md -language docs/adr/ADR-WS-002-resume-and-cluster.md -language docs/adr/ADR-WS-003-stomp-and-broker-relay.md -language docs/compatibility/grpc-advanced-support-matrix.md -language docs/compatibility/grpc-support-matrix.md -language docs/fileserver/configuration.md -language docs/fileserver/design-deviations.md -language docs/fileserver/http-contract.md -language docs/fileserver/operations.md -language docs/fileserver/security.md -language docs/fileserver/storage-certification.md -language docs/fileserver/support-matrix.md -language docs/fileserver/upgrade-guide.md -language docs/httpclient/configuration-reference.md -language docs/httpclient/operations.md -language docs/httpclient/performance-baseline.md -language docs/httpclient/release-checklist.md -language docs/httpclient/repository-adaptation.md -language docs/httpclient/retry-and-ambiguity.md -language docs/httpclient/security.md -language docs/httpclient/streaming.md -language docs/httpclient/support-matrix.md -language docs/jpa/batch-write-guide.md -language docs/jpa/entity-mapping-guide.md -language docs/jpa/experimental-promotion-checklist.md -language docs/jpa/experimental-support-matrix.md -language docs/jpa/migration-guide.md -language docs/jpa/observability.md -language docs/jpa/postgresql-extensions.md -language docs/jpa/query-fetch-guide.md -language docs/jpa/repository-adaptation.md -language docs/jpa/runbooks.md -language docs/jpa/support-matrix.md -language docs/jpa/transaction-guide.md -language docs/mongodb/advanced/encryption.md -language docs/mongodb/advanced/multi-tenancy.md -language docs/mongodb/advanced/sharding.md -language docs/mongodb/advanced/signoff/README.md -language docs/mongodb/bson-mapping-guide.md -language docs/mongodb/consistency-transaction-guide.md -language docs/mongodb/document-modeling-guide.md -language docs/mongodb/query-aggregation-guide.md -language docs/mongodb/repository-adaptation.md -language docs/mongodb/runbooks/failover.md -language docs/mongodb/runbooks/unknown-commit.md -language docs/mongodb/schema-index-migration-guide.md -language docs/mongodb/security-observability.md -language docs/mongodb/support-matrix.md -language docs/notification/adr/NOTIF-ADR-001-durable-acceptance.md -language docs/notification/adr/NOTIF-ADR-002-event-ledger-projection.md -language docs/notification/adr/NOTIF-ADR-003-ambiguous-submission.md -language docs/notification/adr/NOTIF-ADR-004-fcm-fid-primary.md -language docs/notification/at-rest-threat-model.md -language docs/notification/callback-reconciliation.md -language docs/notification/configuration-reference.md -language docs/notification/delivery-evidence.md -language docs/notification/migration-guide.md -language docs/notification/module-mapping.md -language docs/notification/operations.md -language docs/notification/provider-runbooks.md -language docs/notification/security-privacy.md -language docs/notification/support-matrix.md -language docs/observability/log-fields.md -language docs/redis/command-policy.md -language docs/redis/operations.md -language docs/redis/support-matrix.md -language docs/redis/upgrade-guide.md -language docs/runbooks/adapter-adapter-disabled.md -language docs/runbooks/auth-audience-mismatch.md -language docs/runbooks/auth-claim-mapping-failed.md -language docs/runbooks/auth-issuer-mismatch.md -language docs/runbooks/auth-jwks-unavailable.md -language docs/runbooks/auth-kid-unknown.md -language docs/runbooks/auth-public-path-misconfiguration.md -language docs/runbooks/auth-token-expired.md -language docs/runbooks/auth-token-invalid-signature.md -language docs/runbooks/auth-token-malformed.md -language docs/runbooks/auth-token-missing.md -language docs/runbooks/authz-insufficient-permission.md -language docs/runbooks/authz-tenant-mismatch.md -language docs/runbooks/cache-stampede-lock-timeout.md -language docs/runbooks/cache-unavailable.md -language docs/runbooks/db-deadlock.md -language docs/runbooks/db-idle-in-tx-timeout.md -language docs/runbooks/db-query-canceled.md -language docs/runbooks/db-serialization-failure.md -language docs/runbooks/db-unavailable.md -language docs/runbooks/dependency-4xx-client.md -language docs/runbooks/dependency-5xx-server.md -language docs/runbooks/dependency-circuit-open.md -language docs/runbooks/dependency-connect-failed.md -language docs/runbooks/dependency-dns-failed.md -language docs/runbooks/dependency-timeout.md -language docs/runbooks/file-download-streaming-failure.md -language docs/runbooks/grpc-advanced-capabilities.md -language docs/runbooks/grpc-platform-operations.md -language docs/runbooks/idempotency-unavailable.md -language docs/runbooks/lock-acquisition-timeout.md -language docs/runbooks/management-actuator-forbidden.md -language docs/runbooks/migration-failed.md -language docs/runbooks/runtime-jvm-oom.md -language docs/runbooks/startup-profile-mismatch.md -language docs/runbooks/startup-required-adapter-disabled.md -language docs/runbooks/startup-validation-failed.md -language docs/runbooks/template.md -language docs/storage-capability-boundary.md -language docs/web/advanced-capabilities.md -language docs/web/openapi-32-compatibility.md -language docs/web/patch-contract.md -language docs/web/repository-adaptation.md -language docs/web/runbook.md -language docs/web/streaming-contract.md -language docs/web/virtual-thread-profile.md -language docs/websocket/runbook.md -language src/adapter/inbound/messaging/CLAUDE.md -language src/adapter/inbound/web-advanced/CLAUDE.md -language src/adapter/inbound/web/CLAUDE.md -language src/adapter/inbound/websocket/CLAUDE.md -language src/adapter/outbound/cache-redis/CLAUDE.md -language src/adapter/outbound/cache-redis/README.md -language src/adapter/outbound/fileserver/CLAUDE.md -language src/adapter/outbound/fileserver/README.md -language src/adapter/outbound/httpclient/CLAUDE.md -language src/adapter/outbound/httpclient/README.md -language src/adapter/outbound/identifier/CLAUDE.md -language src/adapter/outbound/messaging-kafka/CLAUDE.md -language src/adapter/outbound/messaging/CLAUDE.md -language src/adapter/outbound/notification/CLAUDE.md -language src/adapter/outbound/objectstorage/CLAUDE.md -language src/adapter/outbound/objectstorage/README.md -language src/adapter/outbound/persistence-fileserver/CLAUDE.md -language src/adapter/outbound/persistence-jpa/CLAUDE.md -language src/adapter/outbound/persistence-mongo/CLAUDE.md -language src/adapter/outbound/persistence-notification/CLAUDE.md -language src/adapter/outbound/redis-sdk/README.md -language src/adapter/outbound/redis-sdk/compose/README.md -language src/adapter/outbound/support/CLAUDE.md -language src/app-bootstrap/CLAUDE.md -language src/app-bootstrap/src/test/resources/developer-experience/broken-readme.md -language src/application-core/CLAUDE.md -language src/build-logic/README.md -language src/composition/outbox-relay/CLAUDE.md -language src/config/architecture/README.md -language src/domain-core/CLAUDE.md -language src/platforms/optional-build/README.md -language src/shared-contract/CLAUDE.md +# 언어: 한국어로 옮기지 않은 살아 있는 문서와 ADR. # 참조: 지금 트리·registry에 없는 경로. 고치거나 「> 이력」 인용 블록으로 옮기면 지운다. -reference AGENTS.md src/build-tools/ -reference docs/mongodb/consumer-leaf-guide.md :adapter:outbound:persistence-note:check -reference docs/web/http-contract.md docs/architecture/backend-api-and-server-state-contract.md -reference docs/work/operate.md :a:test -reference docs/work/operate.md :b:test -reference src/README.md .github/ci-gate-matrix.yml -reference src/README.md .github/scripts/verify-gate-matrix.sh # 숫자: 정본(src/gradle/libs.versions.toml, registry)이 정하는 값을 복사한 곳. 정본을 가리키게 고치면 지운다. -number docs/compatibility/grpc-support-matrix.md Spring Boot 4.0.8 -number docs/httpclient/repository-adaptation.md 19 leaf -number docs/httpclient/repository-adaptation.md Spring Boot 4.0.8 -number docs/jpa/repository-adaptation.md 19 leaf -number docs/jpa/repository-adaptation.md Spring Boot 4.0.8 -number docs/manual/01-generator.md 5 leaf -number docs/mongodb/repository-adaptation.md 19 leaf -number docs/mongodb/repository-adaptation.md Spring Boot 4.0.8 -number src/adapter/inbound/graphql/CLAUDE.md Spring Boot 4.0.0 -number src/adapter/inbound/graphql/README.md 19개 leaf -number src/adapter/inbound/graphql/README.md 24개 leaf -number src/adapter/inbound/graphql/README.md 43개 leaf -number src/adapter/inbound/grpc/CLAUDE.md Spring Boot 4.0.0 -number src/adapter/inbound/web/CLAUDE.md Spring Boot 4.0.0 -number src/adapter/inbound/websocket/CLAUDE.md Spring Boot 4.0.8 -number src/adapter/outbound/cache-redis/CLAUDE.md Spring Boot 4.0.0 -number src/adapter/outbound/fileserver/CLAUDE.md Spring Boot 4.0.0 -number src/adapter/outbound/httpclient/CLAUDE.md Spring Boot 4.0.0 -number src/adapter/outbound/identifier/CLAUDE.md Spring Boot 4.0.8 -number src/adapter/outbound/messaging/CLAUDE.md Spring Boot 4.0.8 -number src/adapter/outbound/notification/CLAUDE.md Spring Boot 4.0.0 -number src/adapter/outbound/objectstorage/CLAUDE.md Spring Boot 4.0.0 -number src/adapter/outbound/persistence-jpa/CLAUDE.md Spring Boot 4.0.0 -number src/adapter/outbound/persistence-mongo/CLAUDE.md Spring Boot 4.0.0 -number src/adapter/outbound/support/CLAUDE.md Spring Boot 4.0.0 -number src/app-bootstrap/CLAUDE.md Spring Boot 4.0.0 -number src/domain-core/CLAUDE.md Spring Boot 4.0.0 -number src/shared-contract/CLAUDE.md Spring Boot 4.0.0 diff --git a/scripts/check-docs.py b/scripts/check-docs.py index 3e482356..cb5628f3 100755 --- a/scripts/check-docs.py +++ b/scripts/check-docs.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""문서 검사 넷: 언어, 기록의 머리 블록, 참조, 복사한 숫자. 하나라도 걸리면 rc=1이다. +"""문서 검사 여섯: 언어, 기록의 머리 블록, 참조, 복사한 숫자, 문서 지도, 루트 README 절. 하나라도 걸리면 rc=1이다. 규칙의 정본은 design-docs `conventions/docs-system.md`이고, 이 repo의 적용은 `docs/README.md` 「문서 수명과 언어」다. 이 스크립트는 그 규칙 중 기계로 볼 수 있는 것만 본다. @@ -7,24 +7,40 @@ language 살아 있는 문서(기록이 아닌 .md)는 한국어다. 판정은 보고 언어 훅 H11과 같다: 코드·명령·인용·링크·URL·경로·파일 이름을 빼고, 영어 낱말이 3개 이상이고 한글 덩어리 비율이 0.3 미만이면 영어다. - head 기록(docs/design, docs/history, docs/adr, docs/notification/adr)의 .md는 맨 위에 + head 기록(docs/design, docs/history, docs/adr)의 .md는 맨 위에 머리 블록이 있다. 상태는 종류별 고정 어휘, 작성일은 날짜, 요약은 한국어, 현재 정본과 대체됨이 가리키는 경로는 지금 있다. reference 살아 있는 문서의 인라인 코드 안 repo 경로(src/, docs/, scripts/, compose/, .github/로 시작. 2026-11-07에 지운 infra/ 아래 경로도 본다)와 Gradle 경로(:a:b)가 지금 트리와 - registry에 있다. 코드 블록과 「이력」으로 시작하는 인용 블록은 건너뛴다. 마크다운 + registry에 있다. 「있다」는 git이 아는 파일(추적 + 무시되지 않은 새 파일)과 그 위 폴더다. 디스크에만 + 있는 것(git mv가 남긴 빈 폴더 등)은 새 checkout에 없으므로 세지 않는다. 기록의 「현재 정본」·「대체됨」 + 경로도 같다. 코드 블록과 「이력」으로 시작하는 인용 블록은 건너뛴다. 마크다운 링크는 lychee와 check-work-docs.py --links가 본다. number 살아 있는 문서가 정본이 정하는 숫자를 복사하지 않는다: Spring Boot 버전, leaf 개수. + Spring Boot 버전은 이름 바로 뒤(「Spring Boot」·「Boot」 뒤의 세 자리 버전)만이 아니라 `Spring Boot` + 칸이 있는 표 행의 세 자리 버전과, 정본(src/gradle/libs.versions.toml의 springBoot)과 같은 + 버전 문자열(굵은 글씨·표 칸·코드 안 포함)도 잡는다. + map docs/README.md의 문서 지도가 지금 있는 문서 폴더를 모두 덮는다. 지도는 표의 첫 칸에 적은 + `폴더/`다. docs/ 바로 아래 폴더가 대상이고, 파일 없이 폴더만 가진 묶음 폴더(history/)는 + 그 아래 폴더가 대신한다. 지도에 있지만 없는 폴더도 실패다. + readme 루트 README.md가 정해진 절을 정해진 순서로 가진다: 첫 줄의 제목, 그 아래 한 문단, 그리고 + README_SECTIONS의 ## 제목. 그 사이에 다른 절이 있어도 된다. + +소스 세트의 resources 폴더 아래 .md(src/**/src/<세트>/resources/)는 시험 입력이나 실행 자원이라 문서로 +보지 않는다. 예외 목록(scripts/check-docs-exceptions.txt)은 줄기만 한다. - 목록의 줄은 아래 FROZEN(2026-11-07 기준선의 지문)에 있어야 한다. 목록에 새 줄을 더하면 실패한다. + - FROZEN의 지문은 목록에 그 줄이 있어야 한다. 줄을 지우면 같은 변경에서 FROZEN에서 그 지문도 뺀다. + 남겨 두면 실패한다. 남은 지문은 지운 줄을 다시 더하는 길이 되기 때문이다. - 목록의 줄이 더는 걸리지 않으면(번역했거나 고쳤으면) 그 줄을 지우라고 실패한다. - FROZEN을 늘리는 것은 규칙을 바꾸는 일이다. 소유자 결정 없이 하지 않는다. 파일을 옮겨 경로만 바뀐 줄은 FROZEN에서 옛 지문을 새 지문으로 바꾼다. 지문은 그 줄(탭 포함)의 sha256 앞 16자다: python3 -c 'import hashlib,sys; print(hashlib.sha256(sys.argv[1].encode()).hexdigest()[:16])' "<줄>" + - 2026-11-07 번역 단계에서 목록의 줄을 모두 지워 목록과 FROZEN이 비었다. - python3 scripts/check-docs.py # 넷 모두 - python3 scripts/check-docs.py --only head # 하나만 (language, head, reference, number) + python3 scripts/check-docs.py # 여섯 모두 + python3 scripts/check-docs.py --only head # 하나만 (language, head, reference, number, map, readme) python3 -m unittest discover -s scripts/tests # 이 검사의 시험 Gradle 밖에 둔다. 빌드는 문서를 파싱하지 않는다(AGENTS.md 「Gradle 정책 권위」). @@ -35,6 +51,7 @@ from __future__ import annotations import datetime import hashlib import json +import posixpath import re import subprocess import sys @@ -44,7 +61,7 @@ from pathlib import Path REPO_ROOT = Path(__file__).resolve().parent.parent EXCEPTIONS_FILE = "scripts/check-docs-exceptions.txt" REGISTRY_FILE = "src/config/architecture/modules.json" -CHECKS = ("language", "head", "reference", "number") +CHECKS = ("language", "head", "reference", "number", "map", "readme") # 기록: 본문은 쓴 때의 원문이다. 머리 블록만 고친다. 종류는 폴더가 정한다. RECORD_KINDS = [ @@ -55,11 +72,10 @@ RECORD_KINDS = [ ("docs/history/evidence/", "증거"), ("docs/history/study/", "학습 문서"), ("docs/adr/", "결정 기록"), - ("docs/notification/adr/", "결정 기록"), ] # 리뷰도 기록이다. 머리 블록은 아직 요구하지 않는다(docs/README.md). NOT_LIVING = ("docs/design/", "docs/history/", "docs/reviews/") -DECISION_PREFIXES = ("docs/adr/", "docs/notification/adr/") +DECISION_PREFIXES = ("docs/adr/",) # 살아 있는 문서 중 지운 것을 일부러 적는 곳: 제거 표, 파생 서비스용 변경 안내, 매뉴얼 규칙의 근거 기록. # 참조·숫자 검사는 이 문서들을 보지 않는다(docs/README.md 「문서와 코드를 같은 변경에서 고친다」). HISTORY_HOLDERS = ("docs/capability-status.md", "docs/upgrade/", "docs/work/evidence.md") @@ -80,53 +96,19 @@ HEAD_FIELDS = ("상태", "작성일", "요약", "현재 정본") HEAD_OPTIONAL = ("대체", "대체됨") HEAD_SEARCH_LINES = 20 +# 문서가 아닌 .md: 소스 세트의 resources 폴더 아래 파일은 테스트가 읽는 입력이나 실행 자원이다. +NOT_DOCUMENT = re.compile(r"/src/[A-Za-z]+/resources/") + +# 문서 지도(K5)와 루트 README(K6). 절 목록의 정본은 design-docs `conventions/docs-system.md` 6.1절이다. +MAP_FILE = "docs/README.md" +DOCS_ROOT = "docs/" +README_FILE = "README.md" +README_SECTIONS = ("프로젝트 구조", "시작하기", "기능 켜고 끄기", "문서 지도", "검증", "새 서비스로 시작하기", + "규칙과 기여") + # 2026-11-07 기준선. 예외 목록의 줄마다 sha256 앞 16자. 늘리지 않는다(맨 위 설명). -FROZEN: frozenset[str] = frozenset({ - "0176963415821bbe", "01984fd96d72b997", "02810bf817c5098f", "02f77e3cc483fa7b", "05fff3c3ff8a5c9a", - "06ea362843468b89", "0767d62996355ba0", "077f1849fe8bebcc", "07f88b24645a4899", "09f6eb7c3c494379", - "0a929e243076b4cb", "0d60ec2d41d698e3", "0d9db88d1d98c32b", "0f84458cb40e7c5e", "10894a287a405274", - "110ff8adc628d4e9", "115eed80f3bb629c", "14121ef25eb4aa46", "150219e901d062f4", "199044717780f929", - "1adc480d397a24fc", "1aedb5c86be16e62", "1ef3eec4c410622e", "1f3199d6bef7b3ab", "20a46563da0c570d", - "234a0dffc4f308bf", "23aa784e28c7f730", "24e61cd8377137f1", "26cdb5786cd3cef8", "26f59b7362b9e68d", - "29fa254236927dae", "2a0c27bb25080cdb", "2aa755121374e148", "2bcc75d4e1ebaa5d", "2e77660bd44c1d2c", - "2e7d24cb488ae4f9", "30c75a928243de75", "354c37493e90b01b", "3e867d0b440f18f5", "3fe449c9eca66d87", - "3ff905af6cc2df16", "4053b182a2b89223", "41f268d8aa836143", "4347c5b0dd84ec9b", "449fc1cac0f9380f", - "457310fef9d100a6", "4611a0bfd81bf42c", "462a63de89507bc6", "468248c165ce65f0", "47c9a2b490ceae84", - "4866a2abc9be3133", "48ca99496ac8265e", "494b23454cfaf902", "49d560912ccd3bd6", "49ee572590d74921", - "4c3afe5f9f4265d3", "4cef6042d25d7ce2", "4f4516913c6de5d6", "4f9b0fa57d925ddc", "50cecf0fd2f1ed1f", - "511ed51b27f98b9c", "52879b9f3cbdd66f", "52d9b8b42edf92c5", "52dd5ae3e9bfef22", "53f304d4f21e321e", - "5503b8002ae2673f", "55397a6480705e90", "561988b22b65f79f", "5640b6d1a24b9ad6", "56d9c8bc2e2d7a01", - "570b7b7be5396079", "57603aa52f880d03", "57c4df2758097604", "59e238f79e31e3db", "5acb4cacd9aa7a71", - "5b1f0d60cdd91b33", "5b783704ccce90b9", "5b833f85df94c6fd", "5caaf9a02506595e", "5cd2de3ab18314a9", - "5cda11b0371e8b48", "5e17fde0e8281e0b", "61241c19f875d528", "614d8160fecebe42", "62ac6e83f597894a", - "62ae3935928ec875", "62ae5138ca3f54bf", "29b4daf7b7befa61", "63887df3233e4e7f", "63bbbd89d07abcc5", - "63d3556d23363430", "6407c8198a2ce80f", "6669b8199b2f15be", "6710e607f9ae6ba2", "6c60928d93ca7831", - "6e57bc847800e849", "6f2fef4ed95b870d", "70f8b4b8cb326639", "7227a51a80d75567", "728afb0024d5da55", - "745fabbdac49b041", "74622ec18c9f9985", "74eab10487ee91a4", "7548695a3a57c058", "76030078f4c446ec", - "7698729bcfd126f7", "77ed807b2db1bdb4", "782bc48fcd75361c", "7846dce0563bde1f", "78b5bea3cfb3f84f", - "7a41c841fa3c71c3", "7b3944471a209cdc", "7ba95fb426152c3b", "814a101266f1e722", "8232460887910a0e", - "82b97043efd185d0", "83b56cb713adb544", "84ebb93c8c137862", "8559d433706ac279", "85e199be8e5a5df5", - "86c327f4147ec696", "8c3417a9291e07cf", "9031db861c91b202", "90697a358931eba2", "9084568d44e608c3", - "945be2a3aaccbb2c", "94c5248d3fe6f83f", "95feaea41a059d9a", "966dd5354d327ba4", "97c036827ae94466", - "97fed7ecb0c23137", "982773d6151ae295", "993631c9efdbaa48", "999cc41aeaa485d9", "9b976d47e8cca045", - "9db89af226707449", "9e9437780d412b86", "9ee05526226dd121", "9f6cb144b5b0013d", "a14aae022e52cabd", - "a2db3c73eea72747", "a6e2e42521f27aa8", "a7b7a83d8e7b5914", "a84c5847e6bc413a", "a9cdf0e474dfa4ca", - "ab9a1c81f4d00b17", "ac208a7edf8e6b9e", "ac524f5b860f4b73", "af6bfc4105841865", "b25dfdea45b42ece", - "b2ee46983b09686b", "b6c96aabf4daba15", "b99ef0dca48e547c", "bc89c106ed0333da", "399e08b7f60cd570", - "bd2edda7ff995e5a", "c0f36dd22b6d1df4", "c1cbe5ed9ccaf41a", "c2e62316bf302721", "c30f7e945ca5204b", - "c446b7882073d116", "c555077d0a4ca6dc", "c5556985dac877fb", "c66938fdb57ac8bd", "c7d3f2a6e0e819c7", - "437e813553f5782e", "c9147167591ac87f", "c9682c8986bdfa3f", "c9f15a774cbbb296", "c9f895250a7f6b1f", - "ca9ac59c7e4dd0dd", "ccfd7af308666817", "cde221c994e186e9", "d1c59fa1e5fd22ca", "d2c0d56090ffb617", - "d3a72db1fb71eaf6", "d58784f8ae176897", "d88381653e2c64f9", "d934528c9e7966f7", "da73ed73f0ec1dd9", - "da8381da9de5df66", "dd4f9524437dcc45", "dd6384bc82ce9677", "df5a6c2edc20af59", "e076b4232fc136e9", - "e1ada69597a5d6cd", "e1d8a4d6d6bbfb2e", "e2af4a0f5b0957d5", "e313fbfdd61fba0c", "e347453420828b08", - "e368dfa3ca97d4c7", "e3cc20cbd63d0adb", "e4435ba963a1fbef", "e5182c24f72e2747", "e660a27969605244", - "e7dad258cbc844a0", "e97d1ef509983caa", "e997a8c038464efb", "eb66b6c389ec09e4", "ed7764b9ec0265a0", - "ee8e568418c22e81", "ef22d97e0a67bed8", "f0baa883ab5f959d", "f12cb9b454600534", "f135bd1f9697ad4c", - "f166b8797656c86e", "f191a6842f342b74", "f3ea04dd3a66f76a", "f4c93c2e841f1c68", "f4d7edfeee65b0c3", - "f6528fa83345165e", "fa4172e085723211", "fc0c07879a70ce33", "fd706bf633a51444", "fd793c8cfa94f318", - "fe800048b661a783", "6cfa7cfc6f6a4a7e", -}) +# 처음 217개였다. 2026-11-07 번역 단계에서 목록이 비어 모두 뺐다. +FROZEN: frozenset[str] = frozenset() # --- 언어 판정: ~/.claude/hooks/guard_report.py의 H11과 같은 규칙(design-docs conventions/delegation-loop.md 11절) MIN_ENGLISH = 3 @@ -152,11 +134,20 @@ GRADLE_PATH = re.compile(r"^:[A-Za-z][\w-]*(?::[A-Za-z][\w-]*)+$") HISTORY_QUOTE = re.compile(r"^\s*>\s*(?:\*\*)?이력") # --- 복사한 숫자 +SPRING_BOOT = "Spring Boot 버전" COPIED_NUMBERS = [ - ("Spring Boot 버전", re.compile(r"Spring Boot \d+\.\d+\.\d+")), + (SPRING_BOOT, re.compile(r"\b(?:Spring\s+)?Boot\s+v?\d+\.\d+\.\d+")), ("leaf 개수", re.compile(r"\b\d+\s*개의?\s*leaf|\bleaf\s*\d+\s*개|\b\d+\s+(?:registered\s+)?lea(?:f|ves)\b", re.I)), ] +# 이름 옆이 아닌 Spring Boot 버전: 「기준은 **4.0.8**」, 「| Spring Boot | 4.0.0 |」. +CATALOG_FILE = "src/gradle/libs.versions.toml" +CATALOG_SPRING_BOOT = re.compile(r'^springBoot\s*=\s*"([^"]+)"', re.M) +# 세 자리 버전. 앞이 낱말·점·§이면 다른 수의 일부다(1.2.3.4, RFC 절 번호 §6.5.2). +VERSION = re.compile(r"(?<![\w.§])v?\d+\.\d+\.\d+(?:[.-][A-Za-z][A-Za-z0-9]*)*(?![\w]|\.\d)") +SPRING_BOOT_CELL = re.compile(r"^Spring Boot(?:\s+(?:BOM|버전))?$") +CELL_MARKUP = re.compile(r"[*_`]") +LINK_TEXT = re.compile(r"\[([^\]\n]*)\]\([^)\s]*\)") @dataclass(frozen=True) @@ -179,15 +170,19 @@ def fingerprint(line: str) -> str: return hashlib.sha256(line.encode("utf-8")).hexdigest()[:16] -def tracked_markdown(root: Path) -> list[str]: - """Markdown files git knows or would add: tracked plus untracked files that are not ignored.""" +def tracked_files(root: Path, pathspec: str) -> list[str]: + """Files git knows or would add: tracked plus untracked files that are not ignored.""" result = subprocess.run( - ["git", "-C", str(root), "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", "*.md"], + ["git", "-C", str(root), "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", pathspec], capture_output=True, check=True) names = {name for name in result.stdout.decode("utf-8").split("\0") if name} return sorted(name for name in names if (root / name).is_file()) +def tracked_markdown(root: Path) -> list[str]: + return [name for name in tracked_files(root, "*.md") if not NOT_DOCUMENT.search(name)] + + def record_kind(path: str) -> str | None: for prefix, kind in RECORD_KINDS: if path.startswith(prefix): @@ -278,6 +273,7 @@ def backticked_paths(value: str) -> list[str]: def check_head(root: Path, files: list[str]) -> list[Problem]: problems = [] + known = known_paths(root) for path in files: kind = record_kind(path) if kind is None: @@ -331,7 +327,7 @@ def check_head(root: Path, files: list[str]) -> list[Problem]: if not canonical.startswith("없음") and not targets: fail("현재 정본은 `경로`(여럿이면 쉼표) 또는 「없음 — 이유」다", at) for target in targets: - if not (root / target).exists(): + if not is_known(known, target): fail(f"현재 정본 경로가 없다: {target}", at) if status == "대체됨" and "대체됨" not in fields: fail("상태가 대체됨이면 「대체됨」 칸에 대체한 문서를 적는다") @@ -342,7 +338,7 @@ def check_head(root: Path, files: list[str]) -> list[Problem]: if not targets: fail(f"「{name}」 칸은 `경로`를 적는다", at) for target in targets: - if not (root / target).exists(): + if not is_known(known, target): fail(f"「{name}」 경로가 없다: {target}", at) return problems @@ -394,15 +390,30 @@ def path_candidate(token: str) -> str | None: return token or None -def resolves(root: Path, document: str, target: str) -> bool: - if (root / target).exists(): +def known_paths(root: Path) -> set[str]: + """Every file git knows or would add, and every folder above one. A path that is only on disk does not + count: an empty folder `git mv` leaves behind, or a file nobody added, is not in a fresh checkout.""" + paths: set[str] = set() + for name in tracked_files(root, "."): + parts = name.split("/") + for end in range(1, len(parts) + 1): + paths.add("/".join(parts[:end])) + return paths + + +def is_known(known: set[str], path: str) -> bool: + return posixpath.normpath(path) in known + + +def resolves(root: Path, document: str, target: str, known: set[str]) -> bool: + if is_known(known, target): return True # src/main/... in a leaf document is written relative to that leaf. - folder = (root / document).parent - while folder != root and root in folder.parents: - if (folder / target).exists(): + folder = posixpath.dirname(document) + while folder: + if is_known(known, f"{folder}/{target}"): return True - folder = folder.parent + folder = posixpath.dirname(folder) return False @@ -435,6 +446,7 @@ def path_suffixes(root: Path) -> set[str]: def check_reference(root: Path, files: list[str]) -> list[Problem]: projects = registry_projects(root) + known = known_paths(root) missing: list[tuple[str, int, str]] = [] problems = [] for path in files: @@ -456,7 +468,7 @@ def check_reference(root: Path, files: list[str]) -> list[Problem]: target = path_candidate(token) if target and SOURCE_SET.match(target): continue - if target and target not in seen and not resolves(root, path, target): + if target and target not in seen and not resolves(root, path, target, known): seen.add(target) missing.append((path, number + offset, target)) skip = ignored(root, {target for _, _, target in missing}) @@ -468,24 +480,161 @@ def check_reference(root: Path, files: list[str]) -> list[Problem]: return problems +def catalog_spring_boot(root: Path) -> re.Pattern[str] | None: + """정본의 Spring Boot 버전과 같은 버전 문자열. 카탈로그가 없으면 None(이름 옆과 표 칸만 본다).""" + catalog = root / CATALOG_FILE + found = CATALOG_SPRING_BOOT.search(catalog.read_text(encoding="utf-8")) if catalog.is_file() else None + if not found: + return None + return re.compile(r"(?<![\w.§])v?" + re.escape(found.group(1)) + r"(?![\w]|\.\d)") + + +def spring_boot_cell_versions(line: str) -> list[re.Match[str]]: + """`Spring Boot` 칸(굵은 글씨·코드·링크를 벗긴 칸 전체)이 있는 표 행의 세 자리 버전.""" + if not line.lstrip().startswith("|"): + return [] + cells = [CELL_MARKUP.sub("", LINK_TEXT.sub(r"\1", cell)).strip() for cell in line.strip().strip("|").split("|")] + if not any(SPRING_BOOT_CELL.match(cell) for cell in cells): + return [] + return list(VERSION.finditer(line)) + + def check_number(root: Path, files: list[str]) -> list[Problem]: problems = [] + current = catalog_spring_boot(root) for path in files: if not checked_for_drift(path): continue seen: set[str] = set() for number, line in enumerate((root / path).read_text(encoding="utf-8").split("\n"), start=1): - for label, pattern in COPIED_NUMBERS: - for match in pattern.finditer(line): - text = match.group(0) - if text not in seen: - seen.add(text) - problems.append(Problem("number", path, text, - f"{label}를 복사했다: {text!r}. 정본을 가리킨다", number)) + found = [(label, match) for label, pattern in COPIED_NUMBERS for match in pattern.finditer(line)] + named = [match.span() for _, match in found] + # 이름 옆 복사(「Spring Boot 4.0.8」)는 한 번만 센다: 그 안의 버전을 표·정본 규칙이 다시 세지 않는다. + others = spring_boot_cell_versions(line) + (list(current.finditer(line)) if current else []) + found += [(SPRING_BOOT, match) for match in others + if not any(start <= match.start() and match.end() <= end for start, end in named)] + for label, match in found: + text = match.group(0) + if text not in seen: + seen.add(text) + problems.append(Problem("number", path, text, + f"{label}를 복사했다: {text!r}. 정본을 가리킨다", number)) return problems -RUNNERS = {"language": check_language, "head": check_head, "reference": check_reference, "number": check_number} +def required_folders(paths: list[str]) -> set[str]: + """지도에 있어야 하는 폴더(`docs/` 기준): docs/ 바로 아래 폴더. 파일 없이 폴더만 가진 묶음 폴더는 + 그 바로 아래 폴더가 대신한다(history/ → history/plans/ 등). 더 깊이는 내려가지 않는다.""" + def children(paths: list[str]) -> dict[str, list[str]]: + found: dict[str, list[str]] = {} + for path in paths: + name, slash, rest = path.partition("/") + if slash: + found.setdefault(name, []).append(rest) + return found + + folders: set[str] = set() + for name, inside in children(paths).items(): + if any("/" not in path for path in inside): + folders.add(f"{name}/") + else: + folders |= {f"{name}/{child}/" for child in children(inside)} + return folders + + +def outside_code(lines: list[str]) -> list[tuple[int, str]]: + """(줄 번호, 줄) — 코드 블록 밖의 줄만.""" + kept, fence = [], None + for number, line in enumerate(lines, start=1): + match = FENCE.match(line) + if fence: + if match and match.group(1)[0] == fence[0] and len(match.group(1)) >= len(fence): + fence = None + continue + if match: + fence = match.group(1) + continue + kept.append((number, line)) + return kept + + +def map_entries(lines: list[str]) -> list[tuple[int, str]]: + """(줄 번호, `docs/` 기준 폴더) — 코드 블록 밖 표 행의 첫 칸에 인라인 코드로 적은 `폴더/`.""" + entries = [] + for number, line in outside_code(lines): + cells = line.strip().split("|") + if not line.strip().startswith("|") or len(cells) < 3: + continue + for found in INLINE.finditer(cells[1]): + token = found.group(0).strip("`").strip() + if token.startswith(DOCS_ROOT): + token = token[len(DOCS_ROOT):] + if token.endswith("/") and not PLACEHOLDER.search(token): + entries.append((number, token)) + return entries + + +def check_map(root: Path, files: list[str]) -> list[Problem]: + del files # 지도는 .md만이 아니라 docs/ 아래 모든 파일의 폴더를 본다(스냅숏·yaml만 있는 폴더도 있다). + if not (root / MAP_FILE).is_file(): + return [Problem("map", MAP_FILE, "", "문서 지도가 없다")] + documents = [path[len(DOCS_ROOT):] for path in tracked_files(root, DOCS_ROOT)] + entries = map_entries((root / MAP_FILE).read_text(encoding="utf-8").split("\n")) + mapped = {folder for _, folder in entries} + problems = [Problem("map", MAP_FILE, folder, f"지도에 없는 문서 폴더다: {DOCS_ROOT}{folder}. 지도에 행을 더한다") + for folder in sorted(required_folders(documents) - mapped)] + for number, folder in entries: + if not any(path.startswith(folder) for path in documents): + problems.append(Problem("map", MAP_FILE, folder, f"지도의 폴더가 없다: {DOCS_ROOT}{folder}", number)) + return problems + + +def headings(lines: list[str]) -> list[tuple[int, int, str]]: + """(줄 번호, 수준, 제목) — 코드 블록 밖의 # 제목.""" + found = [] + for number, line in outside_code(lines): + heading = re.match(r"^(#{1,6})\s+(.+?)\s*#*\s*$", line) + if heading: + found.append((number, len(heading.group(1)), heading.group(2))) + return found + + +def check_readme(root: Path, files: list[str]) -> list[Problem]: + del files + + def fail(key: str, message: str, line: int = 0) -> None: + problems.append(Problem("readme", README_FILE, key, message, line)) + + problems: list[Problem] = [] + if not (root / README_FILE).is_file(): + fail("", "루트 README가 없다") + return problems + lines = (root / README_FILE).read_text(encoding="utf-8").split("\n") + found = headings(lines) + first = next((number for number, line in enumerate(lines, start=1) if line.strip()), 0) + if not found or found[0][:2] != (first, 1): + fail("제목", "첫 줄은 `# 제목`이다", first) + else: + sections = [number for number, level, _ in found if level == 2] + intro = lines[first:sections[0] - 1] if sections else lines[first:] + if not any(line.strip() and not line.lstrip().startswith(("#", "|", "```", "~~~")) for line in intro): + fail("소개", "제목 아래, 첫 ## 절 앞에 무엇인지·누가 쓰나 한 문단을 둔다", first) + positions = {} + for number, level, title in found: + if level == 2 and title in README_SECTIONS and title not in positions: + positions[title] = number + for title in README_SECTIONS: + if title not in positions: + fail(title, f"「## {title}」 절이 없다. 절 목록은 {' → '.join(README_SECTIONS)}다") + present = [title for title in README_SECTIONS if title in positions] + for before, after in zip(present, present[1:]): + if positions[before] > positions[after]: + fail(after, f"「## {after}」 절은 「## {before}」 절 뒤에 온다", positions[after]) + return problems + + +RUNNERS = {"language": check_language, "head": check_head, "reference": check_reference, "number": check_number, + "map": check_map, "readme": check_readme} def read_exceptions(text: str) -> list[str]: @@ -505,6 +654,10 @@ def run(root: Path, only: tuple[str, ...] = CHECKS, exceptions: str | None = Non for entry in allowed: if fingerprint(entry) not in frozen: errors.append(f"[exceptions] {EXCEPTIONS_FILE}: 기준선에 없는 예외다. 예외 목록은 늘지 않는다: {entry!r}") + listed = {fingerprint(entry) for entry in allowed} + for orphan in sorted(frozen - listed): + errors.append(f"[exceptions] scripts/check-docs.py FROZEN: 예외 목록에 그 줄이 없는 지문이다. " + f"지운 줄의 지문은 FROZEN에서도 뺀다: {orphan}") allowed_set = set(allowed) for check in only: problems = RUNNERS[check](root, files) diff --git a/scripts/check-repo-layout.py b/scripts/check-repo-layout.py index 805adb87..d05fb1b3 100755 --- a/scripts/check-repo-layout.py +++ b/scripts/check-repo-layout.py @@ -47,6 +47,7 @@ ROOT_ALLOWED = { # 파일 ".gitattributes": "Git 설정", ".gitignore": "Git 설정", + ".lycheeignore": "링크 검사(lychee)가 건너뛸 URL. lychee는 저장소 루트의 이 이름만 읽는다", ".tool-versions": "JDK 버전 고정", ".trivyignore.yaml": "취약점 검사 예외", "AGENTS.md": "규칙 정본", diff --git a/scripts/tests/test_check_docs.py b/scripts/tests/test_check_docs.py index 64ebe46e..2924849e 100644 --- a/scripts/tests/test_check_docs.py +++ b/scripts/tests/test_check_docs.py @@ -109,6 +109,23 @@ class ExceptionListTest(RepositoryTestCase): errors = self.repo.run(("language",), exceptions=self.LINE + "\n", frozen=frozenset()) self.assertFailsWith(errors, "기준선에 없는 예외다") + def test_a_frozen_fingerprint_whose_line_was_removed_fails(self) -> None: + # The line was deleted from the list but its fingerprint stayed: the same line could come back. + orphan = frozenset({check_docs.fingerprint(self.LINE)}) + for only in (("language",), ("head",)): + errors = self.repo.run(only, exceptions="", frozen=orphan) + self.assertFailsWith(errors, "예외 목록에 그 줄이 없는 지문이다") + + def test_a_removed_line_added_back_fails_once_its_fingerprint_is_gone(self) -> None: + self.repo.write("docs/guide.md", ENGLISH * 3) + remaining = "language\tdocs/other.md" + self.repo.write("docs/other.md", ENGLISH * 3) + exceptions = remaining + "\n" + self.LINE + "\n" + errors = self.repo.run(("language",), exceptions=exceptions, + frozen=frozenset({check_docs.fingerprint(remaining)})) + self.assertFailsWith(errors, "기준선에 없는 예외다") + self.assertFalse(any("예외 목록에 그 줄이 없는 지문이다" in error for error in errors), errors) + def test_an_exception_that_no_longer_fails_must_be_removed(self) -> None: self.repo.write("docs/guide.md", KOREAN * 3) self.assertFailsWith(self.repo.run(("language",), exceptions=self.LINE + "\n"), "더는 걸리지 않는다") @@ -124,6 +141,11 @@ class ExceptionListTest(RepositoryTestCase): if check_docs.fingerprint(line) not in check_docs.FROZEN] self.assertEqual(outside, []) + def test_every_frozen_fingerprint_has_its_line_in_the_real_exception_list(self) -> None: + text = (SCRIPTS.parent / check_docs.EXCEPTIONS_FILE).read_text(encoding="utf-8") + listed = {check_docs.fingerprint(line) for line in check_docs.read_exceptions(text)} + self.assertEqual(sorted(check_docs.FROZEN - listed), []) + def test_a_new_line_in_the_real_exception_list_is_not_in_the_frozen_baseline(self) -> None: self.assertNotIn(check_docs.fingerprint("language\tdocs/brand-new-english.md"), check_docs.FROZEN) @@ -160,6 +182,10 @@ class HeadBlockTest(RepositoryTestCase): def test_a_canonical_path_that_does_not_exist_fails(self) -> None: self.assertFailsWith(self.errors_for(head(canonical="`docs/missing.md`")), "현재 정본 경로가 없다") + def test_a_canonical_folder_left_empty_on_disk_fails(self) -> None: + (self.repo.root / "docs/moved").mkdir(parents=True) + self.assertFailsWith(self.errors_for(head(canonical="`docs/moved/`")), "현재 정본 경로가 없다: docs/moved/") + def test_a_canonical_value_without_a_path_fails(self) -> None: self.assertFailsWith(self.errors_for(head(canonical="jpa 문서")), "현재 정본은") @@ -188,6 +214,15 @@ class ReferenceTest(RepositoryTestCase): def test_a_missing_repository_path_fails(self) -> None: self.assertFailsWith(self.errors_for("`docs/gone.md`를 읽는다.\n"), "없는 경로다: docs/gone.md") + def test_a_folder_left_empty_on_disk_fails(self) -> None: + # `git mv` leaves the old folder behind. A fresh checkout does not have it, so it is not a path. + (self.repo.root / "docs/moved").mkdir(parents=True) + self.assertFailsWith(self.errors_for("`docs/moved/`를 읽는다.\n"), "없는 경로다: docs/moved/") + + def test_a_folder_that_holds_a_file_passes(self) -> None: + self.repo.write("docs/kept/a.md", KOREAN) + self.assertEqual(self.errors_for("`docs/kept/`를 읽는다.\n"), []) + def test_an_existing_path_with_a_line_number_passes(self) -> None: self.assertEqual(self.errors_for("`docs/live.md:12`를 읽는다.\n"), []) @@ -245,6 +280,164 @@ class NumberTest(RepositoryTestCase): def test_a_word_count_of_leaves_passes(self) -> None: self.assertEqual(self.errors_for("leaf 하나를 고른다.\n"), []) + def with_catalog(self, version: str = "4.0.8") -> None: + self.repo.write(check_docs.CATALOG_FILE, f'[versions]\nspringBoot = "{version}"\nother = "1.2.3"\n') + + def test_boot_without_spring_fails(self) -> None: + self.assertFailsWith(self.errors_for("BOM은 Boot 4.0.0이 푼다.\n"), "'Boot 4.0.0'") + + def test_a_bold_copy_of_the_catalog_version_fails(self) -> None: + self.with_catalog() + self.assertFailsWith(self.errors_for("이 저장소의 기준은 **4.0.8**이다.\n"), "'4.0.8'") + + def test_the_catalog_version_in_code_fails(self) -> None: + self.with_catalog() + self.assertFailsWith(self.errors_for("`org.springframework.boot:spring-boot:4.0.8`을 쓴다.\n"), "'4.0.8'") + + def test_a_version_in_a_spring_boot_table_row_fails(self) -> None: + self.with_catalog() + errors = self.errors_for("| 의존성 | 버전 |\n| --- | --- |\n| **Spring Boot** | 4.0.0 (BOM이 관리) |\n") + self.assertFailsWith(errors, "'4.0.0'") + + def test_a_copy_next_to_the_name_is_reported_once(self) -> None: + self.with_catalog() + errors = self.errors_for("| Spring Boot | Spring Boot 4.0.8 |\n") + self.assertEqual(len(errors), 1, errors) + self.assertFailsWith(errors, "'Spring Boot 4.0.8'") + + def test_another_library_in_a_table_row_passes(self) -> None: + self.with_catalog() + self.assertEqual(self.errors_for("| Hibernate | **7.1.8.Final** |\n| Spring Boot | 카탈로그 |\n"), []) + + def test_numbers_that_only_contain_the_catalog_version_pass(self) -> None: + self.with_catalog() + self.assertEqual(self.errors_for("RFC 9113 §4.0.8, 버전 14.0.8, 4.0.80, 4.0.8.1, 다른 값 1.2.3.\n"), []) + + def test_a_spring_boot_cell_name_must_be_the_whole_cell(self) -> None: + self.with_catalog() + self.assertEqual(self.errors_for("| Spring Boot BOM이 푸는 Hibernate | 7.1.8.Final |\n"), []) + + +class ScopeTest(RepositoryTestCase): + def test_markdown_under_a_source_set_resources_folder_is_not_a_document(self) -> None: + self.repo.write("src/app/src/test/resources/fixtures/broken-readme.md", "# Broken\n\n" + ENGLISH * 3) + self.assertEqual(self.repo.run(("language",)), []) + + def test_markdown_beside_a_source_set_is_still_a_document(self) -> None: + self.repo.write("src/app/src/test/README.md", "# Tests\n\n" + ENGLISH * 3) + self.assertFailsWith(self.repo.run(("language",)), "src/app/src/test/README.md: 영어 문서다") + + +def table(*rows: str) -> str: + return "| 폴더 | 무엇 |\n| --- | --- |\n" + "".join(f"| {row} | 설명 |\n" for row in rows) + + +class MapTest(RepositoryTestCase): + def errors_for(self, text: str) -> list[str]: + self.repo.write(check_docs.MAP_FILE, "# docs\n\n" + KOREAN + text) + return self.repo.run(("map",)) + + def test_a_map_that_names_every_folder_passes(self) -> None: + self.repo.write("docs/jpa/guide.md", KOREAN) + self.repo.write("docs/history/plans/2026-08-11-x-plan.md", KOREAN) + checks = "| 검사 | 보는 것 |\n| --- | --- |\n| `language` | 언어 |\n" + self.assertEqual(self.errors_for(table("`jpa/`", "`history/plans/`") + "\n" + checks), []) + + def test_a_folder_missing_from_the_map_fails(self) -> None: + self.repo.write("docs/redis/operations.md", KOREAN) + self.assertFailsWith(self.errors_for(table()), "지도에 없는 문서 폴더다: docs/redis/") + + def test_a_folder_without_markdown_must_be_mapped_too(self) -> None: + self.repo.write("docs/security/public-paths-snapshot.txt", "/api/healthcheck\n") + self.assertFailsWith(self.errors_for(table()), "지도에 없는 문서 폴더다: docs/security/") + + def test_a_folder_that_only_holds_folders_is_covered_by_its_subfolders(self) -> None: + self.repo.write("docs/history/plans/2026-08-11-x-plan.md", KOREAN) + self.repo.write("docs/history/study/x.md", KOREAN) + errors = self.errors_for(table("`history/`", "`history/plans/`")) + self.assertFailsWith(errors, "지도에 없는 문서 폴더다: docs/history/study/") + self.assertFalse(any("docs/history/plans/" in error for error in errors), errors) + + def test_folders_below_the_mapped_level_need_no_row(self) -> None: + self.repo.write("docs/history/packages/jpa/README.md", KOREAN) + self.repo.write("docs/mongodb/advanced/sharding.md", KOREAN) + self.repo.write("docs/mongodb/guide.md", KOREAN) + self.assertEqual(self.errors_for(table("`history/packages/`", "`mongodb/`")), []) + + def test_a_mapped_folder_that_does_not_exist_fails(self) -> None: + self.assertFailsWith(self.errors_for(table("`gone/`")), "지도의 폴더가 없다: docs/gone/") + + def test_a_folder_named_outside_the_first_cell_does_not_count(self) -> None: + self.repo.write("docs/redis/operations.md", KOREAN) + self.assertFailsWith(self.errors_for(table("운영") + "| 캐시 | `redis/` |\n"), + "지도에 없는 문서 폴더다: docs/redis/") + + def test_a_folder_inside_a_code_block_does_not_count(self) -> None: + self.repo.write("docs/redis/operations.md", KOREAN) + self.assertFailsWith(self.errors_for("```text\n" + table("`redis/`") + "```\n"), + "지도에 없는 문서 폴더다: docs/redis/") + + def test_a_folder_may_be_written_from_the_repository_root(self) -> None: + self.repo.write("docs/redis/operations.md", KOREAN) + self.assertEqual(self.errors_for(table("`docs/redis/`")), []) + + def test_a_placeholder_folder_is_not_an_entry(self) -> None: + self.assertEqual(self.errors_for(table("`history/packages/<어댑터>/`")), []) + + def test_a_repository_without_the_map_fails(self) -> None: + self.assertFailsWith(self.repo.run(("map",)), "문서 지도가 없다") + + +def readme(sections: tuple[str, ...] = check_docs.README_SECTIONS, title: str = "# 템플릿", + intro: str = "이 저장소가 무엇이고 누가 쓰는지 쓴 한 문단이다.") -> str: + parts = [title, "", intro, ""] if intro else [title, ""] + for section in sections: + parts += [section if section.startswith("#") else f"## {section}", "", KOREAN] + return "\n".join(parts) + + +class ReadmeTest(RepositoryTestCase): + def errors_for(self, text: str) -> list[str]: + self.repo.write(check_docs.README_FILE, text) + return self.repo.run(("readme",)) + + def test_every_section_in_order_passes(self) -> None: + self.assertEqual(self.errors_for(readme()), []) + + def test_other_sections_between_the_required_ones_pass(self) -> None: + sections = check_docs.README_SECTIONS[:2] + ("부록",) + check_docs.README_SECTIONS[2:] + self.assertEqual(self.errors_for(readme(sections)), []) + + def test_each_missing_section_fails(self) -> None: + for missing in check_docs.README_SECTIONS: + with self.subTest(missing=missing): + sections = tuple(section for section in check_docs.README_SECTIONS if section != missing) + self.assertFailsWith(self.errors_for(readme(sections)), f"「## {missing}」 절이 없다") + + def test_sections_out_of_order_fail(self) -> None: + sections = ("시작하기", "프로젝트 구조") + check_docs.README_SECTIONS[2:] + self.assertFailsWith(self.errors_for(readme(sections)), "「## 시작하기」 절은 「## 프로젝트 구조」 절 뒤에 온다") + + def test_a_readme_that_does_not_start_with_a_title_fails(self) -> None: + self.assertFailsWith(self.errors_for(readme(title="템플릿 소개")), "첫 줄은 `# 제목`이다") + self.assertFailsWith(self.errors_for("소개 한 줄\n\n" + readme()), "첫 줄은 `# 제목`이다") + + def test_a_readme_without_an_introduction_fails(self) -> None: + self.assertFailsWith(self.errors_for(readme(intro="")), "한 문단을 둔다") + + def test_a_section_heading_at_another_level_does_not_count(self) -> None: + sections = tuple("### 문서 지도" if section == "문서 지도" else section + for section in check_docs.README_SECTIONS) + self.assertFailsWith(self.errors_for(readme(sections)), "「## 문서 지도」 절이 없다") + + def test_a_section_heading_inside_a_code_block_does_not_count(self) -> None: + sections = tuple(section for section in check_docs.README_SECTIONS if section != "검증") + text = readme(sections) + "\n```markdown\n## 검증\n```\n" + self.assertFailsWith(self.errors_for(text), "「## 검증」 절이 없다") + + def test_a_repository_without_a_readme_fails(self) -> None: + self.assertFailsWith(self.repo.run(("readme",)), "루트 README가 없다") + class CommandLineTest(unittest.TestCase): def test_an_unknown_check_is_a_usage_error(self) -> None: diff --git a/src/README.md b/src/README.md index d51064ec..7db03a60 100644 --- a/src/README.md +++ b/src/README.md @@ -1,24 +1,24 @@ # src — 빌드 스크립트 / 환경 변수 참조 -`src/` 는 Gradle 멀티모듈 루트입니다. 모듈 경계·의존 방향 규칙은 루트 [CLAUDE.md](../CLAUDE.md) -와 [AGENTS.md](../AGENTS.md), 모듈별 규칙은 각 모듈의 `CLAUDE.md` 가 SSOT 입니다. +`src/` 는 Gradle 멀티모듈 루트다. 모듈 경계·의존 방향 규칙은 루트 [CLAUDE.md](../CLAUDE.md) +와 [AGENTS.md](../AGENTS.md), 모듈별 규칙은 각 모듈의 `CLAUDE.md` 가 SSOT이다. 이 문서는 [build.gradle](build.gradle) 과 [.env.example](.env.example)(복사해 `.env` 로 씀) 의 코드 주석에서 덜어낸 **설정 항목 설명과 -결정 근거**를 모아둔 참조용 기록입니다. 두 파일에는 짧은 기능 주석과 "자세한 내용은 README 참조" -포인터만 남기고, "왜 이렇게 했나"는 여기서 풀어 설명합니다. +결정 근거**를 모아둔 참조용 기록이다. 두 파일에는 짧은 기능 주석과 "자세한 내용은 README 참조" +포인터만 남기고, "왜 이렇게 했나"는 여기서 풀어 설명한다. --- ## build.gradle — 빌드 / 검증 게이트 -검증은 로컬 피드백과 저장소 전체 검증을 분리합니다. `:<leaf>:check`는 해당 모듈의 컴파일, -테스트, Spotless, Checkstyle, Error Prone만 담당합니다. 저장소 전체 정책은 이름이 드러나는 -루트 task로 실행하며, CI가 이를 집계합니다. +검증은 로컬 피드백과 저장소 전체 검증을 분리한다. `:<leaf>:check`는 해당 모듈의 컴파일, +테스트, Spotless, Checkstyle, Error Prone만 담당한다. 저장소 전체 정책은 이름이 드러나는 +루트 task로 실행하며, CI가 이를 집계한다. -이 셋의 역할은 겹치지 않습니다. Spotless(google-java-format)가 포맷과 import 순서를 소유하고, -Checkstyle은 **포매터가 표현할 수 없는 것만** — 네이밍과 몇 가지 논리/설계 규칙만 — 봅니다 +이 셋의 역할은 겹치지 않는다. Spotless(google-java-format)가 포맷과 import 순서를 소유하고, +Checkstyle은 **포매터가 표현할 수 없는 것만** — 네이밍과 몇 가지 논리/설계 규칙만 — 본다 (`config/checkstyle/checkstyle.xml`). 줄 길이·들여쓰기·import 순서 모듈이 여기에 없는 것은 누락이 -아니라 포매터와 싸우지 않기 위한 선택입니다. Error Prone은 컴파일 시점 버그 패턴을 담당합니다. +아니라 포매터와 싸우지 않기 위한 선택이다. Error Prone은 컴파일 시점 버그 패턴을 담당한다. | 게이트 | 하는 일 | | --- | --- | @@ -34,8 +34,8 @@ Checkstyle은 **포매터가 표현할 수 없는 것만** — 네이밍과 몇 | `releaseCheck` | tag 전용 검사: `verifyReleaseProvenance` + `verifyPublicPathSnapshot`(`ci`를 다시 돌리지 않음) | 따라서 로컬에서 한 모듈만 수정했다면 `./gradlew :domain-core:check`처럼 focused task를 -먼저 사용합니다. 전체 기동 qualification은 일반 leaf `check`나 `:app-bootstrap:build`에 -매달지 않고 `qualificationCheck`/`mainCheck`에서 실행합니다. +먼저 사용한다. 전체 기동 qualification은 일반 leaf `check`나 `:app-bootstrap:build`에 +매달지 않고 `qualificationCheck`/`mainCheck`에서 실행한다. **2026-09에 삭제한 게이트.** `verifyOneTypePerFile`(Checkstyle의 `OneTopLevelClass`가 같은 규칙을 파싱된 파일에 대해 검사한다), `verifyTrivyignore`·`verifyQuarantineSunset`(빈 레지스트리를 지키는 @@ -44,68 +44,68 @@ Checkstyle은 **포매터가 표현할 수 없는 것만** — 네이밍과 몇 `verifyConfigurationPropertiesProcessor`(`ca.spring-config` convention plugin이 대체). 근거는 `docs/design/2026-09-16-verification-surface-reduction-design.md`. -### Local bootstrap +### 로컬 첫 실행 `scripts/bootstrap-local.sh`(저장소 루트)은 compile → Docker 확인 → DB 기동 대기 → -app 기동(Flyway 포함) → health smoke를 순서대로 실행합니다(예전 `./gradlew bootstrap`, 리뷰 +app 기동(Flyway 포함) → health smoke를 순서대로 실행한다(예전 `./gradlew bootstrap`, 리뷰 BUILD-O3-5로 build-logic 플러그인에서 스크립트로 옮김). DB와 app lifecycle은 저장소 루트의 개발 compose 파일 `compose.yaml`(`db`는 `jpa` profile)이 소유하며, app startup Flyway가 -끝나 public health endpoint가 준비되어야 다음 단계로 넘어갑니다. `src/.env.example`은 커밋된 -env 계약이고 `src/.env`는 로컬 실행 입력입니다. `verifyEnvKeys`는 example/registry/shipped YAML을 -함께 검사합니다. +끝나 public health endpoint가 준비되어야 다음 단계로 넘어간다. `src/.env.example`은 커밋된 +env 계약이고 `src/.env`는 로컬 실행 입력이다. `verifyEnvKeys`는 example/registry/shipped YAML을 +함께 검사한다. -### Traceable version + dependency locking +### 추적 가능한 버전과 의존성 잠금 -- leaf version은 release version뿐입니다(`-PreleaseVersion`/`RELEASE_VERSION`, 기본 `0.0.1`). - revision(`-PgitRevision`/`GIT_SHA`/`GITHUB_SHA`)을 모르면 `-SNAPSHOT`이 붙습니다. revision은 jar +- leaf version은 release version뿐이다(`-PreleaseVersion`/`RELEASE_VERSION`, 기본 `0.0.1`). + revision(`-PgitRevision`/`GIT_SHA`/`GITHUB_SHA`)을 모르면 `-SNAPSHOT`이 붙는다. revision은 jar 이름에 넣지 않고 각 jar manifest의 `Build-Revision`과 app-bootstrap의 - `META-INF/build-info.properties`(`build.revision`)에 남깁니다. 예전에는 version이 + `META-INF/build-info.properties`(`build.revision`)에 남긴다. 예전에는 version이 `<MAJOR>.<MINOR>.<PATCH>+<sha>`라 커밋마다 새 jar 이름이 생겼고 그 잔여물을 `ca.archive-hygiene`이 - 치웠는데, 둘 다 없앴습니다(리뷰 BUILD-O3-5). + 치웠는데, 둘 다 없앴다(리뷰 BUILD-O3-5). - `releaseCheck`가 실행하는 `verifyReleaseProvenance`(루트 `build.gradle`, revision 판정은 `ca.java-conventions`와 같은 함수)는 source revision이 없으면 실패하므로 추적 불가능한 산출물을 - release로 취급할 수 없습니다. 예전 `ca.release-provenance` 플러그인은 없앴습니다(리뷰 BUILD-O3-5). + release로 취급할 수 없다. 예전 `ca.release-provenance` 플러그인은 없앴다(리뷰 BUILD-O3-5). - 모든 subproject가 `lockAllConfigurations()` + `LockMode.STRICT`를 사용하고, lock state는 Gradle - 기본 `<module>/gradle.lockfile`에 둡니다. 이 경로는 Renovate Gradle manager 기본 인식 경로와 - 같습니다. -- lock 갱신은 `./gradlew resolveAndLockAll --write-locks` 한 가지 명령으로 수행합니다. 이 task는 - `--write-locks`가 없으면 실패하며, 일반 build가 lock state를 조용히 다시 쓰지 못하게 합니다. + 기본 `<module>/gradle.lockfile`에 둔다. 이 경로는 Renovate Gradle manager 기본 인식 경로와 + 같다. +- lock 갱신은 `./gradlew resolveAndLockAll --write-locks` 한 가지 명령으로 수행한다. 이 task는 + `--write-locks`가 없으면 실패하며, 일반 build가 lock state를 조용히 다시 쓰지 못하게 한다. -### Reproducible archives (D10) +### 재현 가능한 아카이브 (D10) 모든 `AbstractArchiveTask`는 file timestamp 보존을 끄고, file order를 재현 가능하게 정렬하며, -directory/file mode를 각각 `0755`/`0644`로 고정합니다. Java toolchain은 21이고 로컬·CI patch -version은 root `.tool-versions`의 Temurin 값으로 맞춥니다. +directory/file mode를 각각 `0755`/`0644`로 고정한다. Java toolchain은 21이고 로컬·CI patch +version은 root `.tool-versions`의 Temurin 값으로 맞춘다. -archive task 자체는 timestamp 비보존·재현 가능한 file order·고정 mode를 강제합니다. 현재 저장소에는 +archive task 자체는 timestamp 비보존·재현 가능한 file order·고정 mode를 강제한다. 현재 저장소에는 별도의 `verify-reproducible-build.sh`가 없으므로 byte-for-byte 이중-build 비교를 자동 게이트라고 -주장하지 않습니다. 릴리스 검증의 정본 진입점은 `./gradlew releaseCheck`와 -`.github/workflows/release.yml`입니다. +주장하지 않는다. 릴리스 검증의 정본 진입점은 `./gradlew releaseCheck`와 +`.github/workflows/release.yml`이다. ### `-parameters` 컴파일러 플래그 -- **결정.** 모든 subproject 의 Java 컴파일에 `-parameters` 플래그를 직접 설정합니다. +- **결정.** 모든 subproject 의 Java 컴파일에 `-parameters` 플래그를 직접 설정한다. - **근거.** Spring MVC 는 `@PathVariable` / `@RequestParam` 의 이름을 reflection 의 parameter - metadata 에서 읽습니다. 이 플래그가 없으면 파라미터 이름이 `arg0`, `arg1` 로 컴파일되어 바인딩이 - 깨집니다. Spring Boot Gradle 플러그인은 이 플래그를 자동으로 켜 주지만, 이 프로젝트는 플러그인을 - `apply false` 로 두기 때문에 자동 적용이 일어나지 않습니다. 그래서 각 subproject 의 `JavaCompile` - 에 직접 설정합니다. + metadata 에서 읽는다. 이 플래그가 없으면 파라미터 이름이 `arg0`, `arg1` 로 컴파일되어 바인딩이 + 깨진다. Spring Boot Gradle 플러그인은 이 플래그를 자동으로 켜 주지만, 이 프로젝트는 플러그인을 + `apply false` 로 두기 때문에 자동 적용이 일어나지 않는다. 그래서 각 subproject 의 `JavaCompile` + 에 직접 설정한다. ### `verifyCleanArchitectureDependencies` - **하는 일.** [config/architecture/modules.json](config/architecture/modules.json)의 `allowed_dependencies`를 읽고, 실제 Gradle 프로젝트 의존(`api` / `implementation` / - `compileOnly` / `runtimeOnly`)이 그 범위를 벗어나면 빌드를 실패시킵니다. -- **JSON registry가 의존 방향의 SSOT 입니다.** 새 모듈이나 새 production 의존 edge를 추가하면 - registry와 `:app-bootstrap:architectureTest`의 관련 ArchUnit 규칙을 함께 갱신해야 합니다. settings와 gate는 - 같은 registry를 읽고, 등록되지 않은 leaf나 허용되지 않은 edge를 fail-closed로 거부합니다. + `compileOnly` / `runtimeOnly`)이 그 범위를 벗어나면 빌드를 실패시킨다. +- **JSON registry가 의존 방향의 SSOT이다.** 새 모듈이나 새 production 의존 edge를 추가하면 + registry와 `:app-bootstrap:architectureTest`의 관련 ArchUnit 규칙을 함께 갱신해야 한다. settings와 gate는 + 같은 registry를 읽고, 등록되지 않은 leaf나 허용되지 않은 edge를 fail-closed로 거부한다. -조립 루트가 받는 모듈의 별도 membership 검사는 없습니다. `app-bootstrap`의 `allowed_dependencies` +조립 루트가 받는 모듈의 별도 membership 검사는 없다. `app-bootstrap`의 `allowed_dependencies` 밖의 모듈은 방향 게이트가 막고, 무엇이 실제로 실리는지는 `app-bootstrap/build.gradle`의 의존성이 -정합니다. +정한다. 세 opt-in inbound transport의 test-only composition, 실제 wire 경계, positive-count/zero-skip 증거는 -다음 release-blocking aggregate로 실행합니다. +다음 release-blocking aggregate로 실행한다. ```bash ./gradlew conditionalTransportQualification @@ -113,136 +113,136 @@ archive task 자체는 timestamp 비보존·재현 가능한 file order·고정 ### 파일당 public 최상위 타입 1개 (code-conventions I6) -Checkstyle이 소유합니다 — `OneTopLevelClass`와 `OuterTypeFilename`(`config/checkstyle/checkstyle.xml`). -각 leaf의 `checkstyleMain`/`checkstyleTest`가 그 leaf의 `check`에서 돕니다. +Checkstyle이 소유한다 — `OneTopLevelClass`와 `OuterTypeFilename`(`config/checkstyle/checkstyle.xml`). +각 leaf의 `checkstyleMain`/`checkstyleTest`가 그 leaf의 `check`에서 돈다. -`verifyOneTypePerFile`이라는 루트 태스크가 있었고 삭제했습니다. `src/main/java`를 줄 단위 정규식으로 -읽었고 세 가지가 틀렸습니다: package-private 최상위 타입이 보이지 않았고(126개 main 소스가 한 번도 +`verifyOneTypePerFile`이라는 루트 태스크가 있었고 삭제했다. `src/main/java`를 줄 단위 정규식으로 +읽었고 세 가지가 틀렸다: package-private 최상위 타입이 보이지 않았고(126개 main 소스가 한 번도 매칭되지 않아, 파일 하나에 package-private 타입 다섯 개가 있어도 통과했다), `src/main/java`만 읽었고, -`^public` 앵커 때문에 블록 주석이나 텍스트 블록의 `public`으로 시작하는 줄을 선언으로 셌습니다. -Checkstyle은 파싱된 파일에 같은 질문을 하고, leaf 단위로 돕니다. +`^public` 앵커 때문에 블록 주석이나 텍스트 블록의 `public`으로 시작하는 줄을 선언으로 셌다. +Checkstyle은 파싱된 파일에 같은 질문을 하고, leaf 단위로 돈다. ### `:app-bootstrap:verifyEnvKeys` - **소유.** app-bootstrap. 이 질문("이 애플리케이션의 배포에 무엇을 줘야 하는가")은 composition - root의 것이고, `./gradlew :domain-core:check`가 알아야 할 사항이 아닙니다. 루트 집계 이름은 - `configContractCheck`이고 구현은 `build-logic`의 `ca.config-contract` plugin입니다(소유자 결정 4: + root의 것이고, `./gradlew :domain-core:check`가 알아야 할 사항이 아니다. 루트 집계 이름은 + `configContractCheck`이고 구현은 `build-logic`의 `ca.config-contract` plugin이다(소유자 결정 4: 태스크는 app-bootstrap에 유지, `build-tools` included build는 비워서 삭제). - **하는 일.** `docs/registries/env-keys.yaml`, app-bootstrap의 `application*.yml` + `config/*.yml`, capability 모듈이 싣는 `config/*.yml`·`config/module-defaults/*.yml`(기본 조립에 없어도 검사한다), - `src/.env.example`을 lock-step(서로 어긋나지 않게) 으로 유지합니다. `env-keys.yaml` 이 `APP_` 키의 SSOT 이고, drift 가 생기면 빌드를 - 실패시킵니다. + `src/.env.example`을 lock-step(서로 어긋나지 않게) 으로 유지한다. `env-keys.yaml` 이 `APP_` 키의 SSOT 이고, drift 가 생기면 빌드를 + 실패시킨다. - **막으려는 것 3가지.** (1) 필수 env 가 조용히 누락되는 것, (2) 더 이상 쓰지 않는 stale env 키가 `.env.example` 에 남는 것, (3) 실제로 쓰는 `APP_` 키가 registry 에 등록되지 않고 빠져나가는 것. - **검사 항목.** - **A.** `application.yml` 의 placeholder 중 inline default(`${VAR:default}`)가 없는 **필수** - placeholder(`${VAR}`)는 반드시 `.env.example` 에 존재해야 합니다. - - **B.** `.env.example` 의 모든 키는 shipped configuration의 어떤 `${...}` placeholder 또는 등록된 consumer가 참조해야 합니다. + placeholder(`${VAR}`)는 반드시 `.env.example` 에 존재해야 한다. + - **B.** `.env.example` 의 모든 키는 shipped configuration의 어떤 `${...}` placeholder 또는 등록된 consumer가 참조해야 한다. (아무도 안 쓰는 키는 orphan 으로 간주해 실패) - - **C.** `.env.example` 의 모든 `APP_` 키는 registry 에 `- name: <KEY>` 행이 있어야 합니다. + - **C.** `.env.example` 의 모든 `APP_` 키는 registry 에 `- name: <KEY>` 행이 있어야 한다. - **`SPRING_*` 키는 왜 registry 추적 대상이 아닌가.** `SPRING_*` 는 Spring Boot 가 정의한 native 키라 - 프로젝트가 소유한 계약이 아닙니다. 그래서 C 검사는 일부러 `APP_` prefix 로만 범위를 좁혔습니다. -- **비고.** `src/.env.example`이 커밋된 환경 계약이고 `src/.env`는 로컬 실행용 입력입니다. + 프로젝트가 소유한 계약이 아니다. 그래서 C 검사는 일부러 `APP_` prefix 로만 범위를 좁혔다. +- **비고.** `src/.env.example`이 커밋된 환경 계약이고 `src/.env`는 로컬 실행용 입력이다. ### `verifyPublicPathSnapshot` -- **하는 일.** deny-by-default public path 표면이 승인 없이 바뀌면 빌드를 실패시킵니다. -- **배경.** 이 앱은 deny-by-default 입니다. 즉 `SECURITY_PUBLIC_PATHS` 가 먹이는 명시적 `permitAll()` - 경로를 **제외한** 모든 요청은 인증을 요구합니다 +- **하는 일.** deny-by-default public path 표면이 승인 없이 바뀌면 빌드를 실패시킨다. +- **배경.** 이 앱은 deny-by-default이다. 즉 `SECURITY_PUBLIC_PATHS` 가 먹이는 명시적 `permitAll()` + 경로를 **제외한** 모든 요청은 인증을 요구한다 (`app-bootstrap/src/main/resources/config/security.yml` → `SecuritySettings.publicPaths()` → - `SecurityConfig`). 설정 분할 이전에는 이 SSOT 가 `src/.env` 였고 문서만 그대로 남아 있었습니다. - 스냅샷 플러그인이 실제로 읽는 파일은 `config/security.yml` 입니다 + `SecurityConfig`). 설정 분할 이전에는 이 SSOT 가 `src/.env` 였고 문서만 그대로 남아 있었다. + 스냅샷 플러그인이 실제로 읽는 파일은 `config/security.yml`이다 (`build-logic/.../publicpath/PublicPathSnapshotPlugin.java`). - 이 public 표면이 바뀌는 순간이 곧 보호되던 엔드포인트가 조용히 공개로 노출되는 지점입니다. - 그래서 그 표면을 snapshot 으로 떠 두고, 미승인 변경에 빌드를 실패시킵니다. -- **승인 방법.** `verifyPublicPathSnapshot` 은 항상 읽기 전용입니다. reviewer 가 변경을 승인한 뒤 + 이 public 표면이 바뀌는 순간이 곧 보호되던 엔드포인트가 조용히 공개로 노출되는 지점이다. + 그래서 그 표면을 snapshot 으로 떠 두고, 미승인 변경에 빌드를 실패시킨다. +- **승인 방법.** `verifyPublicPathSnapshot` 은 항상 읽기 전용이다. reviewer 가 변경을 승인한 뒤 `./gradlew updatePublicPathSnapshot -PapprovePublicPathChange` 로 snapshot 을 명시적으로 다시 - 생성합니다. 공개 경로 변경은 보안 리뷰 대상으로 보고 재생성된 snapshot 을 함께 커밋합니다. + 생성한다. 공개 경로 변경은 보안 리뷰 대상으로 보고 재생성된 snapshot 을 함께 커밋한다. - **결정 — 무엇을 snapshot 했나 (프로젝트 선택).** 초기안은 기동 시 - `SecurityFilterChain.getFilters()` 를 introspection 하는 방식이었습니다. 하지만 그 reflection - 은 Spring 버전마다 깨지기 쉽습니다(`permitAll` matcher 가 + `SecurityFilterChain.getFilters()` 를 introspection 하는 방식이었다. 하지만 그 reflection + 은 Spring 버전마다 깨지기 쉽다(`permitAll` matcher 가 `RequestMatcherDelegatingAuthorizationManager` 의 private 필드에 숨어 있음). 그래서 `permitAll()` - 을 실제로 먹이는 결정적 SSOT 인 `SECURITY_PUBLIC_PATHS` 자체를 snapshot 합니다. 탐지 목표(공개 경로 - 변경은 무조건 게이트를 실패시킨다)는 같고, 메커니즘은 더 견고합니다. + 을 실제로 먹이는 결정적 SSOT 인 `SECURITY_PUBLIC_PATHS` 자체를 snapshot 한다. 탐지 목표(공개 경로 + 변경은 무조건 게이트를 실패시킨다)는 같고, 메커니즘은 더 견고하다. - **snapshot 위치.** `docs/security/public-paths-snapshot.txt`. 이 파일은 커밋된 필수 보안 - baseline 입니다. CI 는 Gradle 실행 전에 파일이 비어 있지 않고 Git에 추적되는지 검사하므로 fresh - checkout 에서 누락되거나 untracked 상태면 즉시 실패합니다. 승인된 변경만 update task로 재생성한 - 뒤 보안 리뷰와 함께 커밋합니다. + baseline이다. CI 는 Gradle 실행 전에 파일이 비어 있지 않고 Git에 추적되는지 검사하므로 fresh + checkout 에서 누락되거나 untracked 상태면 즉시 실패한다. 승인된 변경만 update task로 재생성한 + 뒤 보안 리뷰와 함께 커밋한다. ### Trivy suppression과 플래키 격리 — 정책은 유지, 파서는 삭제 **Trivy suppression.** repo 루트 `.trivyignore.yaml`이 유일한 suppression 소스이고, 모든 Trivy 호출이 -`--ignorefile .trivyignore.yaml`로 명시합니다. 항목은 `id`, 비어 있지 않은 `statement`, 90일 이내의 -미래 `expired_at`을 갖춰야 합니다. 이 규칙은 그대로이고, 강제하는 주체가 `.github/CODEOWNERS` 리뷰어로 -바뀌었습니다. `verifyTrivyignore`는 105줄짜리 손으로 쓴 YAML 파서였고 — 들여쓰기 추적, 인라인 스칼라 -처리, 따옴표 제거 — 지키던 파일은 만들어진 이래 계속 비어 있었습니다. 실제 항목이 생기고 그것이 -drift하기 시작하면 그때 자동화합니다. 진짜 항목을 상대로, 진짜 YAML 라이브러리로. +`--ignorefile .trivyignore.yaml`로 명시한다. 항목은 `id`, 비어 있지 않은 `statement`, 90일 이내의 +미래 `expired_at`을 갖춰야 한다. 이 규칙은 그대로이고, 강제하는 주체가 `.github/CODEOWNERS` 리뷰어로 +바뀌었다. `verifyTrivyignore`는 105줄짜리 손으로 쓴 YAML 파서였고 — 들여쓰기 추적, 인라인 스칼라 +처리, 따옴표 제거 — 지키던 파일은 만들어진 이래 계속 비어 있었다. 실제 항목이 생기고 그것이 +drift하기 시작하면 그때 자동화한다. 진짜 항목을 상대로, 진짜 YAML 라이브러리로. -**플래키 격리.** `quarantineTest` 버킷과 CI의 비차단 `quarantine` 잡은 삭제했습니다. 격리된 -테스트가 한 번도 없었습니다. 간헐 실패 테스트는 고치거나 지웁니다. +**플래키 격리.** `quarantineTest` 버킷과 CI의 비차단 `quarantine` 잡은 삭제했다. 격리된 +테스트가 한 번도 없었다. 간헐 실패 테스트는 고치거나 지운다. `flaky-quarantine.yaml` 레지스트리와 `verifyQuarantineSunset`(14일 sunset + drift 검사)은 -삭제했습니다. 250줄짜리 YAML 파서 + Java 렉서(주석과 문자열 리터럴 안의 `@Tag("quarantine")`를 -걸러내려고 인덱스 보존 렉서를 직접 구현)로 항목이 0개인 레지스트리를 지키고 있었습니다. 순서가 -반대입니다 — 실제로 격리된 테스트가 생기고, 그게 주차장이 되기 시작할 때 도입할 정책입니다. +삭제했다. 250줄짜리 YAML 파서 + Java 렉서(주석과 문자열 리터럴 안의 `@Tag("quarantine")`를 +걸러내려고 인덱스 보존 렉서를 직접 구현)로 항목이 0개인 레지스트리를 지키고 있었다. 순서가 +반대다 — 실제로 격리된 테스트가 생기고, 그게 주차장이 되기 시작할 때 도입할 정책이다. ### CI 게이트 배선 - **소유 범위.** 이 계약은 *게이트 배선*(어떤 게이트가 CI 에서 돌고 실패 시 어떻게 릴리스를 막는가)을 - 소유합니다. 개별 scanner/tool/severity *정책* 은 owner 브랜치가 소유하며, 그 20행 매핑의 in-repo - SSOT는 Gradle task graph와 GitHub Actions job graph 그 자체입니다. + 소유한다. 개별 scanner/tool/severity *정책* 은 owner 브랜치가 소유하며, 그 20행 매핑의 in-repo + SSOT는 Gradle task graph와 GitHub Actions job graph 그 자체다. - `.github/ci-gate-matrix.yml`(1,025줄, 107개 게이트 행)과 `.github/scripts/verify-gate-matrix.sh` - (568줄)는 삭제했습니다. 그 표는 이미 두 그래프에 있는 정보의 세 번째 사본이었고, 검사기는 세 사본을 - 서로 같게 유지하는 일을 했습니다. 결과적으로 체크 하나를 추가하려면 Gradle · workflow · 표 · - 검사기 기대값 · Java 계약 테스트 다섯 곳을 같이 고쳐야 했습니다. + > 이력: 게이트 표 `.github/ci-gate-matrix.yml`(1,025줄, 107개 게이트 행)과 그 검사기 + > `.github/scripts/verify-gate-matrix.sh`(568줄)는 삭제했다. 그 표는 이미 두 그래프에 있는 정보의 + > 세 번째 사본이었고, 검사기는 세 사본을 서로 같게 유지하는 일을 했다. 결과적으로 체크 하나를 + > 추가하려면 Gradle · workflow · 표 · 검사기 기대값 · Java 계약 테스트 다섯 곳을 같이 고쳐야 했다. - **워크플로.** `.github/workflows/ci-quality-gates.yml` 의 `release-gate` 잡이 모든 release-blocking - 게이트의 fan-in(단일 required status check)입니다. included build 테스트는 경로 필터가 걸린 + 게이트의 fan-in(단일 required status check)이다. included build 테스트는 경로 필터가 걸린 `build-logic.yml`이, main 단계(`mainCheck`)·configuration-cache·JPA candidate evidence는 - `integration-main.yml`이 돌립니다. 위임 게이트(Trivy SCA/이미지 스캔)는 `dependency-vulnerability.yml` 가 소유하며, + `integration-main.yml`이 돌린다. 위임 게이트(Trivy SCA/이미지 스캔)는 `dependency-vulnerability.yml` 가 소유하며, GitHub Actions 는 워크플로 간 `needs` 를 못 쓰므로 branch protection 의 required check 합집합으로 - 묶습니다. + 묶는다. --- ## .env — 환경 변수 레퍼런스 -`spring-dotenv` 가 `src/.env` 를 읽어 외부화 설정을 주입합니다(`bootRun` 의 working dir 가 `src/` 라 -이 파일이 잡힙니다). 아래는 섹션별 키 설명입니다. 따로 표기가 없으면 `restart-only`(값 변경 시 재기동 -필요)로 간주하세요. +`spring-dotenv` 가 `src/.env` 를 읽어 외부화 설정을 주입한다(`bootRun` 의 working dir 가 `src/` 라 +이 파일이 잡힌다). 아래는 섹션별 키 설명이다. 따로 표기가 없으면 `restart-only`(값 변경 시 재기동 +필요)로 간주한다. -### App identity +### 앱 이름과 profile - **`APP_NAME`** — `spring.application.name` 과 JSON 로그의 `app` 필드. 자유 문자열. -- **`SPRING_PROFILES_ACTIVE`** — 활성 Spring profile. 보통 `local` | `dev` | `stage` | `prod`. JSON - 로그의 `profile` 필드도 이 값을 씁니다. +- **`SPRING_PROFILES_ACTIVE`** — 활성 Spring profile. `local` | `dev` | `prod` 중 정확히 하나다. JSON + 로그의 `profile` 필드도 이 값을 쓴다. -### Runtime safety (기동 시 fail-fast 검사, D8) +### 런타임 안전 검사 (기동할 때 바로 실패시킨다, D8) - **`APP_SERVER_ERROR_INCLUDE_STACKTRACE` / `APP_SERVER_ERROR_INCLUDE_MESSAGE`** — 로컬 디버깅용. - prod에서 `never`가 아니면 `ErrorDetailExposureSafetyValidator`가 기동을 막습니다(exit 71, + prod에서 `never`가 아니면 `ErrorDetailExposureSafetyValidator`가 기동을 막는다(exit 71, `spring.web.error.include-binding-errors`·`include-exception`도 같음). request logging은 body를 - 읽지 않는 계약을 검증합니다. + 읽지 않는 계약을 검증한다. - **`APP_MULTI_INSTANCE_ENABLED`** — `true` 면 cross-instance `DistributedLockPort` - (`distributedLockProvider`)가 조립돼 있어야 하며, 없으면 기동이 실패합니다(exit 72, + (`distributedLockProvider`)가 조립돼 있어야 하며, 없으면 기동이 실패한다(exit 72, `StartupSafetyValidator`). -- **`APP_RATE_LIMIT_ENABLED`** — provider-neutral edge rate-limit interceptor 활성화 +- **`APP_RATE_LIMIT_ENABLED`** — 제공자에 묶이지 않은 앞단 요청 수 제한(rate limit) interceptor를 켠다 (429 + `Retry-After` + `X-RateLimit-*` 응답). 기본값은 `false`이며, `true`로 바꿀 때는 - `APP_RATE_LIMIT_PROVIDER=redis`와 canonical coordination role을 함께 구성해야 합니다. - 비인증 요청의 키는 `getRemoteAddr()` 입니다. 프록시 뒤라면 + `APP_RATE_LIMIT_PROVIDER=redis`와 canonical coordination role을 함께 구성해야 한다. + 비인증 요청의 키는 `getRemoteAddr()`이다. 프록시 뒤라면 `APP_SERVER_FORWARD_HEADERS_STRATEGY=native` 와 `server.tomcat.remoteip.internal-proxies` 로 신뢰할 - 프록시를 지정하세요(`framework` 면 rate limit 이 기동을 거부합니다). + 프록시를 지정한다(`framework` 면 rate limit 이 기동을 거부한다). - **`APP_IDEMPOTENCY_PROVIDER`** — 요청 멱등성 store. `disabled`(기본) | `redis` | `postgresql`. `postgresql` 은 PostgreSQL data source 가 아니면 기동을 거부하므로 `bootRunH2` 에서는 - `disabled` 나 `redis` 를 씁니다. + `disabled` 나 `redis` 를 쓴다. - **`APP_IDEMPOTENCY_TTL`** — 완료 응답을 재생할 수 있는 기간(`replay-ttl`). duration(예: `24h`). - 최대 72h 이고 넘으면 기동을 거부합니다. (D6) `APP_IDEMPOTENCY_PROCESSING_LEASE`(기본 30s)보다 - 짧아도, `APP_IDEMPOTENCY_FAILURE_RETENTION`(기본 24h)보다 길어도 기동을 거부합니다. 24h보다 - 올리려면 `APP_IDEMPOTENCY_FAILURE_RETENTION`도 함께 올립니다. + 최대 72h 이고 넘으면 기동을 거부한다. (D6) `APP_IDEMPOTENCY_PROCESSING_LEASE`(기본 30s)보다 + 짧아도, `APP_IDEMPOTENCY_FAILURE_RETENTION`(기본 24h)보다 길어도 기동을 거부한다. 24h보다 + 올리려면 `APP_IDEMPOTENCY_FAILURE_RETENTION`도 함께 올린다. -### Async executor +### 비동기 executor -`@Async` `ThreadPoolTaskExecutor` 풀 크기 설정입니다. +`@Async` `ThreadPoolTaskExecutor` 풀 크기 설정이다. - **`APP_ASYNC_EXECUTOR_CORE_SIZE`** — 항상 살아있는 워커 수. 1 이상 정수. - **`APP_ASYNC_EXECUTOR_MAX_SIZE`** — 워커 수 상한. core-size 이상. @@ -252,17 +252,17 @@ drift하기 시작하면 그때 자동화합니다. 진짜 항목을 상대로, ### 기능 추가 = 한 줄 + env 기본 조립(`bootJar`)에는 web, 관측(actuator·metrics·tracing·로그), `domain-core`·`application-core`· -`shared-contract`, `adapter:outbound:support`·`adapter:outbound:identifier`만 들어 있습니다. DB·Redis· -Kafka 없이 기동합니다. 나머지 기능은 `app-bootstrap/build.gradle`에 주석 처리된 `runtimeOnly` 한 줄로 -있습니다. +`shared-contract`, `adapter:outbound:support`·`adapter:outbound:identifier`만 들어 있다. DB·Redis· +Kafka 없이 기동한다. 나머지 기능은 `app-bootstrap/build.gradle`에 주석 처리된 `runtimeOnly` 한 줄로 +있다. -- **켜기:** 그 줄의 주석을 풀고, 아래 env를 `src/.env`에 넣습니다. 모듈이 classpath에 있으면 켜집니다. -- **끄기:** 줄을 지웁니다. 모듈의 bean·설정·의존성이 함께 빠집니다. 줄은 두고 잠시 끄려면 "끄는 키"를 - `false`로 줍니다(모든 키의 기본값은 `true`). -- **줄을 바꾼 뒤:** strict lock을 갱신합니다. +- **켜기:** 그 줄의 주석을 풀고, 아래 env를 `src/.env`에 넣는다. 모듈이 classpath에 있으면 켜진다. +- **끄기:** 줄을 지운다. 모듈의 bean·설정·의존성이 함께 빠진다. 줄은 두고 잠시 끄려면 "끄는 키"를 + `false`로 준다(모든 키의 기본값은 `true`). +- **줄을 바꾼 뒤:** strict lock을 갱신한다. `./gradlew :app-bootstrap:resolveAndLockAll --write-locks` - 모든 capability를 한 번에 싣는 jar가 필요하면(compose 레인·CI) `./gradlew :app-bootstrap:qualificationBootJar`를 - 씁니다. 배포용이 아닙니다. + 쓴다. 배포용이 아니다. | capability | `build.gradle` 한 줄 | 켜진 뒤 필요한 env | 끄는 키 | |---|---|---|---| @@ -279,28 +279,28 @@ Kafka 없이 기동합니다. 나머지 기능은 `app-bootstrap/build.gradle` | 알림 (SMTP/SES, JPA 줄도 필요) | `runtimeOnly project(':composition:notification-platform')` | 키 8종과 각 `_ID`(`APP_NOTIFICATION_PLATFORM_*_KEY`, `*_KEY_ID`), 쓰는 provider 설정(`APP_NOTIFICATION_PLATFORM_SMTP_*` 또는 `_SES_*`) | `APP_NOTIFICATION_PLATFORM_ENABLED` | 전체 목록과 타입·기본값은 `docs/registries/env-keys.yaml`, 각 모듈이 제공하는 것은 그 모듈 README의 -"제공하는 것 · 추가할 한 줄 · env 키" 절에 있습니다. 기능 사이의 의존(알림·파일 서버 → JPA, outbox relay -→ JPA + Kafka)은 설정 검사가 아니라 build 줄로 맞춥니다. 표에 "JPA 줄도 필요"라고 적힌 기능은 두 줄을 -함께 넣습니다. +"제공하는 것 · 추가할 한 줄 · env 키" 절에 있다. 기능 사이의 의존(알림·파일 서버 → JPA, outbox relay +→ JPA + Kafka)은 설정 검사가 아니라 build 줄로 맞춘다. 표에 "JPA 줄도 필요"라고 적힌 기능은 두 줄을 +함께 넣는다. -어떤 자동 설정이 켜졌는지는 Spring Boot의 `conditions` endpoint로 봅니다. 기본 노출 목록에는 없으므로 -필요할 때 `management.endpoints.web.exposure.include`에 추가합니다. +어떤 자동 설정이 켜졌는지는 Spring Boot의 `conditions` endpoint로 본다. 기본 노출 목록에는 없으므로 +필요할 때 `management.endpoints.web.exposure.include`에 추가한다. 종속 선택자 둘: -- `APP_GRAPHQL_DEPLOYMENT_MODE` — GraphQL이 켜지면 **필수**이고 기본값이 없습니다. 예전의 boolean과 - enum 두 기본값이 서로 다른 말을 했기 때문에, 안전 태세는 배포가 명시적으로 고릅니다. 허용되는 값은 - 런타임 환경(`local`/`dev`/`prod`)마다 다릅니다. +- `APP_GRAPHQL_DEPLOYMENT_MODE` — GraphQL이 켜지면 **필수**이고 기본값이 없다. 예전의 boolean과 + enum 두 기본값이 서로 다른 말을 했기 때문에, 안전 태세는 배포가 명시적으로 고른다. 허용되는 값은 + 런타임 환경(`local`/`dev`/`prod`)마다 다르다. - `APP_NOTIFICATION_PLATFORM_MODE` — `SERVING`(기본) 또는 `INGEST_ONLY`. 선택 사항이고, 허용 값은 - `NotificationModeSsotTest`가 enum에서 파생합니다. + `NotificationModeSsotTest`가 enum에서 파생한다. ### Compose와 런타임 스모크 -- **Docker Compose 최소 버전 `2.24.4`.** SSOT는 `src/app-bootstrap/compose-lanes/compose-profile-contracts.json` - 이고, 정본 스크립트가 검증합니다. lane은 저장소 루트 `compose.yaml`(개발 환경)을 바탕으로 쓰고, lane에만 - 필요한 overlay·smoke client·스키마 적용은 `src/app-bootstrap/compose-lanes/`에 있습니다. -- 진입점은 둘뿐이고, 그 둘만이 증거입니다. 워크플로에 명령 일부를 인라인하면 one-shot 없이 도는 레인이 - 초록으로 보고됩니다. +- **Docker Compose 최소 버전은 `src/app-bootstrap/compose-lanes/compose-profile-contracts.json`의 + `minimumComposeVersion`이다.** 정본 스크립트가 검증한다. lane은 저장소 루트 `compose.yaml`(개발 환경)을 바탕으로 쓰고, lane에만 + 필요한 overlay·smoke client·스키마 적용은 `src/app-bootstrap/compose-lanes/`에 있다. +- 진입점은 둘뿐이고, 그 둘만이 증거다. 워크플로에 명령 일부를 인라인하면 one-shot 없이 도는 레인이 + 초록으로 보고된다. ```bash # 정적: profile별 정확한 service set, 병합된 모델 전체, mount target 유일성 @@ -311,36 +311,36 @@ Kafka 없이 기동합니다. 나머지 기능은 `app-bootstrap/build.gradle` ./scripts/run-compose-runtime-smoke.sh --matrix src/app-bootstrap/compose-lanes/compose-profile-contracts.json ``` -`--lane <id>`는 실패 재현용이고, 레인 하나가 초록인 것은 matrix가 통과했다는 증거가 아닙니다. +`--lane <id>`는 실패 재현용이고, 레인 하나가 초록인 것은 matrix가 통과했다는 증거가 아니다. -### Optional integration adapters +### 선택형 연동 adapter -Kafka·Redis는 위 "기능 추가 = 한 줄 + env" 표의 한 줄로 고릅니다. 모듈이 있으면 켜지고, 없으면 그 -포트를 구현하는 bean이 아예 없습니다. 아래는 모듈을 고른 뒤 동작을 고르는 키입니다. +Kafka·Redis는 위 "기능 추가 = 한 줄 + env" 표의 한 줄로 고른다. 모듈이 있으면 켜지고, 없으면 그 +포트를 구현하는 bean이 아예 없다. 아래는 모듈을 고른 뒤 동작을 고르는 키다. - **`APP_CACHE_REDIS_ENABLED`** — deprecated(2026-11-30 제거 예정). 읽는 곳이 없고, - 기본 조립에서 Redis를 켜고 끄는 것은 `APP_REDIS_ENABLED`입니다. -- **`APP_CACHE_CANONICAL_DEFAULT_PROVIDER`** — canonical default semantic region 선택. - `disabled`(기본) | `redis`. `redis`는 canonical Redis CACHE role binding을 함께 요구합니다. + 기본 조립에서 Redis를 켜고 끄는 것은 `APP_REDIS_ENABLED`이다. +- **`APP_CACHE_CANONICAL_DEFAULT_PROVIDER`** — 기본 캐시 영역(canonical default semantic region)의 제공자를 고른다. + `disabled`(기본) | `redis`. `redis`는 canonical Redis CACHE role binding을 함께 요구한다. - **`APP_CACHE_REDIS_CLIENT_MODE`** — `managed`는 내장 Lettuce runtime, `external`은 프로젝트가 - 제공한 `RedisClient` bean을 사용합니다. -아래 세 키는 **활성화 스위치가 아니라 선택자**입니다. 어떤 capability가 켜지는지는 위의 build 한 줄과 -끄는 키가 정하고, 이 값들은 켜진 capability가 *무엇으로* 동작할지만 고릅니다. 예전에는 "빈 값 = 비활성"으로 -설명돼 있었고, 그 문장이 남아 있는 동안 두 개의 활성화 모델이 공존했습니다. + 제공한 `RedisClient` bean을 사용한다. +아래 세 키는 **활성화 스위치가 아니라 선택자**이다. 어떤 capability가 켜지는지는 위의 build 한 줄과 +끄는 키가 정하고, 이 값들은 켜진 capability가 *무엇으로* 동작할지만 고른다. 예전에는 "빈 값 = 비활성"으로 +설명돼 있었고, 그 문장이 남아 있는 동안 두 개의 활성화 모델이 공존했다. - **`APP_MESSAGING_BROKER`** — 활성 메시지 브로커 id. Kafka 모듈의 설정 기본값이 `kafka`(등록된 유일한 - broker)라 보통 비워 두지 않습니다. 빈 값을 주면 기동이 거부되면서 이 키 이름을 지목합니다. 이 키를 비워도 메시징이 꺼지지는 - 않습니다 — 끄는 것은 `APP_MESSAGING_ENABLED=false`입니다. + broker)라 보통 비워 두지 않는다. 빈 값을 주면 기동이 거부되면서 이 키 이름을 지목한다. 이 키를 비워도 메시징이 꺼지지는 + 않는다 — 끄는 것은 `APP_MESSAGING_ENABLED=false`이다. - **`APP_MESSAGING_KAFKA_BROKERS`** — `host:port` CSV. Kafka 모듈을 고르면 필수. messaging - platform의 Kafka transport(`app.messaging.brokers.kafka.bootstrap-servers`)가 이 값을 씁니다. - `spring.kafka.bootstrap-servers`는 읽지 않습니다. -- **`APP_NOTIFICATION_SLACK_WEBHOOK_ENABLED`** — Slack webhook R0 provider enable flag. notification 플랫폼이 - 켜졌을 때 어떤 provider를 쓸지 고르는 값입니다. -- **`APP_NOTIFICATION_GOOGLE_EMAIL_ENABLED`** — Google Email R0 provider enable flag. 위와 같습니다. + platform의 Kafka transport(`app.messaging.brokers.kafka.bootstrap-servers`)가 이 값을 쓴다. + `spring.kafka.bootstrap-servers`는 읽지 않는다. +- **`APP_NOTIFICATION_SLACK_WEBHOOK_ENABLED`** — Slack webhook R0 제공자를 켜는 값. notification 플랫폼이 + 켜졌을 때 어떤 provider를 쓸지 고르는 값이다. +- **`APP_NOTIFICATION_GOOGLE_EMAIL_ENABLED`** — Google Email R0 제공자를 켜는 값. 위와 같다. -### Outbound HTTP client +### 외부 HTTP 호출 (HTTP client) -현재 canonical activation은 다음 두 설정 트리만 사용합니다. +현재 canonical activation은 다음 두 설정 트리만 사용한다. ```yaml app: @@ -353,20 +353,20 @@ app: ``` - 기본 `DISABLED`는 binding/provider definition이 모두 비어 있어야 하며 - `DISABLED_VERIFIED`만 게시하고 client, executor, pool, retry/CB registry를 만들지 않습니다. -- `ACTIVE`는 exact destination/provider/operation-catalog binding을 요구합니다. 현재 유일한 + `DISABLED_VERIFIED`만 게시하고 client, executor, pool, retry/CB registry를 만들지 않는다. +- `ACTIVE`는 exact destination/provider/operation-catalog binding을 요구한다. 현재 유일한 buffered-classic readiness card가 `NOT_IMPLEMENTED`이므로 provider resource 생성 전에 - fail-closed합니다. 아직 운영 HTTP provider를 활성화할 수 있다는 뜻이 아닙니다. -- 기존 `APP_OUTBOUND_HTTP_*`와 `app.outbound.http.*`는 canonical 설정이 아닙니다. 루트 `src/.env`, + fail-closed한다. 아직 운영 HTTP provider를 활성화할 수 있다는 뜻이 아니다. +- 기존 `APP_OUTBOUND_HTTP_*`와 `app.outbound.http.*`는 canonical 설정이 아니다. 루트 `src/.env`, `app-bootstrap`의 application YAML, env-key registry에서 제거됐으며 canonical composition에 - 입력하면 상태와 무관하게 기동을 거부합니다. -- 그 키를 시연하던 샘플 모듈의 YAML은 2026-11-07 샘플과 함께 지웠습니다. 이제 저장소 어디에도 남아 있지 않습니다. + 입력하면 상태와 무관하게 기동을 거부한다. +- 그 키를 시연하던 샘플 모듈의 YAML은 2026-11-07 샘플과 함께 지웠다. 이제 저장소 어디에도 남아 있지 않다. - legacy JDK facade가 필요한 fork만 canonical composition 밖에서 - `OutboundHttpSettings.bindLegacy(Binder)`와 legacy configuration을 명시적으로 import합니다. + `OutboundHttpSettings.bindLegacy(Binder)`와 legacy configuration을 명시적으로 import한다. timeout/retry/CB/response-size 설정은 그 migration API 내부 계약일 뿐 canonical provider - readiness를 증명하지 않습니다. + readiness를 증명하지 않는다. -### Logging +### 로그 **Root / app 레벨** — 허용값은 모두 `TRACE` | `DEBUG` | `INFO` | `WARN` | `ERROR` | `OFF`. @@ -376,11 +376,11 @@ app: **패키지별 레벨**(root 를 덮어씀) — 동일 허용값. - **`APP_LOG_LEVEL_SPRING`** / **`APP_LOG_LEVEL_WEB`** — 각 패키지 레벨. -- **`APP_LOG_LEVEL_SQL`** — `DEBUG` 로 두면 JPA/jdbc 연결 후 SQL 문이 출력됩니다. +- **`APP_LOG_LEVEL_SQL`** — `DEBUG` 로 두면 JPA/jdbc 연결 후 SQL 문이 출력된다. **파일 출력 + rolling** -- **`APP_LOG_FILE_ENABLED`** — `true` 면 rolling JSON 파일 appender 를 붙입니다. +- **`APP_LOG_FILE_ENABLED`** — `true` 면 rolling JSON 파일 appender 를 붙인다. - **`APP_LOG_FILE_PATH`** — `bootRun` working dir(`src/`) 기준 상대 경로 또는 절대 경로. - **`APP_LOG_FILE_MAX_SIZE`** — 파일 1개 최대 크기(단위 `KB` | `MB` | `GB`). - **`APP_LOG_FILE_MAX_HISTORY`** — 보관할 rolled archive 개수. 1 이상 정수. @@ -391,14 +391,14 @@ app: - **`APP_LOG_ASYNC_ENABLED`** — `true` 면 appender 를 `AsyncAppender` 로 감싸 non-blocking I/O. - **`APP_LOG_ASYNC_QUEUE_SIZE`** — back-pressure 전 in-memory 큐 깊이. 1 이상 정수. - **`APP_LOG_ASYNC_DISCARDING_THRESHOLD`** — 남은 큐 용량이 이 값 미만이면 `TRACE`/`DEBUG`/`INFO` - 이벤트를 버립니다(`WARN`/`ERROR` 는 항상 유지). `0` = 절대 버리지 않음. 0 이상 정수. + 이벤트를 버린다(`WARN`/`ERROR` 는 항상 유지). `0` = 절대 버리지 않음. 0 이상 정수. **JSON 인코더 세부** - **`APP_LOG_JSON_TIMEZONE`** — IANA timezone(예: `UTC`, `Asia/Seoul`) 또는 `default`(JVM 기본). - **`APP_LOG_JSON_TIMESTAMP_PATTERN`** — 타임스탬프 패턴. 보통 ISO 8601 (`yyyy-MM-dd'T'HH:mm:ss.SSSXXX`). -- **`APP_LOG_JSON_INCLUDE_CALLER_DATA`** — `true` 면 file/method/line 을 추가. **성능 비용이 큽니다.** +- **`APP_LOG_JSON_INCLUDE_CALLER_DATA`** — `true` 면 file/method/line 을 추가. **성능 비용이 크다.** - **`APP_LOG_JSON_LOGGER_NAME_LENGTH`** — `0` = 로거 이름 전체, 양수 = 패키지 축약(예: `36` → `dev.caskeleton.bootstrap.Foo` 가 `d.c.bootstrap.Foo` 로). @@ -407,63 +407,63 @@ app: - **`APP_LOG_SAMPLING_RATE`** — `INFO` 이하 로그를 남길 확률. [0.0, 1.0] float. prod 는 `0.1`(10% 샘플링)이 권장, `WARN`/`ERROR` 는 항상 유지. `1.0` = 샘플링 없음(dev/local/staging 기본). -### Distributed tracing +### 분산 추적 - **`OTEL_EXPORTER_OTLP_ENDPOINT`** — OTLP exporter endpoint. 빈 값 = exporter off(스켈레톤에서 OTel - SEAM 미활성). 값이 있으면 유효한 URL 이어야 하며 기동 시 `TracingProperties` 가 검증합니다. + SEAM 미활성). 값이 있으면 유효한 URL 이어야 하며 기동 시 `TracingProperties` 가 검증한다. - **`APP_TRACING_ENABLED`** — `false` 면 tracing seam 은 꺼지지만, `meta.traceId` 는 - `WebMvcRequestIdFilter` 가 W3C `traceparent` 로 여전히 생성합니다(D4 disabled-fallback 보장). + `WebMvcRequestIdFilter` 가 W3C `traceparent` 로 여전히 생성한다(D4 disabled-fallback 보장). - **`APP_TRACING_SAMPLE_RATE`** — per-profile 기본값을 덮어쓰는 샘플 비율. [0.0, 1.0] float. - - per-profile 기본값(D6): prod = `0.01`, staging = `0.10`, dev/local = `1.0`. + - profile별 기본값(D6): prod = `0.01`, dev/local = `1.0`. - **결정 — 빈 값으로 두는 이유(D-1 ISSUE-1 fix).** 빈 값이어야 per-profile resolver 의 기본값이 - 실제 tracer sampler 까지 도달합니다(`TracingSampleRateResolver` 가 SSOT). 값을 박으면 프로필별 - 기본값이 무시되므로, 특정 비율을 강제하고 싶을 때만 채웁니다. + 실제 tracer sampler 까지 도달한다(`TracingSampleRateResolver` 가 SSOT). 값을 박으면 프로필별 + 기본값이 무시되므로, 특정 비율을 강제하고 싶을 때만 채운다. -### Privacy: user_principal pseudonymization +### 개인정보: user_principal 가명화 - **`APP_PRIVACY_PSEUDONYMIZATION_SALT`** — secret 등급 HMAC-SHA-256 salt. `__LOCAL_DEV_` prefix 는 로컬 전용 sentinel 값이며, - **prod 에서는 secret-manager 가 주입하는 실제 값**을 써야 합니다. + **prod 에서는 secret-manager 가 주입하는 실제 값**을 써야 한다. -### Spring Boot bootstrap +### Spring Boot 기동 - **`SPRING_BANNER_MODE`** — `off` | `console` | `log`. - **`SPRING_MAIN_LAZY_INITIALIZATION`** — `true` 면 빈 생성을 첫 사용 시점까지 지연. - **`SPRING_MAIN_LOG_STARTUP_INFO`** — `true` 면 `Starting`/`Started` 로그 출력. - **`SPRING_THREADS_VIRTUAL_ENABLED`** — `true` 면 Tomcat 요청 처리에 Java 21 virtual threads 사용. -### Jackson — deserialization policy +### Jackson — 역직렬화 정책 -모든 request DTO 는 Jackson 경계를 지납니다. 아래 4개 스위치는 잘못된 입력을 **조용히 강제 변환하지 -않고 즉시 실패**하게 만듭니다. 개별 DTO 에 클래스 레벨 `@JsonIgnoreProperties(ignoreUnknown = true)` -로 이 정책을 완화하는 것은 **금지**이며 ArchUnit 규칙으로 막혀 있습니다. +모든 request DTO 는 Jackson 경계를 지난다. 아래 4개 스위치는 잘못된 입력을 **조용히 강제 변환하지 +않고 즉시 실패**하게 만든다. 개별 DTO 에 클래스 레벨 `@JsonIgnoreProperties(ignoreUnknown = true)` +로 이 정책을 완화하는 것은 **금지**이며 ArchUnit 규칙으로 막혀 있다. - **`..._FAIL_ON_UNKNOWN_PROPERTIES`** — `true`: 타입에 선언되지 않은 JSON 키를 거부(Jackson 2.13+ 기본). - **`..._FAIL_ON_NULL_FOR_PRIMITIVES`** — `true`: primitive 필드에 JSON `null` 이 와도 `0`/`false` 로 강제 변환하지 않고 "필수 필드 누락" 에러로 노출. 또는 wrapper 타입(`Integer`/`Long`/`Boolean`) - 과 `Optional<T>` 를 쓰세요. + 과 `Optional<T>` 를 쓴다. - **`..._FAIL_ON_IGNORED_PROPERTIES`** — `true`: JSON 에 `@JsonIgnore` 처리된 필드가 들어오면 throw (조용히 버리는 대신 계약 drift 를 노출). - **`..._READ_UNKNOWN_ENUM_VALUES_AS_NULL`** — `false`(Jackson 기본 유지): 모르는 enum 값이 조용히 - `null` 이 되지 않고 throw 되어 `VALIDATION_FAILED` 로 드러나게 합니다. + `null` 이 되지 않고 throw 되어 `VALIDATION_FAILED` 로 드러나게 한다. -### Jackson — serialization policy +### Jackson — 직렬화 정책 -응답 생성 쪽 정책입니다. 현재 Jackson/Spring Boot 기본값과 같지만 **명시적으로 못박아**, 미래에 Spring -Boot 기본값이 바뀌어도 wire 계약이 조용히 깨지지 않게 합니다(`spring.mvc.problemdetails.enabled=false` +응답 생성 쪽 정책이다. 현재 Jackson/Spring Boot 기본값과 같지만 **명시적으로 못박아**, 미래에 Spring +Boot 기본값이 바뀌어도 wire 계약이 조용히 깨지지 않게 한다(`spring.mvc.problemdetails.enabled=false` 와 같은 근거). `JacksonSerializationPolicyTest` 가 강제하며, `new BigDecimal(double)` 생성자는 -`no_bigdecimal_double_constructor` ArchUnit 규칙으로 금지됩니다. +`no_bigdecimal_double_constructor` ArchUnit 규칙으로 금지된다. - **`..._WRITE_DATES_AS_TIMESTAMPS`** — `false`(D2 / RFC 3339): `java.time` 값을 ISO-8601 문자열로 직렬화(`OffsetDateTime` → `"...Z"`, `LocalDate` → `"YYYY-MM-DD"`). `true` 면 epoch 숫자나 - `[y,m,d,...]` 배열로 나가 datetime 계약이 깨집니다. -- **BigDecimal plain output** — Jackson 3에는 별도 `WRITE_BIGDECIMAL_AS_PLAIN` 설정 키가 없습니다. + `[y,m,d,...]` 배열로 나가 datetime 계약이 깨진다. +- **BigDecimal plain output** — Jackson 3에는 별도 `WRITE_BIGDECIMAL_AS_PLAIN` 설정 키가 없다. `JacksonSerializationPolicyTest` 가 `"12300000000.00"` plain 출력을 직접 검증하고, `no_bigdecimal_double_constructor` ArchUnit 규칙이 부정확한 `new BigDecimal(double)` 생성을 - 금지합니다. 엔드포인트별 string vs number 선택은 그대로 명시적으로 둡니다(공개/금융 API 는 string, + 금지한다. 엔드포인트별 string vs number 선택은 그대로 명시적으로 둔다(공개/금융 API 는 string, 내부 API 는 number+plain). -### Server / Tomcat +### 서버 / Tomcat - **`APP_SERVER_PORT`** — 1~65535 정수. - **`APP_SERVER_SHUTDOWN`** — `graceful` | `immediate`. @@ -482,20 +482,20 @@ Boot 기본값이 바뀌어도 wire 계약이 조용히 깨지지 않게 합니 - **`APP_SERVER_ERROR_INCLUDE_STACKTRACE`** — `always` | `never` | `on_param`. - **`APP_SERVER_ERROR_INCLUDE_MESSAGE`** — `always` | `never` | `on_param`. -### Presentation +### 표현 계층 (presentation) - **`PRESENTATION_API_BASE_PATH`** — 모든 controller 앞에 붙는 leading-slash 경로(예: `/api` | `/v1` | `""`). -### Auth (OIDC resource server) +### 인증 (OIDC resource server) - **`APP_SECURITY_JWT_ISSUER`** — OIDC issuer URI(Keycloak realm, Auth0 tenant 등). **필수** — 없으면 기동 실패. 예: `https://keycloak.example.com/realms/ca-skeleton`. - **`APP_SECURITY_JWT_AUDIENCE`** — 기대하는 `aud` claim(쉼표 목록 가능, 하나라도 맞으면 통과). JWT 모드에서 **필수** — 비어 있으면 기동 실패. 이 목록의 client 에 대한 `resource_access` role 만 - 권한으로 읽습니다. 예: `ca-skeleton-api`. -- **`SECURITY_PUBLIC_PATHS`** — 인증을 우회하는 경로 CSV. `api-base-path` 뒤의 full path 를 씁니다(예: - `/api/healthcheck`). 이 값의 변경은 `verifyPublicPathSnapshot` 게이트가 감시합니다(위 build.gradle + 권한으로 읽는다. 예: `ca-skeleton-api`. +- **`SECURITY_PUBLIC_PATHS`** — 인증을 우회하는 경로 CSV. `api-base-path` 뒤의 full path 를 쓴다(예: + `/api/healthcheck`). 이 값의 변경은 `verifyPublicPathSnapshot` 게이트가 감시한다(위 build.gradle 설명 참조). ### CORS @@ -512,7 +512,7 @@ Boot 기본값이 바뀌어도 wire 계약이 조용히 깨지지 않게 합니 ### 프로파일과 데이터베이스 프로파일마다 데이터스토어가 다르고, 그 차이는 `app-bootstrap/src/main/resources/application-*.yml` -가 소유합니다. +가 소유한다. | 프로파일 | 데이터스토어 | 스키마 소유자 | 외부 인프라 | | --- | --- | --- | --- | @@ -521,45 +521,45 @@ Boot 기본값이 바뀌어도 wire 계약이 조용히 깨지지 않게 합니 | `prod` | PostgreSQL | Flyway `db/migration/postgresql` | 필요 | | `bootRunH2` (명시적 opt-out) | H2 in-memory | Hibernate `ddl-auto: create-drop` | 없음 | -`./gradlew :app-bootstrap:bootRun` 은 기본 `local` 프로파일에서도 PostgreSQL/Flyway를 사용합니다. +`./gradlew :app-bootstrap:bootRun` 은 기본 `local` 프로파일에서도 PostgreSQL/Flyway를 사용한다. 로컬과 운영의 schema owner를 다르게 두면 migration-only 결함을 개발 중에 놓치기 때문에 바뀐 -계약입니다. 먼저 아래 Compose PostgreSQL을 띄운 뒤 `bootRun`을 실행하세요. +계약이다. 먼저 아래 Compose PostgreSQL을 띄운 뒤 `bootRun`을 실행한다. Docker 없이 빠르게 wiring·요청/응답·애플리케이션 로직만 확인하려면 -`./gradlew :app-bootstrap:bootRunH2`를 명시적으로 사용합니다. 이 태스크만 +`./gradlew :app-bootstrap:bootRunH2`를 명시적으로 사용한다. 이 태스크만 `APP_PERSISTENCE_VENDOR=h2`, `APP_FLYWAY_ENABLED=false`, -`APP_DATASOURCE_DDL_AUTO=create-drop`을 주입합니다. H2에는 PostgreSQL migration tree가 없으므로 -migration/vendor 계약의 증거로 사용하지 않습니다. 멱등성 provider(`APP_IDEMPOTENCY_PROVIDER`)는 -`disabled`(기본)나 `redis`로 둡니다. `postgresql`은 H2 data source에서 기동을 거부합니다. +`APP_DATASOURCE_DDL_AUTO=create-drop`을 주입한다. H2에는 PostgreSQL migration tree가 없으므로 +migration/vendor 계약의 증거로 사용하지 않는다. 멱등성 provider(`APP_IDEMPOTENCY_PROVIDER`)는 +`disabled`(기본)나 `redis`로 둔다. `postgresql`은 H2 data source에서 기동을 거부한다. -`dev` 를 호스트에서 띄우려면(`SPRING_PROFILES_ACTIVE=dev`) PostgreSQL 이 필요합니다. +`dev` 를 호스트에서 띄우려면(`SPRING_PROFILES_ACTIVE=dev`) PostgreSQL 이 필요하다. `compose.yaml` 의 `db` 서비스(`jpa` profile)가 루프백(`127.0.0.1:5433`)에만 게시하며, 이 주소가 -아래 `APP_DATASOURCE_URL` 의 커밋된 기본값입니다. 저장소 루트에서 실행합니다. +아래 `APP_DATASOURCE_URL` 의 커밋된 기본값이다. 저장소 루트에서 실행한다. ```bash docker compose up -d --wait db ``` -컨테이너로 띄우는 `scripts/bootstrap-local.sh` 경로는 이 호스트 포트를 쓰지 않습니다. compose 가 app -컨테이너의 `APP_DATASOURCE_URL` 을 내부 네트워크 주소 `jdbc:postgresql://db:5432/...` 로 덮어씁니다. +컨테이너로 띄우는 `scripts/bootstrap-local.sh` 경로는 이 호스트 포트를 쓰지 않는다. compose 가 app +컨테이너의 `APP_DATASOURCE_URL` 을 내부 네트워크 주소 `jdbc:postgresql://db:5432/...` 로 덮어쓴다. `app.persistence.vendor`(`postgresql` | `h2`)가 어느 vendor 구성을 조립할지 고르는 단일 -스위치입니다. 값이 둘 중 하나가 아니면 기동이 실패하고, prod 에서 `h2` 이거나 datasource URL 이 -`jdbc:h2:` 이면 `PersistenceVendorProdSafetyValidator` 가 기동을 거부합니다(env 로 덮어써도 동일). +스위치다. 값이 둘 중 하나가 아니면 기동이 실패하고, prod 에서 `h2` 이거나 datasource URL 이 +`jdbc:h2:` 이면 `PersistenceVendorProdSafetyValidator` 가 기동을 거부한다(env 로 덮어써도 동일). -### Database (Postgres) +### 데이터베이스 (PostgreSQL) - **`APP_DATASOURCE_URL`** — JDBC URL(예: `jdbc:postgresql://host:5432/dbname`). `dev`·`prod` 에서 쓰이며, 커밋된 기본값 `jdbc:postgresql://localhost:5433/ca_skeleton` 은 위 compose `db` 서비스의 - 호스트 주소입니다. + 호스트 주소다. - **`APP_DATASOURCE_USERNAME`** / **`APP_DATASOURCE_PASSWORD`** — DB 접속 계정. - **`APP_DATASOURCE_DRIVER`** — Hibernate dialect 에 맞는 드라이버(예: `org.postgresql.Driver`). - **`APP_DATASOURCE_DDL_AUTO`** — `none` | `validate` | `update` | `create` | `create-drop`. **prod 는 `validate` 또는 `none`**(`JpaDangerousConfigurationGuard` 가 기동 시 강제). `local` 은 이 값을 쓰지 - 않습니다 — `application-local.yml` 이 `create-drop` 으로 고정합니다. + 않는다 — `application-local.yml` 이 `create-drop` 으로 고정한다. - **`APP_DATASOURCE_SHOW_SQL`** — `true` 면 SQL 을 로그로 echo. - **`APP_DATASOURCE_FORMAT_SQL`** — SQL pretty-print(`SHOW_SQL=true` 일 때만 의미 있음). -- **`APP_DATASOURCE_OPEN_IN_VIEW`** — Hibernate OSIV. **prod 에서는 피하세요.** +- **`APP_DATASOURCE_OPEN_IN_VIEW`** — Hibernate OSIV. **prod 에서는 피한다.** **HikariCP 커넥션 풀** @@ -568,10 +568,10 @@ docker compose up -d --wait db - **`APP_DATASOURCE_CONNECTION_TIMEOUT`** — `acquire()` 가 실패하기 전 대기 시간(ms). - **`APP_DATASOURCE_POOL_IDLE_TIMEOUT`** — idle 연결 회수 임계 시간(ms). - **`APP_DATASOURCE_POOL_MAX_LIFETIME`** — 연결의 최대 수명(ms). broker timeout 전에 rotate 하도록 - 설정합니다. + 설정한다. -### Management / Actuator +### 관리 포트 / Actuator - **결정 — management 포트 분리.** actuator 엔드포인트를 앱 API 와 **같은 소켓에 노출하지 않으려고** - 별도 management 포트를 둡니다. -- **`MANAGEMENT_SERVER_PORT`** — 1~65535 정수. **`APP_SERVER_PORT`(8080)와 달라야 합니다.** + 별도 management 포트를 둔다. +- **`MANAGEMENT_SERVER_PORT`** — 1~65535 정수. **`APP_SERVER_PORT`(8080)와 달라야 한다.** diff --git a/src/adapter/inbound/graphql/CLAUDE.md b/src/adapter/inbound/graphql/CLAUDE.md index 89dd89bf..bec9db91 100644 --- a/src/adapter/inbound/graphql/CLAUDE.md +++ b/src/adapter/inbound/graphql/CLAUDE.md @@ -1,12 +1,12 @@ -# adapter:inbound:graphql — inbound GraphQL adapter (skeleton machinery) +# adapter:inbound:graphql — inbound GraphQL 어댑터(골격 장치) -## Registered identity +## 등록 정보 -- Module ID: `adapter-inbound-graphql` -- Gradle path: `:adapter:inbound:graphql` -- Focused test (derived from Gradle path): `./gradlew :adapter:inbound:graphql:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-inbound-graphql` +- Gradle 경로: `:adapter:inbound:graphql` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:inbound:graphql:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. Package root: `dev.caskeleton.adapter.inbound.graphql`. @@ -46,7 +46,7 @@ sub-package 사이의 경계(Stable↔Advanced 방향, 모듈 레코드)를 값 두 규칙 모두 위반 fixture 로 실제로 잡히는지 같은 테스트가 확인한다. `graphqlStableTest` 의 required-class 검사가 이 테스트가 조용히 사라지는 것을 막는다. -## Responsibility +## 책임 - GraphQL 전송 인프라만: 최소 health 스키마(`skeleton.graphqls`) + `HealthGraphqlController`, 프로토콜 에러 매핑(`error/GraphQlWireErrorMapper`). Spring for GraphQL 이 스키마와 컨트롤러를 @@ -62,28 +62,26 @@ required-class 검사가 이 테스트가 조용히 사라지는 것을 막는 실제 활성화 시 composition root 는 인증/인가·CORS 정책과 GraphiQL/introspection 운영 설정을 함께 명시해야 한다. -## Error-code ownership +## 오류 코드 소유 -`docs/registries/error-codes.yaml` is the skeleton-wide `OperationalError` SSOT; it is not a -catch-all registry for transport-specific presentation codes. GraphQL therefore keeps its own finite -platform wire-code catalogue in `GraphQlErrorCode`. +`docs/registries/error-codes.yaml`은 골격 전체의 `OperationalError` 정본이다. 전송 계층마다 다른 표현 +코드를 모두 받는 registry가 아니다. 그래서 GraphQL은 자기의 유한한 플랫폼 wire 코드 catalog를 +`GraphQlErrorCode`에 둔다. -- GraphQL platform mappers must use `GraphQlErrorCode.platform(...)`. An unregistered platform code - fails immediately. -- application/domain `ApiErrorCode` values remain a separate namespace and pass through with - `GraphQlErrorCode.of(...)`; GraphQL must not rename product errors. Only a registered - `ApiErrorCode` reaches the wire this way — a DataLoader per-key failure carries one, never a free - string (owner decision 2026-09-25). -- new GraphQL-owned platform codes use the `GRAPHQL_` prefix. The existing unprefixed platform - values are frozen legacy wire contracts and are listed explicitly by - `legacyUnprefixedPlatformCodes()`. -- modelled-only capability codes are not added to `platformCodes()` until that capability reaches - the shipped request path. +- GraphQL 플랫폼 mapper는 `GraphQlErrorCode.platform(...)`을 써야 한다. 등록되지 않은 플랫폼 코드는 바로 + 실패한다. +- application·domain `ApiErrorCode` 값은 별도 namespace로 남고 `GraphQlErrorCode.of(...)`로 그대로 지나간다. + GraphQL은 제품 오류의 이름을 바꾸면 안 된다. 이 길로 wire에 닿는 것은 등록된 `ApiErrorCode`뿐이다 — + DataLoader의 키별 실패도 그것을 싣고, 자유 문자열을 싣지 않는다(소유자 결정 2026-09-25). +- GraphQL이 가진 새 플랫폼 코드는 `GRAPHQL_` 접두어를 쓴다. 접두어 없는 기존 플랫폼 값은 얼려 둔 옛 wire + 계약이고 `legacyUnprefixedPlatformCodes()`가 하나씩 적는다. +- 모델만 있는 capability 코드는 그 capability가 출하하는 요청 경로에 닿기 전까지 `platformCodes()`에 + 더하지 않는다. -`GraphQlErrorCodeCatalogTest` pins the exact shipped catalogue, the prefix rule and the -application/platform namespace split. +`GraphQlErrorCodeCatalogTest`가 출하하는 catalog 전체, 접두어 규칙, application·플랫폼 namespace 분리를 +고정한다. -## Allowed +## 허용 - `:application-core`, `:domain-core`, `:shared-contract`. `:application-core` 는 선언만이 아니라 실제 의존이다 — object 인가의 **답하는 계약**(`dev.caskeleton.application.security.ObjectAccessPolicy`)이 @@ -107,7 +105,7 @@ application/platform namespace split. `@ConfigurationProperties` 이므로 `ca.spring-config` convention plugin이 주는 패리티 게이트가 이 선언을 요구한다. -## Forbidden +## 금지 - outbound 어댑터(`:adapter:outbound:*`)에 대한 직접 의존 — 인바운드는 application 아웃바운드 포트를 통해서만 persistence/messaging/cache/http 에 닿는다 (ArchUnit @@ -117,7 +115,7 @@ application/platform namespace split. `HealthcheckController` 와 동일 원칙). feature 스키마/컨트롤러/매퍼는 그 기능을 가진 서비스가 소유한다. - 모듈별 `yml` — 설정은 프레임워크 `spring.graphql.*` 로 composition-root `application.yml` 에 산다. -## Error mapping (`Category → ErrorType`) +## 오류 대응 (`Category → ErrorType`) 모든 client 에러는 `error/GraphQlWireErrorMapper` 하나를 거친다 — 전송 interceptor, 실행 전 pipeline(instrumentation), data fetcher resolver 세 곳이 같은 bean 을 받는다. 순서는 플랫폼 거부 @@ -181,7 +179,7 @@ health 스키마만 소유한다. (`docs/capability-status.md` 제거 표). 다시 필요하면 Spring GraphQL/graphql-java SPI 를 구현하는 형태로 새로 만든다. -## Test +## 테스트 ```bash cd src diff --git a/src/adapter/inbound/graphql/README.md b/src/adapter/inbound/graphql/README.md index ff9c7c63..98e59e89 100644 --- a/src/adapter/inbound/graphql/README.md +++ b/src/adapter/inbound/graphql/README.md @@ -176,15 +176,15 @@ composition root 는 이 leaf 를 채택할 때 인증/인가 및 CORS 정책을 ## 설계서의 "모듈"을 Gradle 모듈로 만들지 않은 이유 -설계서는 Stable 16 + Advanced 12 = 28개 Gradle 모듈을 전제한다. 구현 시점의 레지스트리 -(`src/config/architecture/modules.json`)는 19개 leaf 였고, 28개를 추가하는 것은 레지스트리· +설계서는 Stable 16 + Advanced 12 = 28개 Gradle 모듈을 전제한다. 그 28개를 구현 시점의 레지스트리 +(`src/config/architecture/modules.json`)에 추가하는 것은 레지스트리· `settings.gradle` fail-closed 검증·의존 게이트를 동시에 건드리는 변경이다. GraphQL 표면은 하나의 인바운드 전송 경계이므로 그 **내부** 분할을 레포 전역 SSOT 까지 밀어올리지 않기로 하고, **모듈 = bounded sub-package** 로 매핑했다(선례: httpclient leaf 가 366개 java 파일을 같은 방식으로 담는다). **정직하게 기록해 둘 반례:** 이후 main 에 통합된 자매 플랫폼 messaging 은 정반대로 -**24개 leaf 를 레지스트리에 등록**했다(현재 총 43개 leaf). 즉 레지스트리는 닫혀 있지 않았고, +**자기 leaf 를 레지스트리에 하나씩 등록**했다(지금의 leaf 목록과 수는 레지스트리가 정한다). 즉 레지스트리는 닫혀 있지 않았고, "확장하면 게이트가 깨진다"는 전제는 과했다. 두 플랫폼이 서로 다른 패턴을 쓰고 있으므로 **어느 쪽으로 통일할지는 미결 아키텍처 결정**이다. diff --git a/src/adapter/inbound/grpc/CLAUDE.md b/src/adapter/inbound/grpc/CLAUDE.md index 5c4dff1a..9b4ef61f 100644 --- a/src/adapter/inbound/grpc/CLAUDE.md +++ b/src/adapter/inbound/grpc/CLAUDE.md @@ -1,19 +1,19 @@ -# adapter:inbound:grpc — inbound gRPC adapter (skeleton machinery) +# adapter:inbound:grpc — inbound gRPC 어댑터(골격 장치) -## Registered identity +## 등록 정보 -- Module ID: `adapter-inbound-grpc` -- Gradle path: `:adapter:inbound:grpc` -- Focused test (derived from Gradle path): `./gradlew :adapter:inbound:grpc:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-inbound-grpc` +- Gradle 경로: `:adapter:inbound:grpc` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:inbound:grpc:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. Package root: `dev.caskeleton.adapter.inbound.grpc`. 코드 주석에서 덜어낸 **설계 결정의 근거**는 [README.md](README.md) 가 모아둔다 (이 문서는 모듈 규칙 SSOT). -## Responsibility +## 책임 - gRPC 전송 인프라만: 서버 수명주기(`GrpcServerRunner`), 타입드 설정(`GrpcServerSettings`), feature 인증 정책 경계, 프로토콜 에러 매핑(`GrpcStatusMapper` + @@ -22,13 +22,13 @@ Package root: `dev.caskeleton.adapter.inbound.grpc`. - feature-agnostic: 모든 `io.grpc.BindableService` 빈을 generic 하게 등록하며 구체 기능을 이름으로 알지 않는다. -## Allowed +## 허용 - `:application-core`, `:domain-core`, `:shared-contract`. - `io.grpc:*` (grpc-netty-shaded / grpc-protobuf / grpc-stub / grpc-services), `spring-boot-starter`, `spring-boot-starter-validation`. -## Forbidden +## 금지 - outbound 어댑터(`:adapter:outbound:*`)에 대한 직접 의존 — 인바운드는 application 아웃바운드 포트를 통해서만 persistence/messaging/cache/http 에 닿는다 (ArchUnit @@ -38,7 +38,7 @@ Package root: `dev.caskeleton.adapter.inbound.grpc`. - 프로덕션 feature RPC 를 스켈레톤에 두는 것 — health/reflection 표면만 (web 의 `HealthcheckController` 와 동일 원칙). -## Config knobs (`app.grpc.server.*`) +## 설정 손잡이 (`app.grpc.server.*`) 타입드 `@ConfigurationProperties` 만 두고, 값은 composition-root `application.yml` 에 산다 (모듈별 `yml` 없음). prefix가 `app.grpc`가 아니라 `.server`까지인 이유: 바인딩이 @@ -69,24 +69,22 @@ Package root: `dev.caskeleton.adapter.inbound.grpc`. `enabled=true`는 `allowInsecureLocal=true`와 실제 loopback `bindAddress`가 함께 없으면 configuration binding/startup 단계에서 실패한다. -## Adopting this capability +## 이 capability 채택하기 -gRPC is also a **build-composition opt-in**. The default bootJar does not contain this leaf. +gRPC도 **빌드 조립에서 고르는 것**이다. 기본 bootJar에는 이 leaf가 없다. -1. Add `:adapter:inbound:grpc` to the consuming composition and add the corresponding allowed - dependency edge in `config/architecture/modules.json`. -2. Register settings through the capability root; do not add - `dev.caskeleton.adapter.inbound.grpc` to the shipped `@ConfigurationPropertiesScan`. -3. Provide any feature `BindableService` plus exactly one `GrpcAuthenticationPolicy`. -4. Run `./gradlew :adapter:inbound:grpc:test :conditionalTransportQualification` before promotion. -5. Production adoption is incomplete until composition-owned configuration/env registry entries - exist for the selected runtime contract. +1. 쓰는 조립에 `:adapter:inbound:grpc`를 더하고 `config/architecture/modules.json`에 맞는 허용 의존 + edge를 더한다. +2. 설정은 capability 루트로 등록한다. 출하하는 `@ConfigurationPropertiesScan`에 + `dev.caskeleton.adapter.inbound.grpc`를 더하지 않는다. +3. 기능의 `BindableService`와 정확히 하나의 `GrpcAuthenticationPolicy`를 준다. +4. 승격 전에 `./gradlew :adapter:inbound:grpc:test :conditionalTransportQualification`을 돌린다. +5. 고른 런타임 계약에 대한 조립 소유의 설정·env registry 항목이 생기기 전에는 운영 채택이 끝난 것이 아니다. -**Current transport limit:** the P1 server is plaintext and deliberately permits only loopback -binding. It is therefore suitable for local-process or same-Pod sidecar communication only. It -cannot bind `0.0.0.0` for a normal Kubernetes Service, cannot accept cross-Pod traffic, and must -not be presented as a cluster-facing gRPC endpoint. Cluster exposure requires the deferred TLS/mTLS -credential path and a separately qualified non-loopback bind. +**지금 전송의 한계:** P1 서버는 평문이고 일부러 loopback bind만 허용한다. 그래서 같은 프로세스나 같은 +Pod sidecar 통신에만 맞다. 보통 Kubernetes Service를 위해 `0.0.0.0`에 bind할 수 없고, 다른 Pod의 트래픽을 +받을 수 없으며, 클러스터를 향한 gRPC endpoint로 내세우면 안 된다. 클러스터에 노출하려면 미뤄 둔 TLS/mTLS +credential 경로와 따로 검증한 loopback 아닌 bind가 필요하다. ## Feature 기여 방법 @@ -109,7 +107,7 @@ listener 시작이 실패한다. 정책은 `Optional<Principal> authenticate(Met 이 증거는 local insecure unary qualification일 뿐 production-ready 근거가 아니다. TLS/mTLS, external bind, 메서드별 deadline, streaming/backpressure, generated protobuf 호환성은 P2로 남아 있다. -## Test +## 테스트 ```bash cd src diff --git a/src/adapter/inbound/messaging/CLAUDE.md b/src/adapter/inbound/messaging/CLAUDE.md index 11d9c1a2..e1637a6e 100644 --- a/src/adapter/inbound/messaging/CLAUDE.md +++ b/src/adapter/inbound/messaging/CLAUDE.md @@ -1,25 +1,23 @@ # adapter:inbound:messaging -- Module ID `adapter-inbound-messaging`, Gradle path `:adapter:inbound:messaging`. Registry SSOT: +- 모듈 ID `adapter-inbound-messaging`, Gradle 경로 `:adapter:inbound:messaging`. registry 정본: `src/config/architecture/modules.json`. -- Responsibility: the application's consume side of the vendored messaging platform — the inbox - parts the platform needs from the application (`JdbcInboxRepository` over the application - DataSource, a `TransactionRunner` over its `PlatformTransactionManager`, the inbox migration as - its own Flyway stream `MessagingInboxSchemaStream`) and the application's `MessageHandler` - implementations, each turning a delivery into one use case call. A handler registers nothing - else: the platform decodes what its `destination()` and `schemaVersions()` declare. -- Boundaries: no business rule in a handler (HARD-STOP 4); no persistence entity or repository; no - broker SDK type. Allowed edges come only from the registry entry. -- A handler that calls a write use case is `@SystemCaller(reason = ...)` and constructs the - `@SystemInvoked` use case itself; the use case is never a bean, and no user transport calls the - handler (manual 09 「소비」 step 4, manual 07 「시스템이 부르는 쓰기」, +- 책임: 들여온 메시징 플랫폼의 애플리케이션 소비 쪽이다 — 플랫폼이 애플리케이션에서 받아야 하는 + inbox 부품(애플리케이션 DataSource 위의 `JdbcInboxRepository`, 그 `PlatformTransactionManager` 위의 + `TransactionRunner`, 자기 Flyway stream `MessagingInboxSchemaStream`인 inbox migration)과 애플리케이션의 + `MessageHandler` 구현들이다. 핸들러 하나는 전달 하나를 유스케이스 호출 하나로 바꾼다. 핸들러는 그 밖에 + 아무것도 등록하지 않는다: 플랫폼이 그 `destination()`과 `schemaVersions()`가 선언한 것을 decode한다. +- 경계: 핸들러에 업무 규칙을 두지 않는다(HARD-STOP 4). 영속 엔티티나 repository가 없다. broker SDK 타입이 + 없다. 허용 edge는 registry 항목에서만 온다. +- 쓰기 유스케이스를 부르는 핸들러는 `@SystemCaller(reason = ...)`이고 `@SystemInvoked` 유스케이스를 직접 + 만든다. 유스케이스는 bean이 아니고, 사용자 전송 계층은 핸들러를 부르지 않는다 + (`docs/manual/09-outbox-events.md` 「소비 — 이벤트를 받는 쪽」 순서 4단계, + `docs/manual/07-authorization.md` 「시스템이 부르는 쓰기」, `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`, - `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`). The handler implements only project types - (`MessageHandler<T>`), never `Runnable` or another type outside the project - (`SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`). -- Tests: focused auto-configuration and inbox behavior tests; `./gradlew :adapter:inbound:messaging:check`. - The real Kafka + PostgreSQL redelivery lane is `messagingInboxRedeliveryIntegrationTest` - (`:integrationCheck`). -- Coordinates: group `dev.caskeleton.adapter.inbound`, jar `adapter-inbound-messaging`. Do not drop them — - with the default group this project and `:adapter:outbound:messaging` are one module to Gradle. -- Design and rejected alternatives: `README.md`. + `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`). 핸들러는 프로젝트 타입(`MessageHandler<T>`)만 구현하고, + `Runnable`이나 프로젝트 밖의 다른 타입은 구현하지 않는다(`SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`). +- 시험: 자동 구성과 inbox 동작을 보는 시험. `./gradlew :adapter:inbound:messaging:check`. + 실제 Kafka + PostgreSQL 재전달 lane은 `messagingInboxRedeliveryIntegrationTest`다(`:integrationCheck`). +- 좌표: group `dev.caskeleton.adapter.inbound`, jar `adapter-inbound-messaging`. 지우지 않는다 — 기본 + group이면 Gradle에게 이 프로젝트와 `:adapter:outbound:messaging`은 같은 모듈이 된다. +- 설계와 버린 대안: `README.md`. diff --git a/src/adapter/inbound/web-advanced/CLAUDE.md b/src/adapter/inbound/web-advanced/CLAUDE.md index 18d3212d..1f11e209 100644 --- a/src/adapter/inbound/web-advanced/CLAUDE.md +++ b/src/adapter/inbound/web-advanced/CLAUDE.md @@ -1,46 +1,42 @@ -# adapter:inbound:web-advanced — opt-in web library +# adapter:inbound:web-advanced — 골라 쓰는 web 라이브러리 -## Registered identity +## 등록 정보 -- Module ID: `adapter-inbound-web-advanced` -- Gradle path: `:adapter:inbound:web-advanced` -- Focused test (derived from Gradle path): `./gradlew :adapter:inbound:web-advanced:test --console=plain` -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-inbound-web-advanced` +- Gradle 경로: `:adapter:inbound:web-advanced` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:inbound:web-advanced:test --console=plain` +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.inbound.web.advanced`. What it provides, the one line a -service adds and the settings are in [README.md](README.md). +패키지 루트: `dev.caskeleton.adapter.inbound.web.advanced`. 무엇을 주는지, 서비스가 더하는 한 줄, +설정은 [README.md](README.md)에 있다. -## Responsibility +## 책임 -- Web library code that the servlet production path does not reach: streaming, virtual-thread - admission, JSON Patch / Merge Patch, CBOR/XML codecs, OpenAPI 3.2 generator and breaking-change - policy, URI/method policy, versioning, operation/budget/contract catalogs, security-context - bridge, idempotent response codec, route inventory. -- The three switched MVC capabilities (virtual threads, NDJSON, JSON sequence), each an - `@AutoConfiguration` listed in this leaf's `AutoConfiguration.imports` and off by default. +- servlet 운영 경로가 닿지 않는 web 라이브러리 코드: streaming, virtual thread admission, JSON Patch / + Merge Patch, CBOR·XML codec, OpenAPI 3.2 생성기와 breaking change 정책, URI·method 정책, versioning, + operation·budget·contract catalog, security context bridge, 멱등 응답 codec, route 목록. +- 스위치가 있는 MVC capability 셋(virtual thread, NDJSON, JSON sequence). 각각 이 leaf의 + `AutoConfiguration.imports`에 적힌 `@AutoConfiguration`이고 기본은 꺼져 있다. -## Rules +## 규칙 -- Not in any default composition. `app-bootstrap` main은 이 leaf에 의존하지 않는다; - `app-bootstrap` takes it `testRuntimeOnly` so the whole-repository ArchUnit import reads it. -- It depends on `adapter:inbound:web` (the `core` vocabulary), never the reverse. -- No component-scannable stereotype. A consuming application may scan the adapter packages - (서비스가 `dev.caskeleton.adapter.inbound.web`을 scan할 수 있다), so a - `@Configuration`/`@Component` here would be created whatever its switch says. Switched wiring is - `@AutoConfiguration` + an imports line; imported helpers carry no stereotype - (`MvcStreamingSupportConfiguration`). -- No setting that no code reads, no gate or evidence type in `main` that only tests call — the - release gate and OpenAPI promotion report were removed for exactly that - (`docs/capability-status.md`). -- One generation per feature. Nothing here may re-implement what the production web path already - does another way: forwarded headers (`server.forward-headers-strategy`), CORS/CSRF - (`CorsSettings`/`SecurityConfig`), cache headers (`CacheControlFilter`), the JSON mapper (Boot's - `JsonMapper`), OpenAPI customization (`OpenApiContractConfig`). Those duplicates and the WebFlux - `functional` package were removed on 2026-09-25 (`docs/capability-status.md`). -- Inbound adapter rules from `adapter:inbound:web` apply: no repository access, no business rules, - no DTO leaking into `application-core`/`domain-core`. +- 어떤 기본 조립에도 없다. `app-bootstrap` main은 이 leaf에 의존하지 않는다. + `app-bootstrap`은 저장소 전체 ArchUnit import가 이 leaf를 읽도록 `testRuntimeOnly`로만 받는다. +- `adapter:inbound:web`(`core` 어휘)에 의존하고, 그 반대는 없다. +- component scan에 걸리는 stereotype이 없다. 쓰는 애플리케이션은 어댑터 패키지를 scan할 수 있다 + (서비스가 `dev.caskeleton.adapter.inbound.web`을 scan할 수 있다). 그래서 여기 둔 `@Configuration`이나 + `@Component`는 스위치가 무엇을 말하든 만들어진다. 스위치가 있는 배선은 `@AutoConfiguration` + imports + 한 줄이다. import되는 도우미는 stereotype을 달지 않는다(`MvcStreamingSupportConfiguration`). +- 아무 코드도 읽지 않는 설정, 시험만 부르는 `main`의 gate·증거 타입을 두지 않는다 — 릴리스 gate와 + OpenAPI 승격 보고서를 바로 그 이유로 지웠다(`docs/capability-status.md`). +- 기능마다 세대 하나. 운영 web 경로가 이미 다른 방식으로 하는 일을 여기서 다시 구현하지 않는다: + forwarded header(`server.forward-headers-strategy`), CORS·CSRF(`CorsSettings`/`SecurityConfig`), cache + header(`CacheControlFilter`), JSON mapper(Boot의 `JsonMapper`), OpenAPI 손질(`OpenApiContractConfig`). + 그 중복과 WebFlux `functional` 패키지는 2026-09-25에 지웠다(`docs/capability-status.md`). +- `adapter:inbound:web`의 inbound 어댑터 규칙이 그대로 적용된다: repository 접근 없음, 업무 규칙 없음, + `application-core`·`domain-core`로 새는 DTO 없음. -## Test +## 테스트 ```bash cd src diff --git a/src/adapter/inbound/web/CLAUDE.md b/src/adapter/inbound/web/CLAUDE.md index 35c66ca8..b31212eb 100644 --- a/src/adapter/inbound/web/CLAUDE.md +++ b/src/adapter/inbound/web/CLAUDE.md @@ -1,213 +1,170 @@ -# adapter:inbound:web — inbound HTTP adapter +# adapter:inbound:web — inbound HTTP 어댑터 -## Registered identity +## 등록 정보 -- Module ID: `adapter-inbound-web` -- Gradle path: `:adapter:inbound:web` -- Focused test (derived from Gradle path): `./gradlew :adapter:inbound:web:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-inbound-web` +- Gradle 경로: `:adapter:inbound:web` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:inbound:web:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.inbound.web`. +패키지 루트: `dev.caskeleton.adapter.inbound.web`. 코드 주석에서 덜어낸 **설계 결정의 근거**는 [README.md](README.md) 가 모아둔다 (이 문서는 모듈 규칙 SSOT). -## Responsibility +## 책임 -- HTTP controllers. -- Request/response DTOs. -- Request DTO to application command mapping. -- Authentication, validation, error mapping, filters, and web/security settings. -- Sanitized request correlation context exposed through application-owned `CorrelationIdPort`. -- Transport-owned OpenAPI customization that keeps `ApiError.details` as `type: object` without - leaking Swagger dependencies into `shared-contract`. +- HTTP controller. +- 요청·응답 DTO. +- 요청 DTO를 application command로 바꾸기. +- 인증, 검증, 오류 대응, filter, web·보안 설정. +- 애플리케이션이 가진 `CorrelationIdPort`로 내놓는, 걸러 낸 요청 correlation 문맥. +- `shared-contract`로 Swagger 의존을 새게 하지 않으면서 `ApiError.details`를 `type: object`로 두는, + 전송 계층이 가진 OpenAPI 손질. -Every service ships this leaf, so it holds only what the servlet production path reaches: its -`AutoConfiguration.imports` roots (`WebAdapterAutoConfiguration` imports the envelope, filters, -health and rate-limit beans; `WebSecurityAutoConfiguration` imports the JWT chain, so an application -with its own posture excludes only that root; `WebMethodSecurityAutoConfiguration` imports method -security and the permission port and stays when the chain is replaced; nobody scans -this leaf), and the types -`app-bootstrap`, `web-fileserver` and `composition:fileserver-platform` name — -plus their transitive references. Library code that no production path reaches (streaming, virtual -threads, patch, codecs, OpenAPI 3.2, URI/method policy, versioning, operation, budget, contract, -security-context bridge, `JsonIdempotentResponseCodec`, route inventory) lives in the opt-in leaf -`adapter:inbound:web-advanced`. A new type that nothing on the -production path uses belongs there, not here. This leaf never depends on it (Gradle registry + -ArchUnit `WEB-ARCH-ADV`). +모든 서비스가 이 leaf를 싣는다. 그래서 servlet 운영 경로가 닿는 것만 담는다: 그 `AutoConfiguration.imports` +루트(`WebAdapterAutoConfiguration`은 envelope, filter, health, rate-limit bean을 import한다. +`WebSecurityAutoConfiguration`은 JWT chain을 import하므로, 자기 보안 방식을 가진 애플리케이션은 그 루트만 +뺀다. `WebMethodSecurityAutoConfiguration`은 method security와 권한 포트를 import하고 chain을 바꿔도 남는다. +이 leaf를 scan하는 쪽은 없다), 그리고 `app-bootstrap`, `web-fileserver`, `composition:fileserver-platform`이 +이름을 대는 타입과 그것이 전이로 참조하는 것. 운영 경로가 닿지 않는 라이브러리 코드(streaming, virtual +thread, patch, codec, OpenAPI 3.2, URI·method 정책, versioning, operation, budget, contract, security context +bridge, `JsonIdempotentResponseCodec`, route 목록)는 골라 쓰는 leaf `adapter:inbound:web-advanced`에 있다. +운영 경로에서 아무도 쓰지 않는 새 타입은 여기가 아니라 거기에 둔다. 이 leaf는 그 leaf에 의존하지 않는다 +(Gradle registry + ArchUnit `WEB-ARCH-ADV`). -## Allowed +## 허용 - `:application-core` - `:domain-core` - `:shared-contract` -- `:adapter:outbound:support` — `StrictSettingsBinder` only. `app.security` (`SecuritySettings`, the - authentication mode included) is bound by the one strict binder every module uses (since - 2026-11-01); the ArchUnit inbound/outbound rules allow that class and nothing else from the - leaf. -- Spring Web/Security/Validation dependencies. +- `:adapter:outbound:support` — `StrictSettingsBinder`만. `app.security`(`SecuritySettings`, 인증 모드 포함)는 + 모든 모듈이 쓰는 엄격한 binder 하나로 바인딩한다(2026-11-01부터). ArchUnit inbound·outbound 규칙은 그 + leaf에서 이 클래스만 허용한다. +- Spring Web·Security·Validation 의존성. -## Forbidden +## 금지 -- Direct dependency on `adapter-persistence` or any other `adapter-outbound` type. -- Direct repository or JPA entity access from controllers. -- Core business rules in controller, filter, config, mapper, or settings code. -- DTO leakage into application or domain. +- `adapter:outbound:persistence-jpa`나 다른 `adapter:outbound:*` 타입에 직접 의존하기. +- controller에서 repository나 JPA 엔티티에 직접 접근하기. +- controller, filter, config, mapper, settings 코드 안의 핵심 업무 규칙. +- DTO가 application이나 domain으로 새는 것. -## Boundary validation & mapper contract +## 경계 검증과 mapper 계약 -`feature-boundary-validation-mapping-contract` (design record) fixes the -behaviour at this layer's boundaries. The repo-level guardrails (ArchUnit + -Jackson config + handler) only catch the static violations — the contract below -also drives the runtime patterns reference implementations must follow. +`feature-boundary-validation-mapping-contract`(설계 기록)가 이 계층 경계의 동작을 정한다. 저장소 단위 +가드레일(ArchUnit + Jackson 설정 + handler)은 정적 위반만 잡는다. 아래 계약은 참조 구현이 따라야 할 런타임 +패턴도 정한다. -- **B1 — Jackson policy at the request boundary.** `spring.jackson.deserialization` - pins `fail-on-unknown-properties`, `fail-on-null-for-primitives`, - `fail-on-ignored-properties` to `true` and `read-unknown-enum-values-as-null` - to `false`. Do NOT undo this per-DTO with class-level - `@JsonIgnoreProperties(ignoreUnknown = true)` — ArchUnit rule - `request_dtos_do_not_silence_unknown_fields` blocks it. Use wrapper types - (`Integer`, `Long`, `Boolean`, `Optional<T>`) in request records so JSON - `null` cannot become primitive `0`. -- **B2 — PATCH semantics.** Do not adopt RFC 7396 `application/merge-patch+json` - (`null = deletion`). PATCH endpoints must distinguish *absent* (no change), - *explicit null* (clear field), and *value* (replace). Use - `org.openapitools:jackson-databind-nullable` (`JsonNullable<T>`) or - `Optional<T>` wrappers on request records. -- **B3 — Mapper-internal failures.** Map record canonical-constructor - `IllegalArgumentException`, MapStruct generated NPE, ACL normalization - failures, etc. by throwing `MappingException`; the global handler routes it to `MAPPING_FAILED` (HTTP 400), - never to `BAD_PARAMETER` or `INTERNAL_ERROR`. Plain `IllegalArgumentException` - remains `BAD_PARAMETER` for non-mapper callers. -- **B4 — Validation layering.** Class-level Bean Validation constraints belong - to the *syntax* layer (request DTO). Domain invariants belong to - `application-core` / `domain-core`. Use `@GroupSequence(...)` to short-circuit - invariant evaluation when syntax fails. Keep `@Valid` cascade depth ≤ 3. -- **B5 — Polymorphic deserialization.** Calling - `ObjectMapper.enableDefaultTyping()` / `activateDefaultTyping()` or - referencing `LaissezFaireSubTypeValidator` is the CVE-2019-14379 RCE entry - point and is blocked by ArchUnit (`no_jackson_laissez_faire_subtype_validator`, - `no_jackson_enable_default_typing_call`). Sealed `Command` types must use - `@JsonTypeInfo(use = NAME)` + `@JsonSubTypes`, or a - `BasicPolymorphicTypeValidator` allowlist. -- **B6 — Virtual thread context propagation.** With - `spring.threads.virtual.enabled=true`, do not use `InheritableThreadLocal` - (ArchUnit rule `no_inheritable_thread_local`). Filters and interceptors must - propagate `requestId` / `traceId` via SLF4J 2.0+ MDC or - `RequestContextHolder`. -- **B7 — Outbound ACL mapper scope.** Outbound HTTP / messaging adapter - responses must pass through an ACL mapper (normalization, masking, public - field selection) before reaching `application-core` or `domain-core` — the - same boundary contract as inbound. Raw external response types must not leak - into `domain-core`. -- **B8 — Bulk endpoint partial success.** Envelope `success = true` only when - every item succeeded. Partial failure responds with `success = false` + - `error.code = BATCH_PARTIAL_FAILURE` + `error.details[]` (per-item array) — - a different shape from the single-item endpoint. Document the shape divergence - in the OpenAPI spec. +- **B1 — 요청 경계의 Jackson 정책.** `spring.jackson.deserialization`이 `fail-on-unknown-properties`, + `fail-on-null-for-primitives`, `fail-on-ignored-properties`를 `true`로, `read-unknown-enum-values-as-null`을 + `false`로 고정한다. 클래스 수준 `@JsonIgnoreProperties(ignoreUnknown = true)`로 DTO마다 이것을 되돌리지 + **않는다** — ArchUnit 규칙 `REQUEST_DTOS_DO_NOT_SILENCE_UNKNOWN_FIELDS`가 막는다. 요청 record에는 + wrapper 타입(`Integer`, `Long`, `Boolean`, `Optional<T>`)을 써서 JSON `null`이 primitive `0`이 되지 못하게 + 한다. +- **B2 — PATCH 뜻.** RFC 7396 `application/merge-patch+json`(`null = 삭제`)을 쓰지 않는다. PATCH endpoint는 + *없음*(바꾸지 않음), *명시한 null*(필드 비움), *값*(바꿈)을 구별해야 한다. 요청 record에 + `org.openapitools:jackson-databind-nullable`(`JsonNullable<T>`)이나 `Optional<T>` wrapper를 쓴다. +- **B3 — mapper 안의 실패.** record 정규 생성자의 `IllegalArgumentException`, MapStruct가 생성한 NPE, ACL + 정규화 실패 등은 `MappingException`을 던져 대응시킨다. 전역 handler가 그것을 `MAPPING_FAILED`(HTTP 400)로 + 보내고, `BAD_PARAMETER`나 `INTERNAL_ERROR`로 보내지 않는다. mapper가 아닌 호출자의 평범한 + `IllegalArgumentException`은 계속 `BAD_PARAMETER`다. +- **B4 — 검증 층.** 클래스 수준 Bean Validation 제약은 *문법* 층(요청 DTO)에 속한다. 도메인 불변식은 + `application-core` / `domain-core`에 속한다. 문법이 실패하면 `@GroupSequence(...)`로 불변식 평가를 건너뛴다. + `@Valid` cascade 깊이는 3 이하로 둔다. +- **B5 — 다형 역직렬화.** `ObjectMapper.enableDefaultTyping()` / `activateDefaultTyping()`을 부르거나 + `LaissezFaireSubTypeValidator`를 참조하는 것은 CVE-2019-14379 RCE의 입구이고 ArchUnit이 막는다 + (`NO_JACKSON_LAISSEZ_FAIRE_SUBTYPE_VALIDATOR`, `NO_JACKSON_ENABLE_DEFAULT_TYPING_CALL`). sealed `Command` + 타입은 `@JsonTypeInfo(use = NAME)` + `@JsonSubTypes`나 `BasicPolymorphicTypeValidator` 허용 목록을 쓴다. +- **B6 — virtual thread 문맥 전파.** `spring.threads.virtual.enabled=true`이면 `InheritableThreadLocal`을 쓰지 + 않는다(ArchUnit 규칙 `NO_INHERITABLE_THREAD_LOCAL`). filter와 interceptor는 SLF4J 2.0+ MDC나 + `RequestContextHolder`로 `requestId` / `traceId`를 전파한다. +- **B7 — outbound ACL mapper 범위.** outbound HTTP·메시징 어댑터의 응답은 `application-core`나 `domain-core`에 + 닿기 전에 ACL mapper(정규화, 가리기, 공개 필드 고르기)를 거친다 — inbound와 같은 경계 계약이다. 외부 응답 + 원본 타입은 `domain-core`로 새면 안 된다. +- **B8 — bulk endpoint의 부분 성공.** envelope `success = true`는 모든 항목이 성공했을 때뿐이다. 일부가 + 실패하면 `success = false` + `error.code = BATCH_PARTIAL_FAILURE` + `error.details[]`(항목별 배열)로 + 답한다 — 단일 항목 endpoint와 모양이 다르다. 모양이 다르다는 것을 OpenAPI spec에 적는다. -Domain `@RestControllerAdvice` in a consuming module must be annotated -`@Order(Ordered.HIGHEST_PRECEDENCE)` (or otherwise ordered ahead of this -module's base `GlobalExceptionHandler`), because the base handler's catch-all -`@ExceptionHandler(Exception.class)` would otherwise resolve domain exceptions -to `INTERNAL_ERROR`. +이 모듈을 쓰는 모듈의 도메인 `@RestControllerAdvice`에는 `@Order(Ordered.HIGHEST_PRECEDENCE)`를 단다(또는 +다른 방법으로 이 모듈의 기본 `GlobalExceptionHandler`보다 앞에 둔다). 그렇지 않으면 기본 handler의 +catch-all `@ExceptionHandler(Exception.class)`가 도메인 예외를 `INTERNAL_ERROR`로 만든다. -The base operational handler (`error/GlobalExceptionHandler`), the error-code -contract (`dev.caskeleton.shared.error.ApiErrorCode` + `OperationalError`), the -`error/ErrorResponseFactory`, and the `envelope/EnvelopeBodyAdvice` now live in -production modules (`adapter:inbound:web` / `shared-contract`), so the running application -provides them. 기능 전용 예외 handler와 오류 코드는 그 기능을 가진 모듈에 둔다(`docs/manual/06-errors.md`). +기본 운영 handler(`error/GlobalExceptionHandler`), 오류 코드 계약 +(`dev.caskeleton.shared.error.ApiErrorCode` + `OperationalError`), `error/ErrorResponseFactory`, +`envelope/EnvelopeBodyAdvice`는 이제 운영 모듈(`adapter:inbound:web` / `shared-contract`)에 있어서, 돌아가는 +애플리케이션이 그것을 준다. 기능 전용 예외 handler와 오류 코드는 그 기능을 가진 모듈에 둔다(`docs/manual/06-errors.md`). -## Schema / serialization contract +## schema·직렬화 계약 -`feature-schema-serialization-contract` (design record) fixes the -*response producer* side of the wire contract — the sibling of the B1 *request -consumer* policy above. The deserialization switches (B1) and the -null/empty/missing 3-state (`Patch<T>` + `JsonNullable`, B2) already cover the -inbound side; the rules below cover the outbound side. The Jackson properties -live in `app-bootstrap` (`application.yml` `spring.jackson.serialization.*` / -`spring.jackson.generator.*`); ArchUnit + effective-config tests live in -`app-bootstrap` (`JacksonSerializationPolicyTest`, `no_bigdecimal_double_constructor`). +`feature-schema-serialization-contract`(설계 기록)가 wire 계약의 *응답을 만드는* 쪽을 정한다 — 위 B1 +*요청을 받는* 정책의 짝이다. 역직렬화 스위치(B1)와 null·빈 값·없음 세 상태(`Patch<T>` + `JsonNullable`, +B2)가 이미 inbound 쪽을 덮고, 아래 규칙이 outbound 쪽을 덮는다. Jackson 속성은 `app-bootstrap`의 +`application.yml`(`spring.jackson.deserialization.*`, `spring.jackson.datatype.*`)에 있다. ArchUnit과 실제 +설정 시험도 `app-bootstrap`에 있다(`JacksonSerializationPolicyTest`, `NO_BIGDECIMAL_DOUBLE_CONSTRUCTOR`). -- **S1 — Date / time / timezone.** `WRITE_DATES_AS_TIMESTAMPS=false` is - pinned, so `java.time` values serialize as ISO-8601 strings via `JavaTimeModule` - (`OffsetDateTime` → `"...Z"`, `LocalDate` → `"YYYY-MM-DD"`), never a numeric - epoch or `[y,m,d,...]` array. Server timezone is **UTC**: emit instants as - `OffsetDateTime`/`Instant` with a `Z` offset. Use `LocalDate` only for - date-only calendar fields. Do **not** put timezone-less `LocalDateTime` on a - response DTO — it serializes without an offset and breaks the contract. -- **S2 — Money / BigDecimal.** Default scale 2, rounding `HALF_UP` unless - the domain documents otherwise (KRW/JPY = scale 0 with a schema note). - `WRITE_BIGDECIMAL_AS_PLAIN=true` is pinned so values never serialize in - scientific notation. Pick **one** JSON representation per API and state it in - the OpenAPI schema: **string** (`@JsonSerialize(using = ToStringSerializer.class)`) - for public / financial endpoints (client parses, no precision loss), or - **number + plain** for internal service-to-service endpoints. Never rely on - the default — decide at endpoint design time. -- **S3 — `new BigDecimal(double)` is banned.** The `double`/`float` constructors - capture binary floating-point error (`new BigDecimal(0.1)` ≠ `0.1`). Build from - a `String` (`new BigDecimal("0.1")`) or `BigDecimal.valueOf(double)`. Enforced - by the `no_bigdecimal_double_constructor` ArchUnit rule. -- **S4 — Enum / null·empty·missing.** Request-side unknown enum → - `VALIDATION_FAILED` (B1 `read-unknown-enum-values-as-null=false`); legacy values - map through an explicit adapter, never a silent fallback. The - absent / explicit-null / value distinction is owned by the inbound web mapper - (Controller DTO → Command), expressed with `Patch<T>` (B2); `domain-core` and - `application-core` receive the already-resolved 3-state, never a wire type. -- **S5 — Out of this branch's scope.** OpenAPI drift enforcement is owned by - the verification suite / api-contract-baseline; removed-field-reuse ban tooling - (`x-removed-fields` vs markdown catalog) is `needs-confirmation`; Avro - Schema Registry for outbox/event and response field rename/versioning - (`feature-api-compatibility-deprecation-contract`) are separate branches. +- **S1 — 날짜·시간·시간대.** `WRITE_DATES_AS_TIMESTAMPS=false`로 고정하므로 `java.time` 값은 + `JavaTimeModule`을 거쳐 ISO-8601 문자열로 직렬화한다(`OffsetDateTime` → `"...Z"`, `LocalDate` → + `"YYYY-MM-DD"`). 숫자 epoch나 `[y,m,d,...]` 배열이 되지 않는다. 서버 시간대는 **UTC**다: 시각은 `Z` + offset을 가진 `OffsetDateTime`/`Instant`로 낸다. 날짜만 있는 달력 필드에만 `LocalDate`를 쓴다. 시간대 + 없는 `LocalDateTime`을 응답 DTO에 넣지 **않는다** — offset 없이 직렬화되어 계약을 깬다. +- **S2 — 돈·BigDecimal.** 도메인이 따로 적지 않으면 기본 scale 2, 반올림 `HALF_UP`이다(KRW/JPY는 scale 0과 + schema 메모). 값은 지수 표기로 직렬화되지 않는다 — 설정 키로 고정하지 않고 `JacksonSerializationPolicyTest`가 + 큰 값과 끝자리 0을 단언한다. API마다 JSON 표현을 **하나** 고르고 OpenAPI schema에 적는다: 공개·금융 + endpoint는 **string**(`@JsonSerialize(using = ToStringSerializer.class)`. 클라이언트가 파싱하고 정밀도를 + 잃지 않는다), 내부 서비스 사이 endpoint는 **number + plain**. 기본값에 기대지 않는다 — endpoint를 설계할 + 때 정한다. +- **S3 — `new BigDecimal(double)`은 금지다.** `double`/`float` 생성자는 이진 부동소수점 오차를 담는다 + (`new BigDecimal(0.1)` ≠ `0.1`). `String`(`new BigDecimal("0.1")`)이나 `BigDecimal.valueOf(double)`로 + 만든다. ArchUnit 규칙 `NO_BIGDECIMAL_DOUBLE_CONSTRUCTOR`가 강제한다. +- **S4 — enum과 null·빈 값·없음.** 요청 쪽의 모르는 enum → `VALIDATION_FAILED`(B1 + `read-unknown-enum-values-as-null=false`). 옛 값은 명시한 어댑터로 대응시키고 소리 없는 대체값을 쓰지 + 않는다. 없음·명시한 null·값의 구별은 inbound web mapper(Controller DTO → Command)가 가지고 `Patch<T>`(B2)로 + 나타낸다. `domain-core`와 `application-core`는 이미 풀린 세 상태를 받고 wire 타입은 받지 않는다. +- **S5 — 이 브랜치의 범위 밖.** OpenAPI drift 강제는 검증 suite / api-contract-baseline의 몫이다. 지운 + 필드 재사용 금지 도구(`x-removed-fields` 대 markdown catalog)는 `needs-confirmation`이다. outbox·event용 + Avro Schema Registry와 응답 필드 이름 바꾸기·versioning(`feature-api-compatibility-deprecation-contract`)은 + 다른 브랜치다. -## Business rule validation contract +## 업무 규칙 검증 계약 -`feature-business-rule-validation-contract` (design record) fixes **which -rule is validated at which boundary**, so "validation" does not collapse into the -controller DTO or a DB constraint. It sits on top of the boundary/mapping contract -above and is enforced by ArchUnit + contract tests (not new runtime mechanism). +`feature-business-rule-validation-contract`(설계 기록)는 **어떤 규칙을 어느 경계에서 검증하는지** 정해서, +「검증」이 controller DTO나 DB 제약 하나로 뭉개지지 않게 한다. 위 경계·대응 계약 위에 놓이고, ArchUnit과 +계약 시험이 강제한다(새 런타임 장치가 아니다). -| Layer | Owner | Validates | `error.category` | Enforced by | +| 층 | 소유 | 검증하는 것 | `error.category` | 강제하는 곳 | |---|---|---|---|---| -| syntax / shape | `adapter:inbound:web` request DTO (`@Valid` / `jakarta.validation`) | request shape, types, required fields | `VALIDATION` | `validation_constraints_stay_at_web_boundary` ArchUnit rule | -| use case policy | `application-core` | authorization, cross-aggregate policy, state preconditions | `AUTHZ` / `CONFLICT` | `BusinessRuleValidationContractTest` | -| domain invariant | `domain-core` model / value object **constructor** | business invariants (e.g. end ≥ start) | `CONFLICT` / `VALIDATION` | domain unit tests (e.g. `PeriodTest`) — constructor is the sole, immutable construction path | -| persistence integrity | `adapter-persistence` (translator owned by `feature-persistence-failure-baseline`) | unique / FK / check / serialization | `DATA_INTEGRITY` / `CONFLICT` | `BusinessRuleValidationContractTest` + leak test | +| 문법·모양 | `adapter:inbound:web` 요청 DTO(`@Valid` / `jakarta.validation`) | 요청 모양, 타입, 필수 필드 | `VALIDATION` | ArchUnit 규칙 `VALIDATION_CONSTRAINTS_STAY_AT_WEB_BOUNDARY` | +| 유스케이스 정책 | `application-core` | 인가, aggregate를 가로지르는 정책, 상태 전제 조건 | `AUTHZ` / `CONFLICT` | `BusinessRuleValidationContractTest` | +| 도메인 불변식 | `domain-core` 모델·값 객체 **생성자** | 업무 불변식(예: end ≥ start) | `CONFLICT` / `VALIDATION` | 도메인 단위 시험(예: `PeriodTest`) — 생성자가 유일하고 바뀌지 않는 생성 경로다 | +| 영속 무결성 | `adapter:outbound:persistence-jpa`(번역기는 `feature-persistence-failure-baseline`의 것) | unique / FK / check / serialization | `DATA_INTEGRITY` / `CONFLICT` | `BusinessRuleValidationContractTest` + 누출 시험 | -- **C1 — Validation annotations stay at the web boundary.** `jakarta.validation` - (`@NotNull`, `@Valid`, …) must appear only in `adapter:inbound:web`. `domain-core` and - `application-core` express invariants and policy as plain Java. The - `validation_constraints_stay_at_web_boundary` ArchUnit rule fails the build if a - Bean Validation annotation leaks into `..domain..` or `..application..`. -- **C2 — Business invariants live in the domain, un-bypassable.** Enforce invariants - in the value-object / entity **constructor** (the sole construction path) and keep - the type immutable, so no application-service or persistence path can hand out an - invariant-violating instance. A DB constraint is a backstop, never the only check - (Forbidden: "DB constraint as only invariant"). -- **C3 / C7 — Persistence integrity maps to an operational error, leak-free.** A - unique/FK/check/serialization failure maps to `DATA_INTEGRITY` / `CONFLICT` with a - **client-safe message only**. The raw SQL, constraint/index name, SQLState code, - exception class, and stack frame must never reach `error.message` or - `error.details`. The base `GlobalExceptionHandler` catch-all already replaces the - message with the opaque shared message (`ClientErrorMessages.OPAQUE`) and emits `null` details; the - category-correct mapping (23505 → `CONFLICT/DB_UNIQUE_VIOLATION`, …) is owned by - `feature-persistence-failure-baseline`'s persistence-adapter translator. -- **C8 — Duplicate validation needs a canonical owner.** The same rule MAY be - pre-checked at another layer for UX / performance (e.g. an application pre-check - mirroring a DB unique constraint), but the **canonical owner** of the rule must be - named in a code comment or the relevant `CLAUDE.md`. A duplicate validator with no - documented owner is a review failure (silent contradiction risk). This is a process - gate (PR review), not an automated rule — `needs-confirmation` until an owner-marker - annotation is justified. +- **C1 — 검증 애너테이션은 web 경계에 머문다.** `jakarta.validation`(`@NotNull`, `@Valid`, …)은 + `adapter:inbound:web`에만 나와야 한다. `domain-core`와 `application-core`는 불변식과 정책을 평범한 Java로 + 나타낸다. Bean Validation 애너테이션이 `..domain..`이나 `..application..`으로 새면 ArchUnit 규칙 + `VALIDATION_CONSTRAINTS_STAY_AT_WEB_BOUNDARY`가 빌드를 실패시킨다. +- **C2 — 업무 불변식은 도메인에 있고 우회할 수 없다.** 불변식은 값 객체·엔티티 **생성자**(유일한 생성 + 경로)에서 강제하고 타입을 불변으로 둔다. 그래서 어떤 application service나 영속 경로도 불변식을 어긴 + 인스턴스를 내줄 수 없다. DB 제약은 뒷받침일 뿐 유일한 검사가 아니다(금지: 「불변식을 DB 제약으로만 + 지키기」). +- **C3 / C7 — 영속 무결성은 새는 것 없이 운영 오류로 대응한다.** unique·FK·check·serialization 실패는 + **클라이언트에게 안전한 메시지만** 가진 `DATA_INTEGRITY` / `CONFLICT`로 대응한다. SQL 원문, 제약·index + 이름, SQLState 코드, 예외 클래스, stack frame은 `error.message`나 `error.details`에 닿으면 안 된다. 기본 + `GlobalExceptionHandler` catch-all이 이미 메시지를 불투명한 공용 메시지(`ClientErrorMessages.OPAQUE`)로 + 바꾸고 details를 `null`로 낸다. category가 맞는 대응(23505 → `CONFLICT/DB_UNIQUE_VIOLATION`, …)은 + `feature-persistence-failure-baseline`의 영속 어댑터 번역기가 가진다. +- **C8 — 중복 검증에는 정본 소유자가 있어야 한다.** UX나 성능을 위해 같은 규칙을 다른 층에서 미리 검사할 수 + 있다(예: DB unique 제약을 따라 하는 application 사전 검사). 단 그 규칙의 **정본 소유자**를 코드 주석이나 + 관련 `CLAUDE.md`에 적어야 한다. 소유자를 적지 않은 중복 검증기는 리뷰에서 실패다(소리 없이 서로 어긋날 + 위험). 자동 규칙이 아니라 절차 게이트(PR 리뷰)다 — 소유자 표지 애너테이션이 정당해질 때까지 + `needs-confirmation`이다. -Out of this branch's scope (cross-referenced, not re-implemented here): the -SQLState→code 9-row matrix and the `DataAccessException` translator -(`feature-persistence-failure-baseline`); the Jackson B1/B2 request-boundary switches -and mapper sentinel (`feature-boundary-validation-mapping-contract`); the envelope, -`Category` enum, and `OperationalError` codes +이 브랜치의 범위 밖(참조만 하고 여기서 다시 구현하지 않는다): SQLState → 코드 9행 표와 +`DataAccessException` 번역기(`feature-persistence-failure-baseline`), Jackson B1/B2 요청 경계 스위치와 mapper +표지 예외(`feature-boundary-validation-mapping-contract`), envelope, `Category` enum, `OperationalError` 코드 (`feature-operational-error-observability-foundation`). -## Test +## 테스트 ```bash cd src diff --git a/src/adapter/inbound/web/README.md b/src/adapter/inbound/web/README.md index 134acd95..840517b1 100644 --- a/src/adapter/inbound/web/README.md +++ b/src/adapter/inbound/web/README.md @@ -16,13 +16,12 @@ route inventory)는 opt-in leaf `adapter:inbound:web-advanced` 에 있다 --- -## OpenAPI contract stabilization +## OpenAPI 계약 고정 -Springdoc 3 represents an untyped Java `Object` as an unconstrained OAS 3.1 schema (`{}`). -`OpenApiContractConfig` owns the transport-specific correction for the shared `ApiError.details` -field and publishes it as `type: object`. This preserves the committed HTTP contract without adding -Swagger annotations or dependencies to `shared-contract`. Real-server OpenAPI tests import this -production configuration and compare the result with the committed snapshot. +Springdoc 3은 타입 없는 Java `Object`를 제약 없는 OAS 3.1 schema(`{}`)로 나타낸다. +`OpenApiContractConfig`가 공용 `ApiError.details` 필드에 대한 전송 계층 보정을 가지고 그 필드를 +`type: object`로 낸다. 그래서 `shared-contract`에 Swagger 애너테이션이나 의존성을 더하지 않고 커밋한 HTTP +계약을 지킨다. 실제 서버 OpenAPI 시험은 이 운영 설정을 import하고 결과를 커밋한 snapshot과 비교한다. --- @@ -262,7 +261,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML | `DependencyFailureException` | `ex.errorCode()` (사전분류 `DEPENDENCY_*`) | 코드 결정 | adapter-outbound `OutboundHttpErrorMapper` 가 upstream 실패를 분류. 클라이언트 메시지는 category 문구, **절대 `ex.getMessage()` 아님**. retryable + `retry_after_seconds` 있으면 `RetryAfterAdvisor` 로 `Retry-After` 부착 | | `HttpRequestMethodNotSupportedException` | `METHOD_NOT_ALLOWED` | 405 | D12: 405 는 지원 메서드를 나열한 `Allow` 헤더 필수 | | `HttpMediaTypeNotSupportedException` | `UNSUPPORTED_MEDIA_TYPE` | 415 | D9: 요청 본문 형식 미지원 — 406 과 구별 | -| `MaxUploadSizeExceededException` | `PAYLOAD_TOO_LARGE` | 413 | D8: 과대 본문은 envelope 내 413, raw 500 금지. 멀티파트 전용 413(`UPLOAD_SIZE_EXCEEDED`)은 이 영역의 책임 — 병합 후 정제 | +| `MaxUploadSizeExceededException` | `PAYLOAD_TOO_LARGE` | 413 | D8: 과대 본문은 envelope 내 413, raw 500 금지. multipart와 JSON 본문 모두 이 코드다(multipart 전용 코드는 없다) | | `HttpMediaTypeNotAcceptableException` | `NOT_ACCEPTABLE` | 406 | D9: Accept 에 맞는 표현 없음 — 415 와 구별(합치면 RFC 9110 의미론 상실) | | `MethodArgumentNotValidException` | `VALIDATION_FAILED` | 코드 상태 | 정규화된 field + allowlisted reason code/fixed message 리스트를 details 로. rejectedValue/defaultMessage/iterable key/index는 secret/PII 가능성이 있어 미노출 | | `HttpMessageNotReadableException` | `VALIDATION_FAILED` | 코드 상태 | cause 클래스명을 details 로 | @@ -374,7 +373,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML ## ratelimit -### provider-neutral edge contract +### provider 중립 edge 계약 - inbound web은 `shared-contract`의 `EdgeRateLimitPort`만 호출한다. Redis key, Lua, local counter와 provider 설정을 알지 못한다. @@ -400,8 +399,8 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML filter 는 handler mapping 이전에 실행돼 구체 경로만 보므로 모든 id 가 서로 다른 키가 되어버린다. ### 클라이언트 IP -- 비인증 키의 IP 는 `getRemoteAddr()` 하나다. 헤더를 직접 읽는 모드(`FORWARDED_HEADERS_TRUSTED`)는 - XFF 맨 왼쪽 값(호출자가 쓰는 값)을 키로 써서 삭제했다. +- 비인증 키의 IP 는 `getRemoteAddr()` 하나다. 헤더를 직접 읽는 모드는 없다. XFF 맨 왼쪽 값(호출자가 쓰는 값)을 + 키로 써서 지웠다(`docs/capability-status.md` 「제거된 코드」). - 프록시 뒤에서는 `server.forward-headers-strategy=native` + `server.tomcat.remoteip.internal-proxies` 로 Tomcat 이 신뢰 프록시에게서 온 XFF 만 반영한다. `framework` 는 모든 peer 를 믿으므로 `RateLimitWebConfig` 가 기동을 거부한다. @@ -579,7 +578,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML ## idempotency -### Ownership +### 소유 - `Idempotency-Key`는 HTTP 경계가 읽어 application command/context로 전달할 수 있지만, **claim / fingerprint / replay / in-flight arbitration은 application use case가 소유**한다. - web leaf에는 별도 DB replay 엔진을 두지 않는다. 같은 요청 의미를 web/application 두 계층이 서로 다른 diff --git a/src/adapter/inbound/websocket/CLAUDE.md b/src/adapter/inbound/websocket/CLAUDE.md index 4b54b060..cc19b9f8 100644 --- a/src/adapter/inbound/websocket/CLAUDE.md +++ b/src/adapter/inbound/websocket/CLAUDE.md @@ -1,127 +1,120 @@ -# adapter:inbound:websocket — conditional WebSocket/STOMP boundary +# adapter:inbound:websocket — 고를 때만 켜는 WebSocket·STOMP 경계 -## Registered identity +## 등록 정보 -- Module ID: `adapter-inbound-websocket` -- Gradle path: `:adapter:inbound:websocket` -- Focused test: `./gradlew :adapter:inbound:websocket:test --console=plain` -- Runtime baseline: Java 21, Spring Boot 4.0.8 -- Registry SSOT: `src/config/architecture/modules.json` +- 모듈 ID: `adapter-inbound-websocket` +- Gradle 경로: `:adapter:inbound:websocket` +- 이 모듈만 시험: `./gradlew :adapter:inbound:websocket:test --console=plain` +- 실행 기준: Java 21. Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json` -Package root: `dev.caskeleton.adapter.inbound.websocket`. +패키지 루트: `dev.caskeleton.adapter.inbound.websocket`. -## Responsibility +## 책임 -This leaf contains **two different scopes** and they must not be read as one deployed feature: +이 leaf에는 **서로 다른 범위 둘**이 있고, 배포되는 기능 하나로 읽으면 안 된다. -1. **Opt-in STOMP/SockJS channel** — `stomp/**` owns the Spring transport configuration, typed - `app.websocket.*` settings, handshake principal/origin checks, destination policy, - fixed client-safe STOMP `ERROR` mapping, and best-effort in-process event projection. -2. **Servlet handler library** — `servlet/`, `outbound/`, `budget/` plus the two id records - `core/WebSocketConnectionId` and `protocol/WebSocketMessageId`. No settings keys, no Spring - configuration: a service's own adapter leaf constructs `PlatformWebSocketHandler` and registers - it. README "라이브러리 API" lists the entry points and the wiring. +1. **골라 쓰는 STOMP·SockJS 채널** — `stomp/**`가 Spring 전송 설정, 타입 있는 `app.websocket.*` 설정, + handshake principal·origin 검사, destination 정책, 정해진 클라이언트 안전 STOMP `ERROR` 대응, 할 수 있는 + 만큼만 하는(best-effort) 프로세스 안 이벤트 projection을 가진다. +2. **servlet handler 라이브러리** — `servlet/`, `outbound/`, `budget/`과 id record 둘 + `core/WebSocketConnectionId`, `protocol/WebSocketMessageId`. 설정 키도 Spring 설정도 없다: 서비스 자신의 + 어댑터 leaf가 `PlatformWebSocketHandler`를 만들고 등록한다. README 「라이브러리 API」가 진입점과 배선을 + 적는다. -This leaf does not deduplicate commands and owns no storage SPI. The former `idempotency/` -package (command ledger, `WebSocketActorReference`, `WebSocketEndpointName`) was removed on -2026-09-25. A command that must run at most once goes through the application -`IdempotencyExecutor` inside its use case, with a scope that survives a reconnect (endpoint + actor -+ the client's own message id), never the connection id. +이 leaf는 command 중복을 걸러 내지 않고 저장소 SPI를 가지지 않는다. 예전 `idempotency/` 패키지(command +원장, `WebSocketActorReference`, `WebSocketEndpointName`)는 2026-09-25에 지웠다. 많아야 한 번 돌아야 하는 +command는 그 유스케이스 안에서 애플리케이션 `IdempotencyExecutor`를 거친다. 범위(scope)는 다시 연결해도 +살아남는 값(endpoint + actor + 클라이언트 자신의 message id)이고, connection id가 아니다. -The module itself is absent from both shipped runtime compositions. Being registered and tested -does not activate either scope. +이 모듈은 출하하는 런타임 조립 둘 어디에도 없다. 등록되고 시험된다고 두 범위 중 어느 것도 켜지지 않는다. -## Allowed +## 허용 -- Registered dependency on `:domain-core` for the `@DomainEvent` marker. -- Spring Boot WebSocket and validation starters, managed by the repository BOM. -- Test-only embedded Tomcat/Jetty/SockJS/STOMP clients and Testcontainers (Nginx lane). +- `@DomainEvent` 표지를 위한 `:domain-core` 등록 의존. +- 저장소 BOM이 관리하는 Spring Boot WebSocket·validation starter. +- 시험에서만: 내장 Tomcat·Jetty·SockJS·STOMP 클라이언트와 Testcontainers(Nginx lane). -## Forbidden +## 금지 -- Direct dependency on any `adapter:outbound:*` module. -- Repository, Spring Data, persistence entity, or business policy access. -- Raw `@DomainEvent` payload transmission or reflection-based event serialization. -- Wildcard/blank handshake origins when enabled. -- Anonymous handshakes, arbitrary topic subscriptions, or client sends to broker destinations. -- A production feature `@MessageMapping` in this skeleton leaf. -- A module-local YAML file; composition roots own property values. -- Settings keys, flags or catalogs for behaviour no code in this leaf performs. A bound that the - handler does not enforce is not a field of `WebSocketConnectionBudget`. -- Reactive (WebFlux) WebSocket code: the template is servlet-only. +- 어떤 `adapter:outbound:*` 모듈에든 직접 의존하기. +- repository, Spring Data, 영속 엔티티, 업무 정책 접근. +- `@DomainEvent` payload를 그대로 보내기, 리플렉션 기반 이벤트 직렬화. +- 켜져 있을 때 wildcard·빈 handshake origin. +- 익명 handshake, 아무 topic 구독, 클라이언트가 broker destination으로 보내기. +- 이 골격 leaf 안의 운영 기능 `@MessageMapping`. +- 모듈 안의 YAML 파일. 속성 값은 조립 루트가 가진다. +- 이 leaf의 어떤 코드도 하지 않는 동작을 위한 설정 키·flag·catalog. handler가 강제하지 않는 한계는 + `WebSocketConnectionBudget`의 필드가 아니다. +- reactive(WebFlux) WebSocket 코드: 템플릿은 servlet만 쓴다. -## Typed settings (`app.websocket.*`) +## 타입 있는 설정 (`app.websocket.*`) -There is one property tree and one operator env prefix: `app.websocket.*` ↔ `APP_WEBSOCKET_*`. -They configure the STOMP channel only. The default bootJar does not contain this leaf, so these -values matter only in a composition that adopts it. +속성 트리 하나와 운영자 env 접두어 하나가 있다: `app.websocket.*` ↔ `APP_WEBSOCKET_*`. STOMP 채널만 +설정한다. 기본 bootJar에는 이 leaf가 없으니, 이 값은 이 leaf를 채택한 조립에서만 뜻이 있다. -| property | env | default / role | +| 속성 | env | 기본값·역할 | | --- | --- | --- | -| `app.websocket.enabled` | `APP_WEBSOCKET_ENABLED` | `true`; `false` turns the STOMP/SockJS channel off | +| `app.websocket.enabled` | `APP_WEBSOCKET_ENABLED` | `true`. `false`이면 STOMP·SockJS 채널을 끈다 | | `app.websocket.endpoint` | `APP_WEBSOCKET_ENDPOINT` | `/ws` | -| `app.websocket.allowed-origins` | `APP_WEBSOCKET_ALLOWED_ORIGINS` | `http://localhost:3000`; explicit origins only | +| `app.websocket.allowed-origins` | `APP_WEBSOCKET_ALLOWED_ORIGINS` | `http://localhost:3000`. 명시한 origin만 | | `app.websocket.broadcast-destination` | `APP_WEBSOCKET_BROADCAST_DESTINATION` | `/topic/events` | -| `app.websocket.channel-queue-capacity` | `APP_WEBSOCKET_CHANNEL_QUEUE_CAPACITY` | `10000`; messages each STOMP channel (client inbound, client outbound, broker) queues before rejecting | -| `app.websocket.message-size-limit` | `APP_WEBSOCKET_MESSAGE_SIZE_LIMIT` | `64KB` (Spring default, now explicit) | -| `app.websocket.send-buffer-size-limit` | `APP_WEBSOCKET_SEND_BUFFER_SIZE_LIMIT` | `512KB` (Spring default, now explicit) | -| `app.websocket.send-time-limit` | `APP_WEBSOCKET_SEND_TIME_LIMIT` | `10s` (Spring default, now explicit) | -| `app.websocket.time-to-first-message` | `APP_WEBSOCKET_TIME_TO_FIRST_MESSAGE` | `60s` (Spring default, now explicit) | -| `app.websocket.max-connections` | `APP_WEBSOCKET_MAX_CONNECTIONS` | `1000`; STOMP sessions per node, the next is closed with 1013 | +| `app.websocket.channel-queue-capacity` | `APP_WEBSOCKET_CHANNEL_QUEUE_CAPACITY` | `10000`. STOMP 채널마다(클라이언트 inbound, 클라이언트 outbound, broker) 거절하기 전에 쌓아 두는 메시지 수 | +| `app.websocket.message-size-limit` | `APP_WEBSOCKET_MESSAGE_SIZE_LIMIT` | `64KB`(Spring 기본값을 이제 명시한다) | +| `app.websocket.send-buffer-size-limit` | `APP_WEBSOCKET_SEND_BUFFER_SIZE_LIMIT` | `512KB`(Spring 기본값을 이제 명시한다) | +| `app.websocket.send-time-limit` | `APP_WEBSOCKET_SEND_TIME_LIMIT` | `10s`(Spring 기본값을 이제 명시한다) | +| `app.websocket.time-to-first-message` | `APP_WEBSOCKET_TIME_TO_FIRST_MESSAGE` | `60s`(Spring 기본값을 이제 명시한다) | +| `app.websocket.max-connections` | `APP_WEBSOCKET_MAX_CONNECTIONS` | `1000`. 노드마다 STOMP 세션 수. 그다음 것은 1013으로 닫는다 | -`WebSocketSettings` is `@Validated`. Invalid enabled settings fail context startup. +`WebSocketSettings`는 `@Validated`다. 켜진 상태의 잘못된 설정은 context 기동을 실패시킨다. -## Adopting this capability +## 이 capability 채택하기 -WebSocket is a **build-composition opt-in**, not a dormant feature inside the default bootJar. +WebSocket은 기본 bootJar 안에 잠든 기능이 아니라 **빌드 조립에서 고르는 것**이다. -1. Add `:adapter:inbound:websocket` to the consuming composition's dependencies and add the - matching allowed edge in `config/architecture/modules.json`. -2. Keep settings registration with the capability root; do not add - `dev.caskeleton.adapter.inbound.websocket` back to the shipped - `@ConfigurationPropertiesScan`. -3. The STOMP/SockJS channel is registered by this leaf's own `AutoConfiguration.imports` and is on - whenever the leaf is on a servlet classpath; set a non-wildcard origin allowlist, and - `app.websocket.enabled=false` to turn it off. -4. For the handler library, follow README "라이브러리 API". The handler must be a bean so its - `SmartLifecycle` stop (1001 to every open connection) runs before the web server stops. -5. Run the leaf lanes and the repository conditional-transport aggregate before promoting the - composition: +1. 쓰는 조립의 의존성에 `:adapter:inbound:websocket`을 더하고 `config/architecture/modules.json`에 맞는 허용 + edge를 더한다. +2. 설정 등록은 capability 루트에 둔다. 출하하는 `@ConfigurationPropertiesScan`에 + `dev.caskeleton.adapter.inbound.websocket`을 다시 더하지 않는다. +3. STOMP·SockJS 채널은 이 leaf 자신의 `AutoConfiguration.imports`가 등록하고, leaf가 servlet classpath에 + 있으면 언제나 켜진다. wildcard가 아닌 origin 허용 목록을 정하고, 끄려면 `app.websocket.enabled=false`로 + 한다. +4. handler 라이브러리는 README 「라이브러리 API」를 따른다. handler는 bean이어야 한다. 그래야 그 + `SmartLifecycle` 멈춤(열린 모든 연결에 1001)이 web 서버가 멈추기 전에 돈다. +5. 조립을 승격하기 전에 leaf lane과 저장소 conditional-transport 묶음을 돌린다: `./gradlew :adapter:inbound:websocket:test :adapter:inbound:websocket:systemTest :conditionalTransportQualification`. -## Inbound policy (STOMP) +## inbound 정책 (STOMP) -- The HTTP upgrade must already have a nonblank `Principal`; the adapter does not authenticate - credentials itself. -- STOMP `SUBSCRIBE` is allowed only for the configured broadcast destination. -- Authenticated `SEND` is allowed only below `/app/**`. -- Client `SEND` to `/topic/**` and other destinations is rejected. -- Every client-visible processing failure becomes an ERROR frame with an empty payload and the - fixed `message` `WEBSOCKET_REQUEST_REJECTED`. Its `error-code` header is the carried - `ApiErrorCode` of the first `ApiErrorCarrier` in the cause chain (even behind an - `IllegalArgumentException`), `BAD_PARAMETER` for an `IllegalArgumentException`, and - `WEBSOCKET_REQUEST_REJECTED` otherwise. +- HTTP upgrade에는 이미 비어 있지 않은 `Principal`이 있어야 한다. 어댑터는 credential을 직접 인증하지 않는다. +- STOMP `SUBSCRIBE`는 설정한 broadcast destination에만 허용한다. +- 인증된 `SEND`는 `/app/**` 아래에만 허용한다. +- 클라이언트가 `/topic/**`나 다른 destination으로 보내는 `SEND`는 거절한다. +- 클라이언트에게 보이는 처리 실패는 모두 빈 payload와 정해진 `message` `WEBSOCKET_REQUEST_REJECTED`를 가진 + ERROR frame이 된다. 그 `error-code` header는 cause chain에서 처음 나오는 `ApiErrorCarrier`가 실은 + `ApiErrorCode`(`IllegalArgumentException` 뒤에 있어도), `IllegalArgumentException`이면 `BAD_PARAMETER`, 그 + 밖에는 `WEBSOCKET_REQUEST_REJECTED`다. -## Event projection contract +## 이벤트 projection 계약 -A future feature may contribute a `LiveEventProjector<T>` bean for one exact `@DomainEvent` class. -The broadcaster sends only when exactly one projector matches. Zero or duplicate projectors, -projection failures, invalid event types, null fields, and over-limit maps are dropped. The wire -envelope contains only `type`, bounded string `fields`, and `occurredAt`. The broker channel has its -own bounded executor, so the simple broker's fan-out to subscribers never runs on the thread that -published the domain event; a full broker queue drops the event (best-effort, R1). +나중의 기능이 정확히 하나의 `@DomainEvent` 클래스에 대해 `LiveEventProjector<T>` bean을 기여할 수 있다. +broadcaster는 projector가 정확히 하나 맞을 때만 보낸다. projector가 없거나 둘 이상이거나, projection이 +실패하거나, 이벤트 타입이 잘못됐거나, 필드가 null이거나, map이 한계를 넘으면 버린다. wire envelope에는 +`type`, 한계 있는 문자열 `fields`, `occurredAt`만 있다. broker 채널은 자기 한계 있는 executor를 가지므로, +simple broker가 구독자에게 퍼뜨리는 일은 도메인 이벤트를 발행한 스레드에서 돌지 않는다. broker queue가 차면 +이벤트를 버린다(best-effort, R1). 템플릿에는 WebSocket 이벤트를 발행하거나 projector를 기여하는 기능이 없다. -## Evidence and limits +## 증거와 한계 -| lane | what it proves | +| lane | 증명하는 것 | | --- | --- | -| `test` | STOMP settings/policy, queue/writer/budget, handler size and overflow closes | -| `systemTest` | real Tomcat: STOMP boundary (`WebSocketBoundaryQualificationTest`), handler runtime and abuse contracts, context close sends 1001 | -| `websocketJettyTest` | the handler runtime contract on Jetty | -| `websocketNginxTest` | upgrade/forwarding behind a real Nginx (Docker required; fails without it) | -| `websocketTransportQualificationTest` | no-skip execution of the STOMP boundary test | +| `test` | STOMP 설정·정책, queue·writer·budget, handler 크기와 넘침 종료 | +| `systemTest` | 실제 Tomcat: STOMP 경계(`WebSocketBoundaryQualificationTest`), handler 런타임과 남용 계약, context를 닫으면 1001을 보냄 | +| `websocketJettyTest` | Jetty에서 handler 런타임 계약 | +| `websocketNginxTest` | 실제 Nginx 뒤의 upgrade·forwarding(Docker 필요. 없으면 실패한다) | +| `websocketTransportQualificationTest` | STOMP 경계 시험을 건너뛰지 않고 실행 | -The simple broker is local, single-process, best-effort R1 evidence only. Broker relay, -multi-node/durable delivery, rollback-safe publication and replay/resume are not provided. +simple broker는 로컬·단일 프로세스·best-effort R1 증거일 뿐이다. broker relay, 여러 노드·durable 전달, +롤백에 안전한 발행, replay·resume은 주지 않는다. diff --git a/src/adapter/outbound/cache-redis/CLAUDE.md b/src/adapter/outbound/cache-redis/CLAUDE.md index 79842ed2..b00bee92 100644 --- a/src/adapter/outbound/cache-redis/CLAUDE.md +++ b/src/adapter/outbound/cache-redis/CLAUDE.md @@ -1,211 +1,180 @@ -# adapter:outbound:cache-redis — cache and Redis adapter +# adapter:outbound:cache-redis — cache와 Redis 어댑터 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-cache-redis` -- Gradle path: `:adapter:outbound:cache-redis` -- Focused test (derived from Gradle path): `./gradlew :adapter:outbound:cache-redis:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-outbound-cache-redis` +- Gradle 경로: `:adapter:outbound:cache-redis` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:outbound:cache-redis:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.outbound.cache`. +패키지 루트: `dev.caskeleton.adapter.outbound.cache`. -## Responsibility +## 책임 -- Implement semantic cache ports from `application-core` without exposing Redis concepts to core. -- Own canonical physical keys, digesting, codec/envelope, program catalog, typed Redis atomic - facades, runtime client adaptation, and capability-specific failure semantics. -- Implement absolute soft/hard expiry, write conditions and key invalidation markers behind the - semantic cache port (`CacheRegionPort`). There is no TTL jitter and no stampede protection; - single-flight is the caller's. The revision order is the port's `CacheSourceRevisionOrder`; the - Lua copy is held to it by `CacheRegionContract` (application-core testFixtures), which - `RedisCacheRegionContractTest` and `LiveRedisCacheRegionContractTest` extend. -- Implement the provider-neutral `EdgeRateLimitPort` with dedicated coordination Redis settings, - connection/admission, private keys and versioned atomic programs. -- Keep the legacy cache router isolated while consumers migrate to semantic ports. -- Reuse `adapter:outbound:support` for shared outbound concerns. -- Depend on `:adapter:outbound:redis-runtime` for the shared topology client, connection lifecycle, - the eight `SemanticRedisCommands` and conditional Redis runtime composition used by the semantic - adapters. -- Keep the general-purpose typed SDK in the separate library leaf `:adapter:outbound:redis-sdk` - (see its `README.md`). This leaf does not depend on it in any configuration, tests included; the - SDK's tests and lanes live in that leaf. +- `application-core`의 semantic cache 포트를 구현하고, Redis 개념을 core에 드러내지 않는다. +- 정해진 물리 키, digest, codec·envelope, program catalog, 타입 있는 Redis 원자 창구, runtime client 연결, + capability별 실패 뜻을 가진다. +- semantic cache 포트(`CacheRegionPort`) 뒤에서 절대 soft·hard 만료, 쓰기 조건, 키 무효화 표지를 구현한다. TTL + jitter도 stampede 보호도 없다. single-flight는 호출자의 몫이다. revision 순서는 포트의 + `CacheSourceRevisionOrder`다. Lua 사본은 `CacheRegionContract`(application-core testFixtures)가 그 순서에 + 맞추고, `RedisCacheRegionContractTest`와 `LiveRedisCacheRegionContractTest`가 그 계약을 상속한다. +- provider 중립 `EdgeRateLimitPort`를 전용 조율 Redis 설정, 연결·admission, 전용 키, 버전 있는 원자 program으로 + 구현한다. +- 쓰는 쪽이 semantic 포트로 옮기는 동안 옛 cache router를 떼어 둔다. +- 공용 outbound 관심사는 `adapter:outbound:support`를 다시 쓴다. +- semantic 어댑터가 쓰는 공용 topology client, 연결 lifecycle, `SemanticRedisCommands` 여덟 개, 조건부 Redis + runtime 조립은 `:adapter:outbound:redis-runtime`에 의존한다. +- 범용 typed SDK는 따로 둔 라이브러리 leaf `:adapter:outbound:redis-sdk`에 둔다(그 `README.md`를 본다). 이 + leaf는 시험을 포함해 어떤 설정에서도 그것에 의존하지 않는다. SDK의 시험과 lane은 그 leaf에 있다. -## Redis runtime (`…cache.redis.runtime`) and optional typed SDK (`…cache.redis.sdk`) +## Redis 런타임과 골라 쓰는 typed SDK (`…cache.redis.runtime`, `…cache.redis.sdk`) -Two registered leaves, two packages, one direction: the SDK builds on the runtime, the runtime knows -nothing of the SDK (`RedisRuntimePackageBoundaryTest` in the runtime holds that direction). +등록된 leaf 둘, 패키지 둘, 방향 하나: SDK는 runtime 위에 서고, runtime은 SDK를 모른다(runtime 안의 +`RedisRuntimePackageBoundaryTest`가 그 방향을 지킨다). -- `:adapter:outbound:redis-runtime` is production substrate: `RedisRuntimeSettings` binding, - credential resolution, topology clients, `RedisRuntimeOwner` with the runtime's own lanes - (`RedisConnectionKind.REGULAR`, `SCRIPT`), `SemanticRedisCommands` (the eight commands this leaf - and the health contributor send) and health. `cache-redis` depends on this leaf. -- `:adapter:outbound:redis-sdk` owns the optional general-purpose typed API: `RedisCommandGateway` - (extends `SemanticRedisCommands`), command catalog/policy, operation budgets, command guard, - raw/admin surfaces, programmability and extensions — and its own lanes (`RedisSdkLane`: blocking, - transaction, admin) and admin account, which a service contributes to the runtime as - `RedisLaneContribution`/`RedisAccountContribution` beans (`RedisSdkComposition`). `cache-redis` - does **not** depend on it, in production or in tests. -- The semantic cache/idempotency/rate-limit/lease adapters in this leaf send the runtime's - `SemanticRedisCommands` through their own closed semantic programs (`RegisteredLuaScript`). They - do not pass through `CommandPolicyGuard`, and `redis-command-policy.yml` does not control them. -- Which roles need Redis for correctness is this leaf's `RedisCorrectnessRoleSelectors`, registered - in `META-INF/spring.factories` as the runtime's `RedisCorrectnessRequirement`. +- `:adapter:outbound:redis-runtime`은 운영 기반이다: `RedisRuntimeSettings` 바인딩, credential 해석, topology + client, runtime 자신의 lane(`RedisConnectionKind.REGULAR`, `SCRIPT`)을 가진 `RedisRuntimeOwner`, + `SemanticRedisCommands`(이 leaf와 health contributor가 보내는 명령 여덟 개), health. `cache-redis`가 이 leaf에 + 의존한다. +- `:adapter:outbound:redis-sdk`는 골라 쓰는 범용 typed API를 가진다: `RedisCommandGateway`(`SemanticRedisCommands`를 + 상속), 명령 catalog·정책, operation 예산, 명령 guard, raw·admin surface, programmability, extension — 그리고 + 자기 lane(`RedisSdkLane`: blocking, transaction, admin)과 admin 계정. 서비스가 그것을 + `RedisLaneContribution`/`RedisAccountContribution` bean으로 runtime에 기여한다(`RedisSdkComposition`). + `cache-redis`는 운영에서도 시험에서도 그것에 의존하지 **않는다**. +- 이 leaf의 semantic cache·멱등성·rate-limit·lease 어댑터는 runtime의 `SemanticRedisCommands`를 자기의 닫힌 + semantic program(`RegisteredLuaScript`)으로 보낸다. `CommandPolicyGuard`를 지나지 않고, + `redis-command-policy.yml`이 그것을 다루지 않는다. +- 정확성을 위해 어떤 role에 Redis가 필요한지는 이 leaf의 `RedisCorrectnessRoleSelectors`가 정하고, + `META-INF/spring.factories`에 runtime의 `RedisCorrectnessRequirement`로 등록한다. -The typed SDK described in -`docs/design/2026-08-07-redis-wrapper-typed-api-design.md` remains an optional library -rather than part of the shipped semantic Redis adapter. Delivery status and adaptation history are -in `docs/history/plans/2026-08-07-redis-wrapper-typed-api-status.md`. +`docs/design/2026-08-07-redis-wrapper-typed-api-design.md`가 설명하는 typed SDK는 출하하는 semantic Redis 어댑터의 +일부가 아니라 골라 쓰는 라이브러리로 남는다. 전달 상태와 맞춘 이력은 +`docs/history/plans/2026-08-07-redis-wrapper-typed-api-status.md`에 있다. -- `sdk.api..` is the public contract. It must never import Spring, Lettuce, Micrometer, or any SDK - implementation package; Reactor is confined to `sdk.api.reactive`. -- `sdk.lettuce..` implements the contract; `sdk.config` owns properties, the capability probe, and - the permit authority. -- `:adapter:outbound:redis-sdk/src/main/resources/redis-sdk/redis-command-policy.yml` is the - optional typed SDK command-policy SSOT. A typed-SDK command that is not classified there is - refused. It is not a policy file for this leaf's semantic capability adapters. -- `sdk.lettuce.operations` implements the typed operations. Everything there goes through - `RedisCommandGateway`, the only seam that reaches Lettuce, and every call is admitted by - `CommandPolicyGuard` before it runs. Never call the driver from an operation directly. -- `sdk.cluster` owns client-side slot arithmetic and cluster observation. It depends on `sdk.api` - only and must never import Lettuce: the slot is computed before a command is built, which is what - lets `CommandPolicyGuard` refuse a cross-slot request instead of learning about it from a server - redirect. -- `sdk.programmability` owns transactions, registered Lua scripts, and deployed function calls. A - script body is never accepted at call time: `EVAL` is blocked in the catalog and only `EVALSHA` of - a `RedisScriptRegistry` digest is reachable. `FUNCTION LOAD` is admin-plane, never application. -- Transactions are `WATCH`/`MULTI`/`EXEC` and **never** roll back. `TransactionResult` reports only - "executed" or "a watched key changed, so nothing ran", and no type in this package offers a word - that suggests otherwise. A queued command returns a `QueuedReply` that throws when read before the - commit, because inside the window the server has answered `+QUEUED` and nothing else. Queued - commands pass the same `CommandPolicyGuard` admission as ordinary ones — a transaction is not a - way around the guard — and the window is closed on every exit path, including a callback that - threw, because a connection abandoned in `MULTI` state silently queues the next caller's command. - The queue is write-only on purpose: a read inside the window cannot be branched on, so the reads a - transaction depends on belong before it, under `WATCH`. -- `sdk.raw` is the approved raw command gateway. A command is reachable only when the catalog marks - it `RAW_ONLY` *and* the deployment registered an `ApprovedRawCommand` for it; keys are parsed back - out of the arguments and namespace-checked before anything is sent. Never add a method here that - takes a command name as a string. -- `sdk.admin` is the read-only diagnostic plane. It takes its own gateway (admin ACL account, own - connection), refuses any command the catalog does not classify `ADMIN_ONLY` and read-only, and - projects replies so a slow log or client listing never carries arguments, peer addresses, or - connection names. -- `sdk.extensions.*` holds the Redis 8 modules (JSON, Search, Time Series, Probabilistic). Every - bean is created through `ifSupported(...)` — the capability probe decides, the catalog minimum is - only a pre-filter — and all of them build commands through `ExtensionCommandRunner` so the guard - sees their keys. Search is the exception that proves it: an index is not a key, so its name is - namespaced by `LettuceRedisSearchOperations` itself. -- `RedisSdkModuleBoundaryTest` (in `redis-sdk`) scans the `redis-sdk` source root and enforces the - internal package graph, driver containment, the absence of an arbitrary string command surface, - and the designed module list. -- Decisions that must not be changed without revisiting the design: no unbounded `entries`, - `members`, `rangeAll`, or `keys`; no optional R2 permit or budget; no arbitrary command string - overload; no automatic retry of a non-idempotent write after a timeout; no real key in a metric or - trace tag. +- `sdk.api..`는 공개 계약이다. Spring, Lettuce, Micrometer, SDK 구현 패키지를 import하지 않는다. Reactor는 + `sdk.api.reactive` 안에만 둔다. +- `sdk.lettuce..`가 계약을 구현한다. `sdk.config`는 속성, capability probe, 허가 정본을 가진다. +- `:adapter:outbound:redis-sdk/src/main/resources/redis-sdk/redis-command-policy.yml`이 골라 쓰는 typed SDK의 명령 + 정책 정본이다. 거기 분류되지 않은 typed SDK 명령은 거절한다. 이 leaf의 semantic capability 어댑터를 위한 정책 + 파일이 아니다. +- `sdk.lettuce.operations`가 타입 있는 operation을 구현한다. 거기 있는 모든 것은 Lettuce에 닿는 유일한 이음매인 + `RedisCommandGateway`를 거치고, 모든 호출은 돌기 전에 `CommandPolicyGuard`의 허가를 받는다. operation에서 + driver를 직접 부르지 않는다. +- `sdk.cluster`는 client 쪽 slot 계산과 cluster 관찰을 가진다. `sdk.api`에만 의존하고 Lettuce를 import하지 + 않는다: slot을 명령을 만들기 전에 계산하므로 `CommandPolicyGuard`가 서버 redirect로 알게 되기 전에 cross-slot + 요청을 거절할 수 있다. +- `sdk.programmability`는 트랜잭션, 등록된 Lua script, 배포된 function 호출을 가진다. 호출 때 script 본문을 받지 + 않는다: catalog가 `EVAL`을 막고 `RedisScriptRegistry` digest의 `EVALSHA`만 닿을 수 있다. `FUNCTION LOAD`는 + 애플리케이션이 아니라 admin plane이다. +- 트랜잭션은 `WATCH`/`MULTI`/`EXEC`이고 **절대** 롤백하지 않는다. `TransactionResult`는 「실행됨」이나 「감시한 + 키가 바뀌어서 아무것도 돌지 않음」만 알리고, 이 패키지의 어떤 타입도 다른 뜻을 비치는 말을 주지 않는다. + 줄 세운 명령은 `QueuedReply`를 돌려주고, 커밋 전에 읽으면 던진다. 그 창 안에서 서버는 `+QUEUED`만 답했기 + 때문이다. 줄 세운 명령도 보통 명령과 같은 `CommandPolicyGuard` 허가를 지난다 — 트랜잭션은 guard를 피하는 길이 + 아니다 — 그리고 창은 던진 callback을 포함해 모든 출구에서 닫는다. `MULTI` 상태로 버려진 연결은 다음 호출자의 + 명령을 소리 없이 줄 세우기 때문이다. queue는 일부러 쓰기 전용이다: 창 안의 읽기로는 분기할 수 없으니, + 트랜잭션이 기대는 읽기는 그 앞에서 `WATCH` 아래에 둔다. +- `sdk.raw`는 승인된 raw 명령 gateway다. catalog가 `RAW_ONLY`로 표시했고 *그리고* 배포가 그 명령에 + `ApprovedRawCommand`를 등록했을 때만 닿을 수 있다. 보내기 전에 인자에서 키를 다시 파싱해 namespace를 검사한다. + 명령 이름을 문자열로 받는 메서드를 여기 더하지 않는다. +- `sdk.admin`은 읽기 전용 진단 plane이다. 자기 gateway(admin ACL 계정, 자기 연결)를 받고, catalog가 `ADMIN_ONLY`이자 + 읽기 전용으로 분류하지 않은 명령은 모두 거절하며, slow log나 client 목록이 인자·상대 주소·연결 이름을 싣지 + 않게 응답을 걸러 낸다. +- `sdk.extensions.*`는 Redis 8 모듈(JSON, Search, Time Series, Probabilistic)을 담는다. 모든 bean은 + `ifSupported(...)`로 만든다 — capability probe가 정하고, catalog 최소값은 앞 걸러내기일 뿐이다 — 그리고 모두 + `ExtensionCommandRunner`로 명령을 만들어 guard가 그 키를 본다. Search는 이것을 보여 주는 예외다: index는 키가 + 아니라서 그 이름은 `LettuceRedisSearchOperations`가 직접 namespace를 붙인다. +- `RedisSdkModuleBoundaryTest`(`redis-sdk` 안)가 `redis-sdk` 소스 루트를 scan해 내부 패키지 그래프, driver 가두기, + 아무 문자열 명령 surface 없음, 설계한 모듈 목록을 강제한다. +- 설계를 다시 보지 않고 바꾸면 안 되는 결정: 한계 없는 `entries`, `members`, `rangeAll`, `keys` 없음. 선택 사항인 + R2 허가·예산 없음. 아무 명령 문자열을 받는 overload 없음. timeout 뒤 멱등이 아닌 쓰기의 자동 재시도 없음. + metric이나 trace tag에 실제 키 없음. -## Boundaries +## 경계 -- Allowed dependency edges come only from the module's - `src/config/architecture/modules.json` entry. -- No inbound transport, persistence entity/repository, bootstrap, or sample dependency. -- Cache adapters do not decide business freshness, entitlement, or domain fallback rules. -- Physical Redis TTL must equal encoded hard expiry; future/corrupt schema must never collapse into - an ordinary miss. -- Application/domain code must not receive raw Redis keys, commands, Lua/Function names, SDK - objects, topology, or connection types. -- Cache fail-open behavior must not be reused for session, idempotency, strict quota, lease, or - fencing. -- Rate-limit composition must not reuse `app.cache.redis`, its connection, external client mode or - failure-open semantics; v1 is coordination-role and fail-closed only. -- The standalone runtime/cache service lane is R1 evidence only. Sentinel/Cluster, TLS/ACL, - persistence/restart, eviction and fault evidence are required separately for R2. +- 허용 의존 edge는 이 모듈의 `src/config/architecture/modules.json` 항목에서만 온다. +- inbound 전송, 영속 엔티티·repository, bootstrap, 샘플 의존이 없다. +- cache 어댑터는 업무상 신선도, 자격, 도메인 대체 규칙을 정하지 않는다. +- Redis 물리 TTL은 인코딩한 hard 만료와 같아야 한다. 미래·손상 schema가 보통 miss로 뭉개지면 안 된다. +- application·domain 코드는 raw Redis 키, 명령, Lua·Function 이름, SDK 객체, topology, 연결 타입을 받으면 안 된다. +- cache의 fail-open 동작을 session, 멱등성, 엄격한 quota, lease, fencing에 다시 쓰면 안 된다. +- rate-limit 조립은 `app.cache.redis`, 그 연결, 외부 client 모드, 실패하면 열리는 뜻을 다시 쓰면 안 된다. v1은 + 조율 role이고 실패하면 닫히는 것뿐이다. +- standalone runtime·cache 서비스 lane은 R1 증거일 뿐이다. Sentinel·Cluster, TLS·ACL, 영속·재시작, eviction, 장애 + 증거는 R2를 위해 따로 필요하다. -## Tests +## 테스트 -Focused tests drive the semantic adapters against `InMemorySemanticRedisCommands` from -`testFixtures(project(':adapter:outbound:redis-runtime'))`, the one fake of `SemanticRedisCommands`, -served through `StubRedisRuntimeClient`. R1/R2 promotion requires a separate real Redis service lane; it may never -be silently skipped when selected. +이 모듈만 보는 시험은 semantic 어댑터를 `testFixtures(project(':adapter:outbound:redis-runtime'))`의 +`InMemorySemanticRedisCommands`에 대고 돌린다. `SemanticRedisCommands`의 유일한 fake이고, `StubRedisRuntimeClient`를 +거쳐 쓴다. R1·R2 승격에는 따로 실제 Redis 서비스 lane이 필요하다. 그 lane을 골랐으면 소리 없이 건너뛰면 안 된다. -Two real-server lanes. `redisContainerContractTest` (integration category, in `integrationCheck` only — -not in this leaf's `mainCheck` too, which ran it twice per push to main) starts its own Redis with Testcontainers — the `redis` image of -`config/testing/container-images.properties`, loading `compose/redis/acl/lane-fixture-accounts.acl` — and -runs `LiveRedisCacheRegionContractTest`, `LiveRedisDistributedLeaseContractTest` and -`LiveRedisIdempotencyStoreContractTest` (the `application-core` port contracts the in-memory fakes -also pass), `LiveRedisSemanticPortsTest` and `LiveRedisSemanticScriptAclProbeTest`; a skip fails it -(since 2026-11-01). The idempotency contract was on the explicit-only topology lane alone -until 2026-11-03, so the Lua state machine's stale-handle, renew-refusal and -retry cases reached a real server in no gate. `RedisTestContainer` -starts the server only when that lane names the ACL file. +실제 서버 lane이 둘 있다. `redisContainerContractTest`(integration category, `integrationCheck`에만 있다 — 이 leaf의 +`mainCheck`에도 있었을 때는 main push마다 두 번 돌았다)는 Testcontainers로 자기 Redis를 띄운다 — +`config/testing/container-images.properties`의 `redis` image이고 `compose/redis/acl/lane-fixture-accounts.acl`을 +읽어 들인다 — 그리고 `LiveRedisCacheRegionContractTest`, `LiveRedisDistributedLeaseContractTest`, +`LiveRedisIdempotencyStoreContractTest`(메모리 fake도 통과하는 `application-core` 포트 계약), +`LiveRedisSemanticPortsTest`, `LiveRedisSemanticScriptAclProbeTest`를 돌린다. 건너뛰기가 있으면 실패한다 +(2026-11-01부터). 멱등성 계약은 2026-11-03까지 명시할 때만 도는 topology lane에만 있었다. 그래서 Lua 상태 기계의 +낡은 handle, 갱신 거절, 재시도 경우가 어느 게이트에서도 실제 서버에 닿지 않았다. `RedisTestContainer`는 그 lane이 +ACL 파일을 이름으로 댈 때만 서버를 띄운다. -`redisTopologyTest` is the external-topology lane, declared through `ca.redis-topology-lane`. This -leaf declares `standalone` and `cluster` (`LiveRedisSemanticPortsTest`, `LiveRedisSemanticScriptAclProbeTest`); `redis-runtime` and -`redis-sdk` declare their own lanes for their own classes. It is opt-in and fail-closed: the mode -must be one of `standalone`, `sentinel`, `cluster`, `tls` and one this leaf declares; the endpoint -properties must be present (`sentinel` additionally needs `redis.topology.master`, `tls` needs -`redis.topology.trust-material`); a run that discovers or executes zero tests fails (the -convention, not this leaf, owns that); the classes the leaf names in `redisTopologyLane` must -actually have run; and a skipped test fails the run rather than counting as executed. `tls` is a -lane, not a deployment mode — its shape is standalone and the task maps it so, because what it -qualifies is the transport. +`redisTopologyTest`는 외부 topology lane이고 `ca.redis-topology-lane`으로 선언한다. 이 leaf는 `standalone`과 +`cluster`(`LiveRedisSemanticPortsTest`, `LiveRedisSemanticScriptAclProbeTest`)를 선언한다. `redis-runtime`과 +`redis-sdk`는 자기 클래스에 대해 자기 lane을 선언한다. 고를 때만 돌고 실패하면 닫힌다: 모드는 `standalone`, +`sentinel`, `cluster`, `tls` 중 이 leaf가 선언한 것이어야 하고, endpoint 속성이 있어야 하며(`sentinel`은 +`redis.topology.master`가, `tls`는 `redis.topology.trust-material`이 더 필요하다), 시험을 하나도 찾지 못하거나 +돌리지 않은 실행은 실패하고(그것은 이 leaf가 아니라 규약이 가진다), leaf가 `redisTopologyLane`에 적은 클래스가 +실제로 돌았어야 하며, 건너뛴 시험은 실행한 것으로 세지 않고 실행을 실패시킨다. `tls`는 배포 모드가 아니라 +lane이다 — 모양은 standalone이고 태스크가 그렇게 대응시킨다. 검증하는 것이 전송이기 때문이다. -Two former checks are gone. A scan of the test sources for the literal text `@Tag("redis-topology")` -only improved the message for a failure `failOnNoDiscoveredTests` already produced, and a comment -containing the same text satisfied it. A hand-maintained per-mode floor on the executed count -(20/20/24/4) had to be edited whenever a case was added or removed, and the thing it failed on — -"coverage shrank" — is not a runtime, deployment, data, security or compile failure. +예전 검사 둘은 없어졌다. 시험 소스에서 글자 그대로 `@Tag("redis-topology")`를 찾는 scan은 +`failOnNoDiscoveredTests`가 이미 내는 실패의 메시지를 낫게 할 뿐이었고, 같은 글을 담은 주석으로도 만족됐다. 손으로 +관리하던 모드별 실행 수 하한(20/20/24/4)은 경우를 더하거나 뺄 때마다 고쳐야 했고, 그것이 잡는 「덮는 범위가 +줄었다」는 런타임·배포·데이터·보안·컴파일 실패가 아니다. -## Composition +## 조립 -`RedisRuntimeAutoConfiguration` now belongs to `:adapter:outbound:redis-runtime`. It is the only -place Redis settings and the shared runtime substrate come into existence, and it exists only while -`app.redis.enabled` (env `APP_REDIS_ENABLED`, default `true` — the module is on when present) is -true. It builds the topology client, connection owner and health contributors; `RedisCapabilityConfig` -in this leaf (its own `AutoConfiguration.imports`) composes the semantic ports on top of that runtime. +`RedisRuntimeAutoConfiguration`은 이제 `:adapter:outbound:redis-runtime`의 것이다. Redis 설정과 공용 runtime 기반이 +생기는 유일한 곳이고, `app.redis.enabled`(env `APP_REDIS_ENABLED`, 기본 `true` — 모듈이 있으면 켜진다)가 true인 +동안에만 있다. topology client, 연결 owner, health contributor를 만든다. 이 leaf의 `RedisCapabilityConfig`(자기 +`AutoConfiguration.imports`)가 그 runtime 위에 semantic 포트를 조립한다. -The optional `:adapter:outbound:redis-sdk` is not auto-composed by the shipped application. Its -`RedisStartupProbe` is a library API, not an implicit production guard. In particular there is no -`APP_REDIS_ACKNOWLEDGED_WRITE_LOSS_ACCEPTED` switch: accepting that trade must be an explicit -argument at the probe call site rather than a public setting with no production caller. +골라 쓰는 `:adapter:outbound:redis-sdk`는 출하하는 애플리케이션이 자동으로 조립하지 않는다. 그 +`RedisStartupProbe`는 라이브러리 API이고 숨은 운영 guard가 아니다. 특히 `APP_REDIS_ACKNOWLEDGED_WRITE_LOSS_ACCEPTED` +스위치는 없다: 그 거래를 받아들이는 것은 운영 호출자가 없는 공개 설정이 아니라 probe를 부르는 곳의 명시한 인자여야 +한다. -Every capability renders its keys under the one namespace from `app.redis.namespace` — -`{environment}:{service}:{domain}` — through `CapabilityKeyspace`. Never give a capability its own -prefix tokens: four capabilities each joining two free-form strings produced four different key -shapes, and the deployment's ACL pattern matched none of them. +모든 capability는 `CapabilityKeyspace`를 거쳐 `app.redis.namespace`의 namespace 하나 — +`{environment}:{service}:{domain}` — 아래에 키를 만든다. capability에 자기 접두어 token을 주지 않는다: capability 넷이 +각자 자유 문자열 둘을 이어 붙였더니 키 모양이 넷이 됐고, 배포의 ACL pattern은 그중 어느 것과도 맞지 않았다. -Lanes authenticate as different accounts. `RedisLane.account()` names the lane's `RedisAccount`, -and the topology factory builds one client per *configured* account — so a single-account -deployment still gets exactly one client and one event loop. The `SCRIPT` lane is -the reason it exists: `SCRIPT LOAD` and `EVALSHA` belong to the advanced account, so the account -that reads a cache entry cannot execute a script. +lane은 서로 다른 계정으로 인증한다. `RedisLane.account()`가 lane의 `RedisAccount`를 이름으로 대고, topology factory는 +*설정한* 계정마다 client를 하나 만든다 — 그래서 계정이 하나인 배포는 여전히 client 하나와 event loop 하나만 가진다. +`SCRIPT` lane이 그것이 있는 이유다: `SCRIPT LOAD`와 `EVALSHA`는 advanced 계정의 것이라서, cache 항목을 읽는 계정은 +script를 실행할 수 없다. -The cache's conditional writes run on the same account but on a lane of their own, -`CacheScriptLane.CACHE_SCRIPT` (`app.capabilities.cache.maximum-script-connections`, contributed by -`RedisCacheConfig` as a `RedisLaneContribution`). Do not move them back to `SCRIPT`: that lane is the -idempotency, rate-limit and lease budget, and a cache under load must not take it (decided -2026-11-03). Each lane's wait, refusals and reconnects are meters of `redis-runtime` -(`RedisLaneMetrics`, `redis.lane.*`, tag `lane`), so whether the cache stays off `SCRIPT` is a query, -not an assumption. The `DEGRADED` health order ships with `redis-runtime`, which reports the -status (`config/module-defaults/redis-runtime.yml`). +cache의 조건부 쓰기는 같은 계정이지만 자기 lane `CacheScriptLane.CACHE_SCRIPT`에서 돈다 +(`app.capabilities.cache.maximum-script-connections`, `RedisCacheConfig`가 `RedisLaneContribution`으로 기여한다). +`SCRIPT`로 되돌리지 않는다: 그 lane은 멱등성·rate-limit·lease의 예산이고, 부하를 받는 cache가 그것을 가져가면 +안 된다(2026-11-03에 정함). lane마다 기다림, 거절, 재연결은 `redis-runtime`의 meter(`RedisLaneMetrics`, `redis.lane.*`, +tag `lane`)이다. 그래서 cache가 `SCRIPT`를 쓰지 않는지는 짐작이 아니라 조회로 안다. `DEGRADED` health 순서는 +`redis-runtime`과 함께 나가고, 그 leaf가 상태를 알린다(`config/module-defaults/redis-runtime.yml`). -A Cluster transaction runs on one node, so the SDK's `RedisTransactionRunner` derives a routing key -from the watched keys (or an explicit `RedisSlotTag`) and borrows `RedisSdkLane.TRANSACTION`, which -is pinned to its key's owner, on the node that owns that slot. Routed leases are never pooled: a pooled connection is pinned to the previous caller's -node. +Cluster 트랜잭션은 노드 하나에서 돈다. 그래서 SDK의 `RedisTransactionRunner`는 감시한 키(또는 명시한 +`RedisSlotTag`)에서 routing 키를 끌어내고, 그 slot을 가진 노드에서 키의 주인에 고정된 `RedisSdkLane.TRANSACTION`을 +빌린다. route된 lease는 pool에 두지 않는다: pool에 둔 연결은 앞 호출자의 노드에 고정되어 있다. -Settings binding is a recorded exception to capability criterion 4 (one prefix, `StrictSettingsBinder`; -decided 2026-11-03): `app.redis.*` is bound by `redis-runtime` with setters and `validate()`, -because that leaf has no project dependencies and cannot reach `StrictSettingsBinder` (support); -`app.capabilities.*` (cache, lease, rate-limit provider) is bound strictly by this leaf under the -shared capability-selector root; `app.rate-limit.*` is the HTTP boundary's switch that this leaf only -reads. Renaming the keys would break every deployment's environment for no behavioural gain, so the -three trees stay; a new Redis setting goes into one of them, never a fourth. +설정 바인딩은 capability 기준 4(접두어 하나, `StrictSettingsBinder`)의 기록된 예외다(2026-11-03에 정함): +`app.redis.*`는 `redis-runtime`이 setter와 `validate()`로 바인딩한다. 그 leaf는 프로젝트 의존이 없어서 +`StrictSettingsBinder`(support)에 닿을 수 없기 때문이다. `app.capabilities.*`(cache, lease, rate-limit provider)는 이 +leaf가 공용 capability 선택 루트 아래에서 엄격하게 바인딩한다. `app.rate-limit.*`은 이 leaf가 읽기만 하는 HTTP +경계의 스위치다. 키 이름을 바꾸면 동작 이득 없이 모든 배포의 환경이 깨지니 세 트리를 그대로 둔다. 새 Redis 설정은 +그중 하나에 넣고, 네 번째 트리를 만들지 않는다. -`RedisRuntimeSettings` -must never carry a class-level `@ConfigurationProperties`: `RedisRuntimeAutoConfiguration` binds it, so -`APP_REDIS_ENABLED=false` binds no Redis configuration at all. A properties scan that reached this -package would bind it regardless (bootstrap's `@ConfigurationPropertiesScan` lists only -`dev.caskeleton.bootstrap.*` packages). Role selectors (cache binding, session auth-mode, idempotency/lease/rate-limit provider) -choose which capabilities compose; none of them activates Redis, and with the global switch off -this module contributes no bean at all. +`RedisRuntimeSettings`에는 클래스 수준 `@ConfigurationProperties`를 달면 안 된다: `RedisRuntimeAutoConfiguration`이 +그것을 바인딩하므로 `APP_REDIS_ENABLED=false`이면 Redis 설정을 하나도 바인딩하지 않는다. 이 패키지에 닿는 +properties scan은 그래도 그것을 바인딩하게 된다(bootstrap의 `@ConfigurationPropertiesScan`은 +`dev.caskeleton.bootstrap.*` 패키지만 적는다). role 선택자(cache 바인딩, session 인증 모드, 멱등성·lease·rate-limit +provider)는 어떤 capability를 조립할지 고른다. 그중 어느 것도 Redis를 켜지 않고, 전역 스위치가 꺼져 있으면 이 +모듈은 bean을 하나도 기여하지 않는다. diff --git a/src/adapter/outbound/cache-redis/README.md b/src/adapter/outbound/cache-redis/README.md index 515dc06e..47e879e3 100644 --- a/src/adapter/outbound/cache-redis/README.md +++ b/src/adapter/outbound/cache-redis/README.md @@ -1,372 +1,321 @@ -# Redis semantic adapters +# Redis semantic 어댑터 -This module is the **semantic Redis capability adapter**, not a general Redis SDK. +이 모듈은 범용 Redis SDK가 아니라 **semantic Redis capability 어댑터**다. -The Redis implementation is deliberately split into three Gradle leaves: +Redis 구현은 일부러 Gradle leaf 셋으로 나눈다: -- `:adapter:outbound:redis-runtime` (`dev.caskeleton.adapter.outbound.cache.redis.runtime`) — - shipped connection/topology/settings substrate: `RedisRuntimeSettings`, the lane owner, and the - eight `SemanticRedisCommands` this module sends. It knows nothing of the typed SDK. -- `:adapter:outbound:cache-redis` — shipped application-facing cache, rate-limit, lease and - idempotency adapters. -- `:adapter:outbound:redis-sdk` — optional typed/general-purpose SDK. It is not on the default - application runtime graph. +- `:adapter:outbound:redis-runtime`(`dev.caskeleton.adapter.outbound.cache.redis.runtime`) — 출하하는 연결· + topology·설정 기반: `RedisRuntimeSettings`, lane owner, 이 모듈이 보내는 `SemanticRedisCommands` 여덟 개. typed + SDK를 모른다. +- `:adapter:outbound:cache-redis` — 출하하는, 애플리케이션을 향한 cache·rate-limit·lease·멱등성 어댑터. +- `:adapter:outbound:redis-sdk` — 골라 쓰는 typed·범용 SDK. 기본 애플리케이션 runtime 그래프에 없다. -The default application therefore does not acquire the optional SDK's command policy merely by -selecting a semantic Redis capability. Semantic adapters call the runtime's `SemanticRedisCommands` -directly and own their own correctness rules. +그래서 기본 애플리케이션은 semantic Redis capability를 골랐다는 이유만으로 골라 쓰는 SDK의 명령 정책을 얻지 +않는다. semantic 어댑터는 runtime의 `SemanticRedisCommands`를 직접 부르고 자기 정확성 규칙을 스스로 가진다. -## Using it as a capability module — what it provides, the one line, the env keys +## capability 모듈로 쓰기 — 주는 것, 한 줄, env 키 -The web-only default composition does not ship this module: `app-bootstrap/build.gradle` lists it -as a commented `runtimeOnly` line. A service selects it by uncommenting that one line, and deleting -the line removes everything below: +web만 있는 기본 조립은 이 모듈을 싣지 않는다: `app-bootstrap/build.gradle`이 이것을 주석 처리한 `runtimeOnly` 줄로 +적는다. 서비스는 그 한 줄의 주석을 풀어 고르고, 그 줄을 지우면 아래 것이 모두 빠진다: ```groovy runtimeOnly project(':adapter:outbound:cache-redis') // brings :adapter:outbound:redis-runtime ``` -**Provides**, all registered by this module itself: +**주는 것**. 모두 이 모듈이 스스로 등록한다: -- the port implementations the role selectors ask for — `CacheRegionPort` (cache), - `EdgeRateLimitPort` (rate limit), `DistributedLeasePort` (lease), `IdempotencyStorePort` - (idempotency; the application builds the executor over it); -- `RedisCapabilityConfig` (`AutoConfiguration.imports`, after `RedisRuntimeAutoConfiguration`). With - `APP_REDIS_ENABLED=false` neither it nor redis-runtime's `RedisRuntimeAutoConfiguration` contributes a - bean — no settings, client, connection, thread or health contributor. The module pulls no Spring - Data Redis, so there is no Boot Redis auto-configuration to exclude; -- the readiness contribution `RedisReadinessGroupPostProcessor` (this module's `spring.factories`): - `redisRequired` joins the readiness group only when a correctness role selects Redis. Which roles - those are is this module's `RedisCorrectnessRoleSelectors`, registered in the same file as the - runtime's `RedisCorrectnessRequirement` — the runtime asks, it does not list selectors; -- the shipped settings `config/module-defaults/cache-redis.yml` — `app.redis.enabled`, - `app.rate-limit.*`, and the Redis parts of `app.capabilities.*` (cache, lease, rate-limit, - the Redis idempotency store's tuning). The support leaf's `ModuleDefaultsEnvironmentPostProcessor` - loads it below every application setting. +- role 선택자가 요구하는 포트 구현 — `CacheRegionPort`(cache), `EdgeRateLimitPort`(rate limit), + `DistributedLeasePort`(lease), `IdempotencyStorePort`(멱등성. 애플리케이션이 그 위에 executor를 만든다); +- `RedisCapabilityConfig`(`AutoConfiguration.imports`, `RedisRuntimeAutoConfiguration` 뒤). `APP_REDIS_ENABLED=false`이면 + 그것도 redis-runtime의 `RedisRuntimeAutoConfiguration`도 bean을 기여하지 않는다 — 설정, client, 연결, 스레드, + health contributor가 없다. 이 모듈은 Spring Data Redis를 끌어오지 않으니 뺄 Boot Redis 자동 구성도 없다; +- readiness 기여 `RedisReadinessGroupPostProcessor`(이 모듈의 `spring.factories`): 정확성 role이 Redis를 고를 때만 + `redisRequired`가 readiness group에 들어간다. 어떤 role인지는 이 모듈의 `RedisCorrectnessRoleSelectors`가 정하고, + 같은 파일에 runtime의 `RedisCorrectnessRequirement`로 등록한다 — runtime은 묻기만 하고 선택자를 적지 않는다; +- 출하하는 설정 `config/module-defaults/cache-redis.yml` — `app.redis.enabled`, `app.rate-limit.*`, + `app.capabilities.*`의 Redis 부분(cache, lease, rate-limit, Redis 멱등성 store의 조정). support leaf의 + `ModuleDefaultsEnvironmentPostProcessor`가 모든 애플리케이션 설정보다 아래 우선순위로 읽는다. -The application provides `SecretSourcePort` and `Clock`. +애플리케이션이 `SecretSourcePort`와 `Clock`을 준다. -**Env keys** (`src/.env.example`, registry `docs/registries/env-keys.yaml`): +**env 키**(`src/.env.example`, registry `docs/registries/env-keys.yaml`): -| Purpose | Keys | +| 용도 | 키 | |---|---| -| Switch | `APP_REDIS_ENABLED` (default true; `false` turns the present module off) | -| Connection | `APP_REDIS_MODE`, `APP_REDIS_NODES`, `APP_REDIS_DATABASE`, `APP_REDIS_SENTINEL_*`, `APP_REDIS_TLS_*`, `APP_REDIS_AUTHENTICATION_*` (credential references) | -| Namespace | `APP_REDIS_NAMESPACE_ENVIRONMENT`, `APP_REDIS_NAMESPACE_SERVICE`, `APP_REDIS_NAMESPACE_DOMAIN` | -| Roles | `APP_CACHE_CANONICAL_DEFAULT_PROVIDER`, `APP_RATE_LIMIT_PROVIDER`, `APP_LEASE_PROVIDER`, `APP_IDEMPOTENCY_PROVIDER=redis` | -| Role tuning | `APP_CACHE_REDIS_*`, `APP_RATE_LIMIT_*`, `APP_LEASE_REDIS_*`, `APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT` | -| Prod secrets (per selected role) | `APP_CACHE_REDIS_PASSWORD`, `APP_CACHE_REDIS_KEY_HMAC_SECRET`, `APP_RATE_LIMIT_REDIS_PASSWORD`, `APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET`, `APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET`, `APP_LEASE_REDIS_KEY_HMAC_SECRET` | +| 스위치 | `APP_REDIS_ENABLED`(기본 true. `false`이면 있는 모듈을 끈다) | +| 연결 | `APP_REDIS_MODE`, `APP_REDIS_NODES`, `APP_REDIS_DATABASE`, `APP_REDIS_SENTINEL_*`, `APP_REDIS_TLS_*`, `APP_REDIS_AUTHENTICATION_*`(credential 참조) | +| namespace | `APP_REDIS_NAMESPACE_ENVIRONMENT`, `APP_REDIS_NAMESPACE_SERVICE`, `APP_REDIS_NAMESPACE_DOMAIN` | +| role | `APP_CACHE_CANONICAL_DEFAULT_PROVIDER`, `APP_RATE_LIMIT_PROVIDER`, `APP_LEASE_PROVIDER`, `APP_IDEMPOTENCY_PROVIDER=redis` | +| role 조정 | `APP_CACHE_REDIS_*`, `APP_RATE_LIMIT_*`, `APP_LEASE_REDIS_*`, `APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT` | +| 운영 비밀 값(고른 role마다) | `APP_CACHE_REDIS_PASSWORD`, `APP_CACHE_REDIS_KEY_HMAC_SECRET`, `APP_RATE_LIMIT_REDIS_PASSWORD`, `APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET`, `APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET`, `APP_LEASE_REDIS_KEY_HMAC_SECRET` | -## Activation and composition +## 켜기와 조립 -Redis is on when this module is present. It has one off switch: +이 모듈이 있으면 Redis가 켜진다. 끄는 스위치는 하나다: -`app.redis.enabled=false` / `APP_REDIS_ENABLED=false` (default `true`). +`app.redis.enabled=false` / `APP_REDIS_ENABLED=false`(기본 `true`). -A semantic role does **not** activate Redis by itself: with the switch off this module -contributes no bean at all, whatever a role selector says. Redis idempotency refuses -`app.capabilities.idempotency.key-version` other than 1 at startup (no dual-read yet). +semantic role 혼자서는 Redis를 켜지 **않는다**: 스위치가 꺼져 있으면 role 선택자가 무엇을 말하든 이 모듈은 bean을 +하나도 기여하지 않는다. Redis 멱등성은 기동 때 1이 아닌 `app.capabilities.idempotency.key-version`을 거절한다(아직 +이중 읽기가 없다). -Current role selectors are: +지금의 role 선택자: - cache: `app.capabilities.cache.bindings.default=redis` - rate limit: `app.capabilities.rate-limit.provider=redis` - lease: `app.capabilities.lease.provider=redis` -- idempotency: `app.capabilities.idempotency.provider=redis` +- 멱등성: `app.capabilities.idempotency.provider=redis` -Only selected capabilities contribute their application port bean. +고른 capability만 자기 애플리케이션 포트 bean을 기여한다. -All capabilities render below the single namespace in `app.redis.namespace.*`. Per-capability -namespace settings are deprecated because they made ACL fencing inconsistent. +모든 capability는 `app.redis.namespace.*`의 namespace 하나 아래에 키를 만든다. capability별 namespace 설정은 ACL +fencing을 들쭉날쭉하게 만들어서 폐기 예정이다. -## Runtime ownership +## runtime 소유 -`:adapter:outbound:redis-runtime` owns: +`:adapter:outbound:redis-runtime`이 가진다: -- topology selection (standalone / sentinel / cluster), -- role-aware credentials, -- connection lifecycle and bounded lane leasing, -- the low-level command gateway, +- topology 고르기(standalone / sentinel / cluster), +- role을 아는 credential, +- 연결 lifecycle과 한계 있는 lane 대여, +- 낮은 수준 명령 gateway, - health, -- TLS and connection/client timeouts. +- TLS와 연결·client timeout. -`RedisRuntimeOwner` stops admission before shutdown, drains outstanding leases within a bounded -budget, closes connections, then closes the client. +`RedisRuntimeOwner`는 종료 전에 admission을 멈추고, 한계 있는 예산 안에서 남은 lease를 비우고, 연결을 닫은 뒤 +client를 닫는다. -Connection lane limits and command queue limits are different contracts. In particular: +연결 lane 한계와 명령 queue 한계는 다른 계약이다. 특히: -- `app.redis.capacity.maximum-in-flight-commands` bounds the per-connection command queue. -- `app.redis.capacity.maximum-script-connections` bounds physical SCRIPT lane connections - (default 8). Idempotency, rate limiting and leases share them. -- `app.capabilities.cache.maximum-script-connections` (`APP_CACHE_REDIS_MAXIMUM_SCRIPT_CONNECTIONS`) - bounds the cache's own script lane (`CacheScriptLane`, default 4), contributed only when the cache - binding is `redis`. See "Why the cache has its own script lane" below. -- `app.redis.lifecycle.acquire-timeout` (default 2s) is how long a borrow waits for a returned - connection when its lane is full. +- `app.redis.capacity.maximum-in-flight-commands`는 연결마다 명령 queue를 묶는다. +- `app.redis.capacity.maximum-script-connections`는 SCRIPT lane의 물리 연결을 묶는다(기본 8). 멱등성, rate limit, + lease가 그것을 같이 쓴다. +- `app.capabilities.cache.maximum-script-connections`(`APP_CACHE_REDIS_MAXIMUM_SCRIPT_CONNECTIONS`)는 cache 자신의 + script lane(`CacheScriptLane`, 기본 4)을 묶고, cache 바인딩이 `redis`일 때만 기여한다. 아래 「cache가 자기 script + lane을 가지는 이유」를 본다. +- `app.redis.lifecycle.acquire-timeout`(기본 2s)은 lane이 찼을 때 대여가 돌아올 연결을 기다리는 시간이다. -The second limit exists so a burst of semantic Lua calls cannot turn a command-capacity number such -as 64 into 64 physical Redis sockets. It bounds connections, not callers: a lease holds a connection -for one script round trip, so the ninth concurrent caller waits for one to come back instead of -being refused. Only a borrow still waiting when the acquire timeout runs out is refused, and that -refusal is a `RedisCommandRejectedException` whose metadata is not ambiguous — no command was ever -sent. +두 번째 한계는 semantic Lua 호출이 몰려도 64 같은 명령 용량 숫자가 Redis 물리 socket 64개가 되지 않게 하려고 +있다. 호출자가 아니라 연결을 묶는다: lease는 script 왕복 한 번 동안 연결을 쥐니, 아홉 번째 동시 호출자는 거절되지 +않고 연결 하나가 돌아오기를 기다린다. acquire timeout이 다 됐을 때 아직 기다리는 대여만 거절하고, 그 거절은 +metadata가 모호하지 않은 `RedisCommandRejectedException`이다 — 명령을 한 번도 보내지 않았다. -## Script ACL startup probe +## script ACL 기동 probe -Rate limiting, distributed leases and Redis idempotency execute Lua programs. If any of those roles -select Redis, the composition root runs a startup probe on the SCRIPT lane: +rate limit, 분산 lease, Redis 멱등성은 Lua program을 실행한다. 그 role 중 하나라도 Redis를 고르면 조립 루트가 +SCRIPT lane에서 기동 probe를 돌린다: -1. `SCRIPT LOAD` a program that calls the commands the semantic scripts depend on — `TIME`, then - `HSET`/`PEXPIRE`/`HGET`/`DEL` on its own probe key, which it deletes; -2. execute it through `EVALSHA`; -3. require the expected reply (the value it wrote reads back). +1. semantic script가 기대는 명령을 부르는 program을 `SCRIPT LOAD`한다 — `TIME`, 그다음 자기 probe 키에 + `HSET`/`PEXPIRE`/`HGET`/`DEL`을 하고 그 키를 지운다; +2. `EVALSHA`로 실행한다; +3. 기대한 응답(쓴 값이 다시 읽힌다)을 요구한다. -Redis checks a script's inner commands against the ACL only when they run, so a probe that ran -nothing proved `EVALSHA` and nothing else: an account granted by category (`@read`/`@write`) lacks -`TIME` and failed every rate-limit and idempotency request after a clean start. A deployment whose -effective Redis account lacks script permissions fails during startup rather than at the first -request. +Redis는 script 안의 명령을 돌 때만 ACL과 대조한다. 그래서 아무것도 돌리지 않는 probe는 `EVALSHA`만 증명했다: +category로(`@read`/`@write`) 권한을 준 계정에는 `TIME`이 없었고, 깨끗하게 시작한 뒤 모든 rate-limit·멱등성 요청이 +실패했다. 실제 Redis 계정에 script 권한이 없는 배포는 첫 요청이 아니라 기동 중에 실패한다. -A cache-only deployment (`app.capabilities.cache.bindings.default=redis`, no correctness role) runs -a narrower probe: a program that calls only `SET`/`GET`, the commands the cache's conditional-write -programs use. A server that answers and refuses it fails startup — every conditional record would -otherwise come back degraded while plain reads looked healthy. A Redis that cannot be reached at -startup is logged as a warning and the pod starts: a cache outage degrades, it never stops a pod. +cache만 쓰는 배포(`app.capabilities.cache.bindings.default=redis`, 정확성 role 없음)는 더 좁은 probe를 돌린다: cache의 +조건부 쓰기 program이 쓰는 명령인 `SET`/`GET`만 부르는 program이다. 답은 하지만 그것을 거절하는 서버는 기동을 +실패시킨다 — 그렇지 않으면 보통 읽기는 건강해 보이는데 모든 조건부 기록이 degraded로 돌아온다. 기동 때 닿을 수 +없는 Redis는 경고로 남기고 pod를 시작한다: cache 장애는 성능을 떨어뜨릴 뿐 pod를 멈추지 않는다. -At runtime, `redisRequired` (redis-runtime) probes the SCRIPT lane too when a script role is -selected, so a broken advanced-account credential makes the pod unready instead of leaving the -regular-lane PING to report UP. +런타임에는 script role을 골랐으면 `redisRequired`(redis-runtime)가 SCRIPT lane도 probe한다. 그래서 advanced 계정 +credential이 깨지면 regular lane PING이 UP을 알리게 두지 않고 pod를 unready로 만든다. -## Cache semantics +## cache 뜻 -`RedisCacheRegionAdapter` implements the application cache port. +`RedisCacheRegionAdapter`가 애플리케이션 cache 포트를 구현한다. -Important contracts: +중요한 계약: -- value entries have soft and hard expiry; -- negative entries use the shorter negative TTL; -- Redis physical TTL is the hard expiry; -- cache outages degrade to the application's typed unavailable/degraded outcomes; -- identifiers are rendered through a keyed digest before entering the keyspace. +- 값 항목에는 soft·hard 만료가 있다; +- 부정 항목은 더 짧은 부정 TTL을 쓴다; +- Redis 물리 TTL은 hard 만료다; +- cache 장애는 애플리케이션의 타입 있는 unavailable·degraded 결과로 떨어진다; +- 식별자는 keyspace에 들어가기 전에 키 있는 digest를 거친다. -### Conditional replacement +### 조건부 바꾸기 -`ONLY_IF_OBSERVED` is an atomic server-side compare-and-replace. +`ONLY_IF_OBSERVED`는 서버 쪽 원자 compare-and-replace다. -Every lookup returns a `CacheWriteCondition` naming the state it saw — `absent`, `vacant:<digest>` -(an invalidation marker, an entry of an older region generation, an expired entry) or -`present:<digest>`. A record that carries the condition applies only while the key is still in that -state (registered program, cache script lane). This is what rejects a source load that began before an -invalidation and finished after it. +모든 조회는 본 상태를 이름으로 대는 `CacheWriteCondition`을 돌려준다 — `absent`, `vacant:<digest>`(무효화 표지, 옛 +region generation의 항목, 만료된 항목), `present:<digest>`. 그 조건을 실은 기록은 키가 아직 그 상태일 때만 적용한다 +(등록된 program, cache script lane). 무효화 전에 시작해 무효화 뒤에 끝난 source 읽기를 이것이 거절한다. -A hit also returns an opaque SHA-1 observation token over the stored bytes. SHA-1 here is **not a -security primitive**; it is used only because Redis Lua exposes `redis.sha1hex`, allowing the -script to perform: +hit는 저장된 바이트 위의 불투명한 SHA-1 관찰 token도 돌려준다. 여기서 SHA-1은 **보안 기본 장치가 아니다**. Redis +Lua가 `redis.sha1hex`를 내놓아서 script가 아래를 할 수 있기 때문에 쓴다: `GET current -> compare observation -> SET replacement PX ttl` -inside one Redis execution. A stale source load therefore cannot overwrite a value written between -observation and replacement. +이것을 Redis 실행 한 번 안에서 한다. 그래서 낡은 source 읽기는 관찰과 바꾸기 사이에 쓰인 값을 덮어쓸 수 없다. -`ONLY_IF_SOURCE_REVISION_NEWER` is an atomic server-side revision comparison. The order is the -port's `CacheSourceRevisionOrder` (application-core): a non-negative decimal integer without leading -zeros (a row version, an offset, epoch millis), compared numerically at any length. Any other -revision is refused by `CacheRecordMetadata` itself, for every provider, because text order would -rank revision `10` below `9`. The Lua program reimplements the order (the comparison and the write -must be one step); `CacheRegionContract`, run over the fixture and a real server, keeps it equal. The script reads the stored envelope's -schema version, revision and generation and writes only when: +`ONLY_IF_SOURCE_REVISION_NEWER`는 서버 쪽 원자 revision 비교다. 순서는 포트의 `CacheSourceRevisionOrder` +(application-core)다: 앞자리 0이 없는 음이 아닌 10진 정수(row version, offset, epoch millis)이고, 길이와 관계없이 +숫자로 비교한다. 그 밖의 revision은 모든 provider에서 `CacheRecordMetadata`가 직접 거절한다. 글자 순서로는 revision +`10`이 `9`보다 아래가 되기 때문이다. Lua program은 그 순서를 다시 구현한다(비교와 쓰기가 한 단계여야 한다). +fixture와 실제 서버에 대고 도는 `CacheRegionContract`가 둘을 같게 지킨다. script는 저장된 envelope의 schema version, +revision, generation을 읽고 다음일 때만 쓴다: -- nothing is stored, or the stored entry is from an older region generation (already invalidated); -- otherwise, the stored revision is a decimal integer and the caller's is strictly greater. +- 아무것도 저장돼 있지 않거나, 저장된 항목이 옛 region generation에서 왔다(이미 무효화됨); +- 아니면, 저장된 revision이 10진 정수이고 호출자의 것이 엄격하게 크다. -Everything else — an equal or smaller revision, a stored revision with no numeric order (for -example one written by `UPSERT` as `rev-1`), another schema version, a generation newer than the -writer knows — is `NOT_RECORDED_CONDITION`. +그 밖의 모든 것 — 같거나 작은 revision, 숫자 순서가 없는 저장 revision(예: `UPSERT`가 `rev-1`로 쓴 것), 다른 +schema version, 쓰는 쪽이 아는 것보다 새 generation — 은 `NOT_RECORDED_CONDITION`이다. -Both conditional intents, and any record carrying a write condition, run registered scripts, so -they run on the scripting account (the advanced account when one is configured, the application -account otherwise), on the cache's own script lane. The application account is not granted -`EVALSHA`; on the REGULAR lane every conditional write came back `INDETERMINATE`. Unconditioned -`UPSERT` and `ONLY_IF_ABSENT` stay on the REGULAR lane. +두 조건부 의도와, 쓰기 조건을 실은 모든 기록은 등록된 script를 돌리므로 script 계정(advanced 계정을 설정했으면 그 +계정, 아니면 애플리케이션 계정)으로, cache 자신의 script lane에서 돈다. 애플리케이션 계정에는 `EVALSHA`를 주지 +않는다. REGULAR lane에서는 모든 조건부 쓰기가 `INDETERMINATE`로 돌아왔다. 조건 없는 `UPSERT`와 `ONLY_IF_ABSENT`는 +REGULAR lane에 남는다. -### Why the cache has its own script lane +### cache가 자기 script lane을 가지는 이유 -Recording with the condition a lookup returned is the normal way to use this port, so nearly every -cache fill is a script. On the runtime's SCRIPT lane those fills shared eight connections per pod -with idempotency claims, rate-limit evaluations and lease calls, and a timed-out lease is discarded -rather than pooled, so each timeout also cost a reconnect. A slow Redis or a burst of misses after a -region invalidation filled the lane with cache work; an idempotency claim then waited out its -timeout and answered `UNAVAILABLE`, and a rate-limit call fell to its failure policy. The cache is a -speed feature that may degrade; idempotency, rate limiting and leases are correctness features that -must not (review 2026-11-03 README §4, RR-04-02). +조회가 돌려준 조건으로 기록하는 것이 이 포트를 쓰는 보통 방법이라서 거의 모든 cache 채우기가 script다. runtime의 +SCRIPT lane에서 그 채우기는 pod마다 연결 여덟 개를 멱등성 claim, rate-limit 평가, lease 호출과 같이 썼다. timeout이 +난 lease는 pool로 돌아가지 않고 버려지니, timeout마다 재연결 비용도 들었다. Redis가 느리거나 region 무효화 뒤 miss가 +몰리면 lane이 cache 일로 찼다. 그러면 멱등성 claim은 timeout까지 기다렸다가 `UNAVAILABLE`로 답했고, rate-limit +호출은 실패 정책으로 떨어졌다. cache는 성능이 떨어져도 되는 속도 기능이고, 멱등성·rate limit·lease는 떨어지면 안 +되는 정확성 기능이다(review 2026-11-03 README §4, RR-04-02). -So `CacheScriptLane.CACHE_SCRIPT` is a lane of its own — the same scripting account, its own -connections, its own ceiling (`app.capabilities.cache.maximum-script-connections`, default 4). A cache -that runs out of them degrades (`DEGRADED_UNAVAILABLE`, nothing sent) without touching the SCRIPT -lane. Alternatives not taken: a per-capability permit cap inside the shared SCRIPT lane (still one -pool of connections and one reconnect cost), and running the cache programs on the REGULAR lane -(grants the application account `EVALSHA`, which the account split exists to withhold). +그래서 `CacheScriptLane.CACHE_SCRIPT`는 자기 lane이다 — 같은 script 계정, 자기 연결, 자기 상한 +(`app.capabilities.cache.maximum-script-connections`, 기본 4). 연결이 바닥난 cache는 SCRIPT lane을 건드리지 않고 +성능을 떨어뜨린다(`DEGRADED_UNAVAILABLE`, 보낸 것 없음). 고르지 않은 대안: 공용 SCRIPT lane 안의 capability별 허가 +상한(여전히 연결 pool 하나와 재연결 비용 하나), cache program을 REGULAR lane에서 돌리기(애플리케이션 계정에 +`EVALSHA`를 준다. 계정을 나눈 것은 바로 그것을 주지 않으려는 것이다). -Whether the split holds under load is visible per lane. With a `MeterRegistry` in the context, -`redis-runtime` registers these for every lane it pools — `REGULAR`, `SCRIPT`, `CACHE_SCRIPT` and the -typed SDK's — tagged `lane=<name>` (`RedisLaneMetrics`; rows in `docs/registries/metrics.yaml`): +부하 아래에서 이 분리가 지켜지는지는 lane마다 보인다. context에 `MeterRegistry`가 있으면 `redis-runtime`이 pool로 두는 +모든 lane — `REGULAR`, `SCRIPT`, `CACHE_SCRIPT`, typed SDK의 lane — 에 대해 아래를 `lane=<name>` tag로 등록한다 +(`RedisLaneMetrics`. 행은 `docs/registries/metrics.yaml`): -| Meter | Type | Read it as | +| meter | 타입 | 읽는 법 | | --- | --- | --- | -| `redis.lane.acquire.wait.seconds` (`outcome` = `admitted`/`refused`) | timer, histogram | how long a borrow queued for a connection; a growing admitted p99 comes before refusals | -| `redis.lane.acquire.refused.total` (`reason` = `saturated`/`closing`/`interrupted`/`connect_failed`) | counter | a borrow that got no connection, nothing sent; `saturated` on `SCRIPT` is the starvation this lane exists to prevent | -| `redis.lane.connections.opened.total` | counter | new connections; after warm-up a pooled lane opens one only to replace a discarded one. A routed lease (a Cluster `TRANSACTION` borrow) is opened for each borrow and closed after it without being counted as discarded, so on that lane a steady rate is normal use, not reconnects | -| `redis.lane.connections.discarded.total` (`reason` = `invalidated`/`broken`) | counter | connections closed instead of pooled — `invalidated` is a timed-out or failed call (the lease is not reused), and is what the reconnects replace | -| `redis.lane.connections.active`, `redis.lane.connections.pending` | gauge | connections lent out now; borrows waiting now | +| `redis.lane.acquire.wait.seconds`(`outcome` = `admitted`/`refused`) | timer, histogram | 대여가 연결을 얼마나 기다렸나. 거절보다 먼저 admitted p99가 늘어난다 | +| `redis.lane.acquire.refused.total`(`reason` = `saturated`/`closing`/`interrupted`/`connect_failed`) | counter | 연결을 얻지 못한 대여, 보낸 것 없음. `SCRIPT`의 `saturated`가 이 lane이 막으려는 굶주림이다 | +| `redis.lane.connections.opened.total` | counter | 새 연결. 데운 뒤에는 pool로 두는 lane이 버린 연결을 대신할 때만 연다. route된 lease(Cluster `TRANSACTION` 대여)는 대여마다 열고 그 뒤에 닫지만 버린 것으로 세지 않는다. 그래서 그 lane에서 꾸준한 비율은 재연결이 아니라 보통 사용이다 | +| `redis.lane.connections.discarded.total`(`reason` = `invalidated`/`broken`) | counter | pool로 두지 않고 닫은 연결 — `invalidated`는 timeout이 났거나 실패한 호출(그 lease는 다시 쓰지 않는다)이고, 재연결이 대신하는 것이 이것이다 | +| `redis.lane.connections.active`, `redis.lane.connections.pending` | gauge | 지금 빌려준 연결, 지금 기다리는 대여 | -Every counter series exists from startup at zero, so an alert on "refusals above zero" sees the first -one. A lane refusal is also logged, per call, by `RedisSemanticFailureLogger`. +모든 counter series는 기동 때부터 0으로 있으니, 「거절이 0보다 많다」 경보가 첫 거절을 본다. lane 거절은 +`RedisSemanticFailureLogger`도 호출마다 남긴다. -### Key invalidation +### 키 무효화 -`invalidate(key)` writes a short-lived marker (`GET`, then `SET … PX softTtl` on the REGULAR lane) -instead of deleting the key. While the marker lives, a record whose condition came from an earlier -lookup, an unconditioned `ONLY_IF_ABSENT`, and an unconditioned `ONLY_IF_SOURCE_REVISION_NEWER` are -`NOT_RECORDED_CONDITION`; a fresh lookup returns a `vacant:` condition that records normally; -unconditioned `UPSERT` overwrites it. Limit: the marker lives for the soft TTL, so a source load -slower than that, carrying an `absent` condition, can still land after it. +`invalidate(key)`는 키를 지우지 않고 짧게 사는 표지를 쓴다(REGULAR lane에서 `GET`, 그다음 `SET … PX softTtl`). 표지가 +사는 동안 앞 조회에서 온 조건을 실은 기록, 조건 없는 `ONLY_IF_ABSENT`, 조건 없는 `ONLY_IF_SOURCE_REVISION_NEWER`는 +`NOT_RECORDED_CONDITION`이다. 새 조회는 보통으로 기록되는 `vacant:` 조건을 돌려준다. 조건 없는 `UPSERT`는 표지를 +덮어쓴다. 한계: 표지는 soft TTL 동안 산다. 그래서 그보다 느리고 `absent` 조건을 실은 source 읽기는 여전히 그 뒤에 +들어올 수 있다. -### Stampede +### stampede -There is no stampede protection and no TTL jitter. Concurrent misses on one key each load from the -source. Single-flight, where a source cannot take the burst, is the caller's. +stampede 보호도 TTL jitter도 없다. 한 키에 동시에 난 miss는 각자 source에서 읽는다. source가 몰림을 감당하지 못하면 +single-flight는 호출자의 몫이다. -### Region invalidation +### region 무효화 -Region invalidation increments a generation key; it never scans/deletes the keyspace. +region 무효화는 generation 키를 올린다. keyspace를 scan하거나 지우지 않는다. -Each adapter instance caches the observed generation only for the positive soft TTL. After that -bounded interval it rechecks the server generation. This keeps ordinary cache hits from paying an -extra Redis round trip while ensuring an invalidation issued by another process eventually becomes -visible to every instance. +어댑터 인스턴스마다 본 generation을 양의 soft TTL 동안만 cache한다. 그 한계 있는 시간이 지나면 서버 generation을 다시 +본다. 그래서 보통 cache hit는 Redis 왕복을 더 치르지 않으면서, 다른 프로세스가 낸 무효화도 결국 모든 인스턴스에 +보이게 된다. -## Rate-limit semantics +## rate-limit 뜻 -The rate-limit adapter supports the configured fixed-window, sliding-counter and token-bucket -policies through registered Lua scripts. +rate-limit 어댑터는 설정한 fixed-window, sliding-counter, token-bucket 정책을 등록된 Lua script로 지원한다. -Time is taken from Redis `TIME`, not the caller JVM clock. Multiple application nodes therefore -make the same distributed decision even if their local clocks differ. +시간은 호출자 JVM 시계가 아니라 Redis `TIME`에서 가져온다. 그래서 애플리케이션 노드 여럿의 로컬 시계가 달라도 같은 +분산 판단을 한다. -Script TTLs are computed as integer milliseconds in Java and passed as exact Lua arguments. -`cleanup-grace` is part of the physical state TTL. There is no exposed -`maximum-clock-regression` knob because Redis is the time authority for this state. +script TTL은 Java에서 정수 밀리초로 계산해 정확한 Lua 인자로 넘긴다. `cleanup-grace`는 물리 상태 TTL의 일부다. 이 +상태의 시간 정본은 Redis이므로 `maximum-clock-regression` 손잡이는 내놓지 않는다. -Rate-limit failures remain fail-closed according to the application contract. A connection that -could not be opened is `UNAVAILABLE_BEFORE_SEND` (nothing was sent). The caller's remaining -deadline bounds the lane wait and the reply wait; opening a new connection is still bounded only by -the driver's connect timeout. +rate-limit 실패는 애플리케이션 계약대로 실패하면 닫힌다. 열지 못한 연결은 `UNAVAILABLE_BEFORE_SEND`다(보낸 것 없음). +호출자의 남은 deadline이 lane 대기와 응답 대기를 묶는다. 새 연결 열기는 여전히 driver의 connect timeout만 묶는다. -Evaluation deduplication is **not implemented**: `RateLimitRequest.evaluationId` is ignored, so a -retry after `NO_MUTATION_CONFIRMED` is charged again. Policies default to -`RateLimitEvaluationDedupPolicy.disabled()`, and the adapter refuses a policy that enables it. +평가 중복 제거는 **구현하지 않았다**: `RateLimitRequest.evaluationId`는 무시하므로 `NO_MUTATION_CONFIRMED` 뒤의 +재시도는 다시 센다. 정책 기본값은 `RateLimitEvaluationDedupPolicy.disabled()`이고, 어댑터는 그것을 켠 정책을 +거절한다. -## Idempotency semantics +## 멱등성 뜻 -The Redis idempotency adapter stores owner-safe claim state and executes claim/transition/release -programs atomically. `RedisIdempotencyConfig` contributes only the `IdempotencyStorePort`; the -`IdempotencyExecutor` and its lifecycle policy (lease, replay TTL, retention, codec id, policy -revision) come from app-bootstrap `IdempotencySettings`. This leaf reads only `key-version` and -`command-timeout` under `app.capabilities.idempotency`. +Redis 멱등성 어댑터는 소유자를 안전하게 지키는 claim 상태를 저장하고 claim·전이·놓아주기 program을 원자적으로 +실행한다. `RedisIdempotencyConfig`는 `IdempotencyStorePort`만 기여한다. `IdempotencyExecutor`와 그 lifecycle 정책 +(lease, 재생 TTL, 보존, codec id, 정책 revision)은 `composition:idempotency`의 `IdempotencySettings`에서 온다. 이 +leaf는 `app.capabilities.idempotency` 아래의 `key-version`과 `command-timeout`만 읽는다. -`renew` has its own program rather than the generic transition. Renewal keeps the record in -`EXECUTING`, and the transition answers "already in the target state" before it reads the revision -(that answer exists for a retry whose first reply was lost), so a renewal sent through it was always -`ALREADY_RENEWED_SAME_OPERATION` and never moved the lease. That answer is given only to the handle -the transition was applied from — the record one revision past it, with `lastKind` (written by the -claim, renew and transition programs) naming that transition. Another handle of the same -attempt (one from before a takeover, or the current one a replayed claim returned) used to be told a -start was applied and ran the action a second time (round6 RR6-02-01), and to be told a completion -or failure that followed a takeover was its own (owner decision 2026-11-06); it is now `NOT_OWNER` -or `NOT_CLAIMED`/`NOT_IN_PROGRESS`, as in the PostgreSQL store. Without the kind, a start through the -handle a renewal was applied from was confirmed too — renewal leaves the record `EXECUTING` one -revision past that handle (round8 RR8-04-02); it is `NOT_OWNER`. A failure from the handle that -applied one, asking for the other disposition, is `OPERATION_CONFLICT` (it fell through to -`NOT_OWNER`); the record keeps no retention, so another retention is confirmed (owner decision -2026-11-07). The renew program checks owner, -operation, revision and state, then extends `leaseUntil` from Redis `TIME` and bumps the revision. -A lost renewal reply is recognised by what the renewal recorded — the revision it started from and -the lease it asked for: the same lease is `ALREADY_RENEWED_SAME_OPERATION` with the current handle, -a different lease is `OPERATION_CONFLICT`. +`renew`는 범용 전이가 아니라 자기 program을 가진다. 갱신은 레코드를 `EXECUTING`에 두고, 전이는 revision을 읽기 전에 +「이미 목표 상태다」로 답한다(그 답은 첫 응답을 잃은 재시도를 위해 있다). 그래서 전이를 거쳐 보낸 갱신은 언제나 +`ALREADY_RENEWED_SAME_OPERATION`이었고 lease를 옮기지 못했다. 그 답은 전이를 적용한 handle에게만 준다 — 그 handle은 +한 revision 뒤의 레코드이고, `lastKind`(claim·renew·전이 program이 쓴다)가 그 전이를 이름으로 댄다. 같은 시도의 +다른 handle(넘겨받기 전의 것, 또는 재생된 claim이 돌려준 지금의 것)은 예전에 시작이 적용됐다는 답을 받아 action을 +두 번 돌렸고(round6 RR6-02-01), 넘겨받기 뒤에 온 완료나 실패를 자기 것이라고 들었다(소유자 결정 2026-11-06). 이제는 +PostgreSQL store처럼 `NOT_OWNER`나 `NOT_CLAIMED`/`NOT_IN_PROGRESS`다. kind가 없으면 갱신을 적용한 handle로 하는 +시작도 확인받았다 — 갱신은 레코드를 그 handle보다 한 revision 뒤의 `EXECUTING`에 둔다(round8 RR8-04-02). 이제는 +`NOT_OWNER`다. 실패를 적용한 handle이 다른 disposition을 요구하면 `OPERATION_CONFLICT`다(예전에는 `NOT_OWNER`로 +떨어졌다). 레코드는 retention을 두지 않으므로 다른 retention은 확인해 준다(소유자 결정 2026-11-07). renew program은 +owner, operation, revision, 상태를 검사한 뒤 Redis `TIME`으로 `leaseUntil`을 늘리고 revision을 올린다. 잃은 갱신 +응답은 그 갱신이 기록한 것 — 시작한 revision과 요청한 lease — 으로 알아본다: 같은 lease면 지금 handle과 함께 +`ALREADY_RENEWED_SAME_OPERATION`, 다른 lease면 `OPERATION_CONFLICT`다. -Every program compares the operation a call names with the one the record was claimed under, right -after the owner token: another operation is `OPERATION_CONFLICT` and changes nothing. The PostgreSQL -store and the in-memory fake used to apply it; they now answer the same (owner decision 2026-11-06, -`IdempotencyStoreContract`). The release program also checks the handle's revision, as the -transition does: owner token and operation alone let the handle from before the same attempt took -its claim over release the claim it holds now. A release deletes the record, so a release that finds -no record — its own retry, an expired record, one never claimed — is `ABSENT`; it used to be -confirmed as `ALREADY_RELEASED_SAME_OPERATION`, which the store cannot know. +모든 program은 owner token 바로 뒤에서 호출이 댄 operation과 레코드를 claim한 operation을 비교한다: 다른 operation이면 +`OPERATION_CONFLICT`이고 아무것도 바꾸지 않는다. PostgreSQL store와 메모리 fake는 예전에 그것을 적용했다. 이제 같은 +답을 한다(소유자 결정 2026-11-06, `IdempotencyStoreContract`). 놓아주기 program도 전이처럼 handle의 revision을 +검사한다: owner token과 operation만으로는 같은 시도가 claim을 넘겨받기 전의 handle이 지금 쥔 claim을 놓아줄 수 +있었다. 놓아주기는 레코드를 지우므로, 레코드를 찾지 못한 놓아주기 — 자기 재시도, 만료된 레코드, claim한 적 없는 +것 — 는 `ABSENT`다. 예전에는 store가 알 수 없는 `ALREADY_RELEASED_SAME_OPERATION`으로 확인해 줬다. -A lease that runs out is taken over only from a claim that never started or an attempt marked -retryable — by whoever claims next, the holder's own attempt included: the claim program checks for -a takeover before it replays a same-owner claim, so an attempt whose start was refused takes its -claim over when it claims again instead of being replayed the claim and refused until the record -expired (round6 RR6-02-01). A record still `EXECUTING` when its lease ran out has an unknown effect: the claim -program answers `RECOVERY_REQUIRED` and leaves the record as it is, because the holder may still be -running. The holder's late completion or failure goes through the transition program as it would -have inside the lease, and the next claim replays or retries it; only the lease is final — `RENEW` -refuses one that has run out with `LEASE_EXPIRED` (not `NOT_OWNER`: the holder still completes the -record, re-review 2026-11-04 RR5-01-02), and `INSPECT` reports somebody else's expired execution as -`RECOVERY_REQUIRED`. The transition program reads the lease for a start only: a claim whose lease -ran out is answered `LEASE_EXPIRED` and not started, so nothing runs and the next claim takes it -over (it used to start, and every other request was then told "recovery required" for work that -had just begun; README 15). The PostgreSQL store answers the same; the shared `IdempotencyStoreContract` -holds both to it on a real server (re-review 2026-11-04 RR-01-11 — this store used to take the -record over and run the work a second time; owner decision 2026-11-04 — both stores then abandoned -the record, and a holder that outlived its lease lost its result). +lease가 끝나면 시작하지 않은 claim이나 재시도할 수 있다고 표시한 시도에서만 넘겨받는다 — 다음에 claim하는 누구든, +쥔 쪽 자신의 시도도 포함한다: claim program은 같은 owner의 claim을 재생하기 전에 넘겨받기를 검사한다. 그래서 시작이 +거절된 시도는 다시 claim할 때 레코드가 만료될 때까지 claim을 재생받고 거절당하는 대신 자기 claim을 넘겨받는다 +(round6 RR6-02-01). lease가 끝났을 때 아직 `EXECUTING`인 레코드는 효과를 모른다: claim program은 +`RECOVERY_REQUIRED`로 답하고 레코드를 그대로 둔다. 쥔 쪽이 아직 돌고 있을 수 있기 때문이다. 쥔 쪽의 늦은 완료나 +실패는 lease 안이었을 때처럼 전이 program을 거치고, 다음 claim이 그것을 재생하거나 다시 시도한다. 끝난 것은 +lease뿐이다 — `RENEW`는 끝난 lease를 `LEASE_EXPIRED`로 거절하고(`NOT_OWNER`가 아니다: 쥔 쪽이 여전히 레코드를 +완료한다, re-review 2026-11-04 RR5-01-02), `INSPECT`는 남의 만료된 실행을 `RECOVERY_REQUIRED`로 알린다. 전이 +program은 시작할 때만 lease를 읽는다: lease가 끝난 claim은 `LEASE_EXPIRED`로 답하고 시작하지 않는다. 그래서 아무것도 +돌지 않고 다음 claim이 넘겨받는다(예전에는 시작했고, 그 뒤 다른 모든 요청이 막 시작한 일에 대해 「복구 필요」를 +들었다. README 15). PostgreSQL store도 같은 답을 한다. 공용 `IdempotencyStoreContract`가 둘을 실제 서버에서 거기에 +맞춘다(re-review 2026-11-04 RR-01-11 — 이 store는 예전에 레코드를 넘겨받아 일을 두 번 돌렸다. 소유자 결정 +2026-11-04 — 그 뒤 두 store 모두 레코드를 버렸고, lease보다 오래 산 쥔 쪽은 결과를 잃었다). -The record key lives for the processing lease plus the replay TTL (`afterLease`, kept on the record), -and a renewal stretches it to the new lease plus that margin. With the replay TTL alone, a replay -TTL shorter than the lease dropped the key of a running operation and the next claim ran it again, -and one equal to the lease left no record to answer `RECOVERY_REQUIRED` from (RR-03-11). +레코드 키는 처리 lease에 재생 TTL을 더한 만큼 산다(`afterLease`, 레코드에 둔다). 갱신은 그것을 새 lease에 그 여유를 +더한 만큼 늘린다. 재생 TTL만으로 두면, lease보다 짧은 재생 TTL은 돌고 있는 operation의 키를 버려 다음 claim이 그것을 +다시 돌렸고, lease와 같은 재생 TTL은 `RECOVERY_REQUIRED`로 답할 레코드를 남기지 않았다(RR-03-11). -Redis `TIME` determines lease deadlines. A failure after a command may have executed is returned -as an indeterminate outcome; the adapter does not convert an ambiguous write into a clean -unavailable result that would invite duplicate execution. +lease 기한은 Redis `TIME`이 정한다. 명령이 실행됐을 수 있는 뒤의 실패는 결과를 모름으로 돌려준다. 어댑터는 모호한 +쓰기를 중복 실행을 부르는 깨끗한 unavailable 결과로 바꾸지 않는다. -## Lease semantics +## lease 뜻 -The distributed lease adapter uses owner/operation-safe Lua programs for acquire, inspect, renew and -release. +분산 lease 어댑터는 acquire, inspect, renew, release에 owner·operation을 안전하게 지키는 Lua program을 쓴다. -Unknown mutation outcomes remain indeterminate. Local validity is shortened by the configured drift -budget; a successful renew is the only event that extends it. +결과를 모르는 변경은 모름으로 남는다. 로컬 유효 시간은 설정한 drift 예산만큼 줄인다. 그것을 늘리는 일은 성공한 +renew 하나뿐이다. -## Failure visibility +## 실패 보이기 -Semantic adapters intentionally translate Redis failures into typed application outcomes, but those -translations are not silent. +semantic 어댑터는 Redis 실패를 일부러 타입 있는 애플리케이션 결과로 바꾸지만, 그 번역은 소리 없지 않다. -`RedisSemanticFailureLogger` records only: +`RedisSemanticFailureLogger`는 다음만 남긴다: - capability, - semantic operation, -- exception class. +- 예외 클래스. -It never logs Redis keys, values, command arguments, exception messages or credentials. The first -occurrence of a capability/operation/failure-type combination is WARN; repeats are DEBUG to avoid -turning a Redis outage into a log-flood outage. +Redis 키, 값, 명령 인자, 예외 메시지, credential은 남기지 않는다. capability·operation·실패 타입 조합의 첫 발생은 +WARN이고, 되풀이는 DEBUG다. Redis 장애가 로그 홍수 장애로 번지지 않게 하려는 것이다. -## Optional typed SDK +## 골라 쓰는 typed SDK -`:adapter:outbound:redis-sdk` contains the broader typed command surface, command policy, raw/admin -and extension machinery. It is a separate library leaf that service code takes with -`implementation`; see `src/adapter/outbound/redis-sdk/README.md`. This leaf does not depend on it, -in production or in tests. +`:adapter:outbound:redis-sdk`에는 더 넓은 typed 명령 surface, 명령 정책, raw·admin, extension 장치가 있다. 서비스 +코드가 `implementation`으로 받는 따로 둔 라이브러리 leaf다. `src/adapter/outbound/redis-sdk/README.md`를 본다. 이 +leaf는 운영에서도 시험에서도 그것에 의존하지 않는다. -Its policy file and optional startup/library probes apply only when that SDK is deliberately added -to a composition. Do not infer SDK command-policy enforcement from the presence of a semantic cache -or rate-limit adapter. +그 정책 파일과 골라 쓰는 기동·라이브러리 probe는 그 SDK를 일부러 조립에 더했을 때만 적용된다. semantic cache나 +rate-limit 어댑터가 있다고 SDK 명령 정책이 강제된다고 짐작하지 않는다. -## Verification +## 검증 -Useful focused checks: +쓸 만한 이 모듈 검사: ```bash ./gradlew :adapter:outbound:cache-redis:check @@ -377,18 +326,16 @@ Useful focused checks: ./gradlew architectureCheck ``` -`redisContainerContractTest` runs the cache-region, lease and idempotency-store port contracts (the -ones the in-memory fakes pass; the idempotency contract's timed cases run here on the server's own -clock, and in `test` over the command fake's clock, which proves the fixture's copies of the -programs rather than the programs) and the live semantic-port tests against a Redis it starts itself, under the standalone -topology's ACL file. It is in `integrationCheck` (integration-main.yml's `integration-check` job), and -only there: listing it in `mainCheck` as well ran it twice on every push to main. The image is -`config/testing/container-images.properties` `redis`. +`redisContainerContractTest`는 cache-region, lease, 멱등성 store 포트 계약(메모리 fake가 통과하는 것. 멱등성 계약의 +시간 있는 경우는 여기서 서버 자신의 시계로 돌고, `test`에서는 명령 fake의 시계로 돈다 — 후자는 program 자체가 아니라 +fixture가 가진 program 사본을 증명한다)과 살아 있는 semantic 포트 시험을, standalone topology의 ACL 파일 아래에서 스스로 +띄운 Redis에 대고 돌린다. `integrationCheck`(integration-main.yml의 `integration-check` job)에 있고 거기에만 있다: +`mainCheck`에도 적었을 때는 main push마다 두 번 돌았다. image는 `config/testing/container-images.properties`의 +`redis`다. -Live Redis/topology qualification remains separate from fast unit tests. A release claim for a -specific Redis topology or ACL layout requires the corresponding live qualification lane; the -in-memory gateway is for deterministic contract tests, not evidence that an external Redis -deployment accepts the same network/TLS/ACL configuration. +살아 있는 Redis·topology 검증은 빠른 단위 시험과 따로다. 특정 Redis topology나 ACL 배치에 대한 릴리스 주장에는 그에 +맞는 살아 있는 검증 lane이 필요하다. 메모리 gateway는 결정적인 계약 시험을 위한 것이지, 외부 Redis 배포가 같은 +network·TLS·ACL 설정을 받아들인다는 증거가 아니다. ## 아직 내보내지 않는 지표 @@ -398,4 +345,3 @@ inflight.total, readiness.total, lifecycle.drain.total)는 redis-production-capa 것처럼 적고 있어서, 2026-11-03 재리뷰 수정에서 레지스트리에서 빼고 runbook을 지금 내보내는 `redis.lane.*`(redis-runtime, lane별 대기·거절·연결) 기준으로 고쳤다. capability 단위 지표가 필요해지면 operation 결과를 아는 semantic adapter(이 leaf)에서 내보내고, 그때 레지스트리에 다시 넣는다. - diff --git a/src/adapter/outbound/fileserver/CLAUDE.md b/src/adapter/outbound/fileserver/CLAUDE.md index 2f89dd43..fbece082 100644 --- a/src/adapter/outbound/fileserver/CLAUDE.md +++ b/src/adapter/outbound/fileserver/CLAUDE.md @@ -1,42 +1,39 @@ -# adapter:outbound:fileserver — module rules +# adapter:outbound:fileserver — 모듈 규칙 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-fileserver` -- Gradle path: `:adapter:outbound:fileserver` -- Focused test (derived from Gradle path): `./gradlew :adapter:outbound:fileserver:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-outbound-fileserver` +- Gradle 경로: `:adapter:outbound:fileserver` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:outbound:fileserver:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.outbound.fileserver.platform`. Driven (outbound) adapter for -the HTTP Fileserver platform: it implements the `application-fileserver` ports (content storage, -verification, identifiers, audit, metrics). Design rationale lives in [README.md](README.md). +패키지 루트: `dev.caskeleton.adapter.outbound.fileserver.platform`. HTTP 파일 서버 플랫폼의 driven +(outbound) 어댑터다: `application-fileserver` 포트(내용 저장, 검증, 식별자, 감사, metric)를 구현한다. +설계 근거는 [README.md](README.md)에 있다. -## Responsibility +## 책임 -- Local filesystem content storage, verification, identifiers, audit and metrics behind - `application-fileserver` ports. -- Activated only through `app.fileserver-platform.*` (default off), from - `platform.autoconfigure.FileserverCapabilityAutoConfiguration` registered in this leaf's - `AutoConfiguration.imports`. -- Detailed transport/security/operations contracts live under `docs/fileserver/`; certified - behavior is listed in `docs/fileserver/support-matrix.md`. +- `application-fileserver` 포트 뒤의 로컬 파일 시스템 내용 저장, 검증, 식별자, 감사, metric. +- `app.fileserver-platform.*`(기본 꺼짐)으로만 켠다. 이 leaf의 `AutoConfiguration.imports`에 등록한 + `platform.autoconfigure.FileserverCapabilityAutoConfiguration`에서 켜진다. +- 자세한 전송·보안·운영 계약은 `docs/fileserver/` 아래에 있다. 인증된 동작은 + `docs/fileserver/support-matrix.md`가 적는다. -## Allowed +## 허용 -- Project deps: SSOT is the `adapter-outbound-fileserver` entry in - `src/config/architecture/modules.json`; `src/build.gradle` enforces it. No `:domain-core`. -- External runtime: JDK filesystem, `spring-boot-autoconfigure`, `micrometer-core` and `slf4j-api`. +- 프로젝트 의존: 정본은 `src/config/architecture/modules.json`의 `adapter-outbound-fileserver` 항목이고 + `src/build.gradle`이 강제한다. `:domain-core`는 없다. +- 외부 런타임: JDK 파일 시스템, `spring-boot-autoconfigure`, `micrometer-core`, `slf4j-api`. -## Forbidden +## 금지 -- Inbound adapters, persistence, `app-bootstrap` (ArchUnit - `OUTBOUND_ADAPTERS_*` family rules). -- Leaking filesystem, stream, framework, or provider types across the application ports. -- Advertising a platform feature as implemented unless `docs/fileserver/support-matrix.md` lists it. -- Fully-qualified inline type references; more than one public top-level type per file. +- inbound 어댑터, 영속, `app-bootstrap`(ArchUnit `OUTBOUND_ADAPTERS_*` 규칙 묶음). +- 파일 시스템·stream·프레임워크·provider 타입을 application 포트 너머로 새게 하기. +- `docs/fileserver/support-matrix.md`가 적지 않은 플랫폼 기능을 구현됐다고 내세우기. +- 줄 안에 완전한 이름으로 쓴 타입 참조, 파일 하나에 공개 최상위 타입 둘 이상. -## Tests +## 테스트 ```bash cd src diff --git a/src/adapter/outbound/fileserver/README.md b/src/adapter/outbound/fileserver/README.md index dca317a9..39e29bfc 100644 --- a/src/adapter/outbound/fileserver/README.md +++ b/src/adapter/outbound/fileserver/README.md @@ -1,31 +1,29 @@ -# adapter:outbound:fileserver — design-decision reference +# adapter:outbound:fileserver — 설계 결정 참고 -Outbound (driven) adapter for the HTTP Fileserver platform. Package root: -`dev.caskeleton.adapter.outbound.fileserver.platform`. It implements the `application-fileserver` -ports: local filesystem content storage, upload verification, identifiers, audit and metrics. +HTTP 파일 서버 플랫폼의 outbound(driven) 어댑터다. 패키지 루트: +`dev.caskeleton.adapter.outbound.fileserver.platform`. `application-fileserver` 포트를 구현한다: 로컬 파일 +시스템 내용 저장, 업로드 검증, 식별자, 감사, metric. -The allowed/forbidden production dependency policy is owned by the -`adapter-outbound-fileserver` entry in `src/config/architecture/modules.json`; root Gradle -verification reads that registry. Module rules live in [CLAUDE.md](CLAUDE.md). +허용·금지 운영 의존 정책은 `src/config/architecture/modules.json`의 `adapter-outbound-fileserver` 항목이 +가진다. 루트 Gradle 검증이 그 registry를 읽는다. 모듈 규칙은 [CLAUDE.md](CLAUDE.md)에 있다. -Transport, security, configuration and operations contracts live in `docs/fileserver/`. For the -repository-level choice between this Fileserver platform and Object Storage, see -[`docs/storage-capability-boundary.md`](../../../../docs/storage-capability-boundary.md). +전송·보안·설정·운영 계약은 `docs/fileserver/`에 있다. 이 파일 서버 플랫폼과 Object Storage 중 무엇을 +고를지에 대한 저장소 단위 선택은 +[`docs/storage-capability-boundary.md`](../../../../docs/storage-capability-boundary.md)를 본다. -## Activation +## 켜기 -`app.fileserver-platform.enabled=true` (default `false`). While it is off, the auto-configuration -that binds the block is not processed, so nothing is created. See -`docs/fileserver/configuration.md` for the keys. +`app.fileserver-platform.enabled=true`(기본 `false`). 꺼져 있는 동안은 그 블록을 바인딩하는 자동 구성을 +처리하지 않으니 아무것도 만들지 않는다. 키는 `docs/fileserver/configuration.md`를 본다. -## Tests +## 테스트 -- `platform/**`: auto-configuration, local storage, security and verification tests. -- `testkit/`: content-store contract (this adapter's internal `BlockingContentStore` SPI), - crash-recovery matrix, large-file memory bound and the NFS/PVC certification helpers. -- Port contracts come from `application-fileserver` testFixtures (`testFixtures(project( - ':application-fileserver'))`): `LocalUploadStorageContractTest` extends `UploadStoragePortContract`, - the same contract the application's `FakeUploadStorageGateway` passes. +- `platform/**`: 자동 구성, 로컬 저장, 보안, 검증 시험. +- `testkit/`: 내용 저장 계약(이 어댑터 내부의 `BlockingContentStore` SPI), crash 복구 표, 큰 파일 메모리 + 한계, NFS/PVC 인증 도우미. +- 포트 계약은 `application-fileserver` testFixtures(`testFixtures(project( + ':application-fileserver'))`)에서 온다: `LocalUploadStorageContractTest`가 `UploadStoragePortContract`를 + 상속한다. 애플리케이션의 `FakeUploadStorageGateway`가 통과하는 것과 같은 계약이다. ```bash cd src diff --git a/src/adapter/outbound/httpclient/CLAUDE.md b/src/adapter/outbound/httpclient/CLAUDE.md index 2a9a3149..f1e67aab 100644 --- a/src/adapter/outbound/httpclient/CLAUDE.md +++ b/src/adapter/outbound/httpclient/CLAUDE.md @@ -1,93 +1,86 @@ -# adapter:outbound:httpclient — HTTP Client Platform +# adapter:outbound:httpclient — HTTP client 플랫폼 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-httpclient` -- Gradle path: `:adapter:outbound:httpclient` -- Focused test (derived from Gradle path): `./gradlew :adapter:outbound:httpclient:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-outbound-httpclient` +- Gradle 경로: `:adapter:outbound:httpclient` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:outbound:httpclient:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.outbound.httpclient`. +패키지 루트: `dev.caskeleton.adapter.outbound.httpclient`. -## Design authority +## 설계 정본 -The implementation follows -`docs/design/2026-08-08-httpclient-platform-design.md`. -The design assumes 19 separate Gradle modules; this repository's fail-closed registry -outranks that layout, so those modules are **packages** here. The mapping, and every other -deliberate substitution, is recorded in `docs/httpclient/repository-adaptation.md`. Read it before -moving a type between packages. +구현은 `docs/design/2026-08-08-httpclient-platform-design.md`를 따른다. 설계는 Gradle 모듈 19개를 따로 두는 +것을 전제한다. 이 저장소의 실패하면 닫히는 registry가 그 배치보다 앞서므로, 그 모듈들은 여기서 **패키지**다. +그 대응과 그 밖에 일부러 바꾼 것은 모두 `docs/httpclient/repository-adaptation.md`에 적혀 있다. 타입을 다른 +패키지로 옮기기 전에 그것을 읽는다. -## Responsibility +## 책임 -- Own the public call surfaces: H1 typed service clients (default), H2 generic exchange, H3 dynamic - target. H4 native engine access stays internal to `apache`, `jdk`, and `http3`. -- Blocking only: calls run on the caller's (virtual) thread through `RestClient`. The reactive stack - (`WebClient`, Reactor Netty) was removed by the 2026-09-25 owner decision; do not add it back. -- Own Named Client Profiles, runtime generations, transport SPI, deadlines, evidence-based retry, - resilience, authentication, TLS, SSRF defence, streaming lifecycle, and observability. -- Adapt external HTTP calls behind application/domain ports. -- Reuse `adapter:outbound:support` for shared outbound concerns. +- 공개 호출 surface를 가진다: H1 typed service client(기본), H2 generic exchange, H3 dynamic target. H4 native + engine 접근은 `apache`, `jdk`, `http3` 안에 머문다. +- blocking만: 호출은 `RestClient`를 거쳐 호출자의 (virtual) 스레드에서 돈다. reactive stack(`WebClient`, + Reactor Netty)은 2026-09-25 소유자 결정으로 지웠다. 다시 들이지 않는다. +- Named Client Profile, runtime generation, transport SPI, deadline, 증거 기반 재시도, resilience, 인증, TLS, + SSRF 방어, streaming lifecycle, 관측을 가진다. +- 외부 HTTP 호출을 application·domain 포트 뒤에 맞춘다. +- 공용 outbound 관심사는 `adapter:outbound:support`를 다시 쓴다. -## Package boundaries +## 패키지 경계 -`HttpClientModuleBoundaryTest` and `PublicApiArchitectureTest` enforce the design's module table: +`HttpClientModuleBoundaryTest`와 `PublicApiArchitectureTest`가 설계의 모듈 표를 강제한다: -- `api` depends on nothing else in the platform, and on no Spring, Apache, Jetty, or Resilience4j - type. -- `profile` depends publicly only on `api`. -- transport packages never reach back into the gateways. -- `resilience` never depends on a transport — retry eligibility is transport-neutral. -- no production package depends on the reusable testkit. It lives in Gradle - `testFixtures` (`src/testFixtures/java`) and is consumed explicitly by the ordinary tests, - integration/performance lanes, and JMH. Its dependencies stay on test-fixture/test configurations, - so production still cannot reach it. `PlatformClasses` is the single definition of "production - classes" the boundary rules import. -- Stable code never references `http3`. -- no class uses `org.springframework.web.service.registry` or `RestTemplate`. +- `api`는 플랫폼 안의 다른 어떤 것에도, Spring·Apache·Jetty·Resilience4j 타입에도 의존하지 않는다. +- `profile`은 공개적으로 `api`에만 의존한다. +- transport 패키지는 gateway로 거슬러 닿지 않는다. +- `resilience`는 transport에 의존하지 않는다 — 재시도 자격은 transport와 무관하다. +- 운영 패키지는 다시 쓰는 testkit에 의존하지 않는다. testkit은 Gradle `testFixtures` + (`src/testFixtures/java`)에 있고, 보통 시험, integration·performance lane, JMH가 명시적으로 쓴다. 그 의존은 + test-fixture·test 설정에 머물러서 운영 코드는 여전히 닿지 못한다. 경계 규칙이 import하는 「운영 클래스」의 + 유일한 정의는 `PlatformClasses`다. +- Stable 코드는 `http3`를 참조하지 않는다. +- 어떤 클래스도 `org.springframework.web.service.registry`나 `RestTemplate`를 쓰지 않는다. -## Boundaries +## 경계 -- Allowed dependency edges come only from this module's `src/config/architecture/modules.json` entry. -- No inbound controller/DTO, persistence, bootstrap, or sample dependency. -- Retry and circuit-breaker code is technical resilience; business compensation and use-case - sequencing stay in application/domain layers. -- Application/domain code must not import this module's gateways, operation descriptors, URI types, - Spring HTTP types, engine clients, retry types, or wire DTOs. The repository-level Gradle - dependency gate in `config/architecture/modules.json` enforces that direction; this leaf's - ArchUnit rules only govern boundaries inside the leaf. -- Normal calls use a registered profile and a profile-relative template. Absolute URLs are H3 only. -- Composition is capability-owned under `dev.caskeleton.adapter.outbound.httpclient.autoconfigure`: - profile binding, startup validation, transport registration, service gateways, dynamic targets, - and the actuator endpoint live in this leaf and are published through Boot auto-configuration - metadata. `HttpClientPlatformAutoConfiguration` is gated on `app.httpclient.enabled=true`. While - the switch is off the capability has no beans at all — not an empty registry, nothing. -- `app-bootstrap` must not import HTTP-client implementation or auto-configuration classes from - production code. Build inclusion is decided separately from this runtime activation switch. +- 허용 의존 edge는 이 모듈의 `src/config/architecture/modules.json` 항목에서만 온다. +- inbound controller·DTO, 영속, bootstrap, 샘플 의존이 없다. +- 재시도와 circuit breaker 코드는 기술적 resilience다. 업무 보상과 유스케이스 순서는 application·domain 계층에 + 남는다. +- application·domain 코드는 이 모듈의 gateway, operation descriptor, URI 타입, Spring HTTP 타입, engine client, + 재시도 타입, wire DTO를 import하면 안 된다. 그 방향은 `config/architecture/modules.json`의 저장소 단위 Gradle + 의존 게이트가 강제한다. 이 leaf의 ArchUnit 규칙은 leaf 안의 경계만 다룬다. +- 보통 호출은 등록된 profile과 profile 기준 template을 쓴다. 절대 URL은 H3만 쓴다. +- 조립은 `dev.caskeleton.adapter.outbound.httpclient.autoconfigure` 아래에서 capability가 가진다: profile 바인딩, + 기동 검증, transport 등록, service gateway, dynamic target, actuator endpoint가 이 leaf에 있고 Boot 자동 구성 + metadata로 나간다. `HttpClientPlatformAutoConfiguration`은 `app.httpclient.enabled=true`일 때만 켜진다. + 스위치가 꺼져 있으면 capability에는 bean이 하나도 없다 — 빈 registry가 아니라 아무것도 없다. +- `app-bootstrap`은 운영 코드에서 HTTP client 구현이나 자동 구성 클래스를 import하면 안 된다. 빌드에 넣을지는 + 이 런타임 켜기 스위치와 따로 정한다. -## Tests +## 테스트 -Default lane: `./gradlew :adapter:outbound:httpclient:test`. Additional lanes, all fail-closed: +기본 lane: `./gradlew :adapter:outbound:httpclient:test`. 추가 lane은 모두 실패하면 닫힌다: -| Lane | Purpose | +| lane | 용도 | |---|---| -| `httpClientStableContractTest` | one semantic contract across Apache and JDK | -| `httpClientSecurityTest` | SSRF matrix, credential stripping, tag cardinality | -| `httpClientFailureInjectionTest` | Toxiproxy faults; **requires Docker and fails without it** | -| `httpClientPerformanceTest` | pool, streaming, retry, rotation resource bounds | -| `spring62ApiSurfaceScan` | Spring 6.2 API-surface confinement | -| `spring70CompatibilityTest` | contract suite on the repository baseline | -| `jmh` | per-call overhead benchmarks | +| `httpClientStableContractTest` | Apache와 JDK에 걸친 semantic 계약 하나 | +| `httpClientSecurityTest` | SSRF 표, credential 걷어내기, tag cardinality | +| `httpClientFailureInjectionTest` | Toxiproxy 장애. **Docker가 필요하고 없으면 실패한다** | +| `httpClientPerformanceTest` | pool, streaming, 재시도, 교체의 자원 한계 | +| `spring62ApiSurfaceScan` | Spring 6.2 API surface 가두기 | +| `spring70CompatibilityTest` | 저장소 기준 버전 위의 계약 suite | +| `jmh` | 호출당 부담 benchmark | -A selected lane never skips silently: the fault lane throws without Docker, the contract lane throws -on an empty or unknown transport selection, and the performance lane asserts every bound in every -run — the strict-lane convention fails it when the build sets `performance.assertions.enabled` to -anything but `true` or when one of its tests is skipped. +고른 lane은 소리 없이 건너뛰지 않는다: 장애 lane은 Docker가 없으면 던지고, 계약 lane은 transport 선택이 +비었거나 모르는 것이면 던지고, performance lane은 실행마다 모든 한계를 단언한다 — 빌드가 +`performance.assertions.enabled`에 `true` 아닌 값을 넣거나 그 시험 하나가 건너뛰어지면 strict lane 규약이 +실패시킨다. -The transport port (`BlockingTransportProvider`) has one abstract contract in the test fixtures, -`testkit/BlockingTransportProviderContract`. The engines pass it over a real socket -(`StableTransportProviderContractTest`, the contract lane, once per selected transport) and the -scripted fake the gateway tests stand on passes it in the default lane -(`ScriptedTransportContractTest`). A new transport, or a change to `ScriptedTransport`, inherits the -same class rather than a copy (AGENTS.md rule 6). +transport 포트(`BlockingTransportProvider`)에는 test fixtures에 추상 계약 하나 +`testkit/BlockingTransportProviderContract`가 있다. engine은 실제 socket 위에서 그것을 통과하고 +(`StableTransportProviderContractTest`, 계약 lane, 고른 transport마다 한 번), gateway 시험이 딛고 서는 각본 +fake는 기본 lane에서 그것을 통과한다(`ScriptedTransportContractTest`). 새 transport나 `ScriptedTransport`의 +변경은 사본이 아니라 같은 클래스를 상속한다(AGENTS.md 규칙 6). diff --git a/src/adapter/outbound/httpclient/README.md b/src/adapter/outbound/httpclient/README.md index a0d50646..90a11685 100644 --- a/src/adapter/outbound/httpclient/README.md +++ b/src/adapter/outbound/httpclient/README.md @@ -1,21 +1,20 @@ # adapter:outbound:httpclient -The outbound HTTP Client Platform: a single contract for how this service talks to anything over -HTTP. It is not a wrapper around `RestClient` — it owns the target, the connection resources, the -time budget, the evidence of what actually executed, retry safety, authentication, TLS, SSRF -defence, and observability. +outbound HTTP client 플랫폼이다: 이 서비스가 HTTP로 무엇과든 말하는 방법을 정한 계약 하나. `RestClient`를 감싼 +것이 아니다 — 대상, 연결 자원, 시간 예산, 실제로 무엇이 실행됐는지의 증거, 재시도 안전성, 인증, TLS, SSRF +방어, 관측을 가진다. -Design: `docs/design/2026-08-08-httpclient-platform-design.md` -Adaptation to this repository: `docs/httpclient/repository-adaptation.md` +설계: `docs/design/2026-08-08-httpclient-platform-design.md` +이 저장소에 맞춘 내용: `docs/httpclient/repository-adaptation.md` -## Choosing a surface +## surface 고르기 -| Surface | Use it when | What it fixes for you | +| surface | 이럴 때 쓴다 | 대신 정해 주는 것 | |---|---|---| -| **H1 typed client** (`HttpServiceRegistry`) | almost always | URL, timeout, auth, retry, limits, metrics | -| **H2 generic exchange** (`GenericHttpGateway`, `BlockingStreamingGateway`) | method, path, or body must vary at runtime | scheme, host, port, TLS, credentials, hard limits | -| **H3 dynamic target** (`DynamicTargetGateway`) | the URL comes from a user | full SSRF validation; inherits no credential | -| **H4 native engine** | never, from application code | — | +| **H1 typed client**(`HttpServiceRegistry`) | 거의 언제나 | URL, timeout, 인증, 재시도, 한계, metric | +| **H2 generic exchange**(`GenericHttpGateway`, `BlockingStreamingGateway`) | method, path, body가 런타임에 바뀌어야 할 때 | scheme, host, port, TLS, credential, 단단한 한계 | +| **H3 dynamic target**(`DynamicTargetGateway`) | URL이 사용자에게서 올 때 | SSRF 검증 전체. credential을 물려받지 않는다 | +| **H4 native engine** | 애플리케이션 코드에서는 쓰지 않는다 | — | ```java @HttpClientProfile("users") @@ -28,48 +27,42 @@ public interface UsersClient { } ``` -The interface fails startup unless it names a profile, gives every method a stable operation name, -declares idempotency explicitly, and supplies a key parameter when the operation requires one. +인터페이스가 profile 이름을 대고, 모든 메서드에 안정된 operation 이름을 주고, 멱등성을 명시하고, operation이 +키를 요구하면 키 매개변수를 주지 않으면 기동이 실패한다. -Every call is blocking and runs on the caller's thread — a virtual thread in this template. There is -no reactive (`WebClient`/Reactor Netty) surface; it was removed on 2026-09-25 (decision 9). +모든 호출은 blocking이고 호출자의 스레드에서 돈다 — 이 템플릿에서는 virtual thread다. reactive +(`WebClient`/Reactor Netty) surface는 없다. 2026-09-25에 지웠다(결정 9). -## What the platform decides for you +## 플랫폼이 대신 정하는 것 -- **Time.** One effective deadline covers pool acquire, DNS, connect, TLS, write, read, and every - retry backoff. It is checked before each attempt and also ends an attempt still in flight: Apache - cancels the request at the deadline, the JDK transport bounds its exchange timeout by the time - left, the experimental Jetty HTTP/3 transport aborts the request, and the caller gets - `HttpDeadlineExceededException`. A streaming download's setup (up to the response headers) runs - inside the same deadline; after hand-over each body gap is bounded by `read-idle` and nothing else, - on both transports — on the JDK transport, which has no socket read timeout, a per-stream watchdog - bounds each read's wait. The watchdogs share one daemon thread (`httpclient-jdk-read-idle`): the - first stream that needs it starts it, it ends 60 s after the last wake it had queued, and the next - stream starts it again. It inherits no thread-locals from the request thread that starts it and - uses this module's class loader as its context loader, so it pins neither a request's state nor a - redeployed application's loader. A body that fails - after hand-over throws `HttpBodyReadException`, an `IOException` as `InputStream.read` promises, - whose `failure()` is the same stable exception a buffered call throws - (`HttpResponseTimeoutException` for a stalled body, `HttpResponseTruncatedException` for a cut - one). -- **Evidence.** Each attempt reports `NOT_SENT`, `SENT_NO_RESPONSE`, `RESPONSE_RECEIVED`, or - `PARTIAL_RESPONSE`. `NOT_SENT` is only claimed when a stage failure proves it. -- **Retry.** Never from the HTTP method alone. Idempotency, body replayability, evidence, deadline, - and a per-upstream token budget all have to agree. A sent, non-idempotent request with no response - raises `HttpAmbiguousExecutionException` instead of being retried or reported as a plain failure. -- **Order.** Every physical attempt passes Circuit Breaker → Rate Limiter → Bulkhead, and holds no - permit while a backoff waits. -- **Circuit.** The breaker counts transport failures and 5xx, 408, and 429 against the upstream, - whether the call throws them or returns them as a result (`RETURN_RESULT`). Any other 4xx (404, - 409, 422 …) is a healthy answer, even when it reaches the caller as `HttpRemoteErrorException`. - Window, threshold and open-state wait are per profile under `clients[N].circuit-breaker.*` - (defaults are Resilience4j's; see `docs/httpclient/configuration-reference.md`). An attempt that - the caller's own deadline (`HttpOperation.deadline()`) ended is not counted at all: the caller ran - out of time, the upstream did not fail. An attempt the profile's `total-call` ended still counts. -- **Resources.** Connections and buffers are reclaimed after success, error, decode failure, size - rejection, and cancellation alike. -- **Secrets.** No URL, query value, path variable, token, cookie, or idempotency key reaches a log, - a metric label, or an exception message. +- **시간.** 유효 deadline 하나가 pool 획득, DNS, connect, TLS, 쓰기, 읽기, 모든 재시도 backoff를 덮는다. + 시도마다 그 전에 검사하고, 아직 진행 중인 시도도 끝낸다: Apache는 deadline에 요청을 취소하고, JDK + transport는 남은 시간으로 exchange timeout을 묶고, 실험용 Jetty HTTP/3 transport는 요청을 중단하며, 호출자는 + `HttpDeadlineExceededException`을 받는다. streaming 다운로드의 준비(응답 header까지)는 같은 deadline 안에서 + 돈다. 넘겨준 뒤에는 body 사이의 빈 시간을 두 transport 모두 `read-idle`만으로 묶는다 — socket 읽기 timeout이 + 없는 JDK transport에서는 stream마다 watchdog이 각 읽기의 기다림을 묶는다. watchdog들은 daemon 스레드 하나 + (`httpclient-jdk-read-idle`)를 같이 쓴다: 그것이 필요한 첫 stream이 시작하고, 마지막으로 줄 세운 깨우기 60 s + 뒤에 끝나며, 다음 stream이 다시 시작한다. 그것을 시작한 요청 스레드에서 thread-local을 물려받지 않고 이 + 모듈의 class loader를 context loader로 쓰므로, 요청의 상태도 다시 배포된 애플리케이션의 loader도 붙잡지 + 않는다. 넘겨준 뒤 실패한 body는 `InputStream.read`가 약속한 대로 `IOException`인 `HttpBodyReadException`을 + 던진다. 그 `failure()`는 buffer로 받는 호출이 던지는 것과 같은 안정된 예외다(멈춘 body는 + `HttpResponseTimeoutException`, 잘린 body는 `HttpResponseTruncatedException`). +- **증거.** 시도마다 `NOT_SENT`, `SENT_NO_RESPONSE`, `RESPONSE_RECEIVED`, `PARTIAL_RESPONSE` 중 하나를 알린다. + `NOT_SENT`는 단계 실패가 그것을 증명할 때만 주장한다. +- **재시도.** HTTP method만 보고 하지 않는다. 멱등성, body 재생 가능성, 증거, deadline, upstream별 token 예산이 + 모두 맞아야 한다. 보냈고 멱등이 아니고 응답이 없는 요청은 재시도하거나 평범한 실패로 알리지 않고 + `HttpAmbiguousExecutionException`을 올린다. +- **순서.** 물리 시도마다 Circuit Breaker → Rate Limiter → Bulkhead를 지나고, backoff를 기다리는 동안 허가를 + 쥐고 있지 않는다. +- **circuit.** breaker는 transport 실패와 5xx, 408, 429를 upstream의 실패로 센다. 호출이 그것을 던지든 + 결과로 돌려주든(`RETURN_RESULT`) 같다. 그 밖의 4xx(404, 409, 422 …)는 호출자에게 + `HttpRemoteErrorException`으로 닿아도 건강한 답이다. window, 문턱, 열린 상태의 대기는 profile마다 + `clients[N].circuit-breaker.*` 아래에 있다(기본값은 Resilience4j의 것이다. + `docs/httpclient/configuration-reference.md`를 본다). 호출자 자신의 deadline(`HttpOperation.deadline()`)이 + 끝낸 시도는 아예 세지 않는다: 호출자의 시간이 다 된 것이지 upstream이 실패한 것이 아니다. profile의 + `total-call`이 끝낸 시도는 계속 센다. +- **자원.** 연결과 buffer는 성공, 오류, decode 실패, 크기 거절, 취소 뒤에 똑같이 거둬들인다. +- **비밀 값.** URL, query 값, path 변수, token, cookie, 멱등 키는 로그, metric label, 예외 메시지에 닿지 않는다. ## 제공하는 것 · 추가할 한 줄 · env 키 @@ -93,13 +86,12 @@ no reactive (`WebClient`/Reactor Netty) surface; it was removed on 2026-09-25 (d (필드 전체는 `docs/httpclient/env-fields.yaml`). client가 없으면 `HTTPCLIENT_ACTIVE_WITHOUT_CLIENTS`로 기동이 실패한다. -## Configuration +## 설정 -Profiles live under `app.httpclient.clients[N]`; Dynamic Target policies under -`app.httpclient.dynamic-targets[N]`. Every startup guard, property, and violation code is listed in -`docs/httpclient/configuration-reference.md`. +profile은 `app.httpclient.clients[N]` 아래에, Dynamic Target 정책은 `app.httpclient.dynamic-targets[N]` 아래에 +있다. 모든 기동 guard, 속성, 위반 코드는 `docs/httpclient/configuration-reference.md`에 있다. -## Verification +## 검증 ```bash cd src @@ -110,13 +102,11 @@ cd src ./gradlew :adapter:outbound:httpclient:httpClientFailureInjectionTest --console=plain # needs Docker ``` -No lane skips silently. The fault lane fails without Docker, the contract lane fails on an empty or -unknown transport selection, and the performance lane asserts every bound in every run (it fails -when the build sets `performance.assertions.enabled` to anything but `true`, or when a test is -skipped). +어떤 lane도 소리 없이 건너뛰지 않는다. 장애 lane은 Docker가 없으면 실패하고, 계약 lane은 transport 선택이 +비었거나 모르는 것이면 실패하고, performance lane은 실행마다 모든 한계를 단언한다(빌드가 +`performance.assertions.enabled`에 `true` 아닌 값을 넣거나 시험이 건너뛰어지면 실패한다). -## Further reading +## 더 읽을 것 -`docs/httpclient/` holds the support matrix, configuration reference, retry and ambiguity guide, -security guide, streaming guide, operations runbook, performance baseline, and -release checklist. +`docs/httpclient/`에 support matrix, 설정 참고, 재시도와 모호함 안내, 보안 안내, streaming 안내, 운영 runbook, +성능 기준선, 릴리스 체크리스트가 있다. diff --git a/src/adapter/outbound/identifier/CLAUDE.md b/src/adapter/outbound/identifier/CLAUDE.md index bd2ac640..0d021b3a 100644 --- a/src/adapter/outbound/identifier/CLAUDE.md +++ b/src/adapter/outbound/identifier/CLAUDE.md @@ -1,55 +1,51 @@ -# adapter:outbound:identifier — non-IO infrastructure-capability adapter +# adapter:outbound:identifier — IO 없는 기반 capability 어댑터 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-identifier` -- Gradle path: `:adapter:outbound:identifier` -- Focused test (derived from Gradle path): `./gradlew :adapter:outbound:identifier:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.8. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-outbound-identifier` +- Gradle 경로: `:adapter:outbound:identifier` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:outbound:identifier:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.outbound.identifier`. +패키지 루트: `dev.caskeleton.adapter.outbound.identifier`. -Design decisions previously kept as code comments (algorithm SSOT, salt origin, -build choices) live in [README.md](README.md). +예전에 코드 주석에 두던 설계 결정(알고리즘 정본, salt 출처, 빌드 선택)은 [README.md](README.md)에 있다. -## Responsibility +## 책임 -- `HmacUserPrincipalPseudonymizer` — the `UserPrincipalPseudonymizerPort` implementation - (HMAC-SHA-256 of the UTF-8 principal, lowercase hex). -- `UuidV7DurableOperationIdFactory` — `DurableOperationIdFactory` implementation (UUIDv7 via - `uuid-creator`). The operation id is also the submission event's id, and the messaging platform's - message id accepts only UUIDv7. Wired by `composition:durable-operation`. -- The leaf name says "identifier"; general-purpose clock and random sources are not here. - The name is kept because Gradle paths and consumers use it (README). -- Wiring is `composition/service-runtime` (`PseudonymizationConfig`), not this leaf. +- `HmacUserPrincipalPseudonymizer` — `UserPrincipalPseudonymizerPort` 구현(UTF-8 principal의 HMAC-SHA-256, + 소문자 hex). +- `UuidV7DurableOperationIdFactory` — `DurableOperationIdFactory` 구현(`uuid-creator`로 만든 UUIDv7). + operation id는 제출 이벤트의 id이기도 하고, 메시징 플랫폼의 message id는 UUIDv7만 받는다. + `composition:durable-operation`이 배선한다. +- leaf 이름은 「identifier」다. 범용 시계·난수 출처는 여기 없다. Gradle 경로와 쓰는 쪽이 이 이름을 쓰니 + 이름을 그대로 둔다(README). +- 배선은 이 leaf가 아니라 `composition/service-runtime`(`PseudonymizationConfig`)이다. -## Allowed +## 허용 -Declared in [build.gradle](build.gradle); the registry entry is the SSOT. +[build.gradle](build.gradle)에 선언한다. registry 항목이 정본이다. -- `:application-core` — the ports both classes implement. -- `:shared-contract`, for `HmacSha256` only. The pseudonym is the hex HMAC - of the principal; `HmacUserPrincipalPseudonymizerVectorTest` pins it to a vector computed outside - the JVM, because logs written before and after a release are joined on it. -- `:domain-core` — a feature's server-assigned id adapter implements its domain `*IdFactory` port - here (registry edge `adapter:outbound:identifier -> domain-core`; `docs/manual/02-new-feature.md`). -- `com.github.f4b6a3:uuid-creator` (`libs.uuid.creator`) — UUIDv7 for - `UuidV7DurableOperationIdFactory`. +- `:application-core` — 두 클래스가 구현하는 포트. +- `:shared-contract`, `HmacSha256`만. 가명은 principal의 hex HMAC이다. + `HmacUserPrincipalPseudonymizerVectorTest`가 그것을 JVM 밖에서 계산한 벡터에 고정한다. 릴리스 전후에 쓴 + 로그를 이 값으로 잇기 때문이다. +- `:domain-core` — 기능의 서버 지정 id 어댑터가 여기서 그 도메인 `*IdFactory` 포트를 구현한다(registry + edge `adapter:outbound:identifier -> domain-core`, `docs/manual/02-new-feature.md`). +- `com.github.f4b6a3:uuid-creator`(`libs.uuid.creator`) — `UuidV7DurableOperationIdFactory`의 UUIDv7. -## Forbidden +## 금지 -- Persistence or web technology (JPA/Hibernate/Spring Data/Spring Web) — ArchUnit - `identifier_adapter_does_not_depend_on_other_adapters_or_bootstrap`; - `.claude/hooks/ca_import_gate.py` G4 가 쓰기 시점에 차단. -- inbound adapters, persistence adapters, other outbound leaves, `app-bootstrap`. -- External IO (HTTP / messaging / cache / DB) — that belongs in `adapter-outbound`. +- 영속·web 기술(JPA/Hibernate/Spring Data/Spring Web) — ArchUnit + `IDENTIFIER_ADAPTER_DOES_NOT_DEPEND_ON_OTHER_ADAPTERS_OR_BOOTSTRAP`와 registry 방향 게이트가 막는다. +- inbound 어댑터, 영속 어댑터, 다른 outbound leaf, `app-bootstrap`. +- 외부 IO(HTTP / 메시징 / cache / DB) — 그것은 IO를 하는 outbound 어댑터 leaf에 둔다. -## Test +## 테스트 -Pure unit tests, no Spring context: `HmacUserPrincipalPseudonymizerTest` (including the RFC 4231 -known-answer vector), `HmacUserPrincipalPseudonymizerVectorTest` and -`UuidV7DurableOperationIdFactoryTest`. +Spring context 없는 순수 단위 시험: `HmacUserPrincipalPseudonymizerTest`(RFC 4231 known-answer 벡터 포함), +`HmacUserPrincipalPseudonymizerVectorTest`, `UuidV7DurableOperationIdFactoryTest`. ```bash cd src diff --git a/src/adapter/outbound/messaging-kafka/CLAUDE.md b/src/adapter/outbound/messaging-kafka/CLAUDE.md index 060cd2b3..7f2fa07a 100644 --- a/src/adapter/outbound/messaging-kafka/CLAUDE.md +++ b/src/adapter/outbound/messaging-kafka/CLAUDE.md @@ -1,14 +1,13 @@ # adapter:outbound:messaging-kafka -- Module ID `adapter-outbound-messaging-kafka`, Gradle path `:adapter:outbound:messaging-kafka`. - Registry SSOT: `src/config/architecture/modules.json`. -- Responsibility: the Kafka publishing capability as one `runtimeOnly` line. It has no production - code: it bundles `adapter:outbound:messaging` (the application's bridge) with - `messaging:messaging-spring-boot-starter-kafka` (the vendored platform and its Kafka transport) and - ships the module defaults in `config/module-defaults/messaging.yml`. -- Boundaries: add no code here. A publish rule belongs to the bridge (`adapter:outbound:messaging`), - a Kafka rule to the vendored product (`src/platforms/messaging/CLAUDE.md`); a class here would be a third - place. Allowed edges come only from the registry entry. -- Tests: activation tests (`./gradlew :adapter:outbound:messaging-kafka:test`) and the real-Kafka - lane `messagingKafkaRelayIntegrationTest` (relay → bridge → broker record bytes; `:integrationCheck`). -- Design: `README.md`. +- 모듈 ID `adapter-outbound-messaging-kafka`, Gradle 경로 `:adapter:outbound:messaging-kafka`. + registry 정본: `src/config/architecture/modules.json`. +- 책임: Kafka 발행 capability를 `runtimeOnly` 한 줄로 만든다. 운영 코드가 없다: + `adapter:outbound:messaging`(애플리케이션의 bridge)과 `messaging:messaging-spring-boot-starter-kafka`(들여온 + 플랫폼과 그 Kafka 전송)를 묶고, 모듈 기본값 `config/module-defaults/messaging.yml`을 싣는다. +- 경계: 여기 코드를 더하지 않는다. 발행 규칙은 bridge(`adapter:outbound:messaging`)에, Kafka 규칙은 들여온 + 제품(`src/platforms/messaging/CLAUDE.md`)에 속한다. 여기 클래스를 두면 세 번째 자리가 생긴다. 허용 edge는 + registry 항목에서만 온다. +- 시험: 켜기 시험(`./gradlew :adapter:outbound:messaging-kafka:test`)과 실제 Kafka lane + `messagingKafkaRelayIntegrationTest`(relay → bridge → broker record 바이트, `:integrationCheck`). +- 설계: `README.md`. diff --git a/src/adapter/outbound/messaging/CLAUDE.md b/src/adapter/outbound/messaging/CLAUDE.md index d7d4f08d..bfd3277d 100644 --- a/src/adapter/outbound/messaging/CLAUDE.md +++ b/src/adapter/outbound/messaging/CLAUDE.md @@ -1,50 +1,46 @@ -# adapter:outbound:messaging — messaging adapter +# adapter:outbound:messaging — 메시징 어댑터 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-messaging` -- Gradle path: `:adapter:outbound:messaging` -- Focused test (derived from Gradle path): `./gradlew :adapter:outbound:messaging:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.8. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-outbound-messaging` +- Gradle 경로: `:adapter:outbound:messaging` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:outbound:messaging:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.outbound.messaging`. +패키지 루트: `dev.caskeleton.adapter.outbound.messaging`. -## Responsibility +## 책임 -- Implement outbound message publication and broker integration behind application/domain ports. -- Own broker settings, disabled/fail-safe technical modes, and outbox publication adaptation. -- Own structured rendering of `OutboxRelayFailureReport` through the single unconditional - `Slf4jOutboxRelayFailureReportAdapter` bean. -- Reuse `adapter:outbound:support` for shared technical concerns. +- application·domain 포트 뒤에서 outbound 메시지 발행과 broker 연동을 구현한다. +- broker 설정, 꺼짐·안전 실패 기술 모드, outbox 발행 연결을 가진다. +- 조건 없이 하나만 있는 `Slf4jOutboxRelayFailureReportAdapter` bean으로 `OutboxRelayFailureReport`를 구조화해 + 남긴다. +- 공용 기술 관심사는 `adapter:outbound:support`를 다시 쓴다. -## Boundaries +## 경계 -- Allowed dependency edges come only from the module's - `src/config/architecture/modules.json` entry. -- No inbound DTO/controller, persistence repository/entity, bootstrap, or sample dependency. -- The canonical platform bridge may depend only on `messaging-core-api` (which also holds the - `schema` package); do not import `messaging-runtime-core`, transport SPI implementations, or - broker SDK types under `platformbridge/`. -- There is one publication path: `OutboxMessagePublishAdapter` → `IntegrationEventPublishPort` → - the platform bridge. The legacy `KafkaSender` / `MessageBroker` R0 seam and the fail-open - `MessagePublisher` were removed with the canonical outbox (2026-09-28); do not reintroduce a - second path. -- Canonical producer identity is explicit `app.messaging.producer-id`; never derive it from - `spring.application.name`, host, pod, or process identity. With the module on and no bridge, - startup is refused — the relay would have nothing to publish through. -- The template's `IntegrationEventEncoderPort` (`JsonIntegrationEventEncoder`) lives in - `adapter:outbound:support`, not here: a use case encodes before it appends, in compositions that - may not carry this module. The R1 contract/binding compilers and JSON Schema envelope encoder were - removed on 2026-09-25 (see `docs/capability-status.md`). -- No JSON Schema engine (NetworkNT) on the main classpath. The evidence manifest schema check and the - capability card check (`release/`) are this leaf's tests (`evidence/`); snakeyaml is - test-only (owner decision 2026-09-25). -- Do not hide use-case sequencing or business routing policy in broker adapters. -- `OutboxMessagePublishAdapter` is delegate-only and emits no dependency log. The confirmed - FAILED/DEAD transition owns the one canonical ERROR. +- 허용 의존 edge는 이 모듈의 `src/config/architecture/modules.json` 항목에서만 온다. +- inbound DTO·controller, 영속 repository·엔티티, bootstrap, 샘플 의존이 없다. +- 정해진 플랫폼 bridge는 `messaging-core-api`(`schema` 패키지도 담는다)에만 의존할 수 있다. + `platformbridge/` 아래에서 `messaging-runtime-core`, 전송 SPI 구현, broker SDK 타입을 import하지 않는다. +- 발행 경로는 하나다: `OutboxMessagePublishAdapter` → `IntegrationEventPublishPort` → 플랫폼 bridge. 옛 + `KafkaSender` / `MessageBroker` R0 이음매와 실패해도 열리는(fail-open) `MessagePublisher`는 정해진 outbox와 + 함께 지웠다(2026-09-28). 두 번째 경로를 다시 들이지 않는다. +- 정해진 producer identity는 명시한 `app.messaging.producer-id`다. `spring.application.name`, host, pod, + 프로세스 identity에서 끌어내지 않는다. 모듈이 켜져 있는데 bridge가 없으면 기동을 거절한다 — relay가 발행할 + 길이 없다. +- 템플릿의 `IntegrationEventEncoderPort`(`JsonIntegrationEventEncoder`)는 여기가 아니라 + `adapter:outbound:support`에 있다: 유스케이스는 append하기 전에 인코딩하는데, 이 모듈을 싣지 않는 조립도 + 있다. R1 contract·binding 컴파일러와 JSON Schema envelope 인코더는 2026-09-25에 지웠다 + (`docs/capability-status.md`). +- 주 classpath에 JSON Schema 엔진(NetworkNT)이 없다. 증거 manifest schema 검사와 capability card 검사 + (`release/`)는 이 leaf의 시험(`evidence/`)이다. snakeyaml은 시험에서만 쓴다(소유자 결정 2026-09-25). +- 유스케이스 순서나 업무 라우팅 정책을 broker 어댑터 안에 숨기지 않는다. +- `OutboxMessagePublishAdapter`는 위임만 하고 의존성 로그를 내지 않는다. 확정된 FAILED/DEAD 전이가 정해진 + ERROR 하나를 가진다. -## Tests +## 테스트 -Use unit/contract tests with a fake canonical publisher. No real network or broker is used in -focused tests; settings records receive binding/validation tests when configuration changes. +가짜 정해진 publisher로 단위·계약 시험을 쓴다. 이 모듈만 보는 시험은 실제 네트워크나 broker를 쓰지 않는다. +설정이 바뀌면 settings record에 바인딩·검증 시험을 더한다. diff --git a/src/adapter/outbound/messaging/README.md b/src/adapter/outbound/messaging/README.md index 433775e0..95aa5803 100644 --- a/src/adapter/outbound/messaging/README.md +++ b/src/adapter/outbound/messaging/README.md @@ -25,7 +25,7 @@ bridge는 broker SDK나 transport SPI를 직접 보지 않는다. legacy `KafkaS seam과 그 위의 `MessagePublisher`·`OutboxEnvelopeJson`은 outbox를 canonical 하나로 통일하면서 삭제했다(2026-09-28, 소유자 결정 7). -## canonical platform bridge +## 정해진 플랫폼 bridge `IntegrationEventPublishPort`는 `app.messaging.producer-id`가 명시되고 platform publisher bean이 있을 때만 생성된다. exact `ValidatedIntegrationEvent.envelopeBytes()`를 보존하고 platform의 중앙 diff --git a/src/adapter/outbound/notification/CLAUDE.md b/src/adapter/outbound/notification/CLAUDE.md index 2a7822de..16bd153e 100644 --- a/src/adapter/outbound/notification/CLAUDE.md +++ b/src/adapter/outbound/notification/CLAUDE.md @@ -1,52 +1,49 @@ -# adapter:outbound:notification — notification adapter +# adapter:outbound:notification — 알림 어댑터 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-notification` -- Gradle path: `:adapter:outbound:notification` -- Focused test (derived from Gradle path): `./gradlew :adapter:outbound:notification:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-outbound-notification` +- Gradle 경로: `:adapter:outbound:notification` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:outbound:notification:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.outbound.notification`. +패키지 루트: `dev.caskeleton.adapter.outbound.notification`. -## Responsibility +## 책임 -- Preserve the current raw notification router/provider seams only as the `R0 legacy` compatibility - baseline until the reviewed canonical cutover removes them. -- Implement future provider protocols behind application-owned ports without leaking SDK, transport, - bootstrap, or persistence types. -- Own provider settings, technical fallback mechanics, and provider adaptation; application policy - owns mode, eligibility, retry/fallback decisions and business failure semantics. -- Reuse `adapter:outbound:support` for shared outbound concerns. +- 지금의 raw 알림 router·provider 이음매는 리뷰를 거친 정해진 전환(cutover)이 지울 때까지 `R0 legacy` 호환 + 기준선으로만 지킨다. +- 앞으로의 provider 프로토콜은 애플리케이션이 가진 포트 뒤에서 구현하고, SDK·전송·bootstrap·영속 타입을 + 새게 하지 않는다. +- provider 설정, 기술적 대체 장치, provider 연결을 가진다. 모드, 자격, 재시도·대체 판단, 업무 실패의 뜻은 + 애플리케이션 정책이 가진다. +- 공용 outbound 관심사는 `adapter:outbound:support`를 다시 쓴다. -## Current R0 freeze +## 지금의 R0 동결 -- `RoutingNotifier` performs route-list fan-out over `(Channel, providerId)`. -- `FailOpenNotificationProvider` applies one global fail-open rule. -- `google-email`/`GoogleEmailClient` and `slack-webhook`/`SlackClient` are fake-only extension seams, - not production integrations or qualified provider cards. -- Checked-in provider selector keys drift from the router's `routes` + provider `enabled` grammar. - Preserve and document that drift until the canonical graph replaces it; do not silently reinterpret - the old keys. -- There are no feature/application production consumers and no real-provider, durable, receipt, - security, load, or rotation evidence. -- The exact legacy deletion inventory lives in [README.md](README.md). Do not add behavior to those - classes while building their canonical replacements. +- `RoutingNotifier`가 `(Channel, providerId)` 위에서 route 목록으로 퍼뜨린다. +- `FailOpenNotificationProvider`가 전역 fail-open 규칙 하나를 적용한다. +- `google-email`/`GoogleEmailClient`와 `slack-webhook`/`SlackClient`는 fake로만 쓰는 확장 이음매다. 운영 연동이나 + 검증된 provider card가 아니다. +- 커밋해 둔 provider 선택 키는 router의 `routes` + provider `enabled` 문법과 어긋나 있다. 정해진 그래프가 + 대신할 때까지 그 어긋남을 지키고 적어 둔다. 옛 키를 소리 없이 다르게 해석하지 않는다. +- 기능·애플리케이션 운영 소비자가 없고, 실제 provider·durable·수신 확인·보안·부하·교체 증거가 없다. +- 지울 옛 코드의 정확한 목록은 [README.md](README.md)에 있다. 정해진 대체물을 만드는 동안 그 클래스에 동작을 + 더하지 않는다. -## Boundaries +## 경계 -- Allowed dependency edges come only from the module's - `src/config/architecture/modules.json` entry. -- No inbound DTO/controller, persistence, bootstrap, or sample dependency. -- Provider selection may route configured channels but must not encode business eligibility rules. -- No fully-qualified inline type references. `adapter:outbound:fileserver` already forbids these and - this leaf did not, so the same construct was a defect in one capability and ordinary style in the - next; the platform auto-configurations had accumulated twenty-two of them. A parameter written as - `dev.caskeleton.application.notification.platform.dispatch.ReconciliationJobStorePort jobs` hides - from the import block exactly the cross-leaf edge the import block exists to make readable. +- 허용 의존 edge는 이 모듈의 `src/config/architecture/modules.json` 항목에서만 온다. +- inbound DTO·controller, 영속, bootstrap, 샘플 의존이 없다. +- provider 선택은 설정한 채널로 보낼 수 있지만 업무 자격 규칙을 담으면 안 된다. +- 줄 안에 완전한 이름으로 쓴 타입 참조가 없다. `adapter:outbound:fileserver`는 이미 이것을 금지했고 이 leaf는 + 아니었다. 그래서 같은 구문이 한 capability에서는 결함이고 다음 capability에서는 평범한 문체였다. 플랫폼 자동 + 구성에 그런 것이 스물두 개 쌓여 있었다. + `dev.caskeleton.application.notification.platform.dispatch.ReconciliationJobStorePort jobs`처럼 쓴 매개변수는 + import 블록이 읽기 쉽게 보여 주려고 있는 바로 그 leaf 사이 edge를 import 블록에서 숨긴다. -## Tests +## 테스트 -Use provider/client fakes and contract tests; no real webhook or email network calls. Settings changes -include binding/validation tests. +provider·client fake와 계약 시험을 쓴다. 실제 webhook이나 email 네트워크 호출이 없다. 설정을 바꾸면 +바인딩·검증 시험을 더한다. diff --git a/src/adapter/outbound/notification/README.md b/src/adapter/outbound/notification/README.md index d87708af..b1382322 100644 --- a/src/adapter/outbound/notification/README.md +++ b/src/adapter/outbound/notification/README.md @@ -1,4 +1,4 @@ -# adapter:outbound:notification — R0 legacy truth +# adapter:outbound:notification — R0 legacy의 사실 > 현재 구현 전체는 교체 전 호환성 기준선인 `R0 legacy`다. `GoogleEmailClient`와 > `SlackClient`는 project-supplied seam일 뿐 실제 Google Mail 또는 Slack 연동이 아니며, @@ -12,7 +12,7 @@ correlation / fail-open 의존성 로깅을 재사용한다. `adapter-outbound-notification` row가 SSOT다. 이 문서는 코드 주석에서 덜어낸 **설계 결정의 근거**와 canonical 구현 전 삭제 대상을 모아둔 참조용 기록이다. -## Task 1 R0 truth table +## Task 1 R0 사실 표 | 축 | 현재 사실 | 증거와 한계 | | --- | --- | --- | @@ -54,18 +54,16 @@ client 는 포킹 프로젝트가 채우는 seam 이다. `GoogleEmailProvider`, `SlackWebhookProvider`). `GoogleEmailClient`/`SlackClient` 는 포크가 구현하는 seam 이며 실패는 데코레이터가 fail-open 처리한다. -## Removed R1 outbound experiment +## 지운 R1 outbound 실험 -The old top-level `catalog/`, `provider/`, and `template/` graph was never assembled by production -and has been removed. Do not recreate it to reach the canonical platform. The application R1 public -contract remains governed separately by NOTIF-ADR-005; new runtime code belongs under -`..notification.platform..`. +예전 최상위 `catalog/`, `provider/`, `template/` 그래프는 운영에서 한 번도 조립되지 않았고 지웠다. 정해진 플랫폼에 +닿으려고 그것을 다시 만들지 않는다. 애플리케이션 R1 공개 계약은 따로 NOTIF-ADR-005가 다룬다. 새 런타임 코드는 +`..notification.platform..` 아래에 둔다. -The context-aware HTML safety that was stronger in `LocalEmailRenderer` was carried forward before -removal: `platform.template.TemplateSlotPolicy` now validates operator-authored HTML against the -reviewed tag/attribute subset after rendering. +`LocalEmailRenderer`에서 더 강했던 문맥 인식 HTML 안전 장치는 지우기 전에 옮겨 왔다: 이제 +`platform.template.TemplateSlotPolicy`가 렌더링 뒤에 운영자가 쓴 HTML을 리뷰한 tag·attribute 부분집합과 대조한다. -## Wave G deletion inventory +## Wave G 삭제 목록 다음 surface는 canonical-only cutover와 retained evidence 검증이 끝난 뒤 한 묶음으로 제거한다. 그 전에는 동작을 확장하지 않고 R0 회귀 기준선으로만 유지한다. diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifier.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifier.java index f1026b9e..24cd7cfb 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifier.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifier.java @@ -55,6 +55,13 @@ final class NotificationEvidenceVerifier { /** A contract may extend a base; a longer chain is not followed. */ private static final int MAX_SUPERCLASS_DEPTH = 3; + /** + * The header of the column a table assigns grades in. The support matrix is written in Korean + * (docs/README.md), so its grade column is headed 등급; a table whose grade column is the first one + * lists what each grade requires and assigns nothing. + */ + private static final String GRADE_COLUMN_HEADER = "등급"; + private static final Pattern SUPERCLASS = Pattern.compile("\\bclass\\s+\\w+\\s+extends\\s+(\\w+)"); private static final Pattern PACKAGE = Pattern.compile("(?m)^package\\s+([\\w.]+)\\s*;"); @@ -117,7 +124,7 @@ final class NotificationEvidenceVerifier { } if (!insideTable) { insideTable = true; - gradeColumn = cells.indexOf("Grade"); + gradeColumn = cells.indexOf(GRADE_COLUMN_HEADER); if (gradeColumn > 0) { gradeAssigningTables++; } else { @@ -182,7 +189,9 @@ final class NotificationEvidenceVerifier { throw new IllegalStateException( "notification evidence: " + matrixFile.getName() - + " has no table that assigns a grade (a 'Grade' column that is not the first" + + " has no table that assigns a grade (a '" + + GRADE_COLUMN_HEADER + + "' column that is not the first" + " column), so no claim in it was checked."); } if (!problems.isEmpty()) { diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifierTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifierTest.java index b56efb04..bc574e12 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifierTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifierTest.java @@ -150,7 +150,7 @@ class NotificationEvidenceVerifierTest { Files.writeString( fixture.matrix(), """ - | Channel | Grade | + | 채널 | 등급 | | --- | --- | | email | Experimental | """); @@ -174,7 +174,7 @@ class NotificationEvidenceVerifierTest { Files.writeString( fixture.matrix(), """ - | Grade | Requires | + | 등급 | 필요한 claim | | --- | --- | | Stable | delivery | """); @@ -248,7 +248,7 @@ class NotificationEvidenceVerifierTest { Files.writeString( matrix, """ - | Channel | Grade | + | 채널 | 등급 | | --- | --- | | email | Stable | """); diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationReleaseGateTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationReleaseGateTest.java index 5f8df14b..35d0204b 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationReleaseGateTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationReleaseGateTest.java @@ -17,6 +17,7 @@ import org.junit.jupiter.api.Test; class NotificationReleaseGateTest { private static final Path DOCS = Path.of("..", "..", "..", "..", "docs", "notification"); + private static final Path ADRS = Path.of("..", "..", "..", "..", "docs", "adr"); @Test void requiredDocumentationAndAdrsExist() { @@ -29,10 +30,10 @@ class NotificationReleaseGateTest { assertThat(DOCS.resolve("configuration-reference.md")).exists(); assertThat(DOCS.resolve("migration-guide.md")).exists(); assertThat(DOCS.resolve("module-mapping.md")).exists(); - assertThat(DOCS.resolve("adr/NOTIF-ADR-001-durable-acceptance.md")).exists(); - assertThat(DOCS.resolve("adr/NOTIF-ADR-002-event-ledger-projection.md")).exists(); - assertThat(DOCS.resolve("adr/NOTIF-ADR-003-ambiguous-submission.md")).exists(); - assertThat(DOCS.resolve("adr/NOTIF-ADR-004-fcm-fid-primary.md")).exists(); + assertThat(ADRS.resolve("NOTIF-ADR-001-durable-acceptance.md")).exists(); + assertThat(ADRS.resolve("NOTIF-ADR-002-event-ledger-projection.md")).exists(); + assertThat(ADRS.resolve("NOTIF-ADR-003-ambiguous-submission.md")).exists(); + assertThat(ADRS.resolve("NOTIF-ADR-004-fcm-fid-primary.md")).exists(); } @Test @@ -42,14 +43,16 @@ class NotificationReleaseGateTest { // The terms must appear, but only under the refusal heading. Asserting they are absent // altogether would be the wrong test: a matrix that never mentions guaranteed delivery leaves // the reader to assume it, which is exactly the assumption this document exists to remove. - int refusalHeading = text.indexOf("## Not supported"); + int refusalHeading = text.indexOf("## 지원하지 않는 것"); assertThat(refusalHeading).as("the matrix must state what it refuses to claim").isPositive(); String claims = text.substring(0, refusalHeading); String refusals = text.substring(refusalHeading); - assertThat(claims).doesNotContain("guaranteed delivery", "guaranteed read", "exactly-once"); - assertThat(refusals).contains("guaranteed delivery", "guaranteed read", "exactly-once"); + assertThat(claims) + .doesNotContain( + "전달 보장", "읽음 보장", "정확히 한 번", "guaranteed delivery", "guaranteed read", "exactly-once"); + assertThat(refusals).contains("전달 보장", "읽음 보장", "정확히 한 번"); assertThat(text).contains("PROVIDER_ACCEPTED", "AMBIGUOUS", "FCM_FID"); } @@ -57,7 +60,7 @@ class NotificationReleaseGateTest { void theEvidenceDocumentStatesTheForbiddenPromotions() throws IOException { String text = Files.readString(DOCS.resolve("support-matrix.md")); - assertThat(text).contains("is not `DEVICE_DELIVERED`"); - assertThat(text).contains("is not `DELIVERED`"); + assertThat(text).contains("`DEVICE_DELIVERED`가 아니다"); + assertThat(text).contains("`DELIVERED`가 아니다"); } } diff --git a/src/adapter/outbound/objectstorage/CLAUDE.md b/src/adapter/outbound/objectstorage/CLAUDE.md index f7306d2f..49182c7c 100644 --- a/src/adapter/outbound/objectstorage/CLAUDE.md +++ b/src/adapter/outbound/objectstorage/CLAUDE.md @@ -1,51 +1,46 @@ -# adapter:outbound:objectstorage — module rules +# adapter:outbound:objectstorage — 모듈 규칙 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-objectstorage` -- Gradle path: `:adapter:outbound:objectstorage` -- Focused test: `./gradlew :adapter:outbound:objectstorage:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-outbound-objectstorage` +- Gradle 경로: `:adapter:outbound:objectstorage` +- 이 모듈만 시험: `./gradlew :adapter:outbound:objectstorage:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.outbound.objectstorage`. Design rationale and truthful -readiness live in [README.md](README.md) and -`docs/registries/object-storage-readiness.yaml`. +패키지 루트: `dev.caskeleton.adapter.outbound.objectstorage`. 설계 근거와 사실대로 적은 준비 상태는 +[README.md](README.md)와 `docs/registries/object-storage-readiness.yaml`에 있다. -## Responsibility +## 책임 -- Implement application-core semantic object publication, read, retirement, and operation - resolution ports behind provider-neutral bounded streaming and strict durable control records. -- Compile disabled-by-default `app.object-storage` settings into exact immutable - provider/destination/route/policy bindings before constructing selected resources. -- Provide `filesystem-local-dev` as an R1-only development provider. -- Keep scanner maintenance composition separate; unsupported capabilities contribute no bean. - There is no purge, direct-grant, or multipart port. +- application-core의 semantic object 게시·읽기·폐기·operation 해석 포트를 provider 중립의 한계 있는 streaming과 + 엄격한 durable 제어 레코드 뒤에서 구현한다. +- 기본 꺼짐인 `app.object-storage` 설정을, 고른 자원을 만들기 전에 정확하고 바뀌지 않는 + provider·destination·route·policy 바인딩으로 컴파일한다. +- R1 전용 개발 provider로 `filesystem-local-dev`를 준다. +- scanner 유지보수 조립은 따로 둔다. 지원하지 않는 capability는 bean을 기여하지 않는다. purge·direct-grant· + multipart 포트는 없다. -## Allowed +## 허용 -- Project dependencies are exactly those allowed by the `adapter-outbound-objectstorage` entry in - `src/config/architecture/modules.json`; currently application-core, shared-contract, - application-objectstorage and the registered support edge (`adapter:outbound:support`: its - descriptor-based `SecureFileAccess`/`SecureDirectoryWalk`, which every local-dev file access goes - through, and `StrictSettingsBinder` — the `app.object-storage` tree is bound strictly, environment - included, capability rule 4). -- Provider SDK/configuration types stay within this leaf. -- Provider contributions may describe support without side effects and may construct resources - only after exact selection. +- 프로젝트 의존은 `src/config/architecture/modules.json`의 `adapter-outbound-objectstorage` 항목이 허용한 것뿐이다. + 지금은 application-core, shared-contract, application-objectstorage, 그리고 등록된 support edge + (`adapter:outbound:support`: 모든 local-dev 파일 접근이 거치는 descriptor 기반 `SecureFileAccess`/ + `SecureDirectoryWalk`, 그리고 `StrictSettingsBinder` — `app.object-storage` 트리는 환경 변수까지 엄격하게 + 바인딩한다. capability 규칙 4)다. +- provider SDK·설정 타입은 이 leaf 안에 머문다. +- provider 기여는 부작용 없이 지원 내용을 설명할 수 있고, 정확히 골라진 뒤에만 자원을 만들 수 있다. -## Forbidden +## 금지 -- Inbound adapters, sibling outbound adapters, persistence, or app-bootstrap dependencies. -- Provider keys, paths, locators, SDK types, Spring types, or control-record types leaking into - application-core. -- A default provider/destination/namespace, local-dev in production, or startup mutation when the - capability is disabled. -- Normal routing types implementing the scanner maintenance port. -- Claims above the exact rows in `docs/registries/object-storage-readiness.yaml`. -- Adapting new semantic operations back to legacy caller-keyed overwrite semantics. +- inbound 어댑터, 이웃 outbound 어댑터, 영속, app-bootstrap 의존. +- provider 키·경로·locator·SDK 타입·Spring 타입·제어 레코드 타입이 application-core로 새는 것. +- 기본 provider·destination·namespace, 운영에서 local-dev, capability가 꺼져 있을 때 기동 중 변경. +- 보통 라우팅 타입이 scanner 유지보수 포트를 구현하기. +- `docs/registries/object-storage-readiness.yaml`의 정확한 행보다 높은 주장. +- 새 semantic operation을 옛 호출자 키 기반 덮어쓰기 뜻으로 되돌려 맞추기. -## Test +## 테스트 ```bash cd src diff --git a/src/adapter/outbound/objectstorage/README.md b/src/adapter/outbound/objectstorage/README.md index 0e85a8ba..696b97c3 100644 --- a/src/adapter/outbound/objectstorage/README.md +++ b/src/adapter/outbound/objectstorage/README.md @@ -1,35 +1,32 @@ -# adapter:outbound:objectstorage — design-decision reference +# adapter:outbound:objectstorage — 설계 결정 참고 -Object-storage driven adapter under -`dev.caskeleton.adapter.outbound.objectstorage`. It implements the semantic contracts in -`dev.caskeleton.application.objectstorage` and keeps provider keys, paths, SDK types, and control -records behind the application boundary. +`dev.caskeleton.adapter.outbound.objectstorage` 아래의 object storage driven 어댑터다. +`dev.caskeleton.application.objectstorage`의 semantic 계약을 구현하고, provider 키·경로·SDK 타입·제어 +레코드를 애플리케이션 경계 뒤에 둔다. -The allowed production dependencies are owned by -`src/config/architecture/modules.json`. Module rules live in [CLAUDE.md](CLAUDE.md), the full design -in `docs/design/2026-07-28-objectstorage-production-capability-design.md`, and exact -evidence claims in `docs/registries/object-storage-readiness.yaml`. +허용 운영 의존은 `src/config/architecture/modules.json`이 가진다. 모듈 규칙은 [CLAUDE.md](CLAUDE.md), 전체 +설계는 `docs/design/2026-07-28-objectstorage-production-capability-design.md`, 정확한 증거 주장은 +`docs/registries/object-storage-readiness.yaml`에 있다. -For when to use this capability rather than the HTTP Fileserver platform, see -[`docs/storage-capability-boundary.md`](../../../../docs/storage-capability-boundary.md). +HTTP 파일 서버 플랫폼 대신 이 capability를 언제 쓰는지는 +[`docs/storage-capability-boundary.md`](../../../../docs/storage-capability-boundary.md)를 본다. -## Current readiness +## 지금 준비 상태 -Batch B implements the provider-neutral namespace/control kernel and -`filesystem-local-dev` managed single upload/download at R1. R1 means bounded local functional -evidence only: +Batch B가 provider 중립 namespace·제어 핵심과 `filesystem-local-dev`의 관리형 단일 업로드·다운로드를 R1으로 +구현한다. R1은 한계 있는 로컬 기능 증거만 뜻한다: -- immutable streamed create with exact SHA-256 and exact version inspection; -- full/range bounded reads; -- strict canonical control-record codecs and single-process CAS; -- same-operation replay without invoking the producer again; -- restart/path/symlink/corruption/fault characterization; -- exactly-once selected-provider lifecycle. +- 정확한 SHA-256과 정확한 version 검사를 하는, 바뀌지 않는 streaming 생성; +- 전체·범위 지정의 한계 있는 읽기; +- 엄격한 정규형 제어 레코드 codec과 단일 프로세스 CAS; +- producer를 다시 부르지 않는 같은 operation의 재생; +- 재시작·경로·symlink·손상·장애 특성 확인; +- 고른 provider의 lifecycle을 정확히 한 번. -It does not prove multi-node CAS, power-loss durability, production credentials/TLS/IAM/encryption, -S3 response-loss behavior, or R2 readiness. Direct transfer, multipart, quarantine, retention, and -production reconciliation cards remain R0. Direct transfer and multipart have no code: the unassembled -implementation was removed (recovery path in `docs/capability-status.md` 「제거된 코드」). +여러 노드 CAS, 전원 상실 내구성, 운영 credential·TLS·IAM·암호화, S3 응답 유실 동작, R2 준비는 증명하지 +않는다. direct transfer, multipart, quarantine, retention, 운영 reconciliation card는 R0에 머문다. direct +transfer와 multipart는 코드가 없다: 조립되지 않은 구현을 지웠다(되살리는 길은 `docs/capability-status.md` +「제거된 코드」). ## 제공하는 것 · 추가할 한 줄 · env 키 @@ -49,110 +46,103 @@ implementation was removed (recovery path in `docs/capability-status.md` 「제 bean도 두지 않는다. - env 키: 전용 `APP_*` 키는 없다. provider·destination이 map 구조라 배포의 `application-*.yml`에 `app.object-storage.{default-destination, providers.<id>.*, destinations.<id>.*}`를 적는다(아래 - 「Activation and routing」). 빠지면 기동 시 binding compile이 실패한다. + 「켜기와 라우팅」). 빠지면 기동 시 binding compile이 실패한다. -## Activation and routing +## 켜기와 라우팅 -The canonical namespace is `app.object-storage`. It is on when the module is present and off only -with `app.object-storage.enabled=false`. On requires an explicit provider, exact provider version, -logical destination, route token, binding/policy revisions, and bounded sizes. Settings compile fully before any selected provider creates a -directory, client, thread, scheduler, or credential lookup. +정해진 namespace는 `app.object-storage`다. 모듈이 있으면 켜지고 `app.object-storage.enabled=false`일 때만 +꺼진다. 켜려면 명시한 provider, 정확한 provider version, 논리 destination, route token, binding·policy +revision, 한계 있는 크기가 필요하다. 고른 provider가 디렉터리, client, 스레드, scheduler, credential 조회를 +만들기 전에 설정을 모두 컴파일한다. -`filesystem-local-dev` is rejected under `prod`/`production`. Normal composition contributes only -managed publication, inspection/transfer, retirement, and operation-resolution ports. Scanner -maintenance composition stays separate. There is no purge or direct-grant port. +`filesystem-local-dev`는 `prod`/`production`에서 거절한다. 보통 조립은 관리형 게시, 조회·전송, 폐기, +operation 해석 포트만 기여한다. scanner 유지보수 조립은 따로 둔다. purge나 direct-grant 포트는 없다. -S3 retirement deletes the exact version a HEAD verified (`DeleteObject` with `versionId`). An -`If-Match` condition on DELETE is not used: the qualified MinIO release ignores it (the MinIO lane -shows a stale ETag still deleting), and the SDK documents it for directory buckets only. A version-id -DELETE cannot touch an overwrite that landed after the HEAD, so it is conditional without relying on -the vendor honouring a header. It needs a bucket with versioning enabled: an S3 operation profile -that claims `CONDITIONAL_RETIREMENT` makes startup read `GetBucketVersioning` and refuse anything -but `Enabled`, and a retire that finds no version id is refused rather than turned into a by-key -delete. +S3 폐기는 HEAD가 확인한 정확한 version을 지운다(`versionId`를 준 `DeleteObject`). DELETE에 `If-Match` 조건은 +쓰지 않는다: 검증한 MinIO 릴리스는 그것을 무시하고(MinIO lane에서 낡은 ETag로도 지워진다), SDK는 그것을 +directory bucket에만 적는다. version id를 준 DELETE는 HEAD 뒤에 들어온 덮어쓰기를 건드릴 수 없으니, vendor가 +header를 지키는지에 기대지 않고도 조건부다. versioning이 켜진 bucket이 필요하다: `CONDITIONAL_RETIREMENT`를 +주장하는 S3 operation profile은 기동 때 `GetBucketVersioning`을 읽고 `Enabled`가 아니면 거절한다. version id를 +찾지 못한 폐기는 키 기준 삭제로 바꾸지 않고 거절한다. -The local provider maps provider-neutral logical control keys to `.record` leaf files. This permits -object-store-valid pairs such as `reference` and `reference/lifecycle` without a filesystem -file/directory collision; callers and durable control records retain the canonical logical keys. +로컬 provider는 provider 중립 논리 제어 키를 `.record` leaf 파일에 대응시킨다. 그래서 `reference`와 +`reference/lifecycle`처럼 object store에서는 맞는 짝이 파일 시스템의 파일·디렉터리 충돌 없이 함께 있을 수 +있다. 호출자와 durable 제어 레코드는 정규 논리 키를 그대로 가진다. -## Provider and dependency scope +## provider와 의존 범위 -The AWS SDK v2 BOM stays module-scoped because Spring Boot does not manage -`software.amazon.awssdk:*`. The whole-`byte[]` `ObjectStoragePort` generation and its filesystem/S3 -adapters were removed; the canonical semantic ports are the only generation (recovery path in -`docs/capability-status.md` 「제거된 코드」). +Spring Boot가 `software.amazon.awssdk:*`를 관리하지 않으니 AWS SDK v2 BOM은 모듈 범위에 둔다. `byte[]` 전체를 +쓰던 `ObjectStoragePort` 세대와 그 파일 시스템·S3 어댑터는 지웠다. 정해진 semantic 포트가 유일한 세대다 +(되살리는 길은 `docs/capability-status.md` 「제거된 코드」). -## Verification +## 검증 -Focused contracts cover codecs/state machines, local provider behavior, fail-closed binding, -composition side effects/lifecycle, routing replay/read behavior, and the readiness registry. +이 모듈만 보는 계약이 codec·상태 기계, 로컬 provider 동작, 실패하면 닫히는 바인딩, 조립 부작용·lifecycle, +라우팅 재생·읽기 동작, readiness registry를 덮는다. ```bash cd src ./gradlew :adapter:outbound:objectstorage:check --console=plain ``` -### Provider contract for a new provider +### 새 provider를 위한 provider 계약 -`ObjectStorageProviderContract` is in this leaf's test fixtures, because the `ObjectStorageProvider` -SPI is this leaf's own. The local-dev provider (`LocalDevObjectStorageProviderTest`) and the S3 -provider against MinIO (`MinioS3ManagedObjectProviderContractTest`) both extend it. A provider a -derived service adds extends the same class instead of copying it: +`ObjectStorageProvider` SPI가 이 leaf의 것이므로 `ObjectStorageProviderContract`는 이 leaf의 test fixtures에 +있다. local-dev provider(`LocalDevObjectStorageProviderTest`)와 MinIO에 대고 도는 S3 provider +(`MinioS3ManagedObjectProviderContractTest`)가 모두 그것을 상속한다. 파생 서비스가 더하는 provider는 복사하지 +않고 같은 클래스를 상속한다: ```groovy testImplementation testFixtures(project(':adapter:outbound:objectstorage')) ``` -### MinIO qualification lanes +### MinIO 검증 lane -`objectStorageMinioContractTest` and `objectStorageMinioFaultTest` run a real MinIO and Toxiproxy. -They run in the root `integrationCheck` (main push and nightly) and in -`.github/workflows/object-storage-qualification.yml` on pull requests that touch object storage — -not in this leaf's `mainCheck`, which ran them a second time on every main push. Their images are read from one file, -`src/test/resources/object-storage/minio-provider-evidence.json`, whose `image` digest is the -release the `status`, `excludedProfiles` and `limitations` beside it were measured on. -`MinioQualificationImage` (in `src/test`, checked by the leaf's `test` without Docker) reads it. +`objectStorageMinioContractTest`와 `objectStorageMinioFaultTest`는 실제 MinIO와 Toxiproxy를 돌린다. 루트 +`integrationCheck`(main push와 nightly)와, object storage를 건드리는 pull request의 +`.github/workflows/object-storage-qualification.yml`에서 돈다 — 이 leaf의 `mainCheck`에서는 돌지 않는다. +거기서는 main push마다 두 번 돌았다. image는 파일 하나 +`src/test/resources/object-storage/minio-provider-evidence.json`에서 읽는다. 그 `image` digest는 옆에 적힌 +`status`, `excludedProfiles`, `limitations`를 잰 릴리스다. `MinioQualificationImage`(`src/test`에 있고, leaf의 +`test`가 Docker 없이 검사한다)가 그것을 읽는다. -- The image is pulled before any container is built. If it cannot be pulled the lane fails with - `pinned image unavailable: <reference>`: a supply failure, not an adapter defect. The lane does - not skip, because a skipped vendor lane would be green with no vendor evidence. -- A mirror of the same digest is set with `OBJECT_STORAGE_MINIO_IMAGE` or - `-PobjectStorageMinioImage=<registry>/<repo>@sha256:<evidence digest>`. A value that does not end - in the evidence digest is refused: a different build is a new measurement, made by re-running the - lanes and rewriting the evidence file (image and findings together). -- The local compose runtime (`compose.yaml`, and the compose lanes' smoke client in `src/app-bootstrap/compose-lanes/lane-services.yaml`; `LOCAL_MINIO_IMAGE`) uses the same digest. - `ComposeMinioImageMatchesEvidenceTest` (leaf `test`) fails when the compose default and the - evidence disagree; change both together. -- The contract lane also runs `MinioS3ManagedObjectProviderContractTest`: the S3 adapter itself under - the provider contract the local-dev provider inherits, on the production client factory, over TLS - with a certificate made for the run (a binding only accepts HTTPS). Its first run found two adapter - defects the mocked unit tests could not: every create failed because the SDK cancels the request - body once it holds Content-Length bytes (and at once for an empty body), and every read with a - consumer chunk below the network buffer size failed because Netty delivers 8 KiB buffers. Both - are fixed (`S3AsyncRequestBodyBridge`, `S3AsyncResponseBodyBridge.TRANSPORT_BUFFER_CEILING_BYTES`). +- container를 만들기 전에 image를 받는다. 받지 못하면 lane은 `pinned image unavailable: <reference>`로 + 실패한다: 어댑터 결함이 아니라 공급 실패다. lane은 건너뛰지 않는다. 건너뛴 vendor lane은 vendor 증거 없이 + 초록이 되기 때문이다. +- 같은 digest의 mirror는 `OBJECT_STORAGE_MINIO_IMAGE`나 + `-PobjectStorageMinioImage=<registry>/<repo>@sha256:<evidence digest>`로 정한다. 증거 digest로 끝나지 않는 + 값은 거절한다: 다른 build는 새 측정이고, lane을 다시 돌려 증거 파일(image와 측정 결과를 함께)을 다시 써서 + 만든다. +- 로컬 compose 런타임(`compose.yaml`, 그리고 compose lane의 smoke client + `src/app-bootstrap/compose-lanes/lane-services.yaml`. `LOCAL_MINIO_IMAGE`)도 같은 digest를 쓴다. + `ComposeMinioImageMatchesEvidenceTest`(leaf `test`)는 compose 기본값과 증거가 다르면 실패한다. 둘을 함께 + 바꾼다. +- contract lane은 `MinioS3ManagedObjectProviderContractTest`도 돌린다: S3 어댑터 자체를 local-dev provider가 + 상속하는 provider 계약 아래에서, 운영 client factory로, 그 실행을 위해 만든 인증서로 TLS 위에서 시험한다 + (binding은 HTTPS만 받는다). 첫 실행에서 mock 단위 시험이 찾지 못한 어댑터 결함 둘을 찾았다: SDK가 + Content-Length 바이트를 받으면 요청 body를 취소해서(빈 body이면 바로) 모든 생성이 실패했고, Netty가 8 KiB + buffer로 넘겨서 network buffer 크기보다 작은 소비자 chunk로 하는 모든 읽기가 실패했다. 둘 다 고쳤다 + (`S3AsyncRequestBodyBridge`, `S3AsyncResponseBodyBridge.TRANSPORT_BUFFER_CEILING_BYTES`). -#### Image source (review 05-09, measured 2026-11-02) +#### image 출처 (review 05-09, 2026-11-02 측정) -Docker Hub `minio/minio` and `quay.io/minio/minio` stopped serving MinIO, so the measured digest of -the old release (2024-01-16) could not be mirrored. Two maintained builds were pulled and measured -with the same requests (create-only PUT twice, stale and current `If-Match` PUT, create-only -multipart completion onto an existing key, stale `If-Match` DELETE): +Docker Hub `minio/minio`와 `quay.io/minio/minio`가 MinIO 제공을 멈춰서, 옛 릴리스(2024-01-16)의 측정한 digest를 +mirror할 수 없었다. 유지되는 build 둘을 받아 같은 요청(create-only PUT 두 번, 낡은·현재 `If-Match` PUT, 있는 +키 위의 create-only multipart 완료, 낡은 `If-Match` DELETE)으로 쟀다: -| Candidate | Result | Decision | +| 후보 | 결과 | 결정 | | --- | --- | --- | -| `pgsty/minio@sha256:b6bfe723…` (community fork on Docker Hub, `RELEASE.2026-08-04T00-00-00Z`) | 412 / 412, 200 / 412; DELETE ignores `If-Match` | **Chosen.** Named release tags, `pgsty/mc` with a shell for the compose bucket bootstrap, runs as root like the old image | -| `cgr.dev/chainguard/minio@sha256:0a011000…` (`RELEASE.2026-10-23T20-06-51Z`) | Same results | Rejected: the free tier offers only a moving `latest` tag, it runs as uid 65532 (the compose volume would need re-owning), and `cgr.dev/chainguard/minio-client` has no shell | +| `pgsty/minio@sha256:b6bfe723…`(Docker Hub의 커뮤니티 fork, `RELEASE.2026-08-04T00-00-00Z`) | 412 / 412, 200 / 412. DELETE는 `If-Match`를 무시한다 | **골랐다.** 이름 있는 릴리스 태그, compose bucket 준비용 셸이 있는 `pgsty/mc`, 옛 image처럼 root로 돈다 | +| `cgr.dev/chainguard/minio@sha256:0a011000…`(`RELEASE.2026-10-23T20-06-51Z`) | 같은 결과 | 버렸다: 무료 등급은 움직이는 `latest` 태그만 주고, uid 65532로 돌며(compose volume 소유자를 바꿔야 한다), `cgr.dev/chainguard/minio-client`에는 셸이 없다 | -The new release refuses create-only overwrites, which the old one accepted. So the evidence is now -`status: SUPPORTED` for the managed create-only profiles (`supportedProfiles`), the direct -(presigned) profiles stay excluded because they were not measured, and the adapter allowlist gained -the provider type `s3-compatible-minio-pgsty-release-2026-08-04t00-00-00z` (version -`release-2026-08-04t00-00-00z-sdk-2.30.0`). Only that release may claim `IMMUTABLE_CREATE`; no MinIO -release may claim `MULTI_NODE_LINEARIZABLE_CAS` or `RESPONSE_LOSS_RESOLUTION`, because the evidence -is one single-node container. The 2024-01-16 type stays for servers that still run it, with its -old restrictions. +새 릴리스는 옛 릴리스가 받아 주던 create-only 덮어쓰기를 거절한다. 그래서 증거는 이제 관리형 create-only +profile(`supportedProfiles`)에 대해 `status: SUPPORTED`이고, direct(presigned) profile은 재지 않았으니 계속 +빠지며, 어댑터 허용 목록에 provider 타입 `s3-compatible-minio-pgsty-release-2026-08-04t00-00-00z`(version +`release-2026-08-04t00-00-00z-sdk-2.30.0`)가 더해졌다. 그 릴리스만 `IMMUTABLE_CREATE`를 주장할 수 있다. 증거가 +단일 노드 container 하나이므로 어떤 MinIO 릴리스도 `MULTI_NODE_LINEARIZABLE_CAS`나 `RESPONSE_LOSS_RESOLUTION`을 +주장할 수 없다. 2024-01-16 타입은 아직 그것을 돌리는 서버를 위해 옛 제한과 함께 남는다. -The compose client `minio-init` uses `pgsty/mc` by digest (`LOCAL_MINIO_MC_IMAGE` overrides it). +compose client `minio-init`은 digest로 `pgsty/mc`를 쓴다(`LOCAL_MINIO_MC_IMAGE`가 덮어쓴다). ```bash cd src diff --git a/src/adapter/outbound/persistence-fileserver/CLAUDE.md b/src/adapter/outbound/persistence-fileserver/CLAUDE.md index 1df1b76c..bb4c0a83 100644 --- a/src/adapter/outbound/persistence-fileserver/CLAUDE.md +++ b/src/adapter/outbound/persistence-fileserver/CLAUDE.md @@ -1,67 +1,59 @@ # persistence-fileserver -Relational persistence for the Fileserver capability: entities, Spring Data repositories and the -store adapters that implement `application-fileserver` ports. Root `AGENTS.md` and -`adapter/outbound/persistence-jpa/CLAUDE.md` still apply; this file adds what is local. +파일 서버 capability의 관계형 영속이다: 엔티티, Spring Data repository, `application-fileserver` 포트를 구현하는 +store 어댑터. 루트 `AGENTS.md`와 `adapter/outbound/persistence-jpa/CLAUDE.md`도 그대로 적용된다. 이 파일은 이 +leaf에만 있는 것을 더한다. -## Packages +## 패키지 -- `entity/` — JPA rows only. Every entity extends `AssignedIdEntity`. -- `repository/` — Spring Data interfaces and the SQL text they run (`CleanupClaimSql`). -- package root — the store adapters (`Jpa*`), `FileEntityMapper`, and the `@Configuration` - classes that register them as beans. +- `entity/` — JPA 행만. 모든 엔티티는 `AssignedIdEntity`를 상속한다. +- `repository/` — Spring Data 인터페이스와 그것이 돌리는 SQL 글(`CleanupClaimSql`). +- 패키지 루트 — store 어댑터(`Jpa*`), `FileEntityMapper`, 그것들을 bean으로 등록하는 `@Configuration` + 클래스. -`persistence-notification` follows the same rule (`platform.entity`, `platform.repository`, adapters -in `platform`), so the two capability leaves read the same way. +`persistence-notification`도 같은 규칙(`platform.entity`, `platform.repository`, 어댑터는 `platform`)을 +따르므로 두 capability leaf를 같은 방식으로 읽는다. -## Rules +## 규칙 -- **Transactions.** A store never opens one. Every write starts with - `CallerTransaction.require("<store> <operation>")`, so a use case that forgot - `TransactionPort.inWrite` fails instead of committing statement by statement. -- **New rows.** Ids are assigned before the insert, so an entity must say whether it is new: - extend `AssignedIdEntity` (`Persistable<UUID>`). Without it `save` merges — a SELECT before every - insert, and a second insert under an existing id overwrites the row instead of failing on the - primary key. A new `@Version` column may stay primitive `long`; newness comes from - `Persistable`, not from the version. -- **No policy here.** Retry budgets, lease lengths and other decisions belong to - `application-fileserver` and arrive as port arguments. A claim token or other fence travels in - the port type (`CleanupItem.claimToken`), never in a field of the adapter. -- **Claims.** A queue claim is one statement: CTE + `FOR UPDATE SKIP LOCKED` + `RETURNING` - (`CleanupClaimSql`). Settlements match the claim token and update zero rows for a stale worker. +- **트랜잭션.** store는 트랜잭션을 열지 않는다. 모든 쓰기는 `CallerTransaction.require("<store> <operation>")`로 + 시작한다. 그래서 `TransactionPort.inWrite`를 잊은 유스케이스는 문장마다 커밋하지 않고 실패한다. +- **새 행.** id를 insert 전에 정하므로 엔티티가 새것인지 스스로 말해야 한다: `AssignedIdEntity` + (`Persistable<UUID>`)를 상속한다. 그렇지 않으면 `save`가 merge한다 — insert마다 SELECT가 앞서고, 이미 있는 id로 + 하는 두 번째 insert가 primary key에서 실패하지 않고 행을 덮어쓴다. 새 `@Version` 열은 primitive `long`으로 둬도 + 된다. 새것인지는 version이 아니라 `Persistable`이 정한다. +- **여기에 정책을 두지 않는다.** 재시도 예산, lease 길이 같은 판단은 `application-fileserver`의 것이고 포트 + 인자로 온다. claim token 같은 fence는 어댑터 필드가 아니라 포트 타입(`CleanupItem.claimToken`)에 실려 다닌다. +- **claim.** queue claim은 문장 하나다: CTE + `FOR UPDATE SKIP LOCKED` + `RETURNING`(`CleanupClaimSql`). 마무리 + 처리는 claim token을 맞춰 보고, 낡은 worker이면 0행을 update한다. -## Migrations +## migration -- `src/main/resources/db/migration/jpa/fileserver/V*.sql`, applied as the capability's own Flyway - stream (`flyway_jpa_fileserver_history`). -- An applied file is never edited. Add a new version and its hash to the immutability list; - `persistence-jpa`'s `AppliedMigrationImmutabilityTest` pins these files where they live. +- `src/main/resources/db/migration/jpa/fileserver/V*.sql`. capability 자신의 Flyway stream + (`flyway_jpa_fileserver_history`)으로 적용한다. +- 적용한 파일은 고치지 않는다. 새 버전과 그 hash를 불변 목록에 더한다. `persistence-jpa`의 + `AppliedMigrationImmutabilityTest`가 이 파일들을 있는 자리에서 고정한다. -## Tests +## 테스트 -- `src/test` — this leaf's own tests, no container. Run: +- `src/test` — container 없는 이 leaf 자신의 시험. 돌리기: `./gradlew :adapter:outbound:persistence-fileserver:test --console=plain`. - - `FileserverStoreCallerTransactionTest` — every guarded write of every store refuses without a - caller transaction before it touches a repository (the Transactions rule above, one case per - write; Spring Data repositories are mocks). - - `FileserverPersistenceActivationTest` — the scan covers this package only, behind - `app.fileserver-platform.enabled`, and runs before the JPA root auto-configuration. - - `repository.CleanupClaimSqlTest` — the claim's text keeps its one-statement shape (the Claims - rule); the locking itself is checked on PostgreSQL by - `PostgreSqlFileserverReclamationIntegrationTest`. - - `entity.AssignedIdEntityTest` — newness from `Persistable`, on Hibernate over H2. - A new store write adds its case to the guard test; a new auto-configuration adds its line to the - activation test. -- Port contracts live in `application-fileserver` testFixtures (`*PortContract`, and - `FileQuotaLedgerContract` for the three quota ports, which share one table). The in-memory fakes - and the PostgreSQL tests both extend them; every port this leaf implements has one - (`docs/testing/TESTING_STRATEGY.md` 9.3). The PostgreSQL side of the seven added on - 2026-11-03 is tagged `jpa-contract` and runs in persistence-jpa's - `jpaPlatformContractTest` lane on `FileserverPostgreSqlStack`, whose clock a case moves. -- The real-PostgreSQL tests are still in `persistence-jpa`'s `postgresqlIntegrationTest` source - set, which owns the container and Flyway wiring, and the JPA readiness card - (`persistence-jpa/release/readiness-cards.yaml`, checked by `JpaReadinessRegistryTest`) names them as that - leaf's tasks — moving them means moving the card's tasks and selectors with them: - `postgresqlFileserverMigrationIntegrationTest`, `postgresqlFileserverMetadataIntegrationTest`, - `postgresqlFileserverReclamationIntegrationTest` + - `FileserverStoreCallerTransactionTest` — 모든 store의 보호된 쓰기는 호출자 트랜잭션이 없으면 repository에 + 닿기 전에 거절한다(위 트랜잭션 규칙, 쓰기마다 경우 하나. Spring Data repository는 mock이다). + - `FileserverPersistenceActivationTest` — scan은 `app.fileserver-platform.enabled` 뒤에서 이 패키지만 덮고, + JPA 루트 자동 구성보다 먼저 돈다. + - `repository.CleanupClaimSqlTest` — claim 글이 문장 하나 모양을 지킨다(claim 규칙). 잠금 자체는 + `PostgreSqlFileserverReclamationIntegrationTest`가 PostgreSQL에서 본다. + - `entity.AssignedIdEntityTest` — H2 위의 Hibernate에서 `Persistable`로 새것인지 정한다. + 새 store 쓰기는 보호 시험에 자기 경우를 더한다. 새 자동 구성은 켜기 시험에 자기 줄을 더한다. +- 포트 계약은 `application-fileserver` testFixtures에 있다(`*PortContract`, 그리고 테이블 하나를 같이 쓰는 quota + 포트 셋의 `FileQuotaLedgerContract`). 메모리 fake와 PostgreSQL 시험이 모두 그것을 상속한다. 이 leaf가 구현하는 + 포트는 모두 계약이 있다(`docs/testing/TESTING_STRATEGY.md` 9.3절). 2026-11-03에 더한 일곱 개의 PostgreSQL + 쪽은 `jpa-contract` tag를 달고 persistence-jpa의 `jpaPlatformContractTest` lane에서 + `FileserverPostgreSqlStack` 위에 돈다. 경우마다 그 시계를 옮긴다. +- 실제 PostgreSQL 시험은 아직 `persistence-jpa`의 `postgresqlIntegrationTest` source set에 있다. 그 source set이 + container와 Flyway 배선을 가지고, JPA readiness card(`persistence-jpa/release/readiness-cards.yaml`, + `JpaReadinessRegistryTest`가 검사)가 그 시험을 그 leaf의 태스크로 이름 댄다 — 옮기려면 card의 태스크와 + selector도 함께 옮겨야 한다: `postgresqlFileserverMigrationIntegrationTest`, + `postgresqlFileserverMetadataIntegrationTest`, `postgresqlFileserverReclamationIntegrationTest` (`./gradlew :adapter:outbound:persistence-jpa:<lane> --console=plain`). diff --git a/src/adapter/outbound/persistence-jpa/CLAUDE.md b/src/adapter/outbound/persistence-jpa/CLAUDE.md index bf3622e6..2fd3e384 100644 --- a/src/adapter/outbound/persistence-jpa/CLAUDE.md +++ b/src/adapter/outbound/persistence-jpa/CLAUDE.md @@ -1,112 +1,96 @@ -# adapter:outbound:persistence-jpa — JPA/PostgreSQL persistence adapter +# adapter:outbound:persistence-jpa — JPA·PostgreSQL 영속 어댑터 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-persistence-jpa` -- Gradle path: `:adapter:outbound:persistence-jpa` -- Focused test (derived from Gradle path): `./gradlew :adapter:outbound:persistence-jpa:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-outbound-persistence-jpa` +- Gradle 경로: `:adapter:outbound:persistence-jpa` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:outbound:persistence-jpa:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.outbound.persistence`. +패키지 루트: `dev.caskeleton.adapter.outbound.persistence`. -Design decisions previously kept as code comments (transaction templates, auditing capture, -failure-translation SPI, idempotency/outbox concurrency, distributed-lock TTL) live in -[README.md](README.md). This file stays the SSOT for module rules and contract tables. +예전에 코드 주석으로 두던 설계 결정(트랜잭션 template, 감사 값 잡기, 실패 번역 SPI, 멱등성·outbox 동시성, 분산 +lock TTL)은 [README.md](README.md)에 있다. 이 파일은 모듈 규칙과 계약 표의 정본으로 남는다. -This module is the RDBMS/JPA implementation base. It is not a datastore-neutral -core for MongoDB, Redis, DynamoDB, or other NoSQL stores. Future NoSQL persistence -adapters implement application/domain ports directly and must not depend on this module. +이 모듈은 RDBMS·JPA 구현 기반이다. MongoDB, Redis, DynamoDB나 다른 NoSQL 저장소를 위한 저장소 중립 core가 아니다. +앞으로의 NoSQL 영속 어댑터는 application·domain 포트를 직접 구현하고 이 모듈에 의존하면 안 된다. -## JPA relational persistence platform +## JPA 관계형 영속 플랫폼 -The platform in `docs/design/2026-08-11-jpa-persistence-platform-design.md` is -implemented here. The design models it as 18 Stable library modules; this repository's fail-closed -registry outranks that layout, so those modules are **packages** in this leaf and -`docs/jpa/repository-adaptation.md` records the mapping. Read it before moving a type between -packages. +`docs/design/2026-08-11-jpa-persistence-platform-design.md`의 플랫폼을 여기 구현했다. 설계는 그것을 Stable 라이브러리 +모듈 18개로 모델링한다. 이 저장소의 실패하면 닫히는 registry가 그 배치보다 앞서므로, 그 모듈들은 이 leaf의 +**패키지**이고 `docs/jpa/repository-adaptation.md`가 그 대응을 적는다. 타입을 다른 패키지로 옮기기 전에 그것을 읽는다. -| Platform package | Owns | +| 플랫폼 패키지 | 가지는 것 | |---|---| -| `autoconfigure` | package-private Boot composition root/runtime: vendor and optional-store imports and provider runtime beans. It is intentionally not exported as public API | -| `api` (+ `.capability`, `.error`, `.query`, `.transaction`) | framework-free contracts: operation and query names, the stable error hierarchy, commit-completion evidence, keyset cursors | -| `transaction` | `SpringTransaction`, the one transaction engine (`TransactionPort` over Spring's `PlatformTransactionManager`) | -| `springdata` | repository fragments, safe sort, fetch plans, keyset execution, stream guard | -| `hibernate` (+ `.batch`, `.bulk`, `.stateless`) | statement inspector, statistics, batch, bulk DML, stateless session | -| `postgresql` (+ `.error`, `.lock`, `.constraint`, `.json`, `.array`, `.range`, `.copy`) | SQLSTATE classification, lock options, JSONB, arrays and ranges, COPY | -| `migration` | `FlywaySchemaPolicy` (composed by the `startup` package's dangerous-configuration guard) | -| `startup` | package-private startup policy (`JpaStartupAutoConfiguration`): Flyway migration strategy, datasource env/product checks, OSIV/DDL/Hikari/TLS/H2 guards, the `jpaplatform` actuator view, the readiness `db` contribution. Moved here from app-bootstrap | -| `cache`, `envers`, `querydsl`, `security`, `observation` | opt-in library capabilities and the runtime-role verifier | -| `experimental` | multi-tenancy, RLS, schema/database tenancy, read replica — library code a deployment constructs itself; no flag turns it on | -| `testkit` (`src/testFixtures/java`) | ArchUnit rules, fixtures, query/plan assertions, PostgreSQL matrix, failure injection, Flyway validate gate, concurrent-index inspector and lock-wait inspector | +| `autoconfigure` | package-private Boot 조립 루트·런타임: vendor와 선택 저장소 import, provider runtime bean. 일부러 공개 API로 내놓지 않는다 | +| `api` (+ `.capability`, `.error`, `.query`, `.transaction`) | 프레임워크 없는 계약: operation·query 이름, 안정된 오류 계층, 커밋 완료 증거, keyset cursor | +| `transaction` | `SpringTransaction`, 유일한 트랜잭션 엔진(Spring `PlatformTransactionManager` 위의 `TransactionPort`) | +| `springdata` | repository fragment, 안전한 정렬, fetch plan, keyset 실행, stream guard | +| `hibernate` (+ `.batch`, `.bulk`, `.stateless`) | statement inspector, 통계, batch, bulk DML, stateless session | +| `postgresql` (+ `.error`, `.lock`, `.constraint`, `.json`, `.array`, `.range`, `.copy`) | SQLSTATE 분류, lock 옵션, JSONB, 배열과 범위, COPY | +| `migration` | `FlywaySchemaPolicy`(`startup` 패키지의 위험 설정 guard가 조립한다) | +| `startup` | package-private 기동 정책(`JpaStartupAutoConfiguration`): Flyway migration 전략, datasource env·제품 검사, OSIV·DDL·Hikari·TLS·H2 guard, `jpaplatform` actuator view, readiness `db` 기여. app-bootstrap에서 여기로 옮겼다 | +| `cache`, `envers`, `querydsl`, `security`, `observation` | 골라 쓰는 라이브러리 capability와 runtime role 검증기 | +| `experimental` | multi-tenancy, RLS, schema·database 테넌시, read replica — 배포가 스스로 만드는 라이브러리 코드. 켜는 flag가 없다 | +| `testkit`(`src/testFixtures/java`) | ArchUnit 규칙, fixture, query·plan 단언, PostgreSQL 표, 장애 주입, Flyway validate gate, concurrent index inspector, lock-wait inspector | -`springdata`, `hibernate` (`.batch`, `.bulk`, `.stateless`, statement inspector), `postgresql` -(`.error`, `.lock`, `.constraint`, `.json`, `.array`, `.range`, `.copy`), `api.query`, `envers`, -`querydsl`, `cache`, `observation` and `experimental` are **library API**: no configuration composes -them, and a service calls them from its own adapter leaf, which takes this leaf as `implementation`. -The entry points and the test that proves each one are listed in [README.md](README.md) -"라이브러리 API". +`springdata`, `hibernate`(`.batch`, `.bulk`, `.stateless`, statement inspector), `postgresql`(`.error`, `.lock`, +`.constraint`, `.json`, `.array`, `.range`, `.copy`), `api.query`, `envers`, `querydsl`, `cache`, `observation`, +`experimental`은 **라이브러리 API**다: 어떤 설정도 그것을 조립하지 않고, 서비스가 이 leaf를 `implementation`으로 받는 +자기 어댑터 leaf에서 부른다. 진입점과 각각을 증명하는 시험은 [README.md](README.md) 「라이브러리 API」에 있다. -### Spring composition ownership +### Spring 조립 소유 -`META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports` publishes two -package-private entries: `PersistenceJpaAutoConfiguration` and `PersistenceJpaRuntimeConfig`. -Because Boot loads those candidates independently, **both** require -`app.persistence-jpa.enabled=true`. The first owns vendor/entity/repository and -capability-store imports. The second contributes only the provider runtime beans -(`HibernateProviderPolicy`, `PostgreSqlRuntimeRoleVerifier`). The -transaction engine is `SpringTransaction` alone; the second engine -(`SpringJpaTransactionExecutor`/`FullTransactionRetryCoordinator`) was removed on 2026-09-25 — see -`docs/capability-status.md`. Never rely on the first candidate's condition to gate the sibling -import candidate. +`META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`는 package-private 항목 둘을 내놓는다: +`PersistenceJpaAutoConfiguration`과 `PersistenceJpaRuntimeConfig`. Boot가 그 후보를 따로따로 읽으므로 **둘 다** +`app.persistence-jpa.enabled=true`를 요구한다. 첫째는 vendor·entity·repository와 capability 저장소 import를 가진다. +둘째는 provider runtime bean(`HibernateProviderPolicy`, `PostgreSqlRuntimeRoleVerifier`)만 기여한다. 트랜잭션 엔진은 +`SpringTransaction` 하나뿐이다. 두 번째 엔진(`SpringJpaTransactionExecutor`/`FullTransactionRetryCoordinator`)은 +2026-09-25에 지웠다 — `docs/capability-status.md`를 본다. 첫째 후보의 조건이 이웃 import 후보를 막아 준다고 기대지 +않는다. -`enabled=false` is a full off, not a bean-only one: `JpaActivationEnvironmentPostProcessor` (this -leaf's `spring.factories`) appends Boot's `jdbc`/`hibernate`/`data.jpa`/`flyway` auto-configurations -to `spring.autoconfigure.exclude`, so no DataSource, pool, EntityManagerFactory or Flyway exists. +`enabled=false`는 bean만이 아니라 완전히 끄기다: `JpaActivationEnvironmentPostProcessor`(이 leaf의 `spring.factories`)가 +Boot의 `jdbc`/`hibernate`/`data.jpa`/`flyway` 자동 구성을 `spring.autoconfigure.exclude`에 붙인다. 그래서 DataSource, +pool, EntityManagerFactory, Flyway가 하나도 없다. -The same split applies to owner-safe PostgreSQL idempotency: this leaf constructs the concrete -PostgreSQL store behind `IdempotencyStorePort` (`PostgreSqlIdempotencyStoreConfig`, active only with -`app.capabilities.idempotency.provider=postgresql`), while `composition:idempotency` owns provider -selection, TTL/lease/codec policy, executor construction, and exclusivity validation. With that -provider the leaf also applies the `db/migration/jpa/core` + `db/migration/jpa/idempotency` Flyway -streams and activates the capability registry row at startup (`IdempotencySchemaStream`, skipped -when `app.runtime.migration-on-startup=false`), refuses a non-PostgreSQL data source, and -runs `IdempotencyReaper`. There is no V1/JDBC idempotency store and no `jdbc` provider value. +소유자를 안전하게 지키는 PostgreSQL 멱등성도 같은 분할을 쓴다: 이 leaf는 `IdempotencyStorePort` 뒤의 실제 PostgreSQL +store를 만들고(`PostgreSqlIdempotencyStoreConfig`, `app.capabilities.idempotency.provider=postgresql`일 때만 켜진다), +`composition:idempotency`가 provider 고르기, TTL·lease·codec 정책, executor 만들기, 배타성 검증을 가진다. 그 provider를 +고르면 leaf는 `db/migration/jpa/core` + `db/migration/jpa/idempotency` Flyway stream도 적용하고 기동 때 capability +registry 행을 켜며(`IdempotencySchemaStream`, `app.runtime.migration-on-startup=false`이면 건너뛴다), PostgreSQL이 아닌 +data source를 거절하고, `IdempotencyReaper`를 돌린다. V1·JDBC 멱등성 store도 `jdbc` provider 값도 없다. -This module is a capability selected by one build line (`runtimeOnly -project(':adapter:outbound:persistence-jpa')`); the template's default composition does not carry it. -Everything that only makes sense with a relational store therefore lives here and turns on with the -module: migration startup sequencing, resolved datasource/version validation, OSIV/DDL/pool/TLS/vendor -safety, the sanitized management endpoint/report (`startup`), the metered multi-instance lock -(`lock`), the readiness `db` contribution and the shipped settings -(`config/module-defaults/persistence-jpa.yml`). Use-case assembly does not: the outbox relay is -`composition:outbox-relay` because a driven adapter must not construct or call a use case. The leaf must have -zero imports from `dev.caskeleton.bootstrap`; startup failures go through `adapter:outbound:support` -(`support.startup`), and new composition helpers stay package-private so `verifyJpaApiSurface` does -not grow by wiring accident. +이 모듈은 빌드 한 줄(`runtimeOnly project(':adapter:outbound:persistence-jpa')`)로 고르는 capability다. 템플릿의 기본 +조립은 이것을 싣지 않는다. 그래서 관계형 저장소가 있을 때만 뜻이 있는 것은 모두 여기 있고 모듈과 함께 켜진다: +migration 기동 순서, 해석된 datasource·버전 검증, OSIV·DDL·pool·TLS·vendor 안전, 걸러 낸 관리 endpoint·보고 +(`startup`), metric을 단 다중 인스턴스 lock(`lock`), readiness `db` 기여, 출하하는 설정 +(`config/module-defaults/persistence-jpa.yml`). 유스케이스 조립은 아니다: driven 어댑터가 유스케이스를 만들거나 부르면 +안 되므로 outbox relay는 `composition:outbox-relay`다. leaf에는 `dev.caskeleton.bootstrap` import가 하나도 없어야 한다. +기동 실패는 `adapter:outbound:support`(`support.startup`)를 거치고, 새 조립 도우미는 package-private로 둬서 배선 +실수로 `verifyJpaApiSurface`가 늘지 않게 한다. -### Non-negotiables +### 양보할 수 없는 것 -- No `GenericRepository<T, ID>` and no platform base repository. Domains own their repositories. -- `TransactionCompletionUnknownException` is never retried. `JpaFailureContext` refuses to - represent a retryable completion-unknown failure, and `SpringTransaction` retries nothing. -- A caller that retries re-runs the whole use case in a new transaction and a new Persistence - Context. -- OSIV is false in every runtime profile; Flyway owns schema change and Hibernate only validates. -- A migration that locks a table already in use starts with `SET LOCAL lock_timeout = '5s';` - (`docs/jpa/migration-guide.md` "Bound the lock wait"). `MigrationLockWaitTest` refuses one - without it. Its list of migrations released before the rule never takes a new migration; it - grows only when the inspector learns a statement and finds it in a file already on `main`. -- Flyway holds its PostgreSQL migration lock for the session, never in an open transaction, or a - `CREATE INDEX CONCURRENTLY` migration waits for Flyway forever: `spring.flyway.postgresql.transactional-lock: - false` in the module defaults, and every Flyway built in code starts from - `FlywaySchemaPolicy.configure()` (`JpaProductionArchitectureTest` refuses `Flyway.configure()` and - constructing a Flyway configuration directly — `new FluentConfiguration()`, `new - ClassicConfiguration()`, a subclass; `docs/jpa/migration-guide.md` "Who may change the schema"). -- Metric tags, exception messages, and logs carry no SQL parameters, entity ids, tenant ids, or PII. -- Contracts run against real PostgreSQL. H2 never satisfies one. +- `GenericRepository<T, ID>`도 플랫폼 기반 repository도 없다. 도메인이 자기 repository를 가진다. +- `TransactionCompletionUnknownException`은 절대 재시도하지 않는다. `JpaFailureContext`는 재시도할 수 있는 + completion-unknown 실패를 나타내기를 거절하고, `SpringTransaction`은 아무것도 재시도하지 않는다. +- 재시도하는 호출자는 새 트랜잭션과 새 Persistence Context에서 유스케이스 전체를 다시 돌린다. +- OSIV는 모든 runtime profile에서 false다. schema 변경은 Flyway가 가지고 Hibernate는 검증만 한다. +- 이미 쓰이는 테이블을 잠그는 migration은 `SET LOCAL lock_timeout = '5s';`로 시작한다 + (`docs/jpa/migration-guide.md` "Bound the lock wait"). `MigrationLockWaitTest`가 그것이 없는 migration을 거절한다. 그 + 규칙 전에 릴리스한 migration 목록에는 새 migration을 넣지 않는다. 그 목록은 inspector가 문장을 새로 배우고 이미 + `main`에 있는 파일에서 그것을 찾았을 때만 늘어난다. +- Flyway는 PostgreSQL migration lock을 열린 트랜잭션이 아니라 세션 동안 쥔다. 아니면 `CREATE INDEX CONCURRENTLY` + migration이 Flyway를 영원히 기다린다: 모듈 기본값의 `spring.flyway.postgresql.transactional-lock: false`, 그리고 코드에서 + 만드는 모든 Flyway는 `FlywaySchemaPolicy.configure()`에서 시작한다(`JpaProductionArchitectureTest`가 + `Flyway.configure()`와 Flyway 설정을 직접 만드는 것 — `new FluentConfiguration()`, `new ClassicConfiguration()`, 하위 + 클래스 — 을 거절한다. `docs/jpa/migration-guide.md` "Who may change the schema"). +- metric tag, 예외 메시지, 로그는 SQL 매개변수, entity id, tenant id, 개인정보를 싣지 않는다. +- 계약은 실제 PostgreSQL에 대고 돈다. H2는 어떤 계약도 만족시키지 않는다. -### Platform lanes +### 플랫폼 lane ```bash cd src @@ -126,164 +110,145 @@ cd src :adapter:outbound:persistence-jpa:jpaPlatformPoolContractTest ``` -Every Docker-backed lane fails closed. A selected lane that discovers nothing, or a container that -cannot start, is an error rather than a skip — a skipped contract reports success for a database -nobody tested. +Docker를 쓰는 모든 lane은 실패하면 닫힌다. 고른 lane이 아무것도 찾지 못하거나 container가 시작하지 못하면 건너뛰기가 +아니라 오류다 — 건너뛴 계약은 아무도 시험하지 않은 데이터베이스에 대해 성공을 알린다. -## Responsibility +## 책임 -- JPA entities. -- Spring Data repositories. -- Persistence mappers. -- Repository adapter implementations. -- Outbox append: one model. `JpaOutboxStore` implements `OutboxAppendPort` and persists a - `ValidatedIntegrationEvent`'s exact envelope bytes and hashes; a claim restores the same event - from them. A row without complete canonical metadata is unreadable and goes to DEAD, never - published by guess. `V19` refuses unpublished pre-canonical rows. -- Outbox relay fencing: `claimBatch` records the claiming relay (`lease_owner`) and increments - `lease_token` under the claim's row lock (`V17`); `markPublished`/`markFailed`/`markDead` are one - conditional UPDATE on `event_id` + `IN_FLIGHT` + owner + token and return `APPLIED`/`STALE`. A - completion never loads and overwrites a row. The V2 outbox generation was deleted on 2026-09-25 - (`docs/capability-status.md`). -- `TransactionPort` implementation (`SpringTransaction`) — the bridge between - application transactional intent and Spring's `PlatformTransactionManager`. -- Audit-metadata base + actor seam (`audit/AuditableEntity`, `audit/AuditContextPort`, - `audit/DomainContextAuditContext`) — see "Persistence auditing contract" below. -- Vendor SPI extension points shared by all RDBMS vendors: - - `outbox/jpa/OutboxClaimRepository` — vendor module implements claim strategy (e.g. FOR UPDATE SKIP LOCKED); the implementations sit beside it in `outbox/postgresql` and `outbox/h2`. - - `failure/SqlStateErrorMapping` — vendor module contributes vendor-specific SQLState rows. +- JPA 엔티티. +- Spring Data repository. +- 영속 mapper. +- repository 어댑터 구현. +- outbox append: 모델 하나. `JpaOutboxStore`가 `OutboxAppendPort`를 구현하고 `ValidatedIntegrationEvent`의 정확한 envelope + 바이트와 hash를 저장한다. claim은 그것으로 같은 이벤트를 되살린다. 정해진 metadata가 다 갖춰지지 않은 행은 읽을 수 + 없고 DEAD로 간다. 짐작으로 발행하지 않는다. `V19`는 발행하지 않은 정해진 형식 이전 행을 거절한다. +- outbox relay fencing: `claimBatch`가 claim의 행 lock 아래에서 claim한 relay(`lease_owner`)를 기록하고 + `lease_token`을 올린다(`V17`). `markPublished`/`markFailed`/`markDead`는 `event_id` + `IN_FLIGHT` + owner + token에 + 대한 조건부 UPDATE 하나이고 `APPLIED`/`STALE`을 돌려준다. 완료는 행을 읽어서 덮어쓰지 않는다. V2 outbox 세대는 + 2026-09-25에 지웠다(`docs/capability-status.md`). +- `TransactionPort` 구현(`SpringTransaction`) — 애플리케이션의 트랜잭션 의도와 Spring `PlatformTransactionManager` 사이의 + 다리. +- 감사 metadata 기반 + actor 이음매(`audit/AuditableEntity`, `audit/AuditContextPort`, `audit/DomainContextAuditContext`) — + 아래 「영속 감사 계약」을 본다. +- 모든 RDBMS vendor가 같이 쓰는 vendor SPI 확장점: + - `outbox/jpa/OutboxClaimRepository` — vendor 모듈이 claim 전략(예: FOR UPDATE SKIP LOCKED)을 구현한다. 구현은 그 + 옆 `outbox/postgresql`과 `outbox/h2`에 있다. + - `failure/SqlStateErrorMapping` — vendor 모듈이 vendor 전용 SQLState 행을 기여한다. -## Vendor selection +## vendor 고르기 -Two vendor compositions live in this module, each in its own subpackage, each registering the same -two SPI beans (outbox claim, SQLState mapping): +vendor 조립 둘이 이 모듈에 있고, 각각 자기 하위 패키지에 있으며, 각각 같은 SPI bean 둘(outbox claim, SQLState 대응)을 +등록한다: -| Vendor | Package | Selected by | Schema owner | +| vendor | 패키지 | 고르는 것 | schema 소유 | | --- | --- | --- | --- | -| PostgreSQL | `.postgresql` | `app.persistence.vendor=postgresql` (also the default) | Flyway, `db/migration/postgresql` | -| H2 | `.h2` | `app.persistence.vendor=h2` | Hibernate `ddl-auto`, entities only | +| PostgreSQL | `.postgresql` | `app.persistence.vendor=postgresql`(기본값이기도 하다) | Flyway, `db/migration/postgresql` | +| H2 | `.h2` | `app.persistence.vendor=h2` | Hibernate `ddl-auto`, 엔티티만 | -The outbox and idempotency features keep their pieces together, by feature and then by vendor: -`outbox/{jpa,postgresql,h2}` and `idempotency/{jpa,postgresql}`. The vendor configurations above still -decide which claim repository is registered. None of those feature classes imports a driver type, so -`PERSISTENCE_RDBMS_STAYS_VENDOR_NEUTRAL` still holds with them outside `.postgresql`. +outbox와 멱등성 기능은 기능별, 그다음 vendor별로 조각을 모아 둔다: `outbox/{jpa,postgresql,h2}`와 +`idempotency/{jpa,postgresql}`. 어떤 claim repository를 등록할지는 여전히 위 vendor 설정이 정한다. 그 기능 클래스 중 +driver 타입을 import하는 것이 없으므로, 그것들이 `.postgresql` 밖에 있어도 +`PERSISTENCE_RDBMS_STAYS_VENDOR_NEUTRAL`이 계속 지켜진다. -`config/PersistenceVendorSettings` binds the selector to an enum, so an unknown value fails at -startup instead of loading neither composition and surfacing as a missing `OutboxClaimRepository`. -The module states the choice: its `config/module-defaults/persistence-jpa.yml` defaults the vendor to -PostgreSQL and `spring.flyway.enabled` to `APP_FLYWAY_ENABLED` (true) for every profile; the composition -root's profile files no longer restate them (07-08). H2 is an explicit developer opt-out selected by -the `bootRunH2` task. `PersistenceVendorProdSafetyValidator` (`startup`) refuses H2 under prod -whatever property source supplies it. Under `bootRunH2` the idempotency provider must be `disabled` -or `redis`: the `postgresql` provider refuses an H2 data source at startup. +`config/PersistenceVendorSettings`가 선택자를 enum으로 바인딩한다. 그래서 모르는 값은 두 조립 중 어느 것도 읽지 않고 +`OutboxClaimRepository`가 없다는 오류로 나타나는 대신 기동 때 실패한다. 선택은 모듈이 정한다: 그 +`config/module-defaults/persistence-jpa.yml`이 모든 profile에서 vendor를 PostgreSQL로, `spring.flyway.enabled`를 +`APP_FLYWAY_ENABLED`(true)로 기본 설정한다. 조립 루트의 profile 파일은 더는 그것을 다시 적지 않는다(2026-11-01 +성숙도 리뷰 뒤로. 기본 조립 루트가 고르지 않은 capability의 설정을 알면 안 된다). H2는 `bootRunH2` 태스크가 +고르는, 개발자가 명시해서 빠지는 길이다. `PersistenceVendorProdSafetyValidator`(`startup`)는 어떤 +속성 출처가 주든 prod에서 H2를 거절한다. `bootRunH2`에서는 멱등성 provider가 `disabled`나 `redis`여야 한다: +`postgresql` provider는 기동 때 H2 data source를 거절한다. -H2 is the local-development datastore, not a second production target. It has no migration tree, so -tables that exist only in migrations — capability schema registry, the Spring Integration lock table — do not exist under it. Vendor concurrency and migration -fidelity stay with `postgresqlIntegrationTest`. +H2는 로컬 개발 저장소이지 두 번째 운영 대상이 아니다. migration 트리가 없으므로, migration에만 있는 테이블 — +capability schema registry, Spring Integration lock 테이블 — 은 H2에 없다. vendor 동시성과 migration 충실도는 +`postgresqlIntegrationTest`에 남는다. -The outbox claim is the one vendor statement H2 runs, and it is identical — H2 2.4.240 accepts -`FOR UPDATE SKIP LOCKED` and genuinely skips locked rows, so the claim keeps its meaning. -`H2ClaimSqlTest` executes it against a real H2. H2 has no idempotency store. +outbox claim은 H2가 돌리는 유일한 vendor 문장이고 내용이 같다 — H2 2.4.240은 `FOR UPDATE SKIP LOCKED`를 받고 잠긴 행을 +정말 건너뛰므로 claim이 뜻을 지킨다. `H2ClaimSqlTest`가 그것을 실제 H2에 대고 실행한다. H2에는 멱등성 store가 없다. -### Capability-gated stores +### capability로 막은 store -Adapters that serve one optional capability carry that capability's switch, unlike the rest of this -module. The `fileserver` package is the current case: every `Jpa*` adapter there is annotated -`@ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true")`. +선택 capability 하나를 위한 어댑터는 이 모듈의 나머지와 달리 그 capability의 스위치를 단다. 지금은 `fileserver` +패키지가 그 경우다: 거기 있는 모든 `Jpa*` 어댑터는 +`@ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true")`를 단다. -Without the gate a composition root that merely includes this module builds those beans, and each of -them needs collaborators only the Fileserver configuration supplies. 지운 샘플 모듈이 쓰지도 않는 -Fileserver 협력 객체 때문에 기동에 실패한 일이 그 예다. A store for a capability nobody enabled -should not exist. +그 막음이 없으면 이 모듈을 넣기만 한 조립 루트도 그 bean을 만들고, 각 bean에는 파일 서버 설정만 주는 협력 객체가 +필요하다. 지운 샘플 모듈이 쓰지도 않는 Fileserver 협력 객체 때문에 기동에 실패한 일이 그 예다. 아무도 켜지 않은 +capability의 store는 있으면 안 된다. -## Allowed +## 허용 - `:application-core` - `:domain-core` - `:shared-contract` -- `:adapter:outbound:support` (typed startup failures, EnvironmentPostProcessor order, readiness - group, module-defaults loader) -- Spring Data JPA and Spring transaction. +- `:adapter:outbound:support`(타입 있는 기동 실패, EnvironmentPostProcessor 순서, readiness group, module-defaults 읽기) +- Spring Data JPA와 Spring transaction. -## Forbidden +## 금지 (Forbidden) -- `adapter-web`, `app-bootstrap`, or any outbound adapter other than `adapter:outbound:support`. -- Presentation DTOs. -- Business policy decisions. -- Use case orchestration hidden inside persistence adapters. -- Repository adapters opening `@Transactional` around application workflows — the application - use case owns cross-port transactions via `TransactionPort`. Adapter-local transactions are - allowed only when the port method itself defines a storage protocol that must be atomic (for - example durable-operation claim/read or live-event position allocation + insert). See - [application-core/CLAUDE.md](../../../application-core/CLAUDE.md)). -- **DB drivers** (`org.postgresql..`, `org.h2..`) or **`org.flywaydb.database.postgresql..`** — - those are vendor-specific and belong only in this module's matching vendor package (`.postgresql`, - `.h2`); NoSQL-specific dependencies belong only in their own future modules. - This is enforced by ArchUnit - `PERSISTENCE_RDBMS_STAYS_VENDOR_NEUTRAL` and `PERSISTENCE_RDBMS_STAYS_NEUTRAL_OF_H2` in - `CleanArchitectureTest`. -- NoSQL adapter code. MongoDB/Redis/DynamoDB adapters are sibling modules, not children of this module. -- Any sibling persistence or inbound/outbound adapter not allowed by the registry. +- `adapter-web`, `app-bootstrap`, `adapter:outbound:support`를 뺀 다른 outbound 어댑터. +- 표현 계층 DTO. +- 업무 정책 판단. +- 영속 어댑터 안에 숨긴 유스케이스 조율. +- repository 어댑터가 애플리케이션 흐름을 감싸 `@Transactional`을 여는 것 — 포트를 가로지르는 트랜잭션은 애플리케이션 + 유스케이스가 `TransactionPort`로 가진다. 어댑터 안의 트랜잭션은 포트 메서드 자체가 원자적이어야 하는 저장 프로토콜을 + 정할 때만 허용한다(예: durable operation claim·읽기, live event 위치 할당 + insert). + [application-core/CLAUDE.md](../../../application-core/CLAUDE.md)를 본다. +- **DB driver**(`org.postgresql..`, `org.h2..`)나 **`org.flywaydb.database.postgresql..`** — vendor 전용이라 이 모듈의 + 맞는 vendor 패키지(`.postgresql`, `.h2`)에만 둔다. NoSQL 전용 의존은 앞으로 생길 자기 모듈에만 둔다. + `CleanArchitectureTest`의 ArchUnit `PERSISTENCE_RDBMS_STAYS_VENDOR_NEUTRAL`과 `PERSISTENCE_RDBMS_STAYS_NEUTRAL_OF_H2`가 + 강제한다. +- NoSQL 어댑터 코드. MongoDB·Redis·DynamoDB 어댑터는 이 모듈의 자식이 아니라 이웃 모듈이다. +- registry가 허용하지 않은 이웃 영속 어댑터나 inbound·outbound 어댑터. -## TransactionPort implementation contract +## TransactionPort 구현 계약 -`SpringTransaction` pre-builds one `TransactionTemplate` per mode: +`SpringTransaction`은 모드마다 `TransactionTemplate`을 하나씩 미리 만든다: -| Mode | Propagation | Isolation | Read-only | Timeout | +| 모드 | 전파 | 격리 | 읽기 전용 | timeout | |---|---|---|---|---| -| `inWrite` | `REQUIRED` | `READ_COMMITTED` (pool) | `false` | `app.persistence-jpa.transaction.write-timeout` (30 s) | -| `inRootWrite` | `REQUIRED` | `READ_COMMITTED` (pool) | `false` | same as `inWrite` | -| `inRead` | `REQUIRED` | `READ_COMMITTED` (pool) | `true` | `app.persistence-jpa.transaction.read-timeout` (30 s) | -| `inNew` | `REQUIRES_NEW` | `READ_COMMITTED` (pool) | `false` | 30 s, fixed | +| `inWrite` | `REQUIRED` | `READ_COMMITTED`(pool) | `false` | `app.persistence-jpa.transaction.write-timeout`(30 s) | +| `inRootWrite` | `REQUIRED` | `READ_COMMITTED`(pool) | `false` | `inWrite`와 같음 | +| `inRead` | `REQUIRED` | `READ_COMMITTED`(pool) | `true` | `app.persistence-jpa.transaction.read-timeout`(30 s) | +| `inNew` | `REQUIRES_NEW` | `READ_COMMITTED`(pool) | `false` | 30 s, 고정 | -Isolation is pinned on the pool, not on the templates: the templates use -`ISOLATION_DEFAULT`, the module defaults set `spring.datasource.hikari.transaction-isolation: -TRANSACTION_READ_COMMITTED` (applied once per physical connection), and -`HikariPoolConstraintValidator` refuses to boot with any other level. Naming the level per template -made Spring call `getTransactionIsolation()` at every begin, which pgjdbc answers with a -`SHOW TRANSACTION ISOLATION LEVEL` round trip. +격리 수준은 template이 아니라 pool에 고정한다: template은 `ISOLATION_DEFAULT`를 쓰고, 모듈 기본값이 +`spring.datasource.hikari.transaction-isolation: TRANSACTION_READ_COMMITTED`를 정하며(물리 연결마다 한 번 적용), +`HikariPoolConstraintValidator`가 다른 수준이면 기동을 거절한다. template마다 수준을 대면 Spring이 begin마다 +`getTransactionIsolation()`을 부르고, pgjdbc는 그것에 `SHOW TRANSACTION ISOLATION LEVEL` 왕복으로 답했다. -Every mode is time-bounded (since 2026-11-01). Spring hands the remaining time to each statement, so a -slow query or lock wait is cancelled by the server (`57014` → `DB_QUERY_CANCELED`), and a deadline -that passed before the next statement gets the same code: Spring's `TransactionTimedOutException` -on the JDBC path, and on the JPA path (`JpaTransactionManager`, production) Hibernate's own -`TransactionException`, which has no SQLState and is classified because `SpringTransaction` knows -its deadline passed (`translateAfterDeadline`). A business exception thrown after -the deadline is passed on unchanged. +모든 모드에는 시간 한계가 있다(2026-11-01부터). Spring이 남은 시간을 문장마다 넘기므로 느린 query나 lock 대기는 서버가 +취소하고(`57014` → `DB_QUERY_CANCELED`), 다음 문장 전에 기한이 지난 경우도 같은 코드를 받는다: JDBC 경로에서는 Spring의 +`TransactionTimedOutException`, JPA 경로(`JpaTransactionManager`, 운영)에서는 Hibernate 자신의 `TransactionException`이다. +후자는 SQLState가 없고, `SpringTransaction`이 기한이 지났음을 알기 때문에 분류된다(`translateAfterDeadline`). 기한 뒤에 +던진 업무 예외는 바꾸지 않고 넘긴다. -Pre-built templates are immutable after construction so concurrent callers cannot -observe each other's reconfiguration. `inRootWrite` reuses the pre-built write template, -but first checks `TransactionSynchronizationManager.isActualTransactionActive()`. -When an actual ambient transaction exists it MUST throw -`NestedRootTransactionRejectedException` before invoking either the action or the -`PlatformTransactionManager`. It MUST NOT use `NEVER` or `REQUIRES_NEW`. +미리 만든 template은 만든 뒤 바뀌지 않아서, 동시 호출자가 서로의 재설정을 볼 수 없다. `inRootWrite`는 미리 만든 쓰기 +template을 다시 쓰지만, 먼저 `TransactionSynchronizationManager.isActualTransactionActive()`를 검사한다. 실제 바깥 +트랜잭션이 있으면 action이나 `PlatformTransactionManager`를 부르기 전에 반드시 +`NestedRootTransactionRejectedException`을 던진다. `NEVER`나 `REQUIRES_NEW`를 쓰면 안 된다. -`inRootWrite` returns its action value only after `TransactionTemplate.execute` has -committed. A commit failure propagates the transaction exception and no success value -is returned to the caller. +`inRootWrite`는 `TransactionTemplate.execute`가 커밋한 뒤에만 action 값을 돌려준다. 커밋이 실패하면 트랜잭션 예외를 +올리고 호출자에게 성공 값을 돌려주지 않는다. -### `inNew` pool-sizing constraint (feature-application-port-usecase-contract) +### `inNew` 풀 크기 제약 (feature-application-port-usecase-contract) -`REQUIRES_NEW` acquires a NEW physical JDBC connection while pinning the outer -transaction's connection. Provision the pool to satisfy: +`REQUIRES_NEW`는 바깥 트랜잭션의 연결을 쥔 채 새 물리 JDBC 연결을 얻는다. pool은 다음을 만족하게 잡는다: ``` hikari.maximumPoolSize >= (concurrent_threads × (1 + max_inNew_depth)) + 1 ``` -Loop-per-record `inNew` calls are forbidden (pool exhaustion + deadlock risk). -Batch records inside ONE `inNew`, or move the loop outside the transaction. +레코드마다 `inNew`를 부르는 반복문은 금지다(pool 고갈 + 교착 위험). 레코드를 `inNew` **하나** 안에서 묶어 처리하거나, +반복문을 트랜잭션 밖으로 뺀다. -## Persistence failure translation contract (feature-persistence-failure-baseline) +## 영속 실패 번역 계약 (feature-persistence-failure-baseline) -A raw Spring `DataAccessException` (and the JPA exception / SQLState / constraint name -inside it) must never reach the presentation layer. The -`failure/PersistenceExceptionTranslator` classifies a `DataAccessException` by its -SQLState against the §SQLState → Error Code Matrix and returns a -framework-neutral `shared.error.PersistenceFailureException` carrying one of the -`DB_*` `OperationalError` codes. +날것의 Spring `DataAccessException`(과 그 안의 JPA 예외·SQLState·제약 이름)은 절대 표현 계층에 닿으면 안 된다. +`failure/PersistenceExceptionTranslator`가 `DataAccessException`을 SQLState로 아래 §SQLState → 오류 코드 표와 대조해 +분류하고, `DB_*` `OperationalError` 코드 하나를 실은 프레임워크 중립 `shared.error.PersistenceFailureException`을 돌려준다. -**Standard rows (core):** +**표준 행(core):** | SQLState | code | category | http | retryable | |---|---|---|---|---| @@ -294,81 +259,66 @@ framework-neutral `shared.error.PersistenceFailureException` carrying one of the | `23505` | `DB_UNIQUE_VIOLATION` | `CONFLICT` | 409 | false | | `23514` | `DB_CHECK_VIOLATION` | `DATA_INTEGRITY` | 409 | false | -**Vendor-specific rows (contributed by vendor module via `SqlStateErrorMapping` SPI):** +**vendor 전용 행(vendor 모듈이 `SqlStateErrorMapping` SPI로 기여):** | SQLState | code | vendor | |---|---|---| -| `40P01` | `DB_DEADLOCK` | PostgreSQL (`.postgresql` package) | +| `40P01` | `DB_DEADLOCK` | PostgreSQL(`.postgresql` 패키지) | | `55P03` | `DB_LOCK_TIMEOUT` | PostgreSQL | | `25P03` | `DB_IDLE_IN_TX_TIMEOUT` | PostgreSQL | | `57014` | `DB_QUERY_CANCELED` | PostgreSQL | -| `57P01`, `57P02` | `DB_UNAVAILABLE` (before commit; completion-unknown during it) | PostgreSQL | -| `23513` | `DB_CHECK_VIOLATION` | H2 (`.h2` package) — H2 reports CHECK as 23513, not the standard 23514 the core table maps | -| `HYT00` | `DB_QUERY_CANCELED` | H2 — H2 collapses statement and lock timeout into one state | +| `57P01`, `57P02` | `DB_UNAVAILABLE`(커밋 전. 커밋 중이면 completion-unknown) | PostgreSQL | +| `23513` | `DB_CHECK_VIOLATION` | H2(`.h2` 패키지) — H2는 CHECK를 core 표가 대응시키는 표준 23514가 아니라 23513으로 알린다 | +| `HYT00` | `DB_QUERY_CANCELED` | H2 — H2는 문장 timeout과 lock timeout을 상태 하나로 합친다 | -The PostgreSQL rows are not a second table: before 2026-11-01 a hand-kept second table had already drifted. `PostgreSqlSqlStateErrorMapping` derives -them from `PostgreSqlFailureClassifier` (SQLState → `FailureCategory`) and -`FailureCategory.operationalError()` (category → code) — the same classification the library -`PostgreSqlExceptionTranslator` uses — leaving out the standard rows above, categories with no -specific code (`INTERNAL_ERROR`) and `COMPLETION_UNKNOWN` (phase-dependent). To add a PostgreSQL -state, add it to `PostgreSqlState` and the classifier; `SqlStateClassificationParityTest` fails if -the two paths disagree on any state. +PostgreSQL 행은 두 번째 표가 아니다: 2026-11-01 전에는 손으로 관리하던 두 번째 표가 이미 어긋나 있었다. +`PostgreSqlSqlStateErrorMapping`이 그 행을 `PostgreSqlFailureClassifier`(SQLState → `FailureCategory`)와 +`FailureCategory.operationalError()`(category → 코드)에서 끌어낸다 — 라이브러리 `PostgreSqlExceptionTranslator`가 쓰는 +것과 같은 분류다 — 그리고 위 표준 행, 전용 코드가 없는 category(`INTERNAL_ERROR`), `COMPLETION_UNKNOWN`(단계에 +따라 다르다)을 뺀다. PostgreSQL 상태를 더하려면 `PostgreSqlState`와 classifier에 더한다. 두 경로가 어떤 상태에서든 +다르면 `SqlStateClassificationParityTest`가 실패한다. -**No SQLState, classified by type:** a lost `@Version` race (`OptimisticLockingFailureException`, -JPA `OptimisticLockException`) → `DB_OPTIMISTIC_CONFLICT` (409); an expired Spring -transaction deadline (`TransactionTimedOutException`) → `DB_QUERY_CANCELED`; any other persistence -failure (JPA, Spring data-access or Spring transaction exception) of a transaction -`SpringTransaction` began, once its deadline has passed → `DB_QUERY_CANCELED`. +**SQLState가 없고 타입으로 분류:** 진 `@Version` 경쟁(`OptimisticLockingFailureException`, JPA +`OptimisticLockException`) → `DB_OPTIMISTIC_CONFLICT`(409). 만료된 Spring 트랜잭션 기한(`TransactionTimedOutException`) +→ `DB_QUERY_CANCELED`. `SpringTransaction`이 시작한 트랜잭션의 기한이 지난 뒤의 다른 영속 실패(JPA, Spring +data-access, Spring transaction 예외) → `DB_QUERY_CANCELED`. -**Commit phase (`translateCommitFailure`, ADR-JPA-003):** once the action has returned and -`SpringTransaction` is committing a write transaction it began, a failure with `08*`, `40003`, a -vendor-contributed termination state (`SqlStateErrorMapping.commitOutcomeUnknownStates()`: -PostgreSQL `57P01`, `57P02`) or a transport break with no SQLState becomes -`TransactionCompletionUnknownException` → `DB_COMPLETION_UNKNOWN` (500, never retryable), not -`DB_UNAVAILABLE`: the server may already have committed. A commit the server definitely rejected -(e.g. a deferred `23505`) keeps its row above; a read-only commit keeps `DB_UNAVAILABLE`. +**커밋 단계(`translateCommitFailure`, ADR-JPA-003):** action이 돌아왔고 `SpringTransaction`이 자기가 시작한 쓰기 +트랜잭션을 커밋하는 중이면, `08*`, `40003`, vendor가 기여한 종료 상태(`SqlStateErrorMapping.commitOutcomeUnknownStates()`: +PostgreSQL `57P01`, `57P02`), SQLState 없는 전송 끊김을 가진 실패는 `DB_UNAVAILABLE`이 아니라 +`TransactionCompletionUnknownException` → `DB_COMPLETION_UNKNOWN`(500, 절대 재시도하지 않음)이 된다: 서버가 이미 커밋했을 +수 있다. 서버가 분명히 거절한 커밋(예: 미뤄진 `23505`)은 위 자기 행을 지킨다. 읽기 전용 커밋은 `DB_UNAVAILABLE`을 지킨다. -- A repository adapter that catches a `DataAccessException` calls - `translator.translate(ex)` and rethrows the carrier (`ifPresent(e -> { throw e; })`); - an empty result means an unknown SQLState — rethrow the original so the web catch-all - answers a generic `INTERNAL` envelope (no leak). -- The category SSOT is the 10-value `Category` enum — there is **no** `PERSISTENCE` - category (design record §Audit CATEGORY_DRIFT). +- `DataAccessException`을 잡는 repository 어댑터는 `translator.translate(ex)`를 부르고 carrier를 다시 던진다 + (`ifPresent(e -> { throw e; })`). 빈 결과는 모르는 SQLState라는 뜻이다 — 원래 예외를 다시 던져 web catch-all이 일반 + `INTERNAL` envelope으로 답하게 한다(새는 것 없음). +- category 정본은 값 10개의 `Category` enum이다 — `PERSISTENCE` category는 **없다**(설계 기록 §Audit CATEGORY_DRIFT). -## Persistence auditing contract (feature-persistence-auditing-contract) +## 영속 감사 계약 (feature-persistence-auditing-contract) -Audit metadata (`created_at` / `updated_at` / `created_by` / `updated_by`) is an -infrastructure concern that must never reach `domain-core`. It lives only on the -`audit/AuditableEntity` `@MappedSuperclass`; a domain aggregate persistence entity opts in -by extending it (생성 명령이 만드는 서비스 persistence leaf의 엔티티가 그렇게 한다). The domain aggregate itself carries -zero audit fields, enforced by ArchUnit `domain_is_pure` (no `jakarta.persistence..`) plus -`domain_entities_do_not_carry_audit_fields` (no `createdAt`/`updatedAt`/`createdBy`/`updatedBy` -fields under `..domain..`). +감사 metadata(`created_at` / `updated_at` / `created_by` / `updated_by`)는 기반 관심사이고 `domain-core`에 닿으면 안 된다. +`audit/AuditableEntity` `@MappedSuperclass`에만 있다. 도메인 aggregate의 영속 엔티티가 그것을 상속해서 고른다(생성 +명령이 만드는 서비스 persistence leaf의 엔티티가 그렇게 한다). 도메인 aggregate 자체는 감사 필드를 하나도 갖지 않는다. +ArchUnit `DOMAIN_IS_PURE`(`jakarta.persistence..` 없음)와 `DOMAIN_ENTITIES_DO_NOT_CARRY_AUDIT_FIELDS`(`..domain..` 아래에 +`createdAt`/`updatedAt`/`createdBy`/`updatedBy` 필드 없음)가 강제한다. -- **Capture = Manual explicit-set (current default).** The repository adapter - constructor-injects `Clock` and `AuditContextPort` and stamps audit on `save`: - INSERT (null version) → `initializeAudit(now, actor)`; UPDATE (non-null version) → - carry the persisted `created_*` forward + `applyModification(now, actor)`. - `created_*` is `updatable = false`. -- **Actor seam.** `AuditContextPort.currentActor()` reads the runtime-context-propagation - seam and falls back to `"system"` when no principal is bound (scheduler / Flyway / anonymous). - The actor's value semantics are owned by feature-authentication-authorization-contract - (UNSUPPORTED here); the type is fixed to `String`. -- **Excluded.** Infra/immutable entities such as `IdempotencyRecordEntity` (own - `created_at`, no `updated_at`) do NOT extend `AuditableEntity`. `version`/optimistic-lock - is owned by feature-persistence-failure-baseline / feature-transaction-concurrency-contract, - not by this audit base. -- **Growth path (deferred).** There is no second auditing implementation in the tree. If - manual stamping becomes too error-prone, migrate the canonical `AuditableEntity` contract - atomically to Spring Data listeners while preserving its `created_*`/`updated_*` schema, actor - bound, `Clock`, and `AuditContextPort` semantics. Bulk/native `@Query` UPDATEs bypass listeners - too, so they must continue to stamp audit columns explicitly. +- **잡기 = 손으로 명시해 넣기(지금 기본).** repository 어댑터가 생성자로 `Clock`과 `AuditContextPort`를 받고 `save`에서 + 감사 값을 넣는다: INSERT(version null) → `initializeAudit(now, actor)`. UPDATE(version 있음) → 저장된 `created_*`를 그대로 + 넘기고 + `applyModification(now, actor)`. `created_*`는 `updatable = false`다. +- **actor 이음매.** `AuditContextPort.currentActor()`는 runtime-context 전파 이음매를 읽고, principal이 묶여 있지 않으면 + (scheduler / Flyway / 익명) `"system"`으로 물러선다. actor 값의 뜻은 + feature-authentication-authorization-contract가 가진다(여기서는 UNSUPPORTED). 타입은 `String`으로 고정한다. +- **빠지는 것.** `IdempotencyRecordEntity`(자기 `created_at`, `updated_at` 없음) 같은 기반·불변 엔티티는 `AuditableEntity`를 + 상속하지 **않는다**. `version`·낙관적 lock은 이 감사 기반이 아니라 feature-persistence-failure-baseline / + feature-transaction-concurrency-contract가 가진다. +- **자랄 길(미룸).** 트리에 두 번째 감사 구현은 없다. 손으로 넣는 것이 실수가 너무 잦아지면, 정해진 `AuditableEntity` + 계약을 `created_*`/`updated_*` schema, actor 한계, `Clock`, `AuditContextPort` 뜻을 지키면서 한 번에 Spring Data + listener로 옮긴다. bulk·native `@Query` UPDATE도 listener를 지나지 않으므로 계속 감사 열을 명시해 넣어야 한다. -## MapStruct generated mapper exemption (feature-architecture-enforcement-rules) +## MapStruct 생성 mapper 예외 (feature-architecture-enforcement-rules) -If MapStruct is introduced for persistence mappers, the generated mapper class will -be annotated with `javax.annotation.processing.Generated`. Architecture rules that -forbid mapper boundary violations MUST exempt generated code via ArchUnit predicate: +영속 mapper에 MapStruct를 들이면, 생성된 mapper 클래스에 `javax.annotation.processing.Generated`가 붙는다. mapper 경계 +위반을 금지하는 아키텍처 규칙은 반드시 ArchUnit predicate로 생성 코드를 뺀다: ```java import javax.annotation.processing.Generated; @@ -379,21 +329,17 @@ classes() .should() /* ... boundary rule ... */; ``` -> Note the annotation FQN: MapStruct uses -> `javax.annotation.processing.Generated`. Spring AOT uses -> `org.springframework.aot.generate.Generated` — do **not** mix the two. The -> exemption MUST scope to the specific annotation expected for the build step -> being exempted. +> 애너테이션 FQN에 주의한다: MapStruct는 `javax.annotation.processing.Generated`를 쓴다. Spring AOT는 +> `org.springframework.aot.generate.Generated`를 쓴다 — 둘을 섞지 **않는다**. 예외는 반드시 빼려는 빌드 단계가 기대하는 +> 바로 그 애너테이션으로 범위를 잡는다. -Current ca-tmpl mappers are hand-written so no MapStruct exemption is wired into -ArchUnit yet — when generation is added, follow the predicate above and add a -red/green test using a fixture mapper. +지금 ca-tmpl mapper는 손으로 쓴 것이라 ArchUnit에 MapStruct 예외를 아직 배선하지 않았다 — 생성을 더할 때 위 +predicate를 따르고, fixture mapper로 red/green 시험을 더한다. -## NoSQL extension rule +## NoSQL 확장 규칙 -Do not create `adapter-persistence-nosql-core` preemptively. NoSQL stores have different -models and operational contracts. When a real MongoDB, Redis, or DynamoDB adapter is needed, -create a sibling module: +`adapter-persistence-nosql-core`를 미리 만들지 않는다. NoSQL 저장소는 모델과 운영 계약이 서로 다르다. 실제 MongoDB, +Redis, DynamoDB 어댑터가 필요해지면 이웃 모듈을 만든다: ```text adapter-persistence-mongodb @@ -401,10 +347,9 @@ adapter-persistence-redis adapter-persistence-dynamodb ``` -Such modules implement application/domain ports directly and must not depend on -`adapter:outbound:persistence-jpa`. +그런 모듈은 application·domain 포트를 직접 구현하고 `adapter:outbound:persistence-jpa`에 의존하면 안 된다. -## Test +## 테스트 ```bash cd src diff --git a/src/adapter/outbound/persistence-jpa/README.md b/src/adapter/outbound/persistence-jpa/README.md index 5f07bbd6..35815116 100644 --- a/src/adapter/outbound/persistence-jpa/README.md +++ b/src/adapter/outbound/persistence-jpa/README.md @@ -387,7 +387,7 @@ PUBLISHED backlog 를 한 transaction 으로 지우면 그 사이 모든 row loc cadence 측정 필요). retention 한 값은 reaper-local 이라 `@Value` 로 받지만, canonical 6-property 문서는 app-bootstrap `OutboxSettings` / `application.yml` 에 있다. -## JPA production capability candidate +## JPA 운영 capability 후보 `src/adapter/outbound/persistence-jpa/release/readiness-cards.yaml`이 capability와 독립 schema stream의 machine-readable SSOT다(개수는 registry가 소유한다). `selected` base card와 `implemented-candidate` reliability card를 @@ -420,7 +420,7 @@ Flyway의 PostgreSQL 마이그레이션 잠금은 트랜잭션이 아니라 세 자기 location/history table을 사용하고 non-empty schema adoption 때 version 0 baseline을 명시한 뒤 V1부터 실행한다. -| Capability | Location | History table | 상태 | +| capability | 위치 | history 테이블 | 상태 | |---|---|---|---| | core/adoption | `db/migration/jpa/core` | `flyway_jpa_core_history` | selected candidate | | idempotency | `db/migration/jpa/idempotency` | `flyway_jpa_idempotency_history` | implemented-candidate | diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/platform/PoolLaneClaimTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/platform/PoolLaneClaimTest.java index b7724e94..ef94f18c 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/platform/PoolLaneClaimTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/platform/PoolLaneClaimTest.java @@ -46,7 +46,7 @@ class PoolLaneClaimTest { private static final String REMOVED_FLAG = "performance." + "assertions." + "enabled"; @Test - @DisplayName("no file describing the pool lane mentions the flag that was removed") + @DisplayName("풀 lane을 설명하는 파일은 지운 스위치를 말하지 않는다") void noFileMentionsTheRemovedFlag() { for (String description : LANE_DESCRIPTIONS) { assertThat(read(description)) @@ -56,7 +56,7 @@ class PoolLaneClaimTest { } @Test - @DisplayName("no file describing the pool lane claims a certification or a machine bound") + @DisplayName("풀 lane을 설명하는 파일은 인증이나 기계 상한을 주장하지 않는다") void noFileClaimsACertificationOrAMachineBound() { for (String description : LANE_DESCRIPTIONS) { String text = read(description).toLowerCase(Locale.ROOT); @@ -68,12 +68,15 @@ class PoolLaneClaimTest { .as("%s describes the pool lane as certifying something it does not measure", description) .doesNotContain("pool pressure certification") .doesNotContain("machine-dependent bounds") - .doesNotContain("machine bounds"); + .doesNotContain("machine bounds") + .doesNotContain("풀 압력 인증") + .doesNotContain("기계 상한") + .doesNotContain("기계에 따라 다른 상한"); } } @Test - @DisplayName("the nightly job runs the behaviour lane, under its behaviour name") + @DisplayName("nightly job은 동작 lane을 그 동작 이름으로 돌린다") void theNightlyJobRunsTheBehaviourLane() { String nightly = read(".github/workflows/jpa-nightly.yml"); diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/JpaDocumentationContractTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/JpaDocumentationContractTest.java index 95c1dada..56ed7158 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/JpaDocumentationContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/JpaDocumentationContractTest.java @@ -28,7 +28,7 @@ class JpaDocumentationContractTest { private final JpaReleaseManifest manifest = JpaReleaseManifest.loadFromRepository(); @Test - @DisplayName("the support matrix names the registry's provider baseline, not the target") + @DisplayName("지원 매트릭스는 목표가 아니라 registry의 provider 기준선을 이름 댄다") void theSupportMatrixNamesTheRegistrysProviderBaseline() { String matrix = read("docs/jpa/support-matrix.md"); @@ -42,7 +42,7 @@ class JpaDocumentationContractTest { } @Test - @DisplayName("every gate the registry declares is named in the support matrix") + @DisplayName("registry가 선언한 gate는 모두 지원 매트릭스에 이름이 있다") void everyRegistryGateIsNamedInTheSupportMatrix() { String matrix = read("docs/jpa/support-matrix.md"); @@ -52,7 +52,7 @@ class JpaDocumentationContractTest { } @Test - @DisplayName("the H2 passage separates measurement from guarantee") + @DisplayName("H2 단락은 측정과 보장을 가른다") void theH2PassageSeparatesMeasurementFromGuarantee() { String matrix = read("docs/jpa/support-matrix.md"); @@ -62,18 +62,18 @@ class JpaDocumentationContractTest { assertThat(flowed) .as("two documents disagreed about SKIP LOCKED because they answered different questions") - .contains("not a production guarantee") - .contains("PostgreSQL contract evidence"); + .contains("운영 보장이 아니") + .contains("PostgreSQL 계약 증거"); } @Test - @DisplayName("the boundary document states the gap it does not enforce") + @DisplayName("경계 문서는 강제하지 않는 빈틈을 밝힌다") void theBoundaryDocumentStatesItsGap() { String adaptation = read("docs/jpa/repository-adaptation.md"); assertThat(adaptation) .as("a document may call a boundary enforced only where a test actually enforces it") - .contains("Known gap"); + .contains("알려진 빈틈"); } private static String read(String repositoryRelativePath) { diff --git a/src/adapter/outbound/persistence-mongo/CLAUDE.md b/src/adapter/outbound/persistence-mongo/CLAUDE.md index 3936e48c..c3110014 100644 --- a/src/adapter/outbound/persistence-mongo/CLAUDE.md +++ b/src/adapter/outbound/persistence-mongo/CLAUDE.md @@ -1,185 +1,157 @@ -# adapter:outbound:persistence-mongo — module rules +# adapter:outbound:persistence-mongo — 모듈 규칙 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-persistence-mongo` -- Gradle path: `:adapter:outbound:persistence-mongo` -- Focused test (derived from Gradle path): `./gradlew :adapter:outbound:persistence-mongo:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-outbound-persistence-mongo` +- Gradle 경로: `:adapter:outbound:persistence-mongo` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:outbound:persistence-mongo:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.outbound.mongo`. Driven (outbound) adapter — opt-in MongoDB -Document Persistence Platform. Design rationale lives in [README.md](README.md); the mapping from the -design package's assumed module layout onto this leaf lives in -`docs/mongodb/repository-adaptation.md` and is the file to update when that mapping changes. +패키지 루트: `dev.caskeleton.adapter.outbound.mongo`. driven(outbound) 어댑터 — 골라 쓰는 MongoDB 문서 영속 +플랫폼이다. 설계 근거는 [README.md](README.md)에 있다. 설계 패키지가 가정한 모듈 배치를 이 leaf에 대응시킨 것은 +`docs/mongodb/repository-adaptation.md`에 있고, 그 대응이 바뀌면 고칠 파일이 그것이다. -## Responsibility +## 책임 -- Provide the opt-in Mongo client, template and **platform policy** surface without shipping a fake - business domain. Real forks add their own document, repository, mapper, and application/domain port - implementation. -- It does **not** reimplement idempotency / outbox / lock on Mongo (those stay JPA-only). -- On when present: `MongoRootAutoConfiguration` and everything it imports run unless - `app.persistence-mongo.enabled=false` (`matchIfMissing = true`; the shipped - `config/mongo.yml` maps `APP_PERSISTENCE_MONGO_ENABLED`, default `true`). Absent from the build is - the ordinary off state. The connection URI and database come from Spring's standard - `spring.mongodb.*` settings; platform profiles come from - `app.persistence-mongo.platform.*`. - The connection source is fail-closed: either `spring.mongodb.uri` / - `SPRING_MONGODB_URI` is non-blank, or the selected typed profile supplies `uri-secret` and the - deployment supplies `MongoCredentialResolver`. The typed profile is not documentation-only: - `MongoProfileClientSettingsAutoConfiguration` applies `MongoClientSettingsFactory` to Boot's actual - `MongoClientSettings.Builder` at lowest precedence, so its TLS, Stable API, timeout and pool - policy overrides generic defaults. Without a typed profile (URI-only), - `MongoUriOnlyClientDefaults` applies finite socket/connect/server-selection timeouts and a pool - bound **before** Boot applies the connection string, so URI parameters still win; there is no - setting key of its own. -- Consumers: a service's own adapter leaf takes this leaf as `implementation`. The procedure is - `docs/mongodb/consumer-leaf-guide.md`; the worked example (document, mapper, repository, port - implementation) is the test-source package `…mongo.example`, run by `mongoStableContractTest`. -- `MongoDefaultsEnvironmentPostProcessor`, registered through `META-INF/spring.factories`, loads - `config/mongo.yml` at lowest precedence and, on an explicit `enabled=false`, appends Boot 4's - Mongo auto-configurations (read from Boot's own registration files) to - `spring.autoconfigure.exclude`. -- Two kinds of surface. Auto-configured beans (listed in README.md "자동 구성") turn on with - `enabled=true`. Everything else is **library API** (README.md "라이브러리 API"): a service's own - adapter leaf takes this leaf as `implementation` and constructs the type. Library API is not - registered as a bean and has no property of its own. -- Mongo health integration is leaf-owned. MongoRootAutoConfiguration imports the internal MongoPlatformHealthConfiguration, which adapts MongoPlatformHealthIndicator to Boot's HealthIndicator SPI under the stable bean name mongoPlatformHealthContributor. Application Actuator exposure policy still decides external endpoint exposure. +- 가짜 업무 도메인을 싣지 않고, 골라 쓰는 Mongo client, template, **플랫폼 정책** surface를 준다. 실제 fork가 자기 + 문서, repository, mapper, application·domain 포트 구현을 더한다. +- 멱등성·outbox·lock을 Mongo 위에 다시 구현하지 **않는다**(그것은 JPA에만 남는다). +- 있으면 켜진다: `app.persistence-mongo.enabled=false`가 아니면 `MongoRootAutoConfiguration`과 그것이 import하는 + 모든 것이 돈다(`matchIfMissing = true`. 출하하는 `config/mongo.yml`이 `APP_PERSISTENCE_MONGO_ENABLED`를 대응시키고 + 기본은 `true`). 빌드에 없는 것이 보통의 꺼진 상태다. 연결 URI와 데이터베이스는 Spring의 표준 `spring.mongodb.*` + 설정에서 오고, 플랫폼 profile은 `app.persistence-mongo.platform.*`에서 온다. + 연결 출처는 실패하면 닫힌다: `spring.mongodb.uri` / `SPRING_MONGODB_URI`가 비어 있지 않거나, 고른 typed profile이 + `uri-secret`을 주고 배포가 `MongoCredentialResolver`를 줘야 한다. typed profile은 문서용만이 아니다: + `MongoProfileClientSettingsAutoConfiguration`이 `MongoClientSettingsFactory`를 Boot의 실제 + `MongoClientSettings.Builder`에 가장 낮은 우선순위로 적용하므로, 그 TLS, Stable API, timeout, pool 정책이 일반 + 기본값을 덮는다. typed profile이 없으면(URI만) `MongoUriOnlyClientDefaults`가 Boot가 connection string을 적용하기 + **전에** 유한한 socket·connect·server selection timeout과 pool 한계를 적용하므로, URI 매개변수가 여전히 이긴다. + 자기 설정 키는 없다. +- 쓰는 쪽: 서비스 자신의 어댑터 leaf가 이 leaf를 `implementation`으로 받는다. 절차는 + `docs/mongodb/consumer-leaf-guide.md`다. 작동하는 예(문서, mapper, repository, 포트 구현)는 시험 소스 패키지 + `…mongo.example`이고, `mongoStableContractTest`가 돌린다. +- `META-INF/spring.factories`로 등록한 `MongoDefaultsEnvironmentPostProcessor`가 `config/mongo.yml`을 가장 낮은 + 우선순위로 읽고, 명시한 `enabled=false`이면 Boot 4의 Mongo 자동 구성(Boot 자신의 등록 파일에서 읽는다)을 + `spring.autoconfigure.exclude`에 붙인다. +- surface는 두 가지다. 자동 구성 bean(README.md 「자동 구성」에 적힌 것)은 `enabled=true`로 켜진다. 나머지는 모두 + **라이브러리 API**다(README.md 「라이브러리 API」): 서비스 자신의 어댑터 leaf가 이 leaf를 `implementation`으로 + 받아 타입을 만든다. 라이브러리 API는 bean으로 등록하지 않고 자기 속성이 없다. +- Mongo health 연동은 leaf가 가진다. MongoRootAutoConfiguration이 내부 MongoPlatformHealthConfiguration을 import하고, + 그것이 MongoPlatformHealthIndicator를 안정된 bean 이름 mongoPlatformHealthContributor 아래 Boot의 HealthIndicator + SPI에 맞춘다. 바깥 endpoint 노출은 여전히 애플리케이션 Actuator 노출 정책이 정한다. -## Allowed +## 허용 -- Two project dependencies. `shared-contract` for the `Sha256` and `HmacSha256` helpers (tenant - observable key, admin command digest, credential fingerprint, keyset cursor tag; - `MongoDigestOutputTest` pins the outputs). `application-core`, for - `SecretSourcePort` only. The registry entry's `allowed_dependencies` is - `["application-core", "shared-contract"]`, matching what the build actually uses; the - bridge in `MongoProfileClientSettingsAutoConfiguration` resolves a typed profile's `uri-secret` - through the deployment's configured secret backend. `verifyCleanArchitectureDependencies` only - checks that resolved edges are a subset of the declared ones, so an unused permission passes every - run; `MongoRegistryPermissionParityTest` checks the other direction and fails when the two sets - differ. -- A service selects the leaf with one commented-out line in `app-bootstrap/build.gradle`, - `runtimeOnly project(':adapter:outbound:persistence-mongo')`; the default composition does not - carry it. The leaf is imperative only: the reactive twin (`reactive/**`, reactive - transactions/sessions), the change-stream consumer and the change-stream-to-messaging bridge were - removed on 2026-09-25 (see `docs/capability-status.md`), so the leaf carries neither the reactive - starter nor the reactive-streams driver (`MongoReactiveDriverAbsenceTest`). -- External includes the (sync) Mongo starter, spring-boot-autoconfigure, spring-boot-health, micrometer-core, slf4j-api, and the configuration processor. Jackson annotations are compile-only because Boot Health carries Jackson annotations while runtime JSON serialization remains application-owned. - Versions come from the shared Spring Boot BOM; never pin the driver directly. -- Test-only: ArchUnit, Testcontainers (`mongodb`, `toxiproxy`). +- 프로젝트 의존 둘. `Sha256`과 `HmacSha256` 도우미를 위한 `shared-contract`(테넌트 관찰 키, admin 명령 digest, + credential fingerprint, keyset cursor tag. `MongoDigestOutputTest`가 출력을 고정한다). `SecretSourcePort`만을 위한 + `application-core`. registry 항목의 `allowed_dependencies`는 `["application-core", "shared-contract"]`이고 빌드가 + 실제로 쓰는 것과 맞는다. `MongoProfileClientSettingsAutoConfiguration`의 bridge가 typed profile의 `uri-secret`을 + 배포가 설정한 비밀 값 backend로 해석한다. `verifyCleanArchitectureDependencies`는 해석된 edge가 선언된 것의 + 부분집합인지만 보므로 쓰지 않는 허가는 매번 통과한다. `MongoRegistryPermissionParityTest`가 반대 방향을 보고 두 + 집합이 다르면 실패한다. +- 서비스는 `app-bootstrap/build.gradle`에서 주석 처리한 한 줄 + `runtimeOnly project(':adapter:outbound:persistence-mongo')`로 이 leaf를 고른다. 기본 조립은 싣지 않는다. leaf는 + imperative만이다: reactive 쌍둥이(`reactive/**`, reactive 트랜잭션·세션), change-stream 소비자, change-stream → + 메시징 bridge는 2026-09-25에 지웠다(`docs/capability-status.md`). 그래서 leaf는 reactive starter도 + reactive-streams driver도 싣지 않는다(`MongoReactiveDriverAbsenceTest`). +- 외부 의존: (sync) Mongo starter, spring-boot-autoconfigure, spring-boot-health, micrometer-core, slf4j-api, + configuration processor. Boot Health가 Jackson 애너테이션을 싣지만 런타임 JSON 직렬화는 애플리케이션의 몫이라서 + Jackson 애너테이션은 compile 전용이다. 버전은 공용 Spring Boot BOM에서 온다. driver 버전을 직접 고정하지 않는다. +- 시험 전용: ArchUnit, Testcontainers(`mongodb`, `toxiproxy`). -## Forbidden +## 금지 (Forbidden) -- Inbound adapters, sibling outbound adapters, `app-bootstrap` (ArchUnit - `OUTBOUND_ADAPTERS_*` family rules). -- Shipping placeholder `Example*` document, repository, record, or adapter types in production. -- Adding idempotency/outbox/lock on Mongo without a separately approved contract. -- Fully-qualified inline type references; more than one public top-level type per file. +- inbound 어댑터, 이웃 outbound 어댑터, `app-bootstrap`(ArchUnit `OUTBOUND_ADAPTERS_*` 규칙 묶음). +- 운영 코드에 자리표시용 `Example*` 문서, repository, record, 어댑터 타입을 싣기. +- 따로 승인된 계약 없이 Mongo 위에 멱등성·outbox·lock을 더하기. +- 줄 안에 완전한 이름으로 쓴 타입 참조, 파일 하나에 공개 최상위 타입 둘 이상. -### Package-boundary rules (`MongoModuleBoundaryTest`) +### 패키지 경계 규칙 (`MongoModuleBoundaryTest`) -These reproduce the design's module dependency table. Breaking one fails the build: +설계의 모듈 의존 표를 그대로 옮긴 것이다. 하나라도 어기면 빌드가 실패한다: -- `…mongo.api..` must not import Spring, the MongoDB driver, BSON or Reactor. It is the - framework-free core contract; `api/package-info.java` records why. -- No Stable package may depend on `…mongo.advanced..`. -- No production package may depend on `…mongo.testkit..`. -- `query` ↛ `aggregation`, `schema` ↛ execution packages, `observation` ↛ execution packages, - `migration` ↛ `migration.flamingock`. +- `…mongo.api..`는 Spring, MongoDB driver, BSON, Reactor를 import하지 않는다. 프레임워크 없는 핵심 계약이다. + `api/package-info.java`가 이유를 적는다. +- Stable 패키지는 `…mongo.advanced..`에 의존하지 않는다. +- 운영 패키지는 `…mongo.testkit..`에 의존하지 않는다. +- `query` ↛ `aggregation`, `schema` ↛ 실행 패키지, `observation` ↛ 실행 패키지, `migration` ↛ `migration.flamingock`. -### Consistency-bound templates +### 일관성에 묶인 template -`MongoConsistencyBinder` derives one `MongoTemplate` per consistency profile. Spring Data exposes -setters and no getters for a template's supporting contract, so the parts that must travel — -write-concern resolver, write-result checking, lifecycle events, and the `ApplicationContext` that -supplies entity callbacks and auditing — are passed explicitly as a `MongoTemplateSupportContract`. -Reflection over private fields is forbidden here. A template configured with callbacks registered -programmatically outside a context cannot be reproduced by the bound path; that configuration is -unsupported rather than silently dropped. +`MongoConsistencyBinder`는 일관성 profile마다 `MongoTemplate`을 하나 끌어낸다. Spring Data는 template의 지원 계약에 +setter만 내놓고 getter를 내놓지 않는다. 그래서 따라가야 하는 부분 — write-concern resolver, 쓰기 결과 검사, +lifecycle 이벤트, entity callback과 auditing을 주는 `ApplicationContext` — 을 `MongoTemplateSupportContract`로 명시해 +넘긴다. 여기서 private 필드에 대한 리플렉션은 금지다. context 밖에서 프로그램으로 callback을 등록한 template은 +묶인 경로로 다시 만들 수 없다. 그 설정은 소리 없이 버리지 않고 지원하지 않는 것으로 둔다. -### Public surface +### 공개 surface -Every public top-level type in one jar means `public` is public to every adopter regardless of which -package it sits in. `verifyMongoApiSurface` (in `check`) compares the surface against -`docs/architecture/mongo-api-surface.txt`, which carries the count; growing it takes -`updateMongoApiSurface -PapproveMongoApiSurfaceChange`, which is a review decision. +jar 하나 안의 모든 공개 최상위 타입이므로, `public`은 어느 패키지에 있든 모든 채택자에게 공개다. +`verifyMongoApiSurface`(`check` 안)가 surface를 개수를 담은 `docs/architecture/mongo-api-surface.txt`와 비교한다. +늘리려면 `updateMongoApiSurface -PapproveMongoApiSurfaceChange`가 필요하고, 그것은 리뷰 결정이다. -The architecture rule catalogue (`…mongo.architecture`) is in the **testkit** source set, not -production: it is ArchUnit input, and shipping it put rule text on every consumer's runtime -classpath. Release gating is testkit-only for the same reason and is one implementation, not two: -`…mongo.testkit.release` reads the JUnit XML a lane wrote and is what -`scripts/verify-mongodb-platform.sh` and `src/adapter/outbound/persistence-mongo/release/release-contracts.json` drive. A second -pair on the production classpath — a hand-built set of category names and a gate that checked it — -had no caller outside its own test and no source of truth behind the categories; it is gone rather -than moved. +아키텍처 규칙 catalog(`…mongo.architecture`)는 운영이 아니라 **testkit** source set에 있다: ArchUnit 입력이고, 그것을 +싣으면 모든 쓰는 쪽의 runtime classpath에 규칙 글이 올라갔다. 같은 이유로 릴리스 gate도 testkit 전용이고, 구현은 +둘이 아니라 하나다: `…mongo.testkit.release`가 lane이 쓴 JUnit XML을 읽고, `scripts/verify-mongodb-platform.sh`와 +`src/adapter/outbound/persistence-mongo/release/release-contracts.json`이 그것을 돌린다. 운영 classpath에 있던 두 번째 +짝 — 손으로 만든 category 이름 집합과 그것을 검사한 gate — 은 자기 시험 말고는 호출자가 없었고 category 뒤에 정본도 +없었다. 옮기지 않고 없앴다. -Still pending, and deliberately not done as part of a review sweep: moving implementation packages -under an `internal` root and lowering visibility inside them. That is a mechanical change over ~200 -files and belongs in its own commit, after which the snapshot above is what proves the surface -actually shrank. +아직 남았고, 리뷰 정리의 일부로 일부러 하지 않은 것: 구현 패키지를 `internal` 루트 아래로 옮기고 그 안의 가시성을 +낮추는 일. 약 200개 파일에 걸친 기계적 변경이라 자기 커밋에 둔다. 그 뒤에는 위 snapshot이 surface가 실제로 +줄었다는 증거가 된다. -### Credentials and production profiles +### credential과 운영 profile -A production `MongoProfileProperties` must declare TLS, authentication, strict Stable API, a -non-standalone topology and finite positive timeouts; `validate()` enforces all of them. The URI is a -`secret://` reference and `MongoCredentialResolver` is the only thing that turns one into a -connection string — it hands the value to a caller-supplied function and never returns it, so the -credential is a local for one call rather than a field, a bean property or a log line. +운영 `MongoProfileProperties`는 TLS, 인증, 엄격한 Stable API, standalone이 아닌 topology, 유한한 양의 timeout을 +선언해야 한다. `validate()`가 그것을 모두 강제한다. URI는 `secret://` 참조이고, 그것을 connection string으로 바꾸는 +것은 `MongoCredentialResolver`뿐이다 — 값을 호출자가 준 함수에 넘기고 돌려주지 않으니, credential은 필드나 bean +속성이나 로그 줄이 아니라 호출 한 번의 지역 변수다. -When `platform.profiles` is non-empty, adoption is intentionally fail-closed. In one composition -change provide the data-plane `MongoCredentialResolver` plus `MongoTopologyProbe`, -`MongoSecurityProfile`, admin `MongoCredentialReference`, and `MongoSchemaVersionRange`; README.md -contains the complete 14-field production profile example. Supplying profiles piecemeal and -discovering these requirements one startup failure at a time is not an accepted adoption path. +`platform.profiles`가 비어 있지 않으면 채택은 일부러 실패하면 닫힌다. 조립 변경 하나에서 데이터 plane +`MongoCredentialResolver`와 함께 `MongoTopologyProbe`, `MongoSecurityProfile`, admin `MongoCredentialReference`, +`MongoSchemaVersionRange`를 준다. README.md에 필드 14개짜리 운영 profile 예가 다 있다. profile을 조금씩 주며 그 +요구를 기동 실패 하나씩으로 알아내는 것은 받아들인 채택 길이 아니다. -The default resolver is a bridge over `SecretSourcePort` (`MongoCredentialResolver.fromSecretSource`, -registered when that port has a bean and no other resolver exists); the key is the reference's last -path segment, as in the Redis and HTTP client modules. Not shipped: the TLS lane -(trusted CA, wrong CA, hostname mismatch, expired certificate) which needs a container with real -certificates. Rotation ordering — new generation ready, traffic switch, old lease drain, close — is -covered by `MongoClientGenerationConcurrencyTest`. +기본 resolver는 `SecretSourcePort` 위의 bridge다(`MongoCredentialResolver.fromSecretSource`. 그 포트에 bean이 있고 +다른 resolver가 없을 때 등록한다). 키는 Redis·HTTP client 모듈처럼 참조의 마지막 경로 조각이다. 싣지 않은 것: +실제 인증서를 가진 container가 필요한 TLS lane(믿는 CA, 틀린 CA, hostname 불일치, 만료된 인증서). 교체 순서 — 새 +generation 준비, traffic 전환, 옛 lease 비우기, 닫기 — 는 `MongoClientGenerationConcurrencyTest`가 덮는다. -### Platform invariants that are not stylistic +### 문체가 아닌 플랫폼 불변식 -- Transaction body retry and commit retry are **separate loops**: a new session per body attempt, and - commit-only retry on an unknown commit. The body is never replayed after a commit ambiguity - (`MongoTransactionRetryCoordinator`, ADR-MONGO-003). -- `MongoExecutionOutcome`'s two ambiguous values must not be collapsed into success or failure. -- BSON representations come from `MongoTypeRepresentationManifest`, never from a library default - (ADR-MONGO-002). -- Index and validator changes go through the manifest and the admin plane; ownership gates every drop - (ADR-MONGO-004). -- Every concrete Advanced type is annotated `@MongoAdvancedEntryPoint(capability)` or - `@MongoAdvancedPolicy`, and an entry point takes a `MongoAdvancedCapabilityGuard` and calls - `require` before it exists. `MongoAdvancedRules` enforces both halves; the classification rule is - what keeps "we gate the executable ones" from meaning "the ones somebody remembered". -- The flags have no configuration property. The Advanced types are library API: the adopter's - adapter builds `MongoAdvancedCapabilityFlags` and the guard in code. The Stable auto-configuration - must reference nothing under `..advanced..`. -- Every setting key this leaf binds must change behaviour. A key that nothing reads, or one whose - only effect is to fail startup, is deleted rather than documented (AGENTS.md capability rule 3); - `docs/capability-status.md` records what was removed and why. -- An interface ships only with an implementation in this leaf. Search, vector, time series and - GridFS were contract-only and were removed on 2026-09-25. -- Observation tags are limited to `MongoObservationConvention`'s allowlist. +- 트랜잭션 본문 재시도와 커밋 재시도는 **따로 도는 반복문**이다: 본문 시도마다 새 세션, 모르는 커밋에는 커밋만 + 재시도. 커밋이 모호해진 뒤에는 본문을 다시 돌리지 않는다(`MongoTransactionRetryCoordinator`, ADR-MONGO-003). +- `MongoExecutionOutcome`의 모호한 값 둘을 성공이나 실패로 뭉개면 안 된다. +- BSON 표현은 라이브러리 기본값이 아니라 `MongoTypeRepresentationManifest`에서 온다(ADR-MONGO-002). +- index와 validator 변경은 manifest와 admin plane을 거친다. 모든 drop은 소유권이 막는다(ADR-MONGO-004). +- 모든 구체 Advanced 타입은 `@MongoAdvancedEntryPoint(capability)`나 `@MongoAdvancedPolicy`를 단다. entry point는 + `MongoAdvancedCapabilityGuard`를 받고, 존재하기 전에 `require`를 부른다. `MongoAdvancedRules`가 두 절반을 강제한다. + 「실행되는 것은 막는다」가 「누가 기억해 낸 것은 막는다」가 되지 않게 하는 것이 분류 규칙이다. +- flag에는 설정 속성이 없다. Advanced 타입은 라이브러리 API다: 채택자의 어댑터가 코드로 + `MongoAdvancedCapabilityFlags`와 guard를 만든다. Stable 자동 구성은 `..advanced..` 아래의 어떤 것도 참조하면 안 + 된다. +- 이 leaf가 바인딩하는 모든 설정 키는 동작을 바꿔야 한다. 아무것도 읽지 않는 키나, 효과가 기동 실패뿐인 키는 + 문서로 남기지 않고 지운다(AGENTS.md capability 규칙 3). `docs/capability-status.md`가 무엇을 왜 지웠는지 적는다. +- 인터페이스는 이 leaf 안에 구현이 있을 때만 싣는다. Search, vector, time series, GridFS는 계약만 있었고 + 2026-09-25에 지웠다. +- observation tag는 `MongoObservationConvention`의 허용 목록으로 제한한다. -## Tests +## 테스트 -`MongoCapabilityActivationTest` boots a real `SpringApplication` and proves present = on and an -explicit `enabled=false` = no client, template or platform bean (Boot's Mongo auto-configuration -included). `MongoPersistenceConfigTest` covers typed enablement binding and enabled infrastructure -with a mock `MongoClient` plus a real `MongoTemplate` without a network connection. +`MongoCapabilityActivationTest`는 실제 `SpringApplication`을 띄워 있음 = 켜짐, 명시한 `enabled=false` = client· +template·플랫폼 bean 없음(Boot의 Mongo 자동 구성 포함)을 증명한다. `MongoPersistenceConfigTest`는 타입 있는 켜기 +바인딩과, 네트워크 연결 없이 mock `MongoClient`와 실제 `MongoTemplate`으로 켜진 기반을 덮는다. -Hermetic contract tests carry `@Tag("mongodb-contract")` and run in `mongoStableContractTest`, which -`check` depends on. Container lanes carry `mongodb-replicaset` / `mongodb-failover` and run only in -their own tasks; the default `test` task excludes them, because a lane that needs Docker inside -`check` teaches people to skip `check`. +밀폐된 계약 시험은 `@Tag("mongodb-contract")`를 달고 `check`가 의존하는 `mongoStableContractTest`에서 돈다. container +lane은 `mongodb-replicaset` / `mongodb-failover`를 달고 자기 태스크에서만 돈다. 기본 `test` 태스크는 그것을 뺀다. +`check` 안에 Docker가 필요한 lane이 있으면 사람들이 `check`를 건너뛰게 되기 때문이다. ```bash cd src ./gradlew :adapter:outbound:persistence-mongo:check --console=plain ``` -Release gates run from the repository root: `scripts/verify-mongodb-platform.sh` (Stable) and -`scripts/verify-mongodb-advanced.sh` (Advanced). +릴리스 gate는 저장소 루트에서 돈다: `scripts/verify-mongodb-platform.sh`(Stable)와 +`scripts/verify-mongodb-advanced.sh`(Advanced). diff --git a/src/adapter/outbound/persistence-notification/CLAUDE.md b/src/adapter/outbound/persistence-notification/CLAUDE.md index 156c57c2..9a34f725 100644 --- a/src/adapter/outbound/persistence-notification/CLAUDE.md +++ b/src/adapter/outbound/persistence-notification/CLAUDE.md @@ -1,57 +1,52 @@ -# adapter:outbound:persistence-notification — notification relational persistence +# adapter:outbound:persistence-notification — 알림 관계형 영속 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-persistence-notification`; Gradle path and allowed edges are in - `src/config/architecture/modules.json`. -- Focused test: `./gradlew :adapter:outbound:persistence-notification:test --console=plain`. -- Package root: `dev.caskeleton.adapter.outbound.persistence.notification`. The package rule is - the one `persistence-fileserver` uses, so both capability leaves read the same way: - - `platform.entity` — JPA rows only. - - `platform.repository` — Spring Data interfaces and the SQL text they run (`RecipientClaimSql`). - - `platform` — the store adapters (`Jpa*`, `Jdbc*`, the inbox's `JpaNotificationInbox` and its - outbox helpers), `NotificationRecordMapper` and the payload codec. - - `configuration` — the auto-configuration facade that registers the stores as beans; the leaf - root holds the scan configuration and the schema stream. - Entity constructors, accessors and mutators are public because the stores use them from another - package; an entity never leaves the leaf (the ports carry records). Visibility no longer says so, - so a rule does: `JpaArchitectureRules.entitiesAreUsedOnlyInsideTheirLeaf`, run over the production - graph by `JpaProductionArchitectureTest` (app-bootstrap `architectureTest`) for this leaf and - `persistence-fileserver`. +- 모듈 ID: `adapter-outbound-persistence-notification`. Gradle 경로와 허용 edge는 + `src/config/architecture/modules.json`에 있다. +- 이 모듈만 시험: `./gradlew :adapter:outbound:persistence-notification:test --console=plain`. +- 패키지 루트: `dev.caskeleton.adapter.outbound.persistence.notification`. 패키지 규칙은 + `persistence-fileserver`와 같아서 두 capability leaf를 같은 방식으로 읽는다: + - `platform.entity` — JPA 행만. + - `platform.repository` — Spring Data 인터페이스와 그것이 돌리는 SQL 글(`RecipientClaimSql`). + - `platform` — store 어댑터(`Jpa*`, `Jdbc*`, inbox의 `JpaNotificationInbox`와 그 outbox 도우미), + `NotificationRecordMapper`, payload codec. + - `configuration` — store를 bean으로 등록하는 자동 구성 창구. leaf 루트에는 scan 설정과 schema stream이 있다. + 엔티티 생성자·접근자·변경자는 store가 다른 패키지에서 쓰니 public이다. 엔티티는 leaf를 떠나지 않는다(포트는 + record를 싣는다). 가시성이 더는 그것을 말해 주지 않으므로 규칙이 말한다: + `JpaArchitectureRules.entitiesAreUsedOnlyInsideTheirLeaf`를 `JpaProductionArchitectureTest`(app-bootstrap + `architectureTest`)가 운영 그래프에 대고 이 leaf와 `persistence-fileserver`에 돌린다. -## Where the tests are +## 시험은 어디 있나 -| What | Where | Run | +| 무엇 | 어디 | 돌리기 | |---|---|---| -| Unit and wiring tests | this leaf, `src/test` | `:adapter:outbound:persistence-notification:test` | -| Real PostgreSQL tests of these stores | `persistence-jpa`, `src/postgresqlIntegrationTest/.../persistence/notification` (that lane owns the container and Flyway wiring) | `:adapter:outbound:persistence-jpa:postgresqlIntegrationTest --tests '<class>'` | -| Port contracts the stores must pass | `application-notification` testFixtures, `*.testkit.*Contract` (preference, suppression, deduplication, request, reconciliation job, admin operation, template registry, recipient lease, recipient delivery, delivery attempt, attempt resolver, delivery projection, provider event ledger, contact point, and the side effect over the contact point and suppression stores) | the in-memory fake (`application-notification` test) and the `PostgreSql*ContractTest` in `persistence-jpa` both extend the contract; `jpaPlatformContractTest` runs the PostgreSQL side | -| Migration pins | `persistence-jpa/src/test/resources/db/applied-migrations.sha256` | `AppliedMigrationImmutabilityTest` in `:adapter:outbound:persistence-jpa:test` | +| 단위·배선 시험 | 이 leaf, `src/test` | `:adapter:outbound:persistence-notification:test` | +| 이 store들의 실제 PostgreSQL 시험 | `persistence-jpa`, `src/postgresqlIntegrationTest/.../persistence/notification`(그 lane이 container와 Flyway 배선을 가진다) | `:adapter:outbound:persistence-jpa:postgresqlIntegrationTest --tests '<class>'` | +| store가 통과해야 하는 포트 계약 | `application-notification` testFixtures, `*.testkit.*Contract`(preference, suppression, deduplication, request, reconciliation job, admin operation, template registry, recipient lease, recipient delivery, delivery attempt, attempt resolver, delivery projection, provider event ledger, contact point, 그리고 contact point·suppression store 위의 부수 효과) | 메모리 fake(`application-notification` 시험)와 `persistence-jpa`의 `PostgreSql*ContractTest`가 모두 계약을 상속한다. PostgreSQL 쪽은 `jpaPlatformContractTest`가 돌린다 | +| migration 고정 | `persistence-jpa/src/test/resources/db/applied-migrations.sha256` | `:adapter:outbound:persistence-jpa:test`의 `AppliedMigrationImmutabilityTest` | -A store whose port has a contract in `application-notification` testFixtures is tested by a -PostgreSQL subclass of that contract, not by a separate hand-written PostgreSQL test. A case that is -about the vendor (a CHECK constraint, `@Version` on a bulk update) stays in the subclass. The ports -without a contract (the serving-state read model, consent, inbox), and why, are listed in -`docs/testing/TESTING_STRATEGY.md` §9.2. +`application-notification` testFixtures에 계약이 있는 포트의 store는 따로 손으로 쓴 PostgreSQL 시험이 아니라 +그 계약의 PostgreSQL 하위 클래스로 시험한다. vendor에 관한 경우(CHECK 제약, bulk update의 `@Version`)는 하위 +클래스에 남긴다. 계약이 없는 포트(serving-state 읽기 모델, 동의, inbox)와 그 이유는 +`docs/testing/TESTING_STRATEGY.md` 9.2절에 있다. -## Rules +## 규칙 -- **Every write joins the caller's transaction.** A store write starts with - `CallerTransaction.require("<what>")`; the use case owns the transaction (owner decision 2026-09-25). -- **Migrations** live in `src/main/resources/db/migration/jpa/notification-platform` and run as - their own Flyway stream (`NotificationSchemaStream`, history table - `flyway_jpa_notification_history`). An applied file is never edited: add the next `V<n>__`, pin - its SHA-256 in `applied-migrations.sha256`, and add it to `NotificationFixtures.migrations()`. - A migration that deletes rows states in a SQL comment which row survives and why. A migration - that locks an existing table starts with `SET LOCAL lock_timeout = '5s';` - (`docs/jpa/migration-guide.md` "Bound the lock wait"; `MigrationLockWaitTest` in persistence-jpa - refuses one without it). -- **Insert-or-update is decided by the database.** Never find-then-insert: insert with - `ON CONFLICT (<unique key>) DO NOTHING`, and when it inserted nothing, update the existing row - through the managed entity (`JpaSuppressionStore.upsert`, `JpaPolicyStores.Preferences.save`, - `DeduplicationClaims.insertOrFind`). The conflict target needs a unique constraint in a migration. -- **A bulk or native `UPDATE` of a `@Version` table advances the version** (`version = version + 1`) - and is `@Modifying(clearAutomatically = true, flushAutomatically = true)` when the caller may - re-read the row. `JpaVersionedBulkUpdateRule` (persistence-jpa testFixtures) enforces the - version part in `:app-bootstrap:architectureTest`. -- Repositories extend `Repository`, not `CrudRepository`, and expose only tenant-scoped finders. +- **모든 쓰기는 호출자의 트랜잭션에 합류한다.** store 쓰기는 `CallerTransaction.require("<what>")`로 + 시작한다. 트랜잭션은 유스케이스가 가진다(소유자 결정 2026-09-25). +- **migration**은 `src/main/resources/db/migration/jpa/notification-platform`에 있고 자기 Flyway stream + (`NotificationSchemaStream`, history 테이블 `flyway_jpa_notification_history`)으로 돈다. 적용한 파일은 고치지 + 않는다: 다음 `V<n>__`를 더하고, 그 SHA-256을 `applied-migrations.sha256`에 고정하고, + `NotificationFixtures.migrations()`에 더한다. 행을 지우는 migration은 어떤 행이 남고 왜인지 SQL 주석에 + 적는다. 이미 있는 테이블을 잠그는 migration은 `SET LOCAL lock_timeout = '5s';`로 시작한다 + (`docs/jpa/migration-guide.md` "Bound the lock wait". persistence-jpa의 `MigrationLockWaitTest`가 그것이 없는 + migration을 거절한다). +- **insert냐 update냐는 데이터베이스가 정한다.** 찾은 뒤 insert하지 않는다: `ON CONFLICT (<unique key>) DO + NOTHING`으로 insert하고, 아무것도 insert하지 않았으면 관리되는 엔티티로 있는 행을 update한다 + (`JpaSuppressionStore.upsert`, `JpaPolicyStores.Preferences.save`, `DeduplicationClaims.insertOrFind`). 충돌 + 대상에는 migration에 unique 제약이 있어야 한다. +- **`@Version` 테이블의 bulk·native `UPDATE`는 version을 올린다**(`version = version + 1`). 호출자가 그 행을 다시 + 읽을 수 있으면 `@Modifying(clearAutomatically = true, flushAutomatically = true)`다. version 부분은 + `JpaVersionedBulkUpdateRule`(persistence-jpa testFixtures)이 `:app-bootstrap:architectureTest`에서 강제한다. +- repository는 `CrudRepository`가 아니라 `Repository`를 상속하고, 테넌트 범위의 finder만 내놓는다. diff --git a/src/adapter/outbound/redis-sdk/README.md b/src/adapter/outbound/redis-sdk/README.md index cf641d16..84ff69be 100644 --- a/src/adapter/outbound/redis-sdk/README.md +++ b/src/adapter/outbound/redis-sdk/README.md @@ -1,35 +1,31 @@ -# adapter:outbound:redis-sdk — typed Redis SDK (library) +# adapter:outbound:redis-sdk — 타입 있는 Redis SDK (라이브러리) -A guarded, typed Redis API for service code that needs Redis data structures directly, beyond the -semantic ports `cache-redis` implements (cache, rate limit, lease, idempotency). +`cache-redis`가 구현하는 semantic 포트(cache, rate limit, lease, 멱등성)를 넘어 Redis 자료 구조를 직접 써야 하는 +서비스 코드를 위한, 보호 장치가 있는 타입 있는 Redis API다. -It is a **library, not a capability**. Nothing turns on because this leaf is on the classpath: it -has no `AutoConfiguration.imports`, creates no beans, and has no `enabled` switch of its own. Service -code calls its types directly, so it cannot be taken as `runtimeOnly` (AGENTS.md, library-type -exception to the capability rules). +**capability가 아니라 라이브러리다.** 이 leaf가 classpath에 있다고 켜지는 것은 없다: `AutoConfiguration.imports`가 +없고, bean을 만들지 않고, 자기 `enabled` 스위치가 없다. 서비스 코드가 그 타입을 직접 부르므로 `runtimeOnly`로 +받을 수 없다(AGENTS.md, capability 규칙의 라이브러리 타입 예외). -## Adding it +## 더하기 -In the service's own outbound adapter leaf — never in `domain-core` or `application-core`: +서비스 자신의 outbound 어댑터 leaf에 더한다 — `domain-core`나 `application-core`에는 더하지 않는다: ```groovy implementation project(':adapter:outbound:redis-sdk') ``` -`redis-runtime` comes with it: the SDK's public types extend and return runtime types -(`SemanticRedisCommands`, `RedisLaneContribution`, …), so the SDK declares the runtime as `api`. -The SDK itself also uses `shared-contract` (`HmacSha256` for permit signatures, review 2026-11-01 -01-11) as an `implementation` edge; a consumer does not see it. Register both edges in that leaf's -`allowed_dependencies` in -`src/config/architecture/modules.json` (HARD-STOP 5). Put the adapter behind an application-core -port, as for any other outbound capability. +`redis-runtime`이 함께 온다: SDK의 공개 타입이 runtime 타입(`SemanticRedisCommands`, `RedisLaneContribution`, …)을 +상속하고 돌려주므로 SDK는 runtime을 `api`로 선언한다. SDK 자신은 `shared-contract`(허가 서명용 `HmacSha256`, +review 2026-11-01 01-11)도 `implementation` edge로 쓴다. 쓰는 쪽에는 보이지 않는다. 두 edge 모두 그 leaf의 +`src/config/architecture/modules.json` `allowed_dependencies`에 등록한다(HARD-STOP 5). 다른 outbound capability와 +같이 어댑터를 application-core 포트 뒤에 둔다. -The connections come from `redis-runtime` (package `...cache.redis.runtime`, which knows nothing of -this SDK): its `RedisRuntimeAutoConfiguration` exists only while `APP_REDIS_ENABLED=true` and -provides `RedisRuntimeOwner`, which pools the runtime's own lanes (`REGULAR`, `SCRIPT`). The SDK's -blocking, transaction and admin lanes (`RedisSdkLane`) and its admin account are the SDK's: the -service contributes them to the runtime as beans, one per lane it uses, through -`RedisSdkComposition` — +연결은 `redis-runtime`(패키지 `...cache.redis.runtime`. 이 SDK를 모른다)에서 온다: 그 +`RedisRuntimeAutoConfiguration`은 `APP_REDIS_ENABLED=true`인 동안에만 있고, runtime 자신의 lane(`REGULAR`, +`SCRIPT`)을 pool로 두는 `RedisRuntimeOwner`를 준다. SDK의 blocking·transaction·admin lane(`RedisSdkLane`)과 그 +admin 계정은 SDK의 것이다: 서비스가 쓰는 lane마다 하나씩, `RedisSdkComposition`을 거쳐 bean으로 runtime에 +기여한다 — ```java @Bean RedisLaneContribution redisBlockingLane() { return RedisSdkComposition.blockingLane(32); } @@ -45,67 +41,62 @@ service contributes them to the runtime as beans, one per lane it uses, through } ``` -— and builds `LettuceRedisCommandGateway.over(lease.driver())` over a borrowed lease. The last bean -matters only with an admin account: under `prod`, `SecretSourceValidator` refuses a secret that holds -a lane fixture password (`fixture-admin` is in `compose/redis/acl`), but it learns which variables -are secrets from the registry, from `secret://` references in the environment and from -`RequiredProductionSecrets` beans — not from a reference held in code. Without the bean the admin -account could run in production on the public lane password (review 2026-11-04 RR3-04-03). The SDK -cannot contribute it itself: it depends on `redis-runtime` and `shared-contract` only. The service's -adapter composes the SDK objects it uses on top of that; `LiveRedisOperationsFixture` in this leaf's -tests is a complete worked composition (catalog, permit verifier, guard, executor, operations). +— 그리고 빌린 lease 위에 `LettuceRedisCommandGateway.over(lease.driver())`를 만든다. 마지막 bean은 admin 계정이 +있을 때만 뜻이 있다: `prod`에서 `SecretSourceValidator`는 lane fixture 비밀번호(`fixture-admin`은 +`compose/redis/acl`에 있다)를 가진 비밀 값을 거절한다. 하지만 어떤 변수가 비밀 값인지는 registry, 환경 안의 +`secret://` 참조, `RequiredProductionSecrets` bean에서 배운다 — 코드가 쥔 참조에서는 배우지 않는다. 그 bean이 +없으면 admin 계정이 공개된 lane 비밀번호로 운영에서 돌 수 있었다(review 2026-11-04 RR3-04-03). SDK는 그 bean을 +스스로 기여할 수 없다: `redis-runtime`과 `shared-contract`에만 의존한다. 서비스의 어댑터가 그 위에 자기가 쓰는 +SDK 객체를 조립한다. 이 leaf 시험의 `LiveRedisOperationsFixture`가 완전한 조립 예다(catalog, 허가 검증기, guard, +executor, operations). -## What it provides +## 주는 것 -| Package (`dev.caskeleton.adapter.outbound.cache.redis.sdk.*`) | Contents | +| 패키지 (`dev.caskeleton.adapter.outbound.cache.redis.sdk.*`) | 내용 | | --- | --- | -| `api.key` | typed keys (`ValueKey`, `HashKey`, `ListKey`, `SetKey`, `SortedSetKey`, `StreamKey`, `BitmapKey`, `GeoKey`, `HyperLogLogKey`), `TypedRedisKeys`, `RedisKeyRenderer`, `RedisSlotTag` | -| `api.operations` / `api.reactive` | per-structure operation interfaces, synchronous and Reactor: value, hash, hash-field expiration, list, blocking list, set, sorted set, bitmap, bitfield, HyperLogLog, geo, stream, blocking stream, stream deletion, key, batch. No pub/sub: the SDK has no subscription transport, and the catalog blocks those commands | -| `api.command`, `api.codec`, `api.error` | `OperationBudget`, permits (`MultiKeyPermit`, `AdvancedOperationPermit`), `RedisPolicyAuthority`; `RedisCodec`/`RedisPayloadCodec`; the typed exception family | -| `lettuce.operations` | the `Lettuce*Operations` implementations, `RedisOperationContext`, `RedisOperationLimits` | -| `lettuce.command` | `RedisCommandCatalog` (loaded from `redis-sdk/redis-command-policy.yml`), `CommandPolicyGuard` (every command is admitted here before it runs), exception translation, executors | -| `lettuce.codec` | UTF-8/long/double/bytes codecs, `VersionedJsonCodec`, `RedisCodecRegistry` | -| `lettuce.observability`, `lettuce.connection` | `RedisObservation` through a no-throw sink; `SentinelFailoverObserver`; `RedisSdkLane`, `RedisSdkComposition` (the SDK's lanes and admin account, contributed to the runtime) | +| `api.key` | 타입 있는 키(`ValueKey`, `HashKey`, `ListKey`, `SetKey`, `SortedSetKey`, `StreamKey`, `BitmapKey`, `GeoKey`, `HyperLogLogKey`), `TypedRedisKeys`, `RedisKeyRenderer`, `RedisSlotTag` | +| `api.operations` / `api.reactive` | 자료 구조별 operation 인터페이스, 동기와 Reactor: value, hash, hash 필드 만료, list, blocking list, set, sorted set, bitmap, bitfield, HyperLogLog, geo, stream, blocking stream, stream 삭제, key, batch. pub/sub는 없다: SDK에 구독 전송이 없고 catalog가 그 명령을 막는다 | +| `api.command`, `api.codec`, `api.error` | `OperationBudget`, 허가(`MultiKeyPermit`, `AdvancedOperationPermit`), `RedisPolicyAuthority`. `RedisCodec`/`RedisPayloadCodec`. 타입 있는 예외 묶음 | +| `lettuce.operations` | `Lettuce*Operations` 구현, `RedisOperationContext`, `RedisOperationLimits` | +| `lettuce.command` | `RedisCommandCatalog`(`redis-sdk/redis-command-policy.yml`에서 읽는다), `CommandPolicyGuard`(모든 명령은 돌기 전에 여기서 허가받는다), 예외 번역, executor | +| `lettuce.codec` | UTF-8·long·double·bytes codec, `VersionedJsonCodec`, `RedisCodecRegistry` | +| `lettuce.observability`, `lettuce.connection` | 던지지 않는 sink를 거친 `RedisObservation`. `SentinelFailoverObserver`. `RedisSdkLane`, `RedisSdkComposition`(runtime에 기여하는 SDK의 lane과 admin 계정) | | `cluster` | `SameSlotValidator`, `ClusterScanCursor`, `ClusterTopologyObserver` | | `config` | `ConfiguredRedisPolicyAuthority`, `ConfiguredRedisPermitVerifier`, `RedisCapabilityProbe`, `RedisStartupProbe` | -| `programmability` | `WATCH`/`MULTI`/`EXEC` transactions (never roll back), registered scripts (`EVALSHA` only), deployed functions | -| `raw` | `LettuceRedisRawGateway`: only commands the catalog marks `RAW_ONLY` **and** the service approves in `RawCommandApprovals` | -| `admin` | `LettuceRedisAdminOperations`: read-only diagnostics on the `ADMIN` lane, projected replies | -| `extensions.*` | Redis 8 modules: JSON, Search, Time Series, Probabilistic; each gated by the capability probe | +| `programmability` | `WATCH`/`MULTI`/`EXEC` 트랜잭션(롤백하지 않는다), 등록된 script(`EVALSHA`만), 배포된 function | +| `raw` | `LettuceRedisRawGateway`: catalog가 `RAW_ONLY`로 표시했고 **그리고** 서비스가 `RawCommandApprovals`에서 승인한 명령만 | +| `admin` | `LettuceRedisAdminOperations`: `ADMIN` lane 위의 읽기 전용 진단, 걸러 낸 응답 | +| `extensions.*` | Redis 8 모듈: JSON, Search, Time Series, Probabilistic. 각각 capability probe가 막는다 | -Configuration that is **code, not settings** — there is no `app.redis.*` key for any of these: -operation ceilings and timeouts (`RedisOperationLimits`), the enabled advanced policies -(`ConfiguredRedisPolicyAuthority`), raw command approvals (`RawCommandApprovals`) and registered -scripts (`RedisScriptRegistry`). The service passes them where it composes the SDK. +**설정이 아니라 코드**인 설정 — 아래 어느 것에도 `app.redis.*` 키가 없다: operation 상한과 timeout +(`RedisOperationLimits`), 켠 고급 정책(`ConfiguredRedisPolicyAuthority`), raw 명령 승인(`RawCommandApprovals`), +등록된 script(`RedisScriptRegistry`). 서비스가 SDK를 조립하는 곳에서 넘긴다. -Package rules (driver containment, no string command surface, the transaction and raw-gateway -invariants) are in `src/adapter/outbound/cache-redis/CLAUDE.md` under "Redis runtime and optional -typed SDK"; `RedisSdkModuleBoundaryTest` enforces them. +패키지 규칙(driver 가두기, 문자열 명령 surface 없음, 트랜잭션과 raw gateway의 불변식)은 +`src/adapter/outbound/cache-redis/CLAUDE.md`의 「Redis 런타임과 골라 쓰는 typed SDK」에 있다. +`RedisSdkModuleBoundaryTest`가 강제한다. -## Env keys +## env 키 -The SDK reads none itself. It runs on `redis-runtime`, whose rows in -`docs/registries/env-keys.yaml` (owner `adapter-outbound-redis-runtime`) are the contract: +SDK는 스스로 하나도 읽지 않는다. `redis-runtime` 위에서 돌고, `docs/registries/env-keys.yaml`의 그 행(소유 +`adapter-outbound-redis-runtime`)이 계약이다: -- Required: `APP_REDIS_ENABLED` left at its default `true`, `APP_REDIS_NODES`, `APP_REDIS_MODE`, +- 필수: 기본값 `true`로 둔 `APP_REDIS_ENABLED`, `APP_REDIS_NODES`, `APP_REDIS_MODE`, `APP_REDIS_NAMESPACE_ENVIRONMENT`, `APP_REDIS_NAMESPACE_SERVICE`, `APP_REDIS_NAMESPACE_DOMAIN`, - and `APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE` (or - `APP_REDIS_AUTHENTICATION_ANONYMOUS_ACCESS_ACCEPTED=true`). -- Per SDK surface used: `APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE` (scripts, - functions; falls back to the application account with a startup warning), - `APP_REDIS_CAPACITY_MAXIMUM_SCRIPT_CONNECTIONS`. The blocking, transaction and admin lane - ceilings and the admin account's credential reference are code (`RedisSdkComposition`), not - settings — like every other SDK knob. -- Topology: `APP_REDIS_SENTINEL_*` when `APP_REDIS_MODE=sentinel`, `APP_REDIS_TLS_*` for TLS. + `APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE`(또는 `APP_REDIS_AUTHENTICATION_ANONYMOUS_ACCESS_ACCEPTED=true`). +- 쓰는 SDK surface마다: `APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE`(script, function. 없으면 기동 + 경고와 함께 애플리케이션 계정으로 물러선다), `APP_REDIS_CAPACITY_MAXIMUM_SCRIPT_CONNECTIONS`. blocking· + transaction·admin lane 상한과 admin 계정의 credential 참조는 설정이 아니라 코드(`RedisSdkComposition`)다 — + 다른 모든 SDK 손잡이처럼. +- topology: `APP_REDIS_MODE=sentinel`이면 `APP_REDIS_SENTINEL_*`, TLS는 `APP_REDIS_TLS_*`. -## Tests +## 테스트 ```bash ./gradlew :adapter:outbound:redis-sdk:test --console=plain ``` -Contract tests run the operations against this leaf's own in-memory gateway -(`InMemoryRedisCommandGateway`, test sources); the topology endpoint helper comes from -`testFixtures(project(':adapter:outbound:redis-runtime'))`. The real-server lane is -`redisTopologyTest` (see [compose/README.md](compose/README.md)); this leaf declares `standalone`, `sentinel` -and `cluster` in `build.gradle`. `tls` is qualified by `redis-runtime`. +계약 시험은 이 leaf 자신의 메모리 gateway(`InMemoryRedisCommandGateway`, 시험 소스)에 대고 operation을 돌린다. +topology endpoint 도우미는 `testFixtures(project(':adapter:outbound:redis-runtime'))`에서 온다. 실제 서버 lane은 +`redisTopologyTest`다([compose/README.md](compose/README.md)를 본다). 이 leaf는 `build.gradle`에서 `standalone`, +`sentinel`, `cluster`를 선언한다. `tls`는 `redis-runtime`이 검증한다. diff --git a/src/adapter/outbound/redis-sdk/compose/README.md b/src/adapter/outbound/redis-sdk/compose/README.md index 291b8572..a990dff2 100644 --- a/src/adapter/outbound/redis-sdk/compose/README.md +++ b/src/adapter/outbound/redis-sdk/compose/README.md @@ -1,28 +1,25 @@ -# Redis SDK topology lanes +# Redis SDK topology lane -These lanes exist to answer the questions the deterministic in-memory gateway cannot: how Lettuce -actually behaves during a Sentinel promotion, what a Cluster resharding does to an in-flight -command, and whether the ACL accounts grant exactly what the SDK issues. +이 lane들은 결정적인 메모리 gateway가 답하지 못하는 질문에 답하려고 있다: Sentinel 승격 중에 Lettuce가 실제로 +어떻게 움직이는지, Cluster resharding이 진행 중인 명령에 무엇을 하는지, ACL 계정이 SDK가 내는 명령을 정확히 +허락하는지. -All four have now run on Redis 7.4 and the evidence is recorded in -`docs/redis/support-matrix.md`. `.github/workflows/redis-sdk-topology.yml` runs the standalone lane -on any pull request that touches the Redis leaf, the full supported-version x topology matrix -nightly, and the same matrix on demand for a release candidate. +넷 모두 Redis 7.4에서 돌았고 증거는 `docs/redis/support-matrix.md`에 적혀 있다. +`.github/workflows/redis-sdk-topology.yml`은 Redis leaf를 건드리는 pull request마다 standalone lane을, 매일 밤 +지원 버전 × topology 표 전체를, 릴리스 후보에는 요청할 때 같은 표를 돌린다. -TLS is a lane of that matrix rather than something to wire up by hand. It is `tls`, not a -deployment mode: its shape is standalone and what it qualifies is the transport, so -`redisTopologyTest` maps the lane name to `standalone` for the tests and keeps the tag filter and -the required trust material on the lane. +TLS는 손으로 배선할 것이 아니라 그 표의 lane 하나다. 배포 모드가 아니라 `tls`다: 모양은 standalone이고 검증하는 +것은 전송이다. 그래서 `redisTopologyTest`는 시험에서 lane 이름을 `standalone`으로 대응시키고, tag 필터와 필요한 +신뢰 자료는 lane에 둔다. -## The TLS lane +## TLS lane -`tls/compose.yml` is the standalone shape with the transport swapped. The plaintext port is turned -off entirely (`--port 0`), which is the only configuration that proves anything: a lane accepting -both would let a client that failed to negotiate TLS fall back silently and still pass. +`tls/compose.yml`은 전송만 바꾼 standalone 모양이다. 평문 port는 완전히 끈다(`--port 0`). 이것만이 무언가를 +증명하는 설정이다: 둘 다 받는 lane이면 TLS 협상에 실패한 client가 소리 없이 물러서고도 통과할 수 있다. -Certificates are generated at start-up into a named volume rather than checked in — a private key -in the repository is a private key in the repository, however the file is named — and they last a -day, so a stale lane fails visibly instead of drifting. +인증서는 저장소에 넣지 않고 기동 때 named volume 안에 만든다 — 파일 이름을 어떻게 붙이든 저장소 안의 개인 +키는 저장소 안의 개인 키다 — 그리고 하루 동안만 유효해서, 낡은 lane은 조용히 어긋나지 않고 눈에 띄게 +실패한다. ```bash REDIS_VERSION=7.4 docker compose -f src/adapter/outbound/redis-sdk/compose/tls/compose.yml up -d --wait @@ -33,43 +30,38 @@ cd src && ./gradlew :adapter:outbound:redis-runtime:redisTopologyTest \ -Predis.topology.mode=tls -Predis.topology.trust-material=/tmp/redis-lane-ca.pem ``` -The lane refuses to run without `redis.topology.trust-material`. A TLS lane that trusts anything -qualifies nothing, so "no CA configured" is an error rather than a client with verification off. +lane은 `redis.topology.trust-material` 없이는 돌기를 거절한다. 아무것이나 믿는 TLS lane은 아무것도 검증하지 +않으니, 「CA를 설정하지 않음」은 검증을 끈 client가 아니라 오류다. -## The ACL fixture +## ACL fixture -`acl/lane-fixture-accounts.acl` provisions the accounts every lane uses. Two things about it matter, and -neither can be written in the file itself — **Redis refuses to start if an `aclfile` contains a -comment line**, so the whole file is directives and the explanation lives here. +`compose/redis/acl/lane-fixture-accounts.acl`이 모든 lane이 쓰는 계정을 만든다(각 lane의 `compose.yml`이 저장소 +루트의 그 폴더를 mount한다). 중요한 점이 둘인데, 둘 다 그 파일 안에 쓸 수 없다 — **`aclfile`에 주석 줄이 있으면 +Redis가 시작을 거절한다.** 그래서 파일 전체가 지시문이고 설명은 여기 있다. -`user default off` is the first line and is deliberate. Redis ships `default` enabled and -passwordless; while it is on, every restriction in the remaining accounts can be bypassed by simply -not authenticating, which makes the fixture decorative. Disabling it is what forces a client — and -the compose healthchecks — to pick a named account. +첫 줄 `user default off`는 일부러 둔 것이다. Redis는 `default`를 켜고 비밀번호 없이 내놓는다. 그것이 켜져 있는 +동안에는 인증하지 않기만 해도 나머지 계정의 모든 제한을 우회할 수 있어서 fixture가 장식이 된다. 그것을 꺼야 +client가 — 그리고 compose healthcheck가 — 이름 있는 계정을 고르게 된다. -Every named account carries a real password — `>fixture-application`, `>fixture-advanced`, and so -on. They were `nopass`, which was the more dangerous kind of wrong: an account that accepts any -password made every assertion about authentication pass for the same reason a typo would have, so -the lane's coverage of AUTH, rotation and secret wiring was indistinguishable from no coverage. -`LiveRedisCompositionTest` now presents a wrong password on purpose and requires `WRONGPASS`, which -is only a meaningful assertion because the accounts enforce one. +이름 있는 모든 계정에는 진짜 비밀번호가 있다 — `>fixture-application`, `>fixture-advanced` 같은 것이다. 예전에는 +`nopass`였고, 그것이 더 위험한 쪽의 잘못이었다: 아무 비밀번호나 받는 계정에서는 인증에 대한 모든 단언이 오타가 +있어도 통과할 이유로 통과했다. 그래서 lane이 AUTH, 교체, 비밀 값 배선을 덮는 것과 덮지 않는 것을 구별할 수 +없었다. `LiveRedisCompositionTest`는 이제 일부러 틀린 비밀번호를 내고 `WRONGPASS`를 요구한다. 계정이 비밀번호를 +강제하기 때문에 뜻이 있는 단언이다. -The passwords are fixture values in a throwaway container and are **not** a deployment template: a -real deployment resolves each account's credential through `secret://` and never writes one into -configuration. +이 비밀번호는 버리는 container 안의 fixture 값이고 배포 template이 **아니다**: 실제 배포는 계정마다 credential을 +`secret://`로 해석하고 설정에 쓰지 않는다. -The accounts are also split by role, because that is how the SDK uses them. `ca-skeleton-application` -runs ordinary data commands and cannot execute a script; `ca-skeleton-application-advanced` holds -`SCRIPT LOAD` and `EVALSHA` and nothing else needs to. That separation is real rather than -decorative: `LiveRedisSemanticPortsTest` runs the rate limiter without the advanced account and -requires it to come back `Unavailable`. +계정은 role로도 나뉜다. SDK가 그렇게 쓰기 때문이다. `ca-skeleton-application`은 보통 데이터 명령을 돌리고 +script를 실행할 수 없다. `ca-skeleton-application-advanced`는 `SCRIPT LOAD`와 `EVALSHA`를 가지고, 다른 계정은 그것이 +필요 없다. 이 분리는 장식이 아니라 실제다: `LiveRedisSemanticPortsTest`는 advanced 계정 없이 rate limiter를 돌리고 +그것이 `Unavailable`로 돌아오기를 요구한다. -## Running one +## 하나 돌리기 -Each lane has its own endpoint, because the address a client is given is not the same kind of thing -in each topology. Standalone declares a data node; Sentinel declares a *sentinel*, from which the -primary is resolved and re-resolved when it is promoted; Cluster declares any node, from which the -rest of the topology is discovered. +lane마다 자기 endpoint가 있다. client에게 주는 주소가 topology마다 같은 종류가 아니기 때문이다. standalone은 +데이터 노드를 선언한다. Sentinel은 *sentinel*을 선언하고, 거기서 primary를 찾으며 승격되면 다시 찾는다. Cluster는 +아무 노드나 선언하고, 거기서 나머지 topology를 찾는다. ```bash # Standalone @@ -91,69 +83,61 @@ cd src && ./gradlew :adapter:outbound:redis-runtime:redisTopologyTest :adapter:o -Predis.topology.host=localhost -Predis.topology.port=7100 -Predis.topology.mode=cluster ``` -Each leaf owns the lanes its tests qualify, and names the classes each lane must run in its -`build.gradle` (`redisTopologyLane { requiredClasses ... }`). Selecting a mode a leaf does not -declare fails instead of running nothing, so run only the leaves listed for the lane: +leaf마다 자기 시험이 검증하는 lane을 가지고, lane마다 돌아야 하는 클래스를 `build.gradle`에 적는다 +(`redisTopologyLane { requiredClasses ... }`). leaf가 선언하지 않은 모드를 고르면 아무것도 돌리지 않는 대신 +실패한다. 그러니 lane에 적힌 leaf만 돌린다: -| Lane | `redis-runtime` | `redis-sdk` | `cache-redis` | +| lane | `redis-runtime` | `redis-sdk` | `cache-redis` | | --- | --- | --- | --- | | standalone | `LiveRedisCompositionTest` | `RedisTopologyContractTest`, `LiveRedisGuardrailTest` | `LiveRedisSemanticPortsTest`, `LiveRedisSemanticScriptAclProbeTest` | | sentinel | `LiveRedisCompositionTest` | `RedisTopologyContractTest`, `LiveRedisSentinelPromotionTest` | — | | cluster | `LiveRedisCompositionTest` | `LiveRedisClusterTest`, `LiveRedisClusterTransactionTest` | `LiveRedisSemanticPortsTest`, `LiveRedisSemanticScriptAclProbeTest` | | tls | `LiveRedisTlsTest` | — | — | -Tear a lane down with `docker compose -f src/adapter/outbound/redis-sdk/compose/<lane>/compose.yml down -v`. +lane은 `docker compose -f src/adapter/outbound/redis-sdk/compose/<lane>/compose.yml down -v`로 내린다. -| Lane | Ports | Notes | +| lane | port | 메모 | | --- | --- | --- | -| standalone | 6379 | bridge network, published port | -| sentinel | primary 7010, replica 7011, sentinels 27010–27012 | host network | -| cluster | nodes 7100–7105, bus 17100–17105 | host network; `ready` gates on `cluster_state:ok` | -| tls | 6390 | published port, no plaintext port at all; CA generated per run | +| standalone | 6379 | bridge network, 내놓은 port | +| sentinel | primary 7010, replica 7011, sentinel 27010–27012 | host network | +| cluster | 노드 7100–7105, bus 17100–17105 | host network. `ready`가 `cluster_state:ok`를 기다린다 | +| tls | 6390 | 내놓은 port, 평문 port는 아예 없음. 실행마다 CA를 만든다 | -## Why the Sentinel and Cluster lanes use host networking +## Sentinel과 Cluster lane이 host network를 쓰는 이유 -Neither topology proxies. Sentinel answers `SENTINEL get-master-addr-by-name` with the address it -monitors and the client dials that itself; a cluster client reads `CLUSTER SHARDS` and connects to -every node it names. On a bridge network those are container-internal addresses, so a client on the -host resolves a topology it cannot reach — and after a promotion it resolves a *different* one it -also cannot reach. Sharing the host network namespace makes the address the topology advertises the -address the client can use, which is the difference between testing the SDK and testing Docker's -network. +두 topology 모두 proxy를 하지 않는다. Sentinel은 `SENTINEL get-master-addr-by-name`에 자기가 감시하는 주소로 답하고 +client가 그 주소로 직접 연결한다. cluster client는 `CLUSTER SHARDS`를 읽고 거기 적힌 모든 노드에 연결한다. bridge +network에서는 그것이 container 안쪽 주소라서, host의 client는 닿을 수 없는 topology를 찾게 되고 — 승격 뒤에는 +역시 닿을 수 없는 *다른* topology를 찾는다. host network namespace를 같이 쓰면 topology가 알리는 주소가 client가 +쓸 수 있는 주소가 된다. 그것이 SDK를 시험하는 것과 Docker network를 시험하는 것의 차이다. -That is also why their ports are fixed rather than parameterised: the addresses are written into -Sentinel's and the cluster's own configuration at creation time, and a lane whose two halves can -disagree fails for reasons that are not the SDK's. +같은 이유로 그 port들은 매개변수로 두지 않고 고정한다: 주소는 만들 때 Sentinel과 cluster 자신의 설정에 쓰이고, +두 절반이 서로 어긋날 수 있는 lane은 SDK와 관계없는 이유로 실패한다. -## Selection is by lane, not by hand +## 고르기는 손이 아니라 lane으로 한다 -`redisTopologyTest` derives its JUnit tag expression from the declared mode: `redis-topology & -lane-<mode>`. A promotion test is meaningless without sentinels and a cross-slot test is meaningless -without a cluster, but expressing that as a runtime assumption would turn "the lane was never -started" into a green skip. Selecting by tag keeps it fail-closed — what a mode cannot prove is not -selected, and what is selected must pass. +`redisTopologyTest`는 선언한 모드에서 JUnit tag 식을 끌어낸다: `redis-topology & lane-<mode>`. 승격 시험은 +sentinel 없이는 뜻이 없고 cross-slot 시험은 cluster 없이는 뜻이 없다. 하지만 그것을 런타임 가정으로 나타내면 +「lane이 시작되지 않았다」가 초록 건너뛰기가 된다. tag로 고르면 실패하면 닫힌 상태가 된다 — 모드가 증명할 수 +없는 것은 고르지 않고, 고른 것은 통과해야 한다. -The lane also fails closed on its endpoint: selecting `redisTopologyTest` without host, port, and -mode (and `redis.topology.master` on the Sentinel lane) is an error, never a skip. A topology test -that silently passes because it did not connect is worse than no topology test. +lane은 endpoint에 대해서도 실패하면 닫힌다: host, port, mode(Sentinel lane이면 `redis.topology.master`도) 없이 +`redisTopologyTest`를 고르면 건너뛰기가 아니라 오류다. 연결하지 않아서 소리 없이 통과하는 topology 시험은 +topology 시험이 없는 것보다 나쁘다. -## `min-replicas-to-write` on the Sentinel lane +## Sentinel lane의 `min-replicas-to-write` -The Sentinel lane sets `min-replicas-to-write 1` and `min-replicas-max-lag 1`, and this is not -incidental configuration. Without them the lane measured a promotion in which the superseded primary -kept answering `+OK` for eleven seconds after it had been replaced: **2,086 writes acknowledged to -the caller and then discarded**, with exactly one command failing. With them the same promotion lost -one write and refused 2,020 with `NOREPLICAS`, which the SDK reports as a definite, non-ambiguous -failure a caller can act on. +Sentinel lane은 `min-replicas-to-write 1`과 `min-replicas-max-lag 1`을 정한다. 우연히 둔 설정이 아니다. 그것 +없이 잰 승격에서는 밀려난 primary가 대체된 뒤에도 11초 동안 `+OK`로 답했다: **호출자에게 확인해 준 쓰기 +2,086개가 버려졌고**, 실패한 명령은 정확히 하나였다. 그것을 두고 같은 승격을 재면 쓰기 하나를 잃고 2,020개를 +`NOREPLICAS`로 거절했다. SDK는 그것을 호출자가 대응할 수 있는, 모호하지 않은 확정 실패로 알린다. -Any deployment where an acknowledgement is supposed to mean something has to set these. See -`docs/redis/support-matrix.md` for the full record. +확인 응답에 뜻이 있어야 하는 배포는 모두 이것을 정해야 한다. 전체 기록은 `docs/redis/support-matrix.md`를 본다. -## ACL accounts +## ACL 계정 -`acl/` holds one file per `CommandAccess` level. They are deliberately narrower than the SDK's own -rules, so a mistake in the SDK is still refused by the server — the account is the last boundary and -a permit never widens it. +`compose/redis/acl/`에는 `CommandAccess` 수준마다 파일이 하나씩 있다. 일부러 SDK 자신의 규칙보다 좁게 둔다. 그래서 +SDK의 실수도 서버가 거절한다 — 계정이 마지막 경계이고, 허가는 그것을 넓히지 않는다. -Every lane loads the same file on every data node. Accounts are enforced per node, so "they exist on -one node" is not evidence that a topology enforces them. +모든 lane은 모든 데이터 노드에 같은 파일을 읽어 들인다. 계정은 노드마다 강제되므로 「한 노드에 있다」는 topology가 +그것을 강제한다는 증거가 아니다. diff --git a/src/adapter/outbound/support/CLAUDE.md b/src/adapter/outbound/support/CLAUDE.md index 3afa2f32..a68269c7 100644 --- a/src/adapter/outbound/support/CLAUDE.md +++ b/src/adapter/outbound/support/CLAUDE.md @@ -1,44 +1,42 @@ -# adapter:outbound:support — shared outbound support +# adapter:outbound:support — outbound 공용 지원 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-support` -- Gradle path: `:adapter:outbound:support` -- Focused test (derived from Gradle path): `./gradlew :adapter:outbound:support:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-outbound-support` +- Gradle 경로: `:adapter:outbound:support` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:outbound:support:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package roots: `dev.caskeleton.adapter.outbound` and -`dev.caskeleton.adapter.outbound.support`. +패키지 루트: `dev.caskeleton.adapter.outbound`와 `dev.caskeleton.adapter.outbound.support`. -## Responsibility +## 책임 -- Own reusable outbound correlation, fail-open dependency logging, and auto-configuration seams. -- Provide technical support used by registered messaging/cache/notification/httpclient leaves. -- Own the template's `IntegrationEventEncoderPort` (`messaging/JsonIntegrationEventEncoder`, - registered by `IntegrationEventEncoderAutoConfiguration` over every contract contribution bean, - backing off to a service's own encoder). It lives here because a use case encodes before it - appends to the outbox, in compositions that carry no messaging module; it is the application's - own envelope v1 format, not an external-system protocol. -- Own the descriptor-relative local filesystem primitive (`filesystem/SecureDirectoryWalk`, - `filesystem/SecureFileAccess`): open, create, delete, stat and move below a root one directory - descriptor at a time with `NOFOLLOW_LINKS`, refusing symbolic components and escapes with typed - `IOException`s. A storage capability translates those into its own failure vocabulary (the - Fileserver's `LocalStorageFailures`); nothing here knows an error code. -- Own `StrictSettingsBinder`, the one strict settings binding. It is also the only support class an - inbound leaf may use: `adapter:inbound:web` binds `app.security` with it (registry edge and a - class-named ArchUnit exemption, since 2026-11-01). An empty value for a setting the type - has (`APP_FILESERVER_PLATFORM_QUOTA_NAMESPACE_LIMIT=`) binds as unset; an empty value under a name - the type does not have is still refused (decided 2026-11-03). -- Keep feature-specific clients and routing policies in their owning leaf. +- 다시 쓰는 outbound correlation, fail-open 의존성 로그, 자동 구성 이음매를 가진다. +- 등록된 messaging·cache·notification·httpclient leaf가 쓰는 기술 지원을 준다. +- 템플릿의 `IntegrationEventEncoderPort`(`messaging/JsonIntegrationEventEncoder`)를 가진다. + `IntegrationEventEncoderAutoConfiguration`이 모든 contract contribution bean 위에 등록하고, 서비스 자신의 + 인코더가 있으면 물러선다. 여기 있는 이유는 유스케이스가 outbox에 append하기 전에 인코딩하는데, 메시징 모듈을 + 싣지 않는 조립도 있기 때문이다. 이것은 외부 시스템 프로토콜이 아니라 애플리케이션 자신의 envelope v1 + 형식이다. +- 디렉터리 descriptor 기준의 로컬 파일 시스템 기본 장치(`filesystem/SecureDirectoryWalk`, + `filesystem/SecureFileAccess`)를 가진다: root 아래에서 디렉터리 descriptor를 하나씩 따라가며 + `NOFOLLOW_LINKS`로 열기, 만들기, 지우기, stat, 옮기기를 하고, symbolic 경로 요소와 바깥으로 나가기를 타입 있는 + `IOException`으로 거절한다. 저장 capability가 그것을 자기 실패 어휘로 바꾼다(파일 서버의 + `LocalStorageFailures`). 여기는 오류 코드를 모른다. +- 유일한 엄격 설정 바인딩 `StrictSettingsBinder`를 가진다. inbound leaf가 쓸 수 있는 유일한 support + 클래스이기도 하다: `adapter:inbound:web`이 이것으로 `app.security`를 바인딩한다(registry edge와 클래스 이름을 + 댄 ArchUnit 예외, 2026-11-01부터). 타입에 있는 설정의 빈 값(`APP_FILESERVER_PLATFORM_QUOTA_NAMESPACE_LIMIT=`)은 + 설정 안 함으로 바인딩한다. 타입에 없는 이름 아래의 빈 값은 계속 거절한다(2026-11-03에 정함). +- 기능 전용 client와 라우팅 정책은 그것을 가진 leaf에 둔다. -## Boundaries +## 경계 -- Allowed project dependencies are registry-owned: application, domain, and shared contracts. -- No inbound transport, persistence, bootstrap, or sample dependencies. -- No business rules or external-system-specific protocol implementation. +- 허용 프로젝트 의존은 registry가 가진다: application, domain, shared 계약. +- inbound 전송, 영속, bootstrap, 샘플 의존이 없다. +- 업무 규칙이나 특정 외부 시스템 프로토콜 구현이 없다. -## Tests +## 테스트 -Use focused unit tests for support behavior. Do not start a Spring application context unless the -contract being tested is configuration wiring itself. +지원 동작은 이 모듈만 보는 단위 시험으로 본다. 시험할 계약이 설정 배선 자체가 아니면 Spring application +context를 띄우지 않는다. diff --git a/src/app-bootstrap/CLAUDE.md b/src/app-bootstrap/CLAUDE.md index e12f76f1..21ed43ce 100644 --- a/src/app-bootstrap/CLAUDE.md +++ b/src/app-bootstrap/CLAUDE.md @@ -1,125 +1,118 @@ -# app-bootstrap — application entry point & composition root +# app-bootstrap — 애플리케이션 진입점과 조립 루트 -## Registered identity +## 등록 정보 -- Module ID: `app-bootstrap` -- Gradle path: `:app-bootstrap` -- Focused test (derived from Gradle path): `./gradlew :app-bootstrap:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `app-bootstrap` +- Gradle 경로: `:app-bootstrap` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :app-bootstrap:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.bootstrap`. +패키지 루트: `dev.caskeleton.bootstrap`. -## Responsibility +## 책임 -- Spring Boot entrypoint (`CaSkeletonApplication`). -- Runtime settings and logging bootstrap. -- Final cross-module wiring. -- Architecture tests that inspect all modules. +- Spring Boot 진입점(`CaSkeletonApplication`). +- 런타임 설정과 로깅 시작. +- 모듈을 가로지르는 마지막 배선. +- 모든 모듈을 들여다보는 아키텍처 시험. -## Allowed +## 허용 -- Runtime leaves explicitly declared by this module's Gradle dependencies and permitted by the - architecture registry. The resolved Gradle runtime graph is the runtime SSOT; do not duplicate a - membership list in metadata. -- Spring Boot startup/runtime dependencies. -- ArchUnit in tests. +- 이 모듈의 Gradle 의존성이 분명히 선언하고 아키텍처 registry가 허용한 런타임 leaf. 해석된 Gradle + runtime 그래프가 런타임의 정본이다. 구성원 목록을 metadata에 다시 적지 않는다. +- Spring Boot 시작·런타임 의존성. +- 시험에서 ArchUnit. -## Forbidden +## 금지 -- Concrete business policy. -- Controllers, use cases, repository adapters, or mappers authored directly under bootstrap. -- Settings classes that implement business logic. -- Implementing an `application-core` or `domain-core` port. A class that implements one is an - outbound adapter and belongs in an `adapter/outbound/*` leaf, however its dependencies are - configured — `CompositionRootBoundaryArchitectureTest` enforces this, with no exceptions. -- Raising a startup failure with `throw new IllegalStateException(...)`. Use `StartupFailures` - (`adapter:outbound:support`, package `support.startup`: `envValidation` / `profileMismatch` / - `requiredAdapterDisabled` / `migrationFailed`), so the - failure carries its sysexits exit code and structured log fields — - `StartupFailureContractArchitectureTest` enforces this. -- Answering "is this production?" locally. `dev.caskeleton.shared.runtime.RuntimeEnvironment` owns - the profile vocabulary for the whole repository. -- Depending on `org.testcontainers` from `src/test`. Real-service tests belong to - `src/integrationTest`; see `docs/testing/TESTING_STRATEGY.md`. +- 구체적인 업무 정책. +- bootstrap 아래에 직접 쓴 controller, 유스케이스, repository 어댑터, mapper. +- 업무 로직을 구현하는 설정 클래스. +- `application-core`나 `domain-core` 포트를 구현하기. 포트를 구현하는 클래스는 의존성을 어떻게 + 설정했든 outbound 어댑터이고 `adapter/outbound/*` leaf에 둔다 — + `CompositionRootBoundaryArchitectureTest`가 예외 없이 강제한다. +- 기동 실패를 `throw new IllegalStateException(...)`으로 내기. `StartupFailures` + (`adapter:outbound:support`, 패키지 `support.startup`: `envValidation` / `profileMismatch` / + `requiredAdapterDisabled` / `migrationFailed`)를 써서 실패가 sysexits 종료 코드와 구조화된 로그 + 필드를 싣게 한다 — `StartupFailureContractArchitectureTest`가 강제한다. +- 「운영 환경인가?」를 이 모듈 안에서 답하기. 저장소 전체의 profile 어휘는 + `dev.caskeleton.shared.runtime.RuntimeEnvironment`가 가진다. +- `src/test`에서 `org.testcontainers`에 의존하기. 실제 서비스를 쓰는 시험은 `src/integrationTest`에 + 둔다. `docs/testing/TESTING_STRATEGY.md`를 본다. -## Package layout +## 패키지 배치 -The rules below exist because their absence is what produced the drift this module was reviewed for -(`docs/reviews/2026-09-07-app-bootstrap-module-code-review.md`). Half the -capabilities lived under `autoconfigure/` and half at the package root; `Settings` classes were split -between a `settings/` package and their feature packages with no stated rule; and the same -decomposition problem was solved two different ways in the same leaf — Notification as nine focused -configurations, Redis as one 376-line class. +아래 규칙은 그것이 없어서 이 모듈의 리뷰 대상이 된 어긋남이 생겼기 때문에 있다 +(`docs/reviews/2026-09-07-app-bootstrap-module-code-review.md`). capability의 절반은 `autoconfigure/` +아래, 절반은 패키지 루트에 있었다. `Settings` 클래스는 규칙 없이 `settings/` 패키지와 각 기능 +패키지에 나뉘어 있었다. 그리고 같은 분해 문제를 같은 leaf에서 두 가지로 풀었다 — Notification은 작은 +설정 아홉 개로, Redis는 376줄 클래스 하나로. -- **A capability's assembly lives in the capability's own module**, registered by that module's - `AutoConfiguration.imports`, with its settings in the module's `config/module-defaults/*.yml`. - JPA (startup guards, Flyway strategy, lock decorator, readiness and full-off handling in - `JpaActivationEnvironmentPostProcessor`) is `adapter:outbound:persistence-jpa`; Redis (readiness) is - `adapter:outbound:cache-redis`; notification is `composition:notification-platform`. Every - capability is a commented `runtimeOnly` line in `build.gradle`; the default composition is web, - observability, the cores, support and identifier. This leaf keeps no list of capabilities: no - switch registry, no cross-capability dependency validator, no activation endpoint. Component scan - covers `dev.caskeleton.bootstrap` only; web (`WebAdapterAutoConfiguration`, `WebSecurityAutoConfiguration`, `WebMethodSecurityAutoConfiguration`) and support - (`OutboundSupportConfig`) arrive through their own `AutoConfiguration.imports`. What stays in `autoconfigure/<name>/` is application - composition every application needs: `common` (the clock). The outbox relay, the idempotency - executor and the durable operations (use cases and `/operations` endpoints, 07-08) are - `composition:outbox-relay`, `composition:idempotency` and `composition:durable-operation`, selected - by one `runtimeOnly` line each and building nothing until their ports exist. A capability's role→permission mapping ships in its own - `config/module-defaults` file, not in `config/security.yml`. The runtime wiring every composition root needs — - tracing, the metrics contract filters, domain-context propagation, user-principal pseudonymization - (`PrivacySettings`) and the actuator chain — is `composition:service-runtime`. -- **`<Capability>Settings` lives beside its capability**, not in `settings/`. The `settings/` package - holds only settings that belong to no capability — `BootstrapSettings`, `RuntimeSafetySettings` — - bound strictly with `StrictSettingsBinder`, never scanned. Logging has no settings record: - `logback-spring.xml` reads `app.logging.*` itself and `LoggingConfigurationRule` refuses values - Logback cannot use. -- **`runtime/` holds guards about the application itself** — secrets, numeric bounds, error-detail - exposure, multi-instance coordination, the runtime-profile check (`RuntimeEnvironmentProfileValidator`). - A guard about a capability's settings (the JPA OSIV/DDL/pool/TLS/vendor guards, the Mongo - connection-source rule, the GraphQL deployment-mode rule) ships with that capability's module, so - it exists exactly when the capability does. -- **The startup failure vocabulary lives in `adapter:outbound:support`** (`support.startup`: phases, - error codes, exceptions, `StartupFailures`, `StartupValidationContext`, `StartupOrder`, - `ReadinessGroup`, `RuntimeWarnings`), so capability modules fail the same way without depending on - this leaf. `runtime/startup/` keeps only `StartupFailureExceptionReporter`. -- **An environment-only guard is a `StartupRule` bean** (`support.startup`): it returns violations, - and the one `StartupRuleRunner` raises them before any other singleton exists (declare it with a - `static` `@Bean` method that takes only the `Environment`, the bean factory or an `ObjectProvider` - of static `RequiredProductionSecrets`; in every profile the runner creates each rule and each - `RequiredProductionSecrets` before any rule runs, and fails the boot naming any other bean one of - them creates, and naming any whose runtime class has an `@Value`/`@Autowired`/ - `@Inject`/`@Resource` member, a `@PostConstruct`/`@PreDestroy` callback or a - `@ConfigurationProperties` binding — those are created before the post-processors and would stay - unset). A guard that needs another bean stays a bean. A - capability's production secrets are the capability's: its module contributes a - `RequiredProductionSecrets` bean, and `SecretSourceValidator` checks the names without knowing - which roles exist. +- **capability의 조립은 그 capability 자신의 모듈에 있다.** 그 모듈의 `AutoConfiguration.imports`가 + 등록하고, 설정은 그 모듈의 `config/module-defaults/*.yml`에 둔다. JPA(기동 guard, Flyway 전략, + lock decorator, readiness, `JpaActivationEnvironmentPostProcessor`의 완전히 끄기 처리)는 + `adapter:outbound:persistence-jpa`, Redis(readiness)는 `adapter:outbound:cache-redis`, 알림은 + `composition:notification-platform`이다. 모든 capability는 `build.gradle`에서 주석 처리한 + `runtimeOnly` 한 줄이다. 기본 조립은 web, 관측, core들, support, identifier다. 이 leaf는 capability + 목록을 두지 않는다: 스위치 registry도, capability 사이 의존 검증기도, 켜기 endpoint도 없다. + component scan은 `dev.caskeleton.bootstrap`만 본다. web(`WebAdapterAutoConfiguration`, + `WebSecurityAutoConfiguration`, `WebMethodSecurityAutoConfiguration`)과 support + (`OutboundSupportConfig`)는 자기 `AutoConfiguration.imports`로 들어온다. `autoconfigure/<name>/`에 + 남는 것은 모든 애플리케이션에 필요한 애플리케이션 조립인 `common`(시계)뿐이다. outbox relay, + 멱등성 executor, durable operation(유스케이스와 `/operations` endpoint. 2026-11-01 성숙도 리뷰 뒤로 bootstrap 밖)은 + `composition:outbox-relay`, `composition:idempotency`, `composition:durable-operation`이다. 각각 + `runtimeOnly` 한 줄로 고르고, 자기 포트가 생기기 전에는 아무것도 만들지 않는다. capability의 + role → permission 대응은 `config/security.yml`이 아니라 그 capability의 `config/module-defaults` + 파일에 담긴다. 모든 조립 루트에 필요한 런타임 배선 — tracing, metric 계약 filter, domain-context + 전파, 사용자 principal 가명화(`PrivacySettings`), actuator chain — 은 `composition:service-runtime`이다. +- **`<Capability>Settings`는 `settings/`가 아니라 그 capability 옆에 둔다.** `settings/` 패키지는 + 어느 capability에도 속하지 않는 설정 — `BootstrapSettings`, `RuntimeSafetySettings` — 만 담는다. + 이 설정은 `StrictSettingsBinder`로 엄격하게 바인딩하고 scan하지 않는다. 로깅에는 settings record가 + 없다. `logback-spring.xml`이 `app.logging.*`을 직접 읽고 `LoggingConfigurationRule`이 Logback이 쓸 + 수 없는 값을 거절한다. +- **`runtime/`은 애플리케이션 자체에 대한 guard를 담는다** — 비밀 값, 숫자 한계, 오류 상세 노출, + 여러 인스턴스 조율, runtime profile 검사(`RuntimeEnvironmentProfileValidator`). capability 설정에 + 대한 guard(JPA OSIV·DDL·pool·TLS·vendor guard, Mongo 연결 출처 규칙, GraphQL 배포 모드 규칙)는 그 + capability의 모듈과 함께 나간다. 그래야 capability가 있을 때만 정확히 존재한다. +- **기동 실패 어휘는 `adapter:outbound:support`에 있다**(`support.startup`: phase, 오류 코드, 예외, + `StartupFailures`, `StartupValidationContext`, `StartupOrder`, `ReadinessGroup`, `RuntimeWarnings`). + 그래서 capability 모듈은 이 leaf에 의존하지 않고 같은 방식으로 실패한다. `runtime/startup/`에는 + `StartupFailureExceptionReporter`만 남는다. +- **환경만 보는 guard는 `StartupRule` bean이다**(`support.startup`). 위반을 돌려주고, 유일한 + `StartupRuleRunner`가 다른 singleton이 생기기 전에 그것을 올린다(`Environment`, bean factory, 정적 + `RequiredProductionSecrets`의 `ObjectProvider`만 받는 `static` `@Bean` 메서드로 선언한다. 모든 + profile에서 runner는 어떤 규칙을 돌리기 전에 규칙마다, 그리고 `RequiredProductionSecrets`마다 하나씩 + 만든다. 그중 하나가 만드는 다른 bean이 있으면 그 이름을 대며 기동을 실패시킨다. runtime 클래스에 + `@Value`/`@Autowired`/`@Inject`/`@Resource` 멤버, `@PostConstruct`/`@PreDestroy` 콜백, + `@ConfigurationProperties` 바인딩이 있는 것도 이름을 대며 실패시킨다 — 그런 것은 post-processor보다 + 먼저 만들어져 값이 비어 있게 된다). 다른 bean이 필요한 guard는 bean으로 남는다. capability의 운영 + 비밀 값은 그 capability의 것이다: 그 모듈이 `RequiredProductionSecrets` bean을 내놓고, + `SecretSourceValidator`는 어떤 role이 있는지 모르는 채로 이름을 검사한다. -## Decomposition threshold +## 분해 기준 -State it rather than leaving it to taste, because "it felt long enough" is what produced two -different answers for the same question. +취향에 맡기지 않고 적어 둔다. 「충분히 길다고 느꼈다」가 같은 질문에 두 가지 답을 낳았기 때문이다. -- One `@Configuration` holds one assembly concern. Split when it passes roughly **eight `@Bean` - methods**, or as soon as it assembles two unrelated port families — whichever comes first. -- One `@ConfigurationProperties` class owns one capability namespace. -- A capability that needs more than one configuration gets a root class holding its `enabled` - condition, `@EnableConfigurationProperties`, and an `@Import` of the per-concern classes. Scan - nothing: `@Import` from a gated root is what keeps `enabled=false` load-bearing rather than advisory. - `cache-redis`'s `capability/RedisCapabilityConfig` is the reference example. Optional adapter - capabilities that own reusable Spring composition publish their own root instead. Notification - uses `adapter:outbound:notification`'s `NotificationPlatformAutoConfiguration` plus - `composition:notification-platform`'s `NotificationApplicationCompositionAutoConfiguration`; JPA uses the - package-private `PersistenceJpaAutoConfiguration`, `PersistenceJpaRuntimeConfig` and - `startup.JpaStartupAutoConfiguration` from `adapter:outbound:persistence-jpa`, which is not in the - default composition (`// runtimeOnly project(':adapter:outbound:persistence-jpa')` in - `build.gradle`). - Mongo follows the same rule: the persistence-mongo leaf owns MongoRootAutoConfiguration and its internal health bridge; bootstrap owns no Mongo-specific production health configuration. -- Shared helpers of a split capability get their own type named for what they are, not a `*Util` - bucket — `cache-redis`'s `capability/RedisKeys` is the reference. +- `@Configuration` 하나는 조립 관심사 하나를 담는다. 대략 **`@Bean` 메서드 여덟 개**를 넘거나, 서로 + 관계없는 포트 묶음 둘을 조립하게 되면 — 둘 중 먼저 오는 때에 — 나눈다. +- `@ConfigurationProperties` 클래스 하나는 capability namespace 하나를 가진다. +- 설정이 둘 이상 필요한 capability는 루트 클래스를 둔다. 루트가 `enabled` 조건, + `@EnableConfigurationProperties`, 관심사별 클래스의 `@Import`를 가진다. 아무것도 scan하지 않는다: + 조건이 걸린 루트에서 `@Import`해야 `enabled=false`가 권고가 아니라 실제로 끄는 스위치가 된다. + `cache-redis`의 `capability/RedisCapabilityConfig`가 참조 예다. 다시 쓸 Spring 조립을 가진 optional + 어댑터 capability는 자기 루트를 내놓는다. 알림은 `adapter:outbound:notification`의 + `NotificationPlatformAutoConfiguration`과 `composition:notification-platform`의 + `NotificationApplicationCompositionAutoConfiguration`을 쓴다. JPA는 + `adapter:outbound:persistence-jpa`의 package-private `PersistenceJpaAutoConfiguration`, + `PersistenceJpaRuntimeConfig`, `startup.JpaStartupAutoConfiguration`을 쓰고, 이 모듈은 기본 조립에 + 없다(`build.gradle`의 `// runtimeOnly project(':adapter:outbound:persistence-jpa')`). + Mongo도 같은 규칙을 따른다: persistence-mongo leaf가 MongoRootAutoConfiguration과 그 내부 health + bridge를 가지고, bootstrap은 Mongo 전용 운영 health 설정을 가지지 않는다. +- 나눈 capability의 공용 도우미는 `*Util` 바구니가 아니라 하는 일을 이름으로 단 자기 타입을 가진다 — + `cache-redis`의 `capability/RedisKeys`가 참조 예다. -## Test +## 테스트 ```bash cd src diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/architecture/TemplatePackageOwnershipDocumentTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/architecture/TemplatePackageOwnershipDocumentTest.java index 508b7d22..137c5a94 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/architecture/TemplatePackageOwnershipDocumentTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/architecture/TemplatePackageOwnershipDocumentTest.java @@ -31,8 +31,8 @@ class TemplatePackageOwnershipDocumentTest { private static final String RULE_BOOK = "src/application-core/CLAUDE.md"; private static final String REGISTRY = "src/config/architecture/modules.json"; - private static final String APPLICATION_TABLE = "| Package (`dev.caskeleton.application.*`) |"; - private static final String DOMAIN_TABLE = "| Package (`dev.caskeleton.domain.*`) |"; + private static final String APPLICATION_TABLE = "| 패키지 (`dev.caskeleton.application.*`) |"; + private static final String DOMAIN_TABLE = "| 패키지 (`dev.caskeleton.domain.*`) |"; private static final Pattern PACKAGE_NAME = Pattern.compile("`([a-z][a-z0-9]*)`"); private final Path root = RepositoryContractResources.fromSystemProperty().repositoryRoot(); @@ -83,7 +83,7 @@ class TemplatePackageOwnershipDocumentTest { // then assertThat(missing) .as( - "packages %s lists are not in the leaf its \"Owning leaf\" column names; a package was" + "packages %s lists are not in the leaf its \"소유 leaf\" column names; a package was" + " moved or removed without the table (and TemplatePackageOwnership) following it", RULE_BOOK) .isEmpty(); diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DeveloperExperienceContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DeveloperExperienceContractTest.java index af7bb788..1347650f 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DeveloperExperienceContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DeveloperExperienceContractTest.java @@ -137,8 +137,8 @@ class DeveloperExperienceContractTest { assertThat(readme) .contains("scripts/bootstrap-local.sh") .contains("GET /api/healthcheck") - .contains("## 퀵스타트") - .contains("첫 실행 진입점은 하나입니다."); + .contains("## 시작하기") + .contains("첫 실행 진입점은 하나다."); } @Test diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/RunbookCoverageContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/RunbookCoverageContractTest.java index c89a5109..6345f6f5 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/RunbookCoverageContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/RunbookCoverageContractTest.java @@ -35,11 +35,16 @@ import org.yaml.snakeyaml.Yaml; * <li><b>LINK RESOLUTION</b> — every non-null {@code runbook_link} resolves to an existing file * under {@code docs/runbooks/}. * <li><b>PLACEHOLDER/STUB SMOKE</b> — runbook body must not contain TODO/TBD/PLACEHOLDER/FIXME - * and frontmatter must not have {@code status: stub} — EXCEPT files on the {@code - * LEGACY_STUB_DEBT} below. Files outside this temporary debt set that are stub/placeholder - * FAIL. + * and frontmatter must not have the draft status {@code status: 초안} — EXCEPT files on the + * {@code LEGACY_STUB_DEBT} below. Files outside this temporary debt set that are + * draft/placeholder FAIL. * </ol> * + * <p>A runbook's {@code status} is one of the two words the runbook template ({@code + * docs/runbooks/template.md}) allows: {@code 초안} (draft) or {@code 운영} (in operation). Any other + * value fails, so a stub written with the retired {@code stub} spelling cannot pass as a finished + * runbook. + * * <p>The registry and runbook directory are checked-in contract resources. Missing resources and * every contract violation are hard failures. * @@ -54,7 +59,7 @@ class RunbookCoverageContractTest { * (feature-operational-runbook-contract D9). * * <p>These are only the legacy stub runbooks seeded during Phase D1. This set must exactly match - * the current {@code status: stub} files. Do not add new debt here: complete the runbook or adopt + * the current {@code status: 초안} files. Do not add new debt here: complete the runbook or adopt * the future owned, expiring debt ledger. */ private static final Set<String> LEGACY_STUB_DEBT = @@ -105,6 +110,12 @@ class RunbookCoverageContractTest { "startup-required-adapter-disabled.md", "startup-validation-failed.md"); + /** The draft status: the runbook's body is not written yet. */ + private static final String DRAFT_STATUS = "초안"; + + /** Every status a runbook may declare: draft, or in operation. */ + private static final Set<String> RUNBOOK_STATUSES = Set.of(DRAFT_STATUS, "운영"); + /** Categories exempt from mandatory-runbook requirement (client-error only). */ private static final Set<String> EXEMPT_CATEGORIES = Set.of("VALIDATION", "NOT_FOUND", "CONFLICT", "DATA_INTEGRITY"); @@ -232,7 +243,7 @@ class RunbookCoverageContractTest { } Path trackedRunbook = repositoryResources.requireTrackedFileInside("docs/runbooks", filename); - if (extractFrontmatterStatus(Files.readString(trackedRunbook)).equals("stub")) { + if (extractFrontmatterStatus(Files.readString(trackedRunbook)).equals(DRAFT_STATUS)) { currentStubRunbooks.add(filename); } } @@ -241,7 +252,7 @@ class RunbookCoverageContractTest { assertThat(LEGACY_STUB_DEBT) .as( "LEGACY_STUB_DEBT is temporary containment and must match every and only current " - + "status=stub runbook; do not add new allowlist entries—complete the runbook " + + "status=초안 runbook; do not add new allowlist entries—complete the runbook " + "or adopt the future owned, expiring debt ledger") .containsExactlyInAnyOrderElementsOf(currentStubRunbooks); } @@ -264,15 +275,15 @@ class RunbookCoverageContractTest { Path trackedRunbook = repositoryResources.requireTrackedFileInside("docs/runbooks", filename); String content = Files.readString(trackedRunbook); - // Check for status: stub in frontmatter - boolean hasStubStatus = extractFrontmatterStatus(content).equals("stub"); + // Check for the draft status in frontmatter + boolean hasStubStatus = extractFrontmatterStatus(content).equals(DRAFT_STATUS); // Check for placeholder body text boolean hasPlaceholderBody = PLACEHOLDER_PATTERN.matcher(content).find(); if (hasStubStatus || hasPlaceholderBody) { violations.add( filename + ": " - + (hasStubStatus ? "status=stub" : "") + + (hasStubStatus ? "status=초안" : "") + (hasPlaceholderBody ? " body-contains-placeholder" : "")); } } @@ -285,6 +296,34 @@ class RunbookCoverageContractTest { .isEmpty(); } + @Test + void everyRunbookFrontmatterDeclaresDraftOrOperatingStatus() throws Exception { + // given + List<String> outsideVocabulary = new ArrayList<>(); + + // when + try (Stream<Path> files = Files.list(runbooksDir)) { + for (Path path : files.sorted().toList()) { + String filename = path.getFileName().toString(); + if (!filename.endsWith(".md") || filename.equals("template.md")) { + continue; + } + Path trackedRunbook = + repositoryResources.requireTrackedFileInside("docs/runbooks", filename); + String content = Files.readString(trackedRunbook); + String status = extractFrontmatterStatus(content); + if (!extractFrontmatter(content).isEmpty() && !RUNBOOK_STATUSES.contains(status)) { + outsideVocabulary.add(filename + ": status=" + status); + } + } + } + + // then + assertThat(outsideVocabulary) + .as("A runbook's frontmatter status must be one of %s", RUNBOOK_STATUSES) + .isEmpty(); + } + @Test void runbookCoverageRejectsFrontmatterFromSymlinkOutsideRunbooks(@TempDir Path tempDir) throws Exception { diff --git a/src/application-core/CLAUDE.md b/src/application-core/CLAUDE.md index 0d8b3171..0a8a6bf0 100644 --- a/src/application-core/CLAUDE.md +++ b/src/application-core/CLAUDE.md @@ -1,180 +1,173 @@ -# application-core — application use cases +# application-core — 애플리케이션 유스케이스 -## Registered identity +## 등록 정보 -- Module ID: `application-core` -- Gradle path: `:application-core` -- Focused test (derived from Gradle path): `./gradlew :application-core:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: the Spring Boot 4.x version pinned by the shared version catalog. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `application-core` +- Gradle 경로: `:application-core` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :application-core:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준은 공용 버전 카탈로그(`src/gradle/libs.versions.toml`)가 고정한 Spring Boot 4.x다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.application`. +패키지 루트: `dev.caskeleton.application`. 코드 주석에서 덜어낸 **설계 결정의 근거**는 [README.md](README.md) 가 모아둔다 (이 문서는 모듈 규칙 SSOT). -## Responsibility +## 책임 (Responsibility) -- Use case inbound ports (`CommandUseCase`, `QueryUseCase`) and their command / query contracts. -- Outbound ports (`*Port` interfaces) the use cases depend on. -- Application exceptions and policy types. -- Coordinate domain models through ports. -- Own application transaction boundaries through the `TransactionPort` abstraction. -- Expose framework-free invocation context through ports such as `CorrelationIdPort`; adapters own - MDC or other concrete storage. -- Own the framework-free semantic integration-event draft, validated-event value contract and - exact typed payload contribution SPI. This is the messaging semantic contract R1 boundary only. +- 유스케이스 inbound 포트(`CommandUseCase`, `QueryUseCase`)와 그 command·query 계약. +- 유스케이스가 의존하는 outbound 포트(`*Port` 인터페이스). +- 애플리케이션 예외와 정책 타입. +- 포트를 거쳐 도메인 모델을 조율한다. +- `TransactionPort` 추상화로 애플리케이션 트랜잭션 경계를 가진다. +- `CorrelationIdPort` 같은 포트로 프레임워크 없는 호출 문맥을 내놓는다. MDC 같은 실제 저장소는 + 어댑터가 가진다. +- 프레임워크 없는 integration event 초안(semantic draft), 검증된 이벤트의 값 계약, 정확한 타입의 + payload를 내놓는 SPI를 가진다. 메시징 semantic contract R1 경계까지만이다. -## Allowed +## 허용 - `:domain-core` - `:shared-contract` -- Java standard library types. +- Java 표준 라이브러리 타입. -## Forbidden +## 금지 (Forbidden) -- `adapter-*` implementation classes. +- `adapter-*` 구현 클래스. - `app-bootstrap`. -- Controller request/response DTOs. -- JPA entities and Spring Data repositories. -- HTTP status, transport types (`org.springframework.web..`). -- `org.springframework.transaction.annotation.Transactional` (use `TransactionPort` instead). -- `org.springframework.context.ApplicationContext` — direct dependency forbidden - (`getBean(Class)` reflection-style bypass blocked by the ArchUnit rule `application_does_not_depend_on_application_context`). String-key - bean lookup / `Class.forName(String)` / `BeanFactory#getBeansOfType` remain - ArchUnit's static-analysis blind spot — guard via code review checklist. -- Lombok (`lombok..`) — also forbidden in `domain-core`. Within `application-core`, - Lombok is currently not in scope for the contract; if you intend to use it, - weigh the bytecode opacity cost first. -- Persistence-layer transaction annotations of any kind inside this module. -- Diagnostic frameworks (`org.slf4j`, `java.util.logging`, Logback, Log4j, Micrometer). Express - diagnostic intent through a specific outbound `*Port`; adapters own rendering. -- Messaging provider/runtime types: physical topic, Kafka record or metadata, JSON tree/raw JSON - payload, serializer/schema-validator implementation, security topology and publication epoch. +- controller의 요청·응답 DTO. +- JPA 엔티티와 Spring Data repository. +- HTTP 상태, 전송 타입(`org.springframework.web..`). +- `org.springframework.transaction.annotation.Transactional`(대신 `TransactionPort`를 쓴다). +- `org.springframework.context.ApplicationContext` — 직접 의존 금지 + (`getBean(Class)` 같은 리플렉션식 우회는 ArchUnit 규칙 `APPLICATION_DOES_NOT_DEPEND_ON_APPLICATION_CONTEXT`가 막는다). 문자열 키로 + bean을 찾기, `Class.forName(String)`, `BeanFactory#getBeansOfType`은 ArchUnit 정적 분석이 + 보지 못하는 곳이다. 코드 리뷰 체크리스트로 막는다. +- Lombok(`lombok..`) — `domain-core`에서도 금지다. `application-core`에서는 지금 Lombok이 + 계약 범위에 없다. 쓰려면 바이트코드가 불투명해지는 비용을 먼저 따진다. +- 이 모듈 안의 영속 계층 트랜잭션 애너테이션은 종류를 가리지 않고 금지다. +- 진단 프레임워크(`org.slf4j`, `java.util.logging`, Logback, Log4j, Micrometer). 진단 의도는 + 전용 outbound `*Port`로 나타내고, 어떻게 남길지는 어댑터가 정한다. +- 메시징 provider·런타임 타입: 물리 topic, Kafka record나 metadata, JSON tree·raw JSON payload, + serializer·schema validator 구현, 보안 토폴로지, publication epoch. -## Contract types +## 계약 타입 -| Type | Purpose | +| 타입 | 용도 | |---|---| -| `usecase.UseCase<I, O>` | Base type for inbound ports. Concrete inbound ports MUST extend `CommandUseCase` or `QueryUseCase`. | -| `usecase.CommandUseCase<C extends Command, R>` | Inbound port for write use cases. Implementations MUST be annotated `@UseCaseCapability`. | -| `usecase.QueryUseCase<Q extends Query, R>` | Inbound port for read-only use cases. Implementations MUST declare `transactionMode = READ_ONLY` and `repositoryAccess = READ_REPOSITORY`. | -| `command.Command` | Marker for write intents. Plain immutable types built from domain values. | -| `query.Query` | Marker for read intents. Plain immutable types built from domain values. | -| `transaction.TransactionPort` | Outbound port for join-capable write/read, physical root-only write, and independent write boundaries. Implemented by `adapter-persistence`. | -| `secret.SecretSourcePort` | Framework-free outbound secret-resolution seam. Deployment selects a backend in app-bootstrap; concrete environment/cloud/vault readers belong to outbound adapter leaves. | -| `transaction.NestedRootTransactionRejectedException` | Fail-fast signal raised before action/provider side effects when `inRootWrite` detects an actual ambient transaction. | -| `transaction.TransactionMode` | `WRITE` / `READ_ONLY` / `REQUIRES_NEW`. `NESTED` and `NEVER` are intentionally absent. | -| `transaction.Isolation` | `READ_COMMITTED` (pinned default) / `REPEATABLE_READ` / `SERIALIZABLE`. `READ_UNCOMMITTED` is forbidden (not declared); the vendor default is never used (engine defaults differ — PostgreSQL READ COMMITTED vs MySQL InnoDB REPEATABLE READ). Routing the stricter levels through `TransactionPort` is a `planned` joint change with `feature-application-port-usecase-contract`; the shipped call path pins `READ_COMMITTED`. | -| `capability.UseCaseCapability` | Mandatory annotation on every concrete use case: declares `transactionMode`, `idempotency`, `repositoryAccess`, `externalOutboundAllowed`. | +| `usecase.UseCase<I, O>` | inbound 포트의 기반 타입. 구체 inbound 포트는 반드시 `CommandUseCase`나 `QueryUseCase`를 상속한다. | +| `usecase.CommandUseCase<C extends Command, R>` | 쓰기 유스케이스의 inbound 포트. 구현은 반드시 `@UseCaseCapability`를 단다. | +| `usecase.QueryUseCase<Q extends Query, R>` | 읽기 전용 유스케이스의 inbound 포트. 구현은 반드시 `transactionMode = READ_ONLY`와 `repositoryAccess = READ_REPOSITORY`를 선언한다. | +| `command.Command` | 쓰기 의도의 표지. 도메인 값으로 만든 평범한 불변 타입이다. | +| `query.Query` | 읽기 의도의 표지. 도메인 값으로 만든 평범한 불변 타입이다. | +| `transaction.TransactionPort` | 합류할 수 있는 쓰기·읽기, 물리 루트에서만 하는 쓰기, 독립 쓰기 경계를 내놓는 outbound 포트. `adapter:outbound:persistence-jpa`의 `SpringTransaction`이 구현한다. | +| `secret.SecretSourcePort` | 프레임워크 없는 outbound 비밀 해석 이음매. 배포가 app-bootstrap에서 backend를 고른다. 실제 환경 변수·클라우드·vault 리더는 outbound 어댑터 leaf에 둔다. | +| `transaction.NestedRootTransactionRejectedException` | `inRootWrite`가 실제로 열린 바깥 트랜잭션을 찾았을 때, action이나 provider 부작용 전에 바로 던지는 실패 신호. | +| `transaction.TransactionMode` | `WRITE` / `READ_ONLY` / `REQUIRES_NEW`. `NESTED`와 `NEVER`는 일부러 없다. | +| `transaction.Isolation` | `READ_COMMITTED`(고정 기본값) / `REPEATABLE_READ` / `SERIALIZABLE`. `READ_UNCOMMITTED`는 금지다(선언하지 않았다). vendor 기본값은 쓰지 않는다(엔진마다 기본값이 다르다 — PostgreSQL은 READ COMMITTED, MySQL InnoDB는 REPEATABLE READ). 더 엄격한 수준을 `TransactionPort`로 넘기는 일은 `feature-application-port-usecase-contract`와 함께 바꿀 `planned` 항목이다. 지금 호출 경로는 `READ_COMMITTED`로 고정한다. | +| `capability.UseCaseCapability` | 모든 구체 유스케이스에 반드시 다는 애너테이션: `transactionMode`, `idempotency`, `repositoryAccess`, `externalOutboundAllowed`를 선언한다. | | `capability.Idempotency` | `IDEMPOTENT` / `KEYED` / `NOT_IDEMPOTENT`. | | `capability.RepositoryAccess` | `NONE` / `READ_REPOSITORY` / `WRITE_REPOSITORY`. | -| `messaging.contract.IntegrationEventContractContribution<P>` | Closed exact-record payload type, canonical component order, local schema identity/hash and provider-neutral descriptor contribution. | -| `messaging.event.IntegrationEventDraft<P>` | Typed semantic event before local encoding; never JSON, Kafka or persistence state. Built only through `IntegrationEventDrafts` (`INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`). | -| `messaging.event.IntegrationEventDrafts` | The one way a feature builds a draft: contract id, version and destination from the contract, correlation from the request when canonical (else the event id), `SINGLE_TENANT_SCOPE` for a feature without tenants. | -| `messaging.event.IntegrationIdentity` | The one grammar and the length bounds of event, correlation/causation and aggregate ids. Test a value with `isCanonical(value, bound)`; never copy the pattern. | -| `messaging.event.ValidatedIntegrationEvent` | Stable semantic identities plus immutable exact encoded bytes and hashes, ready for a later durable append boundary. | -| `messaging.event.IntegrationEventEncoderPort` | Framework-free local draft-to-validated-event boundary implemented by an outbound adapter (the template's: `adapter:outbound:support` `JsonIntegrationEventEncoder`). | -| `outbox.OutboxAppendPort` | The one outbox append: a `ValidatedIntegrationEvent`, in the caller's write transaction. | -| `tenant.TenantId` | The tenant identifier and its one grammar (`[A-Za-z0-9][A-Za-z0-9_.-]{0,63}`); the web and GraphQL transport contexts both carry it. Built by a transport from verified authentication data only. | +| `messaging.contract.IntegrationEventContractContribution<P>` | 닫힌 정확한 record payload 타입, 정해진 component 순서, 로컬 schema identity·hash, provider 중립 descriptor 기여. | +| `messaging.event.IntegrationEventDraft<P>` | 로컬 인코딩 전의 타입 있는 semantic 이벤트. JSON·Kafka·영속 상태가 아니다. `IntegrationEventDrafts`로만 만든다(`INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`). | +| `messaging.event.IntegrationEventDrafts` | 기능이 초안을 만드는 유일한 길: contract id·version·destination은 contract에서, correlation은 요청 값이 정규형이면 그 값(아니면 event id), 테넌트가 없는 기능은 `SINGLE_TENANT_SCOPE`. | +| `messaging.event.IntegrationIdentity` | event id, correlation·causation id, aggregate id의 유일한 문법과 길이 한계. 값은 `isCanonical(value, bound)`로 시험한다. 패턴을 복사하지 않는다. | +| `messaging.event.ValidatedIntegrationEvent` | 안정된 semantic identity와 바뀌지 않는 정확한 인코딩 바이트·hash. 뒤의 durable append 경계로 넘길 준비가 된 값이다. | +| `messaging.event.IntegrationEventEncoderPort` | 프레임워크 없는 로컬 경계(초안 → 검증된 이벤트). outbound 어댑터가 구현한다(템플릿은 `adapter:outbound:support`의 `JsonIntegrationEventEncoder`). | +| `outbox.OutboxAppendPort` | 유일한 outbox append: `ValidatedIntegrationEvent` 하나를 호출자의 쓰기 트랜잭션 안에서 넣는다. | +| `tenant.TenantId` | 테넌트 식별자와 그 유일한 문법(`[A-Za-z0-9][A-Za-z0-9_.-]{0,63}`). web과 GraphQL 전송 문맥이 모두 이 값을 싣는다. 전송 계층이 검증된 인증 데이터로만 만든다. | -## Notification (NOTIF-ADR-005) +## 알림 (NOTIF-ADR-005) -None of the notification types are in this leaf. `..notification.platform..` and the simple -`NotificationPort`, `Notification` and `NotificationChannel` directly under -`dev.caskeleton.application.notification` all belong to leaf `application-notification`; the shared -package prefix is the only link. The R1 orchestration types were removed on 2026-09-25. +알림 타입은 이 leaf에 하나도 없다. `..notification.platform..`과 +`dev.caskeleton.application.notification` 바로 아래의 단순한 `NotificationPort`, `Notification`, +`NotificationChannel`은 모두 leaf `application-notification`의 것이다. 패키지 접두어가 같은 것이 +유일한 연결이다. R1 조율 타입은 2026-09-25에 지웠다. -## Naming convention +## 이름 규칙 (Naming convention) -This section is the repository's naming rule book. `NamingConventionTest` (app-bootstrap -architectureTest) enforces the machine-checkable rows; the rest are review rules, and a review checks -them against this table. A new feature follows the "new code" column; the "existing exceptions" are -named so nobody copies them by accident. +이 절이 저장소의 이름 규칙 정본이다. 기계로 볼 수 있는 행은 `NamingConventionTest`(app-bootstrap +architectureTest)가 강제한다. 나머지는 리뷰 규칙이고, 리뷰가 이 표와 대조한다. 새 기능은 「새 코드」 +열을 따른다. 「이미 있는 예외」는 누가 실수로 따라 하지 않게 이름을 적어 둔 것이다. -| Role | Name | Where | Existing exceptions (do not copy) | +| 역할 | 이름 | 위치 | 이미 있는 예외(따라 하지 않는다) | |---|---|---|---| -| Use case (inbound port implementation) | `<Verb><Noun>UseCase`, enforced by ArchUnit | `application` package of the feature | `*ApplicationUseCase` (application-fileserver, application-notification), `*Service` (notification, fileserver) | -| Command / query record | `*Command` / `*Query` | next to its use case | — | -| Aggregate persistence (stores and returns whole aggregates) | `<Aggregate>Repository` | **domain** package of the aggregate, owned by the domain | — | -| Technical store the application owns (outbox, idempotency, operation rows) | `<Thing>StorePort` | application package | `*WritePort` (old onboarding fixture, removed) | -| Read model that returns projections, not aggregates | `<Thing>QueryPort` | application package; returns projections only (ArchUnit) | — | -| Any other outbound port | `<Capability>Port` | application package | — | -| Server-assigned id generation | `<Aggregate>IdFactory extends IdFactory<<Aggregate>Id>` | domain package; the id record `implements ResourceId<Self>` | `OutboxEventIdFactory` (sample; event ids are not resource ids) | -| Configuration binding | `*Settings` (operational) or `*Policy` (authorization / domain policy), enforced by ArchUnit | the leaf that binds it | — | -| Throwable | `*Exception`, enforced by ArchUnit | — | — | -| Contract test kit for a port | abstract `<Port>Contract` in the port owner's testFixtures; the fake's and each adapter's test extend it | testFixtures | value-type tests were once named `*ContractTest`; they are `*ValueTypesTest` now | +| 유스케이스(inbound 포트 구현) | `<Verb><Noun>UseCase`, ArchUnit이 강제 | 기능의 `application` 패키지 | `*ApplicationUseCase`(application-fileserver, application-notification), `*Service`(notification, fileserver) | +| command·query record | `*Command` / `*Query` | 그 유스케이스 옆 | — | +| aggregate 영속(aggregate 전체를 저장하고 돌려준다) | `<Aggregate>Repository` | aggregate의 **domain** 패키지, 도메인이 가진다 | — | +| 애플리케이션이 가진 기술 저장소(outbox, 멱등성, operation 행) | `<Thing>StorePort` | application 패키지 | `*WritePort`(옛 onboarding fixture, 지움) | +| aggregate가 아니라 projection을 돌려주는 읽기 모델 | `<Thing>QueryPort` | application 패키지. projection만 돌려준다(ArchUnit) | — | +| 그 밖의 outbound 포트 | `<Capability>Port` | application 패키지 | — | +| 서버가 정하는 id 생성 | `<Aggregate>IdFactory extends IdFactory<<Aggregate>Id>` | domain 패키지. id record는 `implements ResourceId<Self>` | `OutboxEventIdFactory`(샘플. event id는 resource id가 아니다) | +| 설정 바인딩 | `*Settings`(운영) 또는 `*Policy`(인가·도메인 정책), ArchUnit이 강제 | 그것을 바인딩하는 leaf | — | +| Throwable | `*Exception`, ArchUnit이 강제 | — | — | +| 포트의 계약 시험 키트 | 포트 소유자의 testFixtures에 둔 추상 `<Port>Contract`. fake의 시험과 각 어댑터의 시험이 상속한다 | testFixtures | 값 타입 시험의 이름이 한때 `*ContractTest`였다. 지금은 `*ValueTypesTest`다 | -The one-line rule for stores: **if the domain would recognise the thing it stores, it is a -`Repository` in the domain; if it is plumbing the application needs, it is a `StorePort` in the -application.** +저장소의 한 줄 규칙: **도메인이 알아볼 만한 것을 저장하면 도메인의 `Repository`다. 애플리케이션에 +필요한 배관이면 application의 `StorePort`다.** -## Package ownership +## 패키지 소유 (Package ownership) -This section is the rule book for **which packages the template owns** and where a business feature -goes. `docs/manual/03-placement.md` points here. +이 절은 **템플릿이 어떤 패키지를 가지는지**와 업무 기능이 어디로 가는지의 정본이다. +`docs/manual/03-placement.md`가 이곳을 가리킨다. -- A business feature is `dev.caskeleton.application.<feature>` (and `dev.caskeleton.domain.<feature>`, - `...adapter.inbound.web.<feature>`, `...bootstrap.autoconfigure.<feature>`): one package per feature - directly under each root, no `command`/`usecase`/`port` sub-packages. -- `<feature>` is **not** one of the template package names below. A feature beside a template - package of the same name lands in the same package tree, and every upstream template update merges - into it. -- Template packages never import a feature package. Business code does not go into a template - package, even when the name fits. -- Everything under the two roots that is not listed here is a feature. A derived service adds - features without editing this list; the template edits it when it adds, renames or removes one of - its own packages. +- 업무 기능은 `dev.caskeleton.application.<feature>`다(그리고 `dev.caskeleton.domain.<feature>`, + `...adapter.inbound.web.<feature>`, `...bootstrap.autoconfigure.<feature>`). 루트마다 바로 아래에 + 기능 하나당 패키지 하나를 두고, `command`·`usecase`·`port` 하위 패키지를 두지 않는다. +- `<feature>`는 아래 템플릿 패키지 이름 중 하나가 **아니다**. 같은 이름의 템플릿 패키지 옆에 둔 + 기능은 같은 패키지 트리에 들어가고, upstream 템플릿 갱신이 올 때마다 그 기능에 섞여 들어간다. +- 템플릿 패키지는 기능 패키지를 import하지 않는다. 이름이 맞아도 업무 코드를 템플릿 패키지에 넣지 + 않는다. +- 두 루트 아래에서 여기 적히지 않은 것은 모두 기능이다. 파생 서비스는 이 목록을 고치지 않고 기능을 + 더한다. 템플릿은 자기 패키지를 더하거나, 이름을 바꾸거나, 지울 때 이 목록을 고친다. -| Package (`dev.caskeleton.application.*`) | Owning leaf | Holds | +| 패키지 (`dev.caskeleton.application.*`) | 소유 leaf | 담는 것 | |---|---|---| -| `usecase`, `command`, `query` | application-core | inbound port base types and the command/query markers | -| `capability` | application-core | `@UseCaseCapability` and its enums | -| `transaction` | application-core | `TransactionPort` and its modes | -| `security` | application-core | authorization port, `@RequiresPermission`, `@SystemInvoked`, `@SystemCaller`, `ObjectAccessPolicy` | +| `usecase`, `command`, `query` | application-core | inbound 포트 기반 타입과 command·query 표지 | +| `capability` | application-core | `@UseCaseCapability`와 그 enum | +| `transaction` | application-core | `TransactionPort`와 그 모드 | +| `security` | application-core | 인가 포트, `@RequiresPermission`, `@SystemInvoked`, `@SystemCaller`, `ObjectAccessPolicy` | | `tenant` | application-core | `TenantId` | | `observability` | application-core | `CorrelationIdPort`, `UserPrincipalPseudonymizerPort` | | `secret` | application-core | `SecretSourcePort`, `SecretReference` | -| `messaging` | application-core | the integration-event semantic contract | -| `outbox` | application-core | transactional outbox append and relay | -| `idempotency` | application-core | keyed idempotency executor and store port | -| `operation` | application-core | durable (long-running) operations | -| `lease`, `lock` | application-core | distributed lease and lock ports | -| `cache` | application-core | cache region port | -| `realtime` | application-core | live event replay port | -| `notification` | application-notification | notification capability | -| `fileserver` | application-fileserver | file server capability | -| `objectstorage` | application-objectstorage | object storage capability (its `content.CallBudget` is the call deadline it carries) | +| `messaging` | application-core | integration event semantic contract | +| `outbox` | application-core | 트랜잭션 outbox append와 relay | +| `idempotency` | application-core | 키 기반 멱등성 executor와 store 포트 | +| `operation` | application-core | durable(오래 걸리는) operation | +| `lease`, `lock` | application-core | 분산 lease·lock 포트 | +| `cache` | application-core | cache region 포트 | +| `realtime` | application-core | live event 재생 포트 | +| `notification` | application-notification | 알림 capability | +| `fileserver` | application-fileserver | 파일 서버 capability | +| `objectstorage` | application-objectstorage | 오브젝트 스토리지 capability(`content.CallBudget`은 그것이 싣는 호출 기한이다) | -| Package (`dev.caskeleton.domain.*`) | Owning leaf | Holds | +| 패키지 (`dev.caskeleton.domain.*`) | 소유 leaf | 담는 것 | |---|---|---| | `identifier` | domain-core | `ResourceId`, `IdFactory` | | `stereotype` | domain-core | `@AggregateRoot`, `@DomainEvent`, `@ValueObject` | -Enforcement: +강제하는 곳: -- `scripts/new-feature.sh` refuses a feature name that is already a package under any of the five - roots, in any leaf — every template package included. -- `NamingConventionTest.FEATURE_PACKAGES_DO_NOT_REUSE_TEMPLATE_PACKAGE_NAMES`: a feature package - under either root does not take a name from these tables. Every feature has a domain package, so a - feature named `operation` is caught at `dev.caskeleton.domain.operation`. -- `NamingConventionTest.TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES`: a feature class written - into a template package keeps the template's name but imports its own domain, and that import is - what fails. -- These tables are the rule book; the machine copy the rules read is `TemplatePackageOwnership` - (app-bootstrap `src/test`, so both the architecture suite and the document-contract lane see it). - `TemplatePackageOwnershipDocumentTest` (document-contract lane, `mainCheck`) fails when the tables - and that class differ in a package name or owning leaf, or when a listed package is not in the - leaf the table names; `TemplatePackageOwnershipRuleTest` (architectureTest) fails when a listed - name exists in no production class. A new template package joins both in the same change. -- Not caught: a new template package that nobody lists. Features are generated into the same leaves - (`scripts/new-feature.sh`), so an unlisted package is indistinguishable from a feature. Listing it - is part of adding it. -- Rejected alternatives: allowing only the listed top-level packages (every derived feature would - have to edit the template's list — a merge conflict per feature), and a separate - `application-platform` leaf for the platform packages (weighed in the 2026-11-01 maturity review: clearer - boundary, but more registry edges than a naming rule needs). +- `scripts/new-feature.sh`는 다섯 루트 중 어디든, 어느 leaf든 이미 패키지로 있는 기능 이름을 + 거절한다. 템플릿 패키지도 모두 여기 걸린다. +- `NamingConventionTest.FEATURE_PACKAGES_DO_NOT_REUSE_TEMPLATE_PACKAGE_NAMES`: 두 루트 아래의 기능 + 패키지는 이 표의 이름을 쓰지 않는다. 기능마다 domain 패키지가 있으므로 `operation`이라는 기능은 + `dev.caskeleton.domain.operation`에서 걸린다. +- `NamingConventionTest.TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES`: 템플릿 패키지 안에 쓴 + 기능 클래스는 템플릿 이름을 지니지만 자기 도메인을 import한다. 실패하는 것은 그 import다. +- 이 표가 정본이다. 규칙이 읽는 기계용 사본은 `TemplatePackageOwnership`이다(app-bootstrap + `src/test`에 있어서 architecture suite와 document-contract lane이 모두 본다). + `TemplatePackageOwnershipDocumentTest`(document-contract lane, `mainCheck`)는 표와 그 클래스의 + 패키지 이름이나 소유 leaf가 다르거나, 표에 적힌 패키지가 표가 말한 leaf에 없으면 실패한다. + `TemplatePackageOwnershipRuleTest`(architectureTest)는 적힌 이름이 운영 클래스 어디에도 없으면 + 실패한다. 새 템플릿 패키지는 같은 변경에서 둘 모두에 들어간다. +- 못 잡는 것: 아무도 적지 않은 새 템플릿 패키지. 기능은 같은 leaf에 생성되므로 + (`scripts/new-feature.sh`) 적히지 않은 패키지는 기능과 구별되지 않는다. 적는 것까지가 패키지를 + 더하는 일이다. +- 버린 대안: 적힌 최상위 패키지만 허용하기(파생 기능마다 템플릿 목록을 고쳐야 한다 — 기능마다 + 병합 충돌이 난다), 플랫폼 패키지용 `application-platform` leaf를 따로 두기(2026-11-01 성숙도 + 리뷰에서 따졌다: 경계는 더 분명하지만, 이름 규칙에 필요한 것보다 registry edge가 많아진다). -## Canonical use case shape +## 정해진 유스케이스 모양 (Canonical use case shape) ```java @RequiresPermission("user:register") @@ -201,145 +194,137 @@ public class RegisterUserUseCase implements CommandUseCase<RegisterUserCommand, } ``` -The class is plain Java. A composition root constructs it with its ports and configuration values; -application-core never self-registers with a DI framework. It is **not final**: a mutating use case -declares `@RequiresPermission`, the web adapter enforces it through a CGLIB proxy, and CGLIB cannot -subclass a final class (`RequiresPermissionProxyabilityTest`). It is registered as a bean for the -same reason — a use case built with `new` is never checked. A use case only the system calls (a -scheduler, a relay, a message consumer) carries `@SystemInvoked(reason = ...)` instead of a -permission and is not a bean: it is a write with no permission check, so no user request may reach -it. Its system caller constructs it — a composition module for a scheduler, a -`@SystemCaller(reason = ...)` message handler in `..adapter.inbound.messaging..`, or a -`@SystemCaller` scheduled job in the service's own `..adapter.inbound.scheduler..` package. Manual -07 「시스템이 부르는 쓰기」 is the canonical list of the three and where each lives. All of it is -enforced — a `@SystemInvoked` bean fails startup, an inbound adapter that depends on one without -being a `@SystemCaller` fails `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, -`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS` keeps the mark (and classes nested in a marked -one) off user transports, `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS` keeps a user transport -from calling a system caller (by its class or by a project interface it implements), and -`SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES` keeps a system caller from being a `Runnable` or any -other type outside the project, which no dependency rule could follow. Paths that name no type (a -bean looked up by name, a function a configuration hands over) are not seen; manual 07 lists them -and what holds them. A composition with `@RequiresPermission` -beans but no enforcing advisor fails startup too (`composition:service-runtime` -`PermissionEnforcementGuard`, both checks). +이 클래스는 평범한 Java다. 조립 루트가 포트와 설정 값을 넣어 만든다. application-core는 DI +프레임워크에 스스로 등록하지 않는다. 클래스는 **final이 아니다**: 상태를 바꾸는 유스케이스는 +`@RequiresPermission`을 선언하고, web 어댑터는 CGLIB proxy로 그것을 강제하는데, CGLIB는 final +클래스를 상속하지 못한다(`RequiresPermissionProxyabilityTest`). 같은 이유로 bean으로 등록한다. +`new`로 만든 유스케이스는 검사를 받지 않는다. 시스템만 부르는 유스케이스(스케줄러, relay, 메시지 +소비자)는 권한 대신 `@SystemInvoked(reason = ...)`를 달고 bean이 아니다. 권한 검사가 없는 쓰기라서 +사용자 요청이 닿으면 안 되기 때문이다. 그 시스템 호출자가 유스케이스를 만든다: 스케줄러는 조립 +모듈, 메시지 핸들러는 `..adapter.inbound.messaging..` 안의 `@SystemCaller(reason = ...)`, 예약 +작업은 서비스 자신의 `..adapter.inbound.scheduler..` 패키지 안의 `@SystemCaller`다. 이 셋과 각각의 +위치는 `docs/manual/07-authorization.md` 「시스템이 부르는 쓰기」가 정본 목록이다. 모두 강제된다: +`@SystemInvoked` bean은 기동에 실패한다. `@SystemCaller`가 아닌 inbound 어댑터가 그 유스케이스에 +의존하면 `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`가 실패한다. +`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`는 그 표지(그리고 표지가 붙은 클래스 안에 든 +클래스)를 사용자 전송 계층에 두지 못하게 한다. `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`는 사용자 +전송 계층이 시스템 호출자를 부르지 못하게 한다(그 클래스로든, 그것이 구현한 프로젝트 인터페이스로든). +`SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`는 시스템 호출자가 `Runnable`이나 프로젝트 밖의 다른 +타입이 되지 못하게 한다. 그런 타입은 어떤 의존 규칙도 따라가지 못한다. 타입 이름이 드러나지 않는 +경로(이름으로 찾는 bean, 설정이 넘겨주는 함수)는 보지 못한다. 매뉴얼 07장이 그 경로와 그것을 막는 +곳을 적는다. `@RequiresPermission` bean이 있는데 강제할 advisor가 없는 조립도 기동에 실패한다 +(`composition:service-runtime`의 `PermissionEnforcementGuard`, 두 검사 모두). -## Allowed transactional shapes +## 허용하는 트랜잭션 모양 (Allowed transactional shapes) -| Use case shape | `transactionMode` | TransactionPort call | When | +| 유스케이스 모양 | `transactionMode` | TransactionPort 호출 | 언제 | |---|---|---|---| -| Write command | `WRITE` | `tx.inWrite(...)` | Default for `CommandUseCase`. | -| Physical-root write command | `WRITE` | `tx.inRootWrite(...)` | Only when orchestration must prove there is no ambient transaction and expose a result after commit. | -| Read-only query | `READ_ONLY` | `tx.inRead(...)` | Default for `QueryUseCase`. | -| Outbox / audit / compensation | `REQUIRES_NEW` | `tx.inNew(...)` | Only when the use case MUST commit independently of the caller. | +| 쓰기 command | `WRITE` | `tx.inWrite(...)` | `CommandUseCase`의 기본. | +| 물리 루트 쓰기 command | `WRITE` | `tx.inRootWrite(...)` | 바깥 트랜잭션이 없음을 증명하고 커밋 뒤에 결과를 내놓아야 하는 조율일 때만. | +| 읽기 전용 query | `READ_ONLY` | `tx.inRead(...)` | `QueryUseCase`의 기본. | +| outbox·감사·보상 | `REQUIRES_NEW` | `tx.inNew(...)` | 유스케이스가 반드시 호출자와 따로 커밋해야 할 때만. | -`NESTED` and `NEVER` propagation are forbidden. -`inRootWrite` MUST reject an actual ambient transaction before invoking its action or -`PlatformTransactionManager`; it MUST NOT emulate root-only behavior with `REQUIRES_NEW`. -Both `inWrite` and `inRootWrite` satisfy the direct boundary fitness rule for a -`WRITE_REPOSITORY + WRITE` use case. READ and REQUIRES_NEW mappings remain exclusive. +`NESTED`와 `NEVER` 전파는 금지다. +`inRootWrite`는 action이나 `PlatformTransactionManager`를 부르기 전에 실제로 열린 바깥 트랜잭션을 +반드시 거절한다. 루트 전용 동작을 `REQUIRES_NEW`로 흉내 내면 안 된다. +`WRITE_REPOSITORY + WRITE` 유스케이스의 직접 경계 적합성 규칙은 `inWrite`와 `inRootWrite`가 모두 +만족한다. READ와 REQUIRES_NEW의 대응은 계속 서로 배타적이다. -### Callback signature contract +### 콜백 시그니처 계약 -`TransactionPort` callbacks are `Supplier<T>` / `Runnable` and cannot throw checked -exceptions. This matches Spring's `TransactionCallback<T>` constraint. Wrap domain -checked exceptions into `RuntimeException` subclasses -(`DomainException extends RuntimeException`); `IOException` → `UncheckedIOException`; -`SQLException` is auto-translated by Spring's `DataAccessException` hierarchy. +`TransactionPort` 콜백은 `Supplier<T>` / `Runnable`이라 checked 예외를 던지지 못한다. Spring +`TransactionCallback<T>`의 제약과 같다. 도메인의 checked 예외는 `RuntimeException` 하위 클래스로 +감싼다(`DomainException extends RuntimeException`). `IOException`은 `UncheckedIOException`으로 +감싼다. `SQLException`은 Spring의 `DataAccessException` 계층이 자동으로 번역한다. -### `inNew` pool-sizing constraint +### `inNew` 풀 크기 제약 -`inNew` acquires a new physical JDBC connection. Pool size MUST satisfy: +`inNew`는 새 물리 JDBC 연결을 얻는다. 풀 크기는 반드시 다음을 만족한다. ``` hikari.maximumPoolSize >= (concurrent_threads × (1 + max_inNew_depth)) + 1 ``` -**Forbidden**: calling `tx.inNew(...)` inside a loop over many records — pool -exhaustion + deadlock risk. Batch records inside ONE `inNew` call, or move the -loop outside the transaction boundary. +**금지**: 많은 레코드를 도는 반복문 안에서 `tx.inNew(...)`를 부른다 — 풀이 바닥나고 교착이 생길 +수 있다. 레코드를 `inNew` 호출 **하나** 안에서 묶어 처리하거나, 반복문을 트랜잭션 경계 밖으로 뺀다. -## Idempotency (KEYED) — feature-rate-limit-idempotency-contract +## 멱등성 (KEYED) — feature-rate-limit-idempotency-contract -`@UseCaseCapability(idempotency = Idempotency.KEYED)` is **supported**. A KEYED use case wraps -its work with `dev.caskeleton.application.idempotency.IdempotencyExecutor` — the one owner-safe -generation; the V1 `IdempotencyScope`/`tryBegin` API is gone. +`@UseCaseCapability(idempotency = Idempotency.KEYED)`는 **지원한다**. KEYED 유스케이스는 자기 일을 +`dev.caskeleton.application.idempotency.IdempotencyExecutor`로 감싼다. 소유자를 안전하게 지키는 +유일한 세대다. V1 `IdempotencyScope`/`tryBegin` API는 없어졌다. -- **Scope**: the caller passes an `IdempotencyScopeDigest` — a versioned HMAC of - principal + client key + operation code, computed before the executor sees it. The raw - `Idempotency-Key` never reaches this layer or the store. -- **Store**: `IdempotencyStorePort`, contributed by exactly one provider selected with - `app.capabilities.idempotency.provider` (`redis` → `cache-redis`, `postgresql` → - `persistence-jpa`; default `disabled`). In-memory prod storage is forbidden. -- **Executor**: built once by `composition:idempotency` `IdempotencyAutoConfiguration` from - `IdempotencySettings` (processing lease 30s, replay TTL `APP_IDEMPOTENCY_TTL` 24h ≤72h and not - shorter than the lease, failure retention 24h and not shorter than the replay TTL). Do not - construct it in a use case or a service's own config. -- The action returns `IdempotentAction.Outcome` (`Success` / `RetryableNoEffect` / - `EffectUnknown`); a thrown exception counts as effect-unknown. In progress → 409 - `IDEMPOTENT_IN_FLIGHT`, fingerprint mismatch (SHA-256) → 422 `IDEMPOTENT_REQUEST_MISMATCH`; - `IdempotencyUnavailableException` and `IdempotencyRecoveryRequiredException` mean the store - could not prove the outcome, so do not blindly retry. -- Every store answers an execution whose processing lease ran out with `RecoveryRequired` and never - takes it over; only a claim that never started or a retryable failure is taken over. The answer - leaves the record to its holder: the holder's first late `complete`/`markFailed` is recorded, a - lease that ran out is not renewed and a claim whose lease ran out is not started — both answer - `LEASE_EXPIRED`, not `NOT_OWNER`, and the executor turns a refused start into "not applied" - (owner decision 2026-11-04). A record lives for the lease plus the replay TTL. `IdempotencyStoreContract` holds Redis and PostgreSQL to both on - real servers; the in-memory fake models no time, so it runs only the contract's time-free cases. -- Every transition names the operation its record was claimed under (`IdempotencyOwner.claimOperationId()`). - Another one is `OPERATION_CONFLICT` in every store and changes nothing; so is an inspection that - brings the owner token under another operation (owner decision 2026-11-06). -- A transition already applied is confirmed ("already …") only to the handle it was applied from — - the record one revision past it, moved there by that kind of transition. Any other handle is - `NOT_OWNER`, the same attempt's handle from before a takeover included, and so is a start through - the handle a renewal was applied from; a start through a released handle is `ABSENT` or - `NOT_OWNER` by whether the store keeps the released record (owner decision 2026-11-06, +- **범위(scope)**: 호출자가 `IdempotencyScopeDigest`를 넘긴다. principal + client key + operation + code의 버전 있는 HMAC이고, executor가 받기 전에 계산한다. 원본 `Idempotency-Key`는 이 계층에도 + store에도 닿지 않는다. +- **store**: `IdempotencyStorePort`. `app.capabilities.idempotency.provider`로 고른 provider 정확히 + 하나가 내놓는다(`redis` → `cache-redis`, `postgresql` → `persistence-jpa`, 기본값 `disabled`). + 운영에서 메모리 저장소는 금지다. +- **executor**: `composition:idempotency`의 `IdempotencyAutoConfiguration`이 `IdempotencySettings`로 + 한 번 만든다(처리 lease 30s, 재생 TTL `APP_IDEMPOTENCY_TTL` 24h ≤72h이고 lease보다 짧지 않다, 실패 + 보존 24h이고 재생 TTL보다 짧지 않다). 유스케이스나 서비스 자신의 설정에서 만들지 않는다. +- action은 `IdempotentAction.Outcome`(`Success` / `RetryableNoEffect` / `EffectUnknown`)을 + 돌려준다. 던진 예외는 효과를 모름(effect-unknown)으로 센다. 처리 중이면 409 + `IDEMPOTENT_IN_FLIGHT`, fingerprint(SHA-256)가 다르면 422 `IDEMPOTENT_REQUEST_MISMATCH`다. + `IdempotencyUnavailableException`과 `IdempotencyRecoveryRequiredException`은 store가 결과를 + 증명하지 못했다는 뜻이니 무턱대고 다시 시도하지 않는다. +- 모든 store는 처리 lease가 끝난 실행에 `RecoveryRequired`로 답하고 그 실행을 넘겨받지 않는다. + 넘겨받는 것은 시작하지 않은 claim이나 다시 시도할 수 있는 실패뿐이다. 이 답은 레코드를 가진 + 쪽에게 남긴다: 가진 쪽이 늦게 보낸 첫 `complete`/`markFailed`는 기록한다. lease가 끝난 것은 + 갱신하지 않고, lease가 끝난 claim은 시작하지 않는다. 둘 다 `NOT_OWNER`가 아니라 `LEASE_EXPIRED`로 + 답하고, executor는 거절된 시작을 「적용 안 됨」으로 바꾼다(소유자 결정 2026-11-04). 레코드는 + lease에 재생 TTL을 더한 만큼 산다. `IdempotencyStoreContract`가 Redis와 PostgreSQL을 실제 서버에서 + 둘 모두에 맞춘다. 메모리 fake는 시간을 모델링하지 않으니 계약 중 시간이 없는 경우만 돈다. +- 모든 전이는 그 레코드를 claim한 operation을 이름으로 댄다(`IdempotencyOwner.claimOperationId()`). + 다른 operation이면 모든 store에서 `OPERATION_CONFLICT`이고 아무것도 바꾸지 않는다. owner token을 + 다른 operation으로 가져온 조회도 같다(소유자 결정 2026-11-06). +- 이미 적용된 전이는 그것을 적용한 handle에게만 「already …」로 확인해 준다. 그 handle은 그 전이로 + 옮겨 간, 한 revision 뒤의 레코드다. 다른 handle은 모두 `NOT_OWNER`다. 넘겨받기 전의 같은 시도의 + handle도, 갱신을 적용한 handle로 하는 시작도 그렇다. 놓아준 handle로 하는 시작은 store가 놓아준 + 레코드를 남기느냐에 따라 `ABSENT`나 `NOT_OWNER`다(소유자 결정 2026-11-06, `IdempotencyStoreContract`). -- The applying handle resending `markFailed` with another disposition is `OPERATION_CONFLICT` and - the recorded failure stays; with only another retention it is `ALREADY_MARKED_SAME_OPERATION` and - the first retention stays — retention, like a completion's replay TTL, is not compared (owner - decision 2026-11-07). +- 적용한 handle이 다른 disposition으로 `markFailed`를 다시 보내면 `OPERATION_CONFLICT`이고 기록된 + 실패가 남는다. retention만 다르면 `ALREADY_MARKED_SAME_OPERATION`이고 처음 retention이 남는다 — + retention은 완료의 재생 TTL처럼 비교하지 않는다(소유자 결정 2026-11-07). -The former ArchUnit freeze rule `inbound_port_implementations_do_not_declare_keyed_idempotency` -and its fixture were removed when this branch merged. +예전 ArchUnit 동결 규칙 `inbound_port_implementations_do_not_declare_keyed_idempotency`와 그 fixture는 +이 브랜치가 병합될 때 지웠다. -## Read / query path (feature-application-query-bypass-contract) +## 읽기·query 경로 (feature-application-query-bypass-contract) -The read side has two equally-valid shapes; pick per read, do not force one: +읽기 쪽에는 똑같이 유효한 모양이 둘 있다. 읽기마다 고르고, 하나를 강요하지 않는다. -| Shape | Returns | When | How | +| 모양 | 돌려주는 것 | 언제 | 어떻게 | |---|---|---|---| -| **Through-aggregate** (default for simple reads) | domain aggregate via a `*Repository` port | read shape == write aggregate **and** the aggregate is the minimal invariant boundary (no lazy collections needed) | `QueryUseCase` → repository port → `Order` | -| **Projection (CQRS-lite)** | application-layer projection DTO via a `*QueryPort` | read shape ≠ write, or to skip aggregate hydration / lazy-collection joins | `QueryUseCase` → `*QueryPort` → `OrderSummary` (record); query via JPQL `SELECT new` / JdbcTemplate | +| **aggregate를 거쳐서**(단순 읽기의 기본) | `*Repository` 포트로 받은 도메인 aggregate | 읽기 모양 == 쓰기 aggregate **이고** aggregate가 최소 불변식 경계일 때(지연 컬렉션이 필요 없음) | `QueryUseCase` → repository 포트 → `Order` | +| **projection (CQRS-lite)** | `*QueryPort`로 받은 애플리케이션 계층 projection DTO | 읽기 모양 ≠ 쓰기, 또는 aggregate 수화·지연 컬렉션 join을 건너뛰려 할 때 | `QueryUseCase` → `*QueryPort` → `OrderSummary`(record). query는 JPQL `SELECT new` / JdbcTemplate | -- **Purity guardrail (core, machine-enforced):** a read port whose simple name ends - with `QueryPort` MUST return application-layer projection DTOs only — never a domain - aggregate, JPA entity, or web type, **including through generic type arguments** - (`List<DomainType>`). Enforced by ArchUnit `query_ports_do_not_leak_domain_jpa_or_web_types`. - Projection usage itself is **opt-in**, not a forced default. -- **Strict ceremony:** every read goes through a `QueryUseCase` bean. There is no thin - web→read-port path — that would bypass the mandatory `@UseCaseCapability` fitness function. -- **Transaction:** reads default to `TransactionPort.inRead`. A no-tx (autocommit) read - is an opt-in only when `spring.jpa.open-in-view=false` is confirmed **and** the read is - projection-only (no lazy access) **and** a single statement; otherwise keep `inRead`. -- **Capability:** a repository-backed projection read is still - `repositoryAccess = READ_REPOSITORY`. "Projection vs aggregate" is the return *shape* axis, - orthogonal to the repository-access *level* axis — no new enum. Outbound-HTTP reads (no - repository) stay `RepositoryAccess.NONE`. -- Full CQRS with a separate physical read store is out of scope — escalation only. +- **순수성 가드레일(core, 기계로 강제):** 단순 이름이 `QueryPort`로 끝나는 읽기 포트는 반드시 + 애플리케이션 계층 projection DTO만 돌려준다 — 도메인 aggregate, JPA 엔티티, web 타입은 **제네릭 + 타입 인자를 거쳐서도**(`List<DomainType>`) 안 된다. ArchUnit + `QUERY_PORTS_DO_NOT_LEAK_DOMAIN_JPA_OR_WEB_TYPES`가 강제한다. projection 사용 자체는 강요된 기본이 + 아니라 **선택**이다. +- **엄격한 절차:** 모든 읽기는 `QueryUseCase` bean을 거친다. web → 읽기 포트로 바로 가는 얇은 + 경로는 없다. 그런 경로는 필수인 `@UseCaseCapability` 적합성 검사를 건너뛴다. +- **트랜잭션:** 읽기의 기본은 `TransactionPort.inRead`다. 트랜잭션 없는(autocommit) 읽기는 + `spring.jpa.open-in-view=false`가 확인됐고 **그리고** 읽기가 projection만 쓰고(지연 접근 없음) + **그리고** 문장 하나일 때만 고를 수 있다. 아니면 `inRead`를 쓴다. +- **capability:** repository를 쓰는 projection 읽기도 `repositoryAccess = READ_REPOSITORY`다. + 「projection이냐 aggregate냐」는 돌려주는 *모양* 축이고, repository 접근 *수준* 축과 따로다 — 새 + enum이 없다. outbound HTTP 읽기(repository 없음)는 `RepositoryAccess.NONE`이다. +- 물리적으로 따로 둔 읽기 저장소를 쓰는 완전한 CQRS는 범위 밖이다. 올려서 정할 일이다. -## ArchUnit guardrails (enforced) +## ArchUnit 가드레일(강제됨) -- `application_does_not_depend_on_adapters_or_transport` -- `application_does_not_use_spring_transactional_annotation` -- `application_does_not_depend_on_application_context` +- `APPLICATION_DOES_NOT_DEPEND_ON_ADAPTERS_OR_TRANSPORT` +- `APPLICATION_DOES_NOT_USE_SPRING_TRANSACTIONAL_ANNOTATION` +- `APPLICATION_DOES_NOT_DEPEND_ON_APPLICATION_CONTEXT` - `APPLICATION_HAS_NO_DIAGNOSTIC_FRAMEWORK` -- `inbound_port_implementations_end_with_use_case` -- `inbound_port_implementations_declare_capability` -- `query_ports_do_not_leak_domain_jpa_or_web_types` (`*QueryPort` return purity) +- `INBOUND_PORT_IMPLEMENTATIONS_END_WITH_USE_CASE` +- `INBOUND_PORT_IMPLEMENTATIONS_DECLARE_CAPABILITY` +- `QUERY_PORTS_DO_NOT_LEAK_DOMAIN_JPA_OR_WEB_TYPES`(`*QueryPort` 반환 순수성) -## Test +## 테스트 ```bash cd src @@ -347,5 +332,5 @@ cd src ./gradlew :app-bootstrap:architectureTest ``` -The messaging types above establish semantic contract R1 only. They do not claim JSON Schema -qualification, Kafka publication, durable outbox persistence or any messaging R2 capability. +위 메시징 타입은 semantic contract R1까지만 세운다. JSON Schema 검증, Kafka 발행, durable outbox +영속, 그 밖의 메시징 R2 capability를 주장하지 않는다. diff --git a/src/application-core/README.md b/src/application-core/README.md index cce525f4..026f6593 100644 --- a/src/application-core/README.md +++ b/src/application-core/README.md @@ -117,10 +117,10 @@ JSON Schema diff로 호환성을 검사하는 fixture: payload schema가 닫혀 - 외부 `*Port`(outbound adapter 에 바인딩된 포트)를 호출하려면 `externalOutboundAllowed = true` 가 필요하다. 없으면 outbound 어댑터 호출 금지. - `repositoryAccess` 가 `WRITE_REPOSITORY` 가 아닌 유스케이스는 리포지토리 포트의 쓰기 - 메서드(save/delete/update/insert)를 호출할 수 없다 — `read_only_use_cases_do_not_call_repository_write_methods` + 메서드(save/delete/update/insert)를 호출할 수 없다 — `READ_ONLY_USE_CASES_DO_NOT_CALL_REPOSITORY_WRITE_METHODS` 규칙이 막는다. 단 정적 분석은 **직접 호출만** 잡으므로, helper/mapper 를 거친 쓰기는 리뷰가 본다. - `bulkWrite = true` 는 `WRITE_REPOSITORY` 를 함께 요구한다(대량 쓰기도 결국 쓰기). - `bulk_write_capability_requires_write_repository_access` 가 강제. + `BULK_WRITE_CAPABILITY_REQUIRES_WRITE_REPOSITORY_ACCESS` 가 강제. - 이 애너테이션은 `docs/registries/capabilities.yaml` 의 7개 capability 를 코드로 구현한 것이며, **코드가 SSOT** 다. 추가 플래그의 의미: - `sensitiveRead` — PII/자격증명/비밀을 읽는 유스케이스 선언. 필드 단위 마커(엔티티 FQN + diff --git a/src/build-logic/README.md b/src/build-logic/README.md index 279ff8c3..cd9fe39b 100644 --- a/src/build-logic/README.md +++ b/src/build-logic/README.md @@ -1,69 +1,67 @@ # build-logic -The included build that holds this repository's Gradle conventions: the architecture core, the -conventions every leaf applies, and one test-lane mechanism. A check that is about one capability -(notification, Mongo, messaging, GraphQL, JPA) is not here — it is a test in the leaf that owns the -capability, and the files it reads are declared as that test task's inputs. +이 저장소의 Gradle 규약을 담은 included build다: 아키텍처 핵심, 모든 leaf가 적용하는 규약, 시험 lane +장치 하나. capability 하나에 대한 검사(알림, Mongo, 메시징, GraphQL, JPA)는 여기 없다 — 그것은 그 +capability를 가진 leaf의 시험이고, 그 시험이 읽는 파일은 그 시험 태스크의 입력으로 선언한다. -## What is here +## 여기 있는 것 -| Plugin | Owns | +| 플러그인 | 가지는 것 | | --- | --- | -| `ca.architecture-registry` (settings) | project inclusion, directory mapping, and the parsed registry every other reader shares | -| `ca.architecture` | `verifyCleanArchitectureDependencies` (per-module direction), `verifyApplicationCoreDependencyPurity` (domain-core, shared-contract, application-*), `verifyNoIgnoredSourcePackages`, `architectureCheck` | -| `ca.java-conventions` | Java toolchain/compiler baseline, dependency locking, the Mockito test agent, the per-leaf `mainCheck` lifecycle, the leaf version (release version only) and `sourceRevision` (`JavaConventionsPlugin.sourceRevision`, also what the root `verifyReleaseProvenance` checks) | -| `ca.quality-conventions` | Spotless, Checkstyle, Error Prone, SpotBugs/FindSecBugs wiring shared by Java leaves | -| `ca.java-library` / `ca.spring-library` / `ca.spring-config` | leaf-level composition of the Java/quality conventions for plain and Spring libraries | -| `ca.platform-module` / `ca.grpc-platform-module` | what a vendored platform leaf (`messaging:*`, `grpc:*`, `grpc-advanced:*`) is: `java-library`, plus the gRPC BOM for the leaves that had it | -| `ca.strict-test-lane` | the one "named tests ran, none skipped" mechanism: tagged / named / own-source-set `Test` lanes that fail when they execute nothing, miss a `requires` class, or (with `rejectSkipped`) skip anything. A `performance()` lane always rejects skips and runs with `performance.assertions.enabled=true`; a build (`-P`, `GRADLE_OPTS`) or lane that sets another value fails it before a test runs. `mainStage()` moves a tagged lane out of `test` into the leaf's `mainCheck`; `explicitOnly(reason)` keeps a lane that needs an outside input out of every aggregate, and the aggregate prints the reason. Extra test source sets are Gradle `jvm-test-suite` suites declared in the leaf (`testing { suites { … } }`); a lane named after its suite makes the suite's own `Test` task strict, and `ca.java-conventions` gives every suite the BOM's JUnit | -| `ca.strict-lane-stages` (root of each build with strict lanes: the main build and optional-platforms) | the other half of the lane mechanism: `verifyStrictLaneStages --dry-run` fails when a strict lane of that build that is not `explicitOnly` is in the task plan of no declared stage that a workflow executes, or when a declared stage is executed by no workflow. The workflows are read together (`WorkflowGradleInvocations.readAll`, so a reusable workflow is judged by its callers) and their `run:` scripts parsed as bash (`ShellScript`: quotes, comments, heredoc bodies, substitutions and compound commands are read as the shell reads them, so a `cd` in a heredoc or a string is data). A command does not count when Gradle runs no task with it — `--dry-run`/`-m` (also in a bundle such as `-qm`), `-v`/`--version`, `-h`/`-?`/`--help`, `--status`, `--stop`, `--foreground` (also in a bundle such as `-qv`) — or rejects it: a short-option bundle whose later letter takes a value (`-mx`: only the first letter of a bundle takes one), or a value given to an option that takes none (`-m=yes`). The reader follows Gradle 9.0's parser. `GradleCommandLineTest` holds its option tables to the `--help` of the Gradle that runs build-logic — an upgrade that adds an option, as 9.2 adds `--task-graph`, fails until the option is placed — and runs the launcher with each no-task option but `--stop` and `--foreground` (both return a daemon action, not a build, in Gradle's `BuildActionsFactory`); which options take a value was probed against 9.0.0 in round 9 and is not re-run. Nor does a command for another build count (the build a command starts is its step's `working-directory`, or the job's or workflow's `defaults.run.working-directory`, moved by each `cd <literal relative path>` the same `run:` shell surely ran before it — alone in its list, or before the command in the same `&&` list — then joined with `-p`; the plugin reads this build's own directory from where it sits under the repository that holds `.github/workflows`). Every other command that does not count gives one of three reasons. **Its failure may not fail its step**: `\|\| true`, `\|\| :` or any `\|\|` but `\|\| exit <non-zero>`, a pipe's left side without `pipefail` (on with `shell: bash` or a top-level `set -o pipefail`), `!`, `&`, an `if`/`while` condition, the part before `&&` of a list that is not the script's last command, after `set +e`, after a `trap` whose `EXIT` or `ERR` action may `exit` with status 0 (a bare `exit` keeps the status in an `EXIT` trap, not in an `ERR` one), and `continue-on-error`. **It may not run**: after `\|\|`, after `&&` in a list that is not the script's last command, inside `if`/`while`/`for`/`case` or a function body, after a top-level `exit`, `exec <command>` or `set -n`, after one elsewhere — in a compound command, an and-or list or a function the script calls — that may end the script with status 0 (`exit 0`, a bare `exit` other than right after `\|\|`, `exit "$code"`), replace it or stop it running commands (`set -o noexec`), under an `if:` other than `always()`/`success()`/`!cancelled()`, in a workflow that starts only on events someone or something asks for (`workflow_dispatch`, `repository_dispatch`, `issue_comment`, a pull request with `types: [labeled]`, `workflow_run`, …; `push`, `pull_request`, `pull_request_target`, `merge_group`, `schedule` and `release` count), in a workflow whose change-flow triggers all carry a `paths` or `paths-ignore` filter (a change outside those paths does not start it; owner decision 2026-11-06), for any stage but `:releaseCheck` in a workflow that starts without a request or a path filter only on the release flow — `release`, or a `push` with `tags`/`tags-ignore` and no `branches`/`branches-ignore`, which a branch push does not start (owner decision 2026-11-07; `:releaseCheck` is the tag-only stage) — in a reusable (`workflow_call`-only) workflow that no counted job calls with `uses: ./.github/workflows/<file>`, and in a job that `needs`, directly or through other jobs, a job with such an `if:` or with `continue-on-error`, unless its own `if:` is `always()` or `!cancelled()`. **This check does not read it**, although its failure would fail the step (a false failure on purpose): `\|\| exit 1`, `\|\| { …; exit 1; }`, inside `{ }` or `( )`, `$( )`, `bash -c`, `gradlew` as another command's argument (`timeout 60 ./gradlew`), after a directory change the reader does not follow (`cd "$VAR"`, `cd -`, `cd ~`, an absolute path, `pushd`/`popd`, `builtin cd`, `eval`/`source`, a `cd` anywhere inside a compound command or a function body, one joined with `\|\|`, piped or in the background, and the lines after a `cd` that shares an `&&` list with other commands — not guessed), a step whose `shell:` is not `bash` or `sh`, and a step with no `shell:` in a job whose `runs-on` may be a Windows runner, whose default shell is `pwsh` (a Windows label, an expression such as `${{ matrix.os }}`, a self-hosted label set without `linux` or `macos`; Linux and macOS runners default to `bash -e` and a `container:` job to `sh -e`, which are read alike). An `exit` that fails the step — `exit 1`, or `cmd \|\| exit` — and one in an uncalled function, a `( )` subshell or `$( )` stop nothing after them from counting. The failure names every command that names the stage but does not execute it, with its reason or the other build it starts, and says to run the stage as `./gradlew` on a line of its own. A lane the command removes with `-x` is not covered — matched the way Gradle matches task and project names, abbreviations included (`TaskSelectors`, a copy of Gradle's internal `NameMatcher`). A `run:` input of a `uses:` step is not a command. The plan is Gradle's own; the workflows are read for their `run:` steps with YAML folding applied (review 2026-11-01 08-01, 2026-11-03 RR-06-03/04, 2026-11-04 RR2-04-04, owner decision 2026-11-04 on `cd`, RR5-02-01/02/03 in round 9, 2026-11-05 RR6-04-01..06, 2026-11-06 RR7-05-01, owner decision 2026-11-07 on the release flow) | -| `ca.redis-topology-lane` | the Redis topology lane (mode selection, `-P` property validation, per-mode required classes) the redis-sdk-topology workflow drives | -| `ca.api-surface` | read-only public API surface verification with a separate update task, wired into the leaf's `check` (owner decision 20); optionally holds other leaves' imports to a reviewed adopter subset (`adopterBaseline`) | -| `ca.config-contract` | app-bootstrap's `verifyEnvKeys` (moved from the deleted build-tools included build; owner decision 4 keeps the task in app-bootstrap) | -| `ca.bootrun-dotenv` | `bootRun`'s `.env` | +| `ca.architecture-registry` (settings) | 프로젝트 포함, 디렉터리 대응, 다른 모든 읽는 쪽이 같이 쓰는 파싱된 registry | +| `ca.architecture` | `verifyCleanArchitectureDependencies`(모듈별 방향), `verifyApplicationCoreDependencyPurity`(domain-core, shared-contract, application-*), `verifyNoIgnoredSourcePackages`, `architectureCheck` | +| `ca.java-conventions` | Java toolchain·컴파일러 기준, 의존성 잠금, Mockito 시험 agent, leaf별 `mainCheck` lifecycle, leaf 버전(릴리스 버전만)과 `sourceRevision`(`JavaConventionsPlugin.sourceRevision`. 루트 `verifyReleaseProvenance`가 검사하는 것도 이것이다) | +| `ca.quality-conventions` | Java leaf가 같이 쓰는 Spotless, Checkstyle, Error Prone, SpotBugs·FindSecBugs 배선 | +| `ca.java-library` / `ca.spring-library` / `ca.spring-config` | 평범한 라이브러리와 Spring 라이브러리를 위한 Java·품질 규약의 leaf 단위 조합 | +| `ca.platform-module` / `ca.grpc-platform-module` | 들여온 플랫폼 leaf(`messaging:*`, `grpc:*`, `grpc-advanced:*`)가 무엇인가: `java-library`, 그리고 원래 gRPC BOM을 쓰던 leaf에는 그 BOM | +| `ca.strict-test-lane` | 「이름 댄 시험이 돌았고 건너뛴 것이 없다」를 보는 유일한 장치: tag·이름·자기 source set으로 고른 `Test` lane이 아무것도 실행하지 않거나, `requires` 클래스를 빠뜨리거나, (`rejectSkipped`이면) 무엇이든 건너뛰면 실패한다. `performance()` lane은 언제나 건너뛰기를 거절하고 `performance.assertions.enabled=true`로 돈다. 빌드(`-P`, `GRADLE_OPTS`)나 lane이 다른 값을 넣으면 시험이 돌기 전에 실패한다. `mainStage()`는 tag로 고른 lane을 `test`에서 빼 leaf의 `mainCheck`로 옮긴다. `explicitOnly(reason)`는 바깥 입력이 필요한 lane을 모든 묶음 태스크에서 빼고, 묶음 태스크가 그 이유를 출력한다. 시험 source set을 더 두려면 leaf에 Gradle `jvm-test-suite` suite로 선언한다(`testing { suites { … } }`). suite 이름을 딴 lane은 그 suite 자신의 `Test` 태스크를 엄격하게 만들고, `ca.java-conventions`는 모든 suite에 BOM의 JUnit을 준다 | +| `ca.strict-lane-stages` (strict lane이 있는 각 빌드의 루트: 주 빌드와 optional-platforms) | lane 장치의 나머지 절반: `verifyStrictLaneStages --dry-run`은 그 빌드의 `explicitOnly`가 아닌 strict lane이 workflow가 실행하는 선언된 단계 어느 것의 태스크 계획에도 없거나, 선언된 단계를 실행하는 workflow가 없으면 실패한다. workflow는 함께 읽고(`WorkflowGradleInvocations.readAll`. 그래서 재사용 workflow는 그것을 부르는 쪽으로 판정한다) `run:` 스크립트는 bash로 파싱한다(`ShellScript`: 따옴표, 주석, heredoc 본문, 치환, 복합 명령을 셸이 읽듯 읽는다. 그래서 heredoc이나 문자열 안의 `cd`는 데이터다). Gradle이 태스크를 하나도 돌리지 않는 명령은 세지 않는다 — `--dry-run`/`-m`(`-qm` 같은 묶음 안도), `-v`/`--version`, `-h`/`-?`/`--help`, `--status`, `--stop`, `--foreground`(`-qv` 같은 묶음 안도) — Gradle이 거절하는 명령도 세지 않는다: 뒤 글자가 값을 받는 짧은 옵션 묶음(`-mx`: 묶음에서는 첫 글자만 값을 받는다), 값을 받지 않는 옵션에 준 값(`-m=yes`). 읽는 방식은 Gradle 9.0의 파서를 따른다. `GradleCommandLineTest`는 옵션 표를 build-logic을 돌리는 Gradle의 `--help`와 맞춘다 — 옵션을 더하는 업그레이드는(9.2가 `--task-graph`를 더하듯) 그 옵션을 자리에 넣기 전까지 실패한다 — 그리고 `--stop`과 `--foreground`를 뺀 태스크 없는 옵션마다 launcher를 돌린다(둘은 Gradle `BuildActionsFactory`에서 빌드가 아니라 daemon 동작을 돌려준다). 어떤 옵션이 값을 받는지는 round 9에 9.0.0으로 탐침했고 다시 돌리지 않는다. 다른 빌드를 위한 명령도 세지 않는다(명령이 시작하는 빌드는 그 step의 `working-directory`, 또는 job이나 workflow의 `defaults.run.working-directory`에서 시작해, 같은 `run:` 셸이 그 앞에서 반드시 돌린 `cd <리터럴 상대 경로>`마다 옮기고 — 혼자 있는 목록이거나 같은 `&&` 목록에서 그 명령 앞에 있을 때 — 그다음 `-p`로 이은 곳이다. 플러그인은 이 빌드 자신의 디렉터리를 `.github/workflows`를 가진 저장소 아래 어디에 있는지로 읽는다). 세지 않는 그 밖의 명령은 모두 세 이유 중 하나를 댄다. **실패해도 step이 실패하지 않을 수 있다**: `\|\| true`, `\|\| :`, `\|\| exit <0 아닌 값>`이 아닌 모든 `\|\|`, `pipefail` 없는 pipe의 왼쪽(`shell: bash`나 최상위 `set -o pipefail`이면 켜진다), `!`, `&`, `if`/`while` 조건, 스크립트의 마지막 명령이 아닌 목록에서 `&&` 앞부분, `set +e` 뒤, `EXIT`나 `ERR` 동작이 상태 0으로 `exit`할 수 있는 `trap` 뒤(`EXIT` trap 안의 맨 `exit`는 상태를 지키지만 `ERR` trap 안에서는 아니다), `continue-on-error`. **돌지 않을 수 있다**: `\|\|` 뒤, 스크립트의 마지막 명령이 아닌 목록에서 `&&` 뒤, `if`/`while`/`for`/`case` 안이나 함수 본문 안, 최상위 `exit`·`exec <command>`·`set -n` 뒤, 다른 곳 — 복합 명령, and-or 목록, 스크립트가 부르는 함수 — 에서 스크립트를 상태 0으로 끝낼 수 있는 것(`exit 0`, `\|\|` 바로 뒤가 아닌 맨 `exit`, `exit "$code"`), 스크립트를 바꿔치는 것, 명령 실행을 멈추는 것(`set -o noexec`) 뒤, `always()`/`success()`/`!cancelled()`가 아닌 `if:` 아래, 누가 또는 무엇이 요청해야만 시작하는 이벤트(`workflow_dispatch`, `repository_dispatch`, `issue_comment`, `types: [labeled]`인 pull request, `workflow_run`, …. `push`, `pull_request`, `pull_request_target`, `merge_group`, `schedule`, `release`는 센다)로만 시작하는 workflow 안, 변경 흐름 트리거가 모두 `paths`나 `paths-ignore` 필터를 가진 workflow 안(그 경로 밖의 변경은 workflow를 시작하지 않는다. 소유자 결정 2026-11-06), 요청이나 경로 필터 없이 릴리스 흐름에서만 시작하는 workflow 안의 `:releaseCheck`가 아닌 단계 — 릴리스 흐름은 `release`, 또는 `tags`/`tags-ignore`가 있고 `branches`/`branches-ignore`가 없는 `push`로, 브랜치 push로는 시작하지 않는다(소유자 결정 2026-11-07. `:releaseCheck`가 태그 전용 단계다) — 센 job 어느 것도 `uses: ./.github/workflows/<file>`로 부르지 않는 재사용(`workflow_call`만 있는) workflow 안, 그리고 그런 `if:`나 `continue-on-error`를 가진 job을 직접 또는 다른 job을 거쳐 `needs`하는 job 안(자기 `if:`가 `always()`나 `!cancelled()`이면 예외). **이 검사가 읽지 않는다**(실패하면 step이 실패하지만, 일부러 거짓 실패로 둔다): `\|\| exit 1`, `\|\| { …; exit 1; }`, `{ }`나 `( )` 안, `$( )`, `bash -c`, 다른 명령의 인자인 `gradlew`(`timeout 60 ./gradlew`), 읽는 쪽이 따라가지 않는 디렉터리 이동 뒤(`cd "$VAR"`, `cd -`, `cd ~`, 절대 경로, `pushd`/`popd`, `builtin cd`, `eval`/`source`, 복합 명령이나 함수 본문 안의 `cd`, `\|\|`로 이은 것, pipe나 background로 돌린 것, 다른 명령과 같은 `&&` 목록에 있는 `cd`의 뒤 줄 — 짐작하지 않는다), `shell:`이 `bash`나 `sh`가 아닌 step, `runs-on`이 Windows runner일 수 있는 job에서 `shell:`이 없는 step(기본 셸이 `pwsh`다. Windows label, `${{ matrix.os }}` 같은 표현식, `linux`나 `macos`가 없는 self-hosted label 집합. Linux·macOS runner의 기본은 `bash -e`, `container:` job의 기본은 `sh -e`이고 둘을 같이 읽는다). step을 실패시키는 `exit` — `exit 1`, `cmd \|\| exit` — 와 부르지 않는 함수, `( )` subshell, `$( )` 안의 `exit`는 그 뒤의 명령이 세지는 것을 막지 않는다. 실패 메시지는 단계 이름을 대지만 그 단계를 실행하지 않는 모든 명령을 그 이유나 그것이 시작하는 다른 빌드와 함께 대고, 단계를 혼자 있는 줄의 `./gradlew`로 돌리라고 말한다. 명령이 `-x`로 뺀 lane은 덮인 것이 아니다 — Gradle이 태스크·프로젝트 이름을 맞추는 방식(약어 포함)으로 맞춘다(`TaskSelectors`, Gradle 내부 `NameMatcher`의 사본). `uses:` step의 `run:` 입력은 명령이 아니다. 계획은 Gradle 자신의 것이다. workflow는 YAML folding을 적용해 `run:` step을 읽는다(review 2026-11-01 08-01, 2026-11-03 RR-06-03/04, 2026-11-04 RR2-04-04, `cd`에 대한 소유자 결정 2026-11-04, round 9의 RR5-02-01/02/03, 2026-11-05 RR6-04-01..06, 2026-11-06 RR7-05-01, 릴리스 흐름에 대한 소유자 결정 2026-11-07) | +| `ca.redis-topology-lane` | redis-sdk-topology workflow가 돌리는 Redis topology lane(모드 고르기, `-P` 속성 검증, 모드별 필수 클래스) | +| `ca.api-surface` | 읽기 전용 공개 API surface 검증과 따로 둔 갱신 태스크. leaf의 `check`에 배선한다(소유자 결정 20). 다른 leaf의 import를 리뷰한 adopter 부분집합(`adopterBaseline`)에 묶을 수도 있다 | +| `ca.config-contract` | app-bootstrap의 `verifyEnvKeys`(지운 build-tools included build에서 옮겼다. 소유자 결정 4가 그 태스크를 app-bootstrap에 둔다) | +| `ca.bootrun-dotenv` | `bootRun`의 `.env` | -Plain classes rather than plugins, because settings and projects load plugins through different -mechanisms and more than one caller needs each: +플러그인이 아니라 평범한 클래스로 둔 것. settings와 project는 플러그인을 서로 다른 방식으로 읽어 +들이고, 각각을 부르는 쪽이 둘 이상이기 때문이다: -| Class | Owns | +| 클래스 | 가지는 것 | | --- | --- | -| `dev.caskeleton.buildlogic.ModuleRegistry` | reading and validating `config/architecture/modules.json` | -| `dev.caskeleton.buildlogic.RequiredTestExecution` | the single decision "a test this build names must actually have run" | -| `dev.caskeleton.buildlogic.JavaPublicTypes` | public top-level types, parsed by javac rather than matched with a regular expression | +| `dev.caskeleton.buildlogic.ModuleRegistry` | `config/architecture/modules.json`을 읽고 검증하기 | +| `dev.caskeleton.buildlogic.RequiredTestExecution` | 「이 빌드가 이름을 댄 시험은 실제로 돌았어야 한다」는 단 하나의 판정 | +| `dev.caskeleton.buildlogic.JavaPublicTypes` | 공개 최상위 타입. 정규식으로 맞추지 않고 javac로 파싱한다 | -JMH benchmarks use the community `me.champeau.jmh` plugin; `ca.quality-conventions` only turns -Error Prone, `-Werror`, SpotBugs and Checkstyle off for benchmark and generated code. +JMH benchmark는 커뮤니티 플러그인 `me.champeau.jmh`를 쓴다. `ca.quality-conventions`는 benchmark와 +생성된 코드에서 Error Prone, `-Werror`, SpotBugs, Checkstyle을 끄기만 한다. -## What was removed, and what covers it +## 지운 것과 그것을 대신하는 것 -| Removed | Covered by | +| 지운 것 | 대신하는 것 | | --- | --- | -| `ca.runtime-membership` | the direction gate: nothing outside `allowed_dependencies` can reach a composition root | -| `ca.evidence`, `ca.conditional-transport-qualification`, `ca.strict-qualification` | `strictTestLanes` lanes with `requires` + `rejectSkipped`; the root `conditionalTransportQualification` and `verifyMessagingContracts` only aggregate them | -| `ca.dependency-policy` | a `componentSelection` rejection rule in the leaf (notification: YAML dataformat; messaging: Jackson 2 and any YAML module) and the registry (web-advanced has no allowed consumer). `rejectAll()` constraints were tried and do not fail: Spring's dependency management overrides the rejected version | -| `ca.graphql-platform` | the `graphqlStableTest` lane and `GraphQlProductionClassesTest` in the GraphQL leaf | -| `ca.jpa-test-lanes` | the lanes declared in `adapter/outbound/persistence-jpa/build.gradle` | -| `ca.test-jvm-agents`, `quarantineTest` | `ca.java-conventions`; the quarantine bucket had no tests | +| `ca.runtime-membership` | 방향 게이트: `allowed_dependencies` 밖의 것은 조립 루트에 닿을 수 없다 | +| `ca.evidence`, `ca.conditional-transport-qualification`, `ca.strict-qualification` | `requires` + `rejectSkipped`를 쓴 `strictTestLanes` lane. 루트 `conditionalTransportQualification`과 `verifyMessagingContracts`는 그 lane을 묶기만 한다 | +| `ca.dependency-policy` | leaf 안의 `componentSelection` 거절 규칙(notification: YAML dataformat, messaging: Jackson 2와 모든 YAML 모듈)과 registry(web-advanced는 허용된 소비자가 없다). `rejectAll()` 제약도 써 봤지만 실패하지 않는다: Spring의 의존성 관리가 거절한 버전을 덮어쓴다 | +| `ca.graphql-platform` | GraphQL leaf의 `graphqlStableTest` lane과 `GraphQlProductionClassesTest` | +| `ca.jpa-test-lanes` | `adapter/outbound/persistence-jpa/build.gradle`에 선언한 lane | +| `ca.test-jvm-agents`, `quarantineTest` | `ca.java-conventions`. quarantine 묶음에는 시험이 없었다 | | `ca.jmh-benchmarks` | `me.champeau.jmh` | -| build-tools `ca.jpa-evidence`, `ca.jpa-qualification` (+ `junit` evidence reader) | owner decision 4: persistence-jpa `JpaReadinessRegistryTest`, readiness lanes that require every cited scenario and reject skips, the leaf's `jpaReleaseQualification` aggregate over `config/jpa/release-registry.json` | -| build-tools `ca.config-contract` | moved here unchanged | -| `ca.public-path-snapshot` | app-bootstrap `PublicPathSnapshotTest` (lane `publicPathSnapshotTest`, root alias `verifyPublicPathSnapshot`) | -| `ca.archive-hygiene` | nothing to clean: leaf versions no longer carry the revision, so no stale traceable jar is produced | +| build-tools `ca.jpa-evidence`, `ca.jpa-qualification`(+ `junit` 증거 읽기) | 소유자 결정 4: persistence-jpa `JpaReadinessRegistryTest`, 인용한 시나리오를 모두 요구하고 건너뛰기를 거절하는 readiness lane, `config/jpa/release-registry.json`을 묶는 leaf의 `jpaReleaseQualification` | +| build-tools `ca.config-contract` | 바꾸지 않고 여기로 옮겼다 | +| `ca.public-path-snapshot` | app-bootstrap `PublicPathSnapshotTest`(lane `publicPathSnapshotTest`, 루트 별칭 `verifyPublicPathSnapshot`) | +| `ca.archive-hygiene` | 치울 것이 없다: leaf 버전이 더는 revision을 싣지 않으니 낡은 추적 가능 jar가 생기지 않는다 | | `ca.developer-bootstrap` | `scripts/bootstrap-local.sh` | -| `JpaAdopterApiSurfaceTest` (a regex import scan in persistence-jpa) | `ca.api-surface` `adopterBaseline` | +| `JpaAdopterApiSurfaceTest`(persistence-jpa의 정규식 import 검사) | `ca.api-surface` `adopterBaseline` | -## Testing a convention +## 규약 시험하기 ```bash cd src ./gradlew -p build-logic test --console=plain ``` -The lane and registry conventions are covered by Gradle TestKit against real builds rather than by -reading the plugin source, because the properties that matter — a lane that discovers nothing fails, -a lane reuses a result only when its classes and its lane policy (`rejectSkipped`, `requires`, tag, -category) are unchanged and it starts no server, a malformed registry is refused before any project is included — are -runtime behaviour rather than text in a script. Two of those tests exist because the obvious reading -of the Gradle documentation was wrong: `failOnNoDiscoveredTests` does not fire when a tag filter -matches nothing, and `failOnNoMatchingTests` does not fire when only *some* of the named tests are -missing. +lane과 registry 규약은 플러그인 소스를 읽는 대신 Gradle TestKit으로 실제 빌드에 대고 시험한다. +중요한 성질 — 아무것도 찾지 못한 lane은 실패한다, lane은 클래스와 lane 정책(`rejectSkipped`, +`requires`, tag, category)이 바뀌지 않았고 서버를 띄우지 않을 때만 결과를 다시 쓴다, 잘못된 registry는 +어떤 프로젝트도 포함하기 전에 거절된다 — 이 스크립트의 글이 아니라 런타임 동작이기 때문이다. 그중 +시험 둘은 Gradle 문서를 그대로 읽으면 틀렸기 때문에 있다: tag 필터가 아무것도 맞추지 못할 때 +`failOnNoDiscoveredTests`가 동작하지 않고, 이름을 댄 시험 중 *일부만* 없을 때 +`failOnNoMatchingTests`가 동작하지 않는다. diff --git a/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverDocumentationCoverageTest.java b/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverDocumentationCoverageTest.java index 29af491b..3a5dbf88 100644 --- a/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverDocumentationCoverageTest.java +++ b/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverDocumentationCoverageTest.java @@ -68,13 +68,13 @@ class FileserverDocumentationCoverageTest { List<String> requiredRunbooks = List.of( - "Storage full", - "Orphan growth", - "Verification backlog", - "NFS ambiguity", - "PVC remount", - "Nginx delegation failure", - "Cleanup backlog"); + "## 저장소 가득 참", + "## 고아 객체 증가", + "## 검증 적체", + "## NFS 결과 모름", + "## PVC 다시 마운트", + "## Nginx 위임 실패", + "## 정리 적체"); assertThat(requiredRunbooks).allSatisfy(runbook -> assertThat(operations).contains(runbook)); assertThat(operations) @@ -91,7 +91,7 @@ class FileserverDocumentationCoverageTest { assertThat(matrix) .as("an omitted capability reads as an unstated claim; absence must be explicit") - .contains("Explicitly not claimed") + .contains("## 주장하지 않는 것") .contains("ReadWriteMany"); } @@ -143,8 +143,9 @@ class FileserverDocumentationCoverageTest { * Table keys from the configuration reference, minus the ones already qualified by a section. * * <p>The document writes a bare key inside a per-section table (for example {@code root} under - * "Storage") and a qualified one elsewhere ({@code upload.ttl}); only the qualified form can be - * bound without reconstructing the section context, so the bare ones are read with their heading. + * the {@code storage} heading) and a qualified one elsewhere ({@code upload.ttl}); only the + * qualified form can be bound without reconstructing the section context, so the bare ones are + * read with their heading. */ private static List<String> documentedSettingKeys(Path configuration) throws IOException { List<String> keys = new ArrayList<>(); diff --git a/src/composition/outbox-relay/CLAUDE.md b/src/composition/outbox-relay/CLAUDE.md index f63f9fa9..1f890d5f 100644 --- a/src/composition/outbox-relay/CLAUDE.md +++ b/src/composition/outbox-relay/CLAUDE.md @@ -1,21 +1,19 @@ # composition:outbox-relay -- Module ID `composition-outbox-relay`, Gradle path `:composition:outbox-relay`. Registry SSOT: +- 모듈 ID `composition-outbox-relay`, Gradle 경로 `:composition:outbox-relay`. registry 정본: `src/config/architecture/modules.json`. -- Responsibility: assemble and drive the application's outbox relay. It builds - `PublishPendingOutboxEventsUseCase` by hand from `app.outbox.*` (`OutboxSettings`, strict binding), - runs it from `OutboxRelayScheduler` (fixed-delay ticks, a `SmartLifecycle` that stops above the - messaging platform's admission phase), and owns the outbox metrics (`OutboxMetrics`: gauges on a - thread of their own, the cycle-outcome counter from the relay). -- Boundaries: it names ports only — `OutboxStorePort`, `OutboxMessagePublishPort`, - `OutboxRelayFailureReportPort`, `TransactionPort` — never a module type, so removing the - persistence or messaging line removes the relay. No business rule, no SQL, no broker type. The - relay use case is never a bean (`@SystemInvoked`, no permission gate). Allowed edges come only from - the registry entry. -- Startup refusals live here because only here do the settings meet the ports: a batch whose worst - case (`batch-size` × the publish port's `longestAttempt`) reaches `in-flight-timeout` fails startup. -- Tests: `./gradlew :composition:outbox-relay:check`. The shutdown order is pinned against the - platform's own phase constant (`OutboxRelayShutdownOrderTest`); the end-to-end relay → bridge → real - Kafka path is `:adapter:outbound:messaging-kafka:messagingKafkaRelayIntegrationTest`. -- Design and rejected alternatives: `README.md`. Operations: `docs/runbooks/outbox-publish-failed.md`, +- 책임: 애플리케이션의 outbox relay를 조립하고 돌린다. `app.outbox.*`(`OutboxSettings`, 엄격한 + 바인딩)로 `PublishPendingOutboxEventsUseCase`를 손으로 만들고, `OutboxRelayScheduler`(고정 지연 + tick, 메시징 플랫폼의 admission phase보다 위에서 멈추는 `SmartLifecycle`)에서 돌리며, outbox metric + (`OutboxMetrics`: 자기 스레드에서 도는 gauge, relay가 내는 cycle 결과 counter)을 가진다. +- 경계: 포트만 이름으로 댄다 — `OutboxStorePort`, `OutboxMessagePublishPort`, + `OutboxRelayFailureReportPort`, `TransactionPort`. 모듈 타입은 대지 않으니 persistence나 messaging + 줄을 지우면 relay도 빠진다. 업무 규칙, SQL, broker 타입이 없다. relay 유스케이스는 bean이 아니다 + (`@SystemInvoked`, 권한 검사 없음). 허용 edge는 registry 항목에서만 온다. +- 기동 거절은 여기 있다. 설정과 포트가 만나는 곳이 여기뿐이기 때문이다: 최악의 경우 + (`batch-size` × 발행 포트의 `longestAttempt`)가 `in-flight-timeout`에 닿는 batch는 기동에 실패한다. +- 시험: `./gradlew :composition:outbox-relay:check`. 종료 순서는 플랫폼 자신의 phase 상수에 맞춰 + 고정한다(`OutboxRelayShutdownOrderTest`). relay → bridge → 실제 Kafka로 가는 끝에서 끝까지 경로는 + `:adapter:outbound:messaging-kafka:messagingKafkaRelayIntegrationTest`다. +- 설계와 버린 대안: `README.md`. 운영: `docs/runbooks/outbox-publish-failed.md`, `docs/runbooks/outbox-dead-letter.md`. diff --git a/src/composition/service-runtime/README.md b/src/composition/service-runtime/README.md index 0fcd9479..271b74ba 100644 --- a/src/composition/service-runtime/README.md +++ b/src/composition/service-runtime/README.md @@ -287,6 +287,6 @@ runtimeOnly project(':composition:service-runtime') - **SHAPE-OWNERSHIP(하드 규칙): 이 클래스는 `HealthEndpoint` / `HealthIndicator` / `HealthComponent`를 import·구현·의존해선 안 된다** — health 엔드포인트의 형태(shape)는 runtime-health 브랜치 소유다. 보안 매칭은 오직 엔드포인트 id 문자열로만 하고 health 내부 구조에는 절대 손대지 않는다. ArchUnit - 규칙 `management_security_does_not_depend_on_health_internals`(`CleanArchitectureTest`)가 이를 정적 + 규칙 `MANAGEMENT_SECURITY_DOES_NOT_DEPEND_ON_HEALTH_INTERNALS`(`CleanArchitectureTest`)가 이를 정적 으로 강제한다. diff --git a/src/config/architecture/README.md b/src/config/architecture/README.md index 07a8d32b..b494cad8 100644 --- a/src/config/architecture/README.md +++ b/src/config/architecture/README.md @@ -1,13 +1,14 @@ -# Architecture module registry +# 아키텍처 모듈 registry -`modules.json` records Gradle project identity and the exact production project edges each leaf may -see. An empty `allowed_dependencies` list is meaningful: it means the leaf is intentionally -project-standalone, not that the registry entry is unfinished. +`modules.json`은 Gradle 프로젝트의 정체(id, Gradle 경로, 소스 경로)와 각 leaf가 볼 수 있는 운영 +프로젝트 edge를 정확히 적는다. 빈 `allowed_dependencies` 목록에도 뜻이 있다: 그 leaf가 일부러 다른 +프로젝트에 기대지 않는다는 뜻이지, registry 항목을 덜 채웠다는 뜻이 아니다. -`adapter-outbound-persistence-mongo` is the important example. That leaf owns the Mongo provider -implementation without importing application/domain project types; composition into application -ports is owned by the bootstrap/autoconfiguration side. Its empty dependency list is therefore an -explicit boundary and must remain empty until a real project edge is introduced and reviewed. +`domain-core`, `shared-contract`, 들여온 메시징 제품의 `messaging-core-api`가 그 예다. 빈 목록은 +분명한 경계이고, 실제 프로젝트 edge를 들여와 리뷰하기 전까지 비어 있어야 한다. 반대로 목록에 적힌 +edge는 빌드가 실제로 쓰는 것과 맞아야 한다. 예를 들어 `adapter-outbound-persistence-mongo`의 목록은 +`["application-core", "shared-contract"]`이고 `MongoRegistryPermissionParityTest`가 두 방향을 모두 +본다. -Runtime composition membership is derived from resolved runtime classpaths by the build logic; it is -not duplicated as a per-module field in this registry. +런타임 조립 구성원은 빌드 로직이 해석된 runtime classpath에서 얻는다. 이 registry에 모듈마다 칸으로 +다시 적지 않는다. diff --git a/src/domain-core/CLAUDE.md b/src/domain-core/CLAUDE.md index 7e32ff10..70bf470b 100644 --- a/src/domain-core/CLAUDE.md +++ b/src/domain-core/CLAUDE.md @@ -1,36 +1,36 @@ -# domain-core — pure domain layer +# domain-core — 순수 도메인 계층 -## Registered identity +## 등록 정보 -- Module ID: `domain-core` -- Gradle path: `:domain-core` -- Focused test (derived from Gradle path): `./gradlew :domain-core:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `domain-core` +- Gradle 경로: `:domain-core` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :domain-core:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.domain`. +패키지 루트: `dev.caskeleton.domain`. 코드 주석에서 덜어낸 **설계 결정의 근거**는 [README.md](README.md) 가 모아둔다 (이 문서는 모듈 규칙 SSOT). -## Responsibility +## 책임 -- Business concepts, entities, value objects, enums, domain events, domain services. -- Repository ports where this reference implementation still keeps domain-owned persistence contracts. -- Domain invariants and core rules. +- 업무 개념, 엔티티, 값 객체, enum, 도메인 이벤트, 도메인 서비스. +- 이 참조 구현이 아직 도메인 소유 영속 계약을 두는 곳의 repository 포트. +- 도메인 불변식과 핵심 규칙. -## Allowed +## 허용 -- Java standard library. -- Value-only shared operational types only if truly needed. +- Java 표준 라이브러리. +- 값만 담은 공용 운영 타입은 정말 필요할 때만. -## Forbidden +## 금지 -- Spring annotations. -- JPA annotations. -- Servlet/HTTP types. -- Adapter, application, bootstrap, or presentation DTO dependencies. +- Spring 애너테이션. +- JPA 애너테이션. +- Servlet·HTTP 타입. +- 어댑터, application, bootstrap, 표현 계층 DTO 의존. -## Test +## 테스트 ```bash cd src diff --git a/src/domain-core/README.md b/src/domain-core/README.md index 29f3ab82..d89d7f84 100644 --- a/src/domain-core/README.md +++ b/src/domain-core/README.md @@ -57,7 +57,7 @@ 네이밍 규칙 대신, `@ValueObject` 처럼 **명시적이고 의도가 드러나는 선언**을 기준으로 모델링 가드레일을 걸 수 있게 한다. - **왜 프레임워크 중립으로 두나.** 일부러 어떤 프레임워크에도 의존하지 않게 만들어서 - `domain-core`가 순수 라이브러리로 남게 한다(`domain_is_pure` 가드레일). + `domain-core`가 순수 라이브러리로 남게 한다(`DOMAIN_IS_PURE` 가드레일). ### `@ValueObject` — 값 객체 @@ -67,7 +67,7 @@ 단 하나의 생성 경로에서 자기 불변식을 검증한다. - **강제 규칙 — public 무인자 생성자 금지.** `@ValueObject` 타입과 `..domain.vo..` 아래 모든 타입은 public 무인자 생성자를 노출하면 안 된다. 빈 생성자는 검증을 건너뛰고 객체를 만들 수 - 있는 "불변식 우회 뒷문"이기 때문이다(`value_objects_have_no_public_no_arg_constructor`). + 있는 "불변식 우회 뒷문"이기 때문이다(`VALUE_OBJECTS_HAVE_NO_PUBLIC_NO_ARG_CONSTRUCTOR`). - **왜 `RUNTIME` 리텐션인가.** ArchUnit(바이트코드 검사)과 리플렉션 기반 테스트가 둘 다 이 애너테이션을 읽을 수 있어야 해서 런타임까지 유지한다. @@ -79,7 +79,7 @@ - **상태 변경은 의도가 드러나는 메서드로만.** 상태 변경은 불변식을 강제하는, 의도가 분명한 애그리거트 메서드를 통해서만 일어나야 한다. 날것의 `setXxx` 세터를 public 으로 열어두면 안 된다. - **강제 규칙 — public 세터 금지.** `@AggregateRoot` 타입의 모든 `set*` 메서드는 - package-private 또는 protected 여야 한다(`aggregate_root_setters_are_not_public`). 이 + package-private 또는 protected 여야 한다(`AGGREGATE_ROOT_SETTERS_ARE_NOT_PUBLIC`). 이 가시성은 Vernon Option A(ORM 외부에서 매핑하는 방식)로 객체를 재구성할 때 의존하는 지점이다. - **이 규칙의 한계.** ArchUnit 은 정적으로 `set*` 라는 이름 패턴까지만 잡을 수 있다. `applyXxx` 처럼 이름이 다른 상태 변경 메서드는 자동 검사가 닿지 않으므로 코드 리뷰가 잡아야 @@ -94,6 +94,6 @@ 포맷·HTTP 같은 전송 계층 타입을 절대 참조하지 않는다는 뜻이다. 도메인 이벤트를 통합 이벤트나 와이어 이벤트로 번역하는 일은 애플리케이션/인프라 경계의 책임이지 도메인의 책임이 아니다. - **강제 규칙 두 가지.** 모든 `@DomainEvent` 타입은 (1) `record` 여야 하고 - (`domain_events_are_records`, 불변성 보장), (2) 어떤 전송 패키지(`org.apache.kafka..`, + (`DOMAIN_EVENTS_ARE_RECORDS`, 불변성 보장), (2) 어떤 전송 패키지(`org.apache.kafka..`, `org.springframework.http..`, `jakarta.ws.rs..`)도 의존하면 안 된다 - (`domain_events_are_transport_free`). + (`DOMAIN_EVENTS_ARE_TRANSPORT_FREE`). diff --git a/src/platforms/grpc-advanced/CLAUDE.md b/src/platforms/grpc-advanced/CLAUDE.md index 158830ae..d78e9d8d 100644 --- a/src/platforms/grpc-advanced/CLAUDE.md +++ b/src/platforms/grpc-advanced/CLAUDE.md @@ -1,6 +1,6 @@ -# grpc-advanced — local authority for the advanced gRPC capabilities +# grpc-advanced — 고급 gRPC capability의 지역 정본 -이 문서는 `grpc-advanced:*` family의 **local authority**다. leaf 목록·gradle path·허용 의존성은 +이 문서는 `grpc-advanced:*` family의 **지역 정본(local authority)**이다. leaf 목록·gradle path·허용 의존성은 `src/config/architecture/modules.json`이 SSOT다. Root 정책(`CLAUDE.md` / `AGENTS.md`)과 충돌하면 root가 이긴다. diff --git a/src/platforms/grpc/CLAUDE.md b/src/platforms/grpc/CLAUDE.md index 190f58d1..3e128277 100644 --- a/src/platforms/grpc/CLAUDE.md +++ b/src/platforms/grpc/CLAUDE.md @@ -1,6 +1,6 @@ -# grpc — local authority for the gRPC platform family +# grpc — gRPC 플랫폼 family의 지역 정본 -이 문서는 `grpc:*` family의 **local authority**다. gRPC platform은 기본 application build와 분리된 +이 문서는 `grpc:*` family의 **지역 정본(local authority)**이다. gRPC platform은 기본 application build와 분리된 `src/platforms/optional-build` build가 소유한다. 여기서 정하는 것은 family별 framework 규칙, 증거 등급, Stable 범위의 경계와 application에 채택될 때 필요한 계약이다. @@ -132,64 +132,61 @@ cd src (`GrpcMetricCardinalityPolicy`가 거부한다). -### Adoption-time observability gate +### 채택할 때의 관측 게이트 -The metric names implemented by `grpc-observability` are **not registered in -`docs/registries/metrics.yaml` yet** because this optional family is not a shipped runtime capability. -Do not present those names as repository-certified metrics until adoption adds registry entries with -the repository's `.seconds` / `.total` unit naming and the corresponding validation gate. +`grpc-observability`가 구현한 metric 이름은 **아직 `docs/registries/metrics.yaml`에 등록하지 +않았다**. 이 optional family는 출하하는 런타임 capability가 아니기 때문이다. 채택하면서 저장소의 +`.seconds` / `.total` 단위 이름 규칙에 맞는 registry 항목과 그에 맞는 검증 게이트를 더하기 전에는 그 +이름을 저장소가 인증한 metric처럼 내세우지 않는다. -### Durable operation ledger adoption +### durable operation 원장 채택 -`grpc-spring-boot-starter` does not pull the JPA ledger adapter transitively (11-M9). A deployment that -needs durable operation idempotency adds `:grpc:grpc-operation-ledger-jpa` explicitly, defines a -`GrpcOperationLedger` bean (`new JpaGrpcOperationLedger(repository)`), includes that adapter's Flyway -location `db/migration/grpc` (V001 table, V002 retention index, V003 claim attempt), and sets the flag below. A deployment -that does not adopt the ledger pays no Spring Data JPA classpath cost. +`grpc-spring-boot-starter`는 JPA 원장 어댑터를 전이 의존으로 끌어오지 않는다(2026-09-18 리뷰가 찾은 문제). durable +operation 멱등성이 필요한 배포는 `:grpc:grpc-operation-ledger-jpa`를 직접 더하고, +`GrpcOperationLedger` bean(`new JpaGrpcOperationLedger(repository)`)을 정의하고, 그 어댑터의 Flyway +위치 `db/migration/grpc`(V001 테이블, V002 보존 index, V003 claim attempt)를 넣고, 아래 flag를 켠다. +원장을 채택하지 않는 배포는 Spring Data JPA classpath 비용을 내지 않는다. -| Key (`app.grpc.platform.*`) | Default | What it does | +| 키 (`app.grpc.platform.*`) | 기본값 | 하는 일 | | --- | --- | --- | -| `operation-ledger-enabled` | `false` | `true`: the starter assembles `GrpcIdempotencyInterceptor` (bean `grpcIdempotencyInterceptor`) and `GrpcOperationLedgerRetention` (bean `grpcOperationLedgerRetention`) over the deployment's `GrpcOperationLedger` bean, and refuses startup when there is none. `false`: neither bean exists, and a method that is `IDEMPOTENCY_KEY_REQUIRED` refuses startup | -| `operation-ledger-claim-ttl` | `5m` | How long an `IN_PROGRESS` claim is trusted to have a live owner. After it, a retry of the same request takes the claim over (`GrpcOperationLedger.reclaimStale`). Refused at startup unless longer than every keyed method's deadline | -| `operation-ledger-retention` | `24h` | How long a finished (`COMMITTED`/`FAILED_TERMINAL`) record is kept before `GrpcOperationLedgerRetention.purgeExpired` may delete it. `IN_PROGRESS` rows are never purged | +| `operation-ledger-enabled` | `false` | `true`: starter가 배포의 `GrpcOperationLedger` bean 위에 `GrpcIdempotencyInterceptor`(bean `grpcIdempotencyInterceptor`)와 `GrpcOperationLedgerRetention`(bean `grpcOperationLedgerRetention`)을 조립하고, 원장 bean이 없으면 기동을 거절한다. `false`: 두 bean 모두 없고, `IDEMPOTENCY_KEY_REQUIRED`인 메서드가 있으면 기동을 거절한다 | +| `operation-ledger-claim-ttl` | `5m` | `IN_PROGRESS` claim의 주인이 살아 있다고 믿는 시간. 지나면 같은 요청의 재시도가 claim을 넘겨받는다(`GrpcOperationLedger.reclaimStale`). 키가 필요한 모든 메서드의 deadline보다 길지 않으면 기동에서 거절한다 | +| `operation-ledger-retention` | `24h` | 끝난(`COMMITTED`/`FAILED_TERMINAL`) 레코드를 `GrpcOperationLedgerRetention.purgeExpired`가 지울 수 있게 되기 전까지 두는 시간. `IN_PROGRESS` 행은 지우지 않는다 | -Defaults: the 5-minute TTL is the value the ledger contract and interceptor tests certify, far beyond -a unary deadline, and short enough that a key whose owner died unblocks within a client's retry -patience. The 24-hour retention matches the HTTP idempotency replay TTL -(`app.capabilities.idempotency.replay-ttl`). A retry of a key after its record was purged is a new -operation, so the retention must exceed the callers' retry window. +기본값: 5분 TTL은 원장 계약 시험과 interceptor 시험이 인증한 값이다. unary deadline보다 훨씬 길고, +주인이 죽은 키가 클라이언트의 재시도 인내 안에 풀릴 만큼 짧다. 24시간 보존은 HTTP 멱등성 재생 TTL +(`app.capabilities.idempotency.replay-ttl`)과 같다. 레코드를 지운 뒤 같은 키로 하는 재시도는 새 +operation이므로, 보존 시간은 호출자의 재시도 창보다 길어야 한다. -These keys are not in `docs/registries/env-keys.yaml`: no `app.grpc.platform.*` key is, because the -optional build is not part of the shipped runtime. They join the registry when a composition root -adopts the platform. +이 키들은 `docs/registries/env-keys.yaml`에 없다. optional 빌드는 출하하는 런타임이 아니라서 +`app.grpc.platform.*` 키는 하나도 없다. 조립 루트가 플랫폼을 채택할 때 registry에 들어간다. -**Why the starter assembles the interceptor (option (b)), and not (a).** The 2026-11-01 maturity review proposed (a): -delete the flag and judge by whether a ledger bean exists. (b) was chosen on 2026-11-03 and is recorded in -ADR-GRPC-004: the flag stays and means what it says — when true, the -decision function is assembled and its TTL comes from configuration. (a) would have removed the false promise but left every adopter to rebuild the same -assembly and TTL validation by hand; (b) keeps that in one place. The interceptor bean has no -`@ConditionalOnMissingBean` on purpose: a replacement would silently ignore `operation-ledger-claim-ttl`. -Duplicates of a running operation are refused (`REJECT_IN_PROGRESS`), not told to wait; a -wait-and-poll option becomes a key when a keyed method needs it. +**starter가 interceptor를 조립하는 이유(선택지 (b)), (a)가 아닌 이유.** 2026-11-01 성숙도 리뷰는 +(a)를 제안했다: flag를 지우고 원장 bean이 있는지로 판단한다. 2026-11-03에 (b)를 골랐고 ADR-GRPC-004에 +적었다: flag를 남기고 flag는 말 그대로의 뜻이다 — true이면 판정 함수를 조립하고 그 TTL은 설정에서 +온다. (a)는 거짓 약속을 없앴겠지만 채택하는 쪽마다 같은 조립과 TTL 검증을 손으로 다시 만들게 +했다. (b)는 그것을 한곳에 둔다. interceptor bean에는 일부러 `@ConditionalOnMissingBean`이 없다: +바꿔 넣은 bean은 `operation-ledger-claim-ttl`을 소리 없이 무시하게 된다. 돌고 있는 operation의 +중복은 기다리라고 하지 않고 거절한다(`REJECT_IN_PROGRESS`). 기다렸다가 다시 묻는 선택지는 키가 +필요한 메서드가 그것을 필요로 할 때 키가 된다. -**Server wiring is still the adopter's, and stays a separate decision.** The starter builds no -server, so assembling the decision does not wire the platform into `adapter:inbound:grpc` (see "배선은 -별도 결정" above). `GrpcIdempotencyInterceptor` is a decision function, not an `io.grpc.ServerInterceptor`. -The adopter injects the bean by type and calls it from its own `IDEMPOTENCY` stage interceptor -(`GrpcServerInterceptorChain.builder().stage(GrpcServerInterceptorStage.IDEMPOTENCY, ...)`) or from -its typed service adapter: `decide(...)` before the mutation, `recordCommit(...)` inside the mutation's -transaction, `recordFailure(...)` on a terminal failure. Both record calls take the `GrpcClaimToken` -the `PROCEED` decision carried: a commit by an attempt whose claim was taken over is refused (its -transaction rolls back) and its failure is ignored, so a slow owner cannot write over the attempt that -took its claim (ADR-GRPC-004). +**서버 배선은 여전히 채택하는 쪽의 몫이고, 따로 정할 일로 남는다.** starter는 서버를 만들지 +않으므로, 판정을 조립한다고 플랫폼이 `adapter:inbound:grpc`에 배선되지는 않는다(위 "배선은 +별도 결정"을 본다). `GrpcIdempotencyInterceptor`는 판정 함수이고 `io.grpc.ServerInterceptor`가 +아니다. 채택하는 쪽은 bean을 타입으로 주입받아 자기 `IDEMPOTENCY` 단계 interceptor +(`GrpcServerInterceptorChain.builder().stage(GrpcServerInterceptorStage.IDEMPOTENCY, ...)`)나 자기 +typed service adapter에서 부른다: 변경 전에 `decide(...)`, 변경의 트랜잭션 안에서 +`recordCommit(...)`, 끝난 실패에 `recordFailure(...)`. 두 기록 호출은 모두 `PROCEED` 판정이 실어 온 +`GrpcClaimToken`을 받는다: claim을 넘겨준 시도의 커밋은 거절되고(그 트랜잭션은 롤백된다) 그 실패는 +무시된다. 그래서 느린 주인이 claim을 가져간 시도를 덮어쓰지 못한다(ADR-GRPC-004). -**Purge scheduling is the adopter's.** `GrpcOperationLedgerRetention.purgeExpired(now)` deletes -expired finished rows in bounded batches (500 per statement) until a batch comes back short. The -starter does not schedule it: it owns no scheduler and cannot know which replica should run it, and a -scheduled bean would force a task scheduler onto every deployment. The adopter calls it from its own -scheduler (for example hourly); concurrent runs on several replicas are safe because the delete skips -locked rows. Running it never is safe but lets the table grow without bound. +**지우기 일정은 채택하는 쪽의 몫이다.** `GrpcOperationLedgerRetention.purgeExpired(now)`는 기한이 지난 +끝난 행을 한계 있는 batch(문장 하나에 500)로 지우고, batch가 덜 차서 돌아오면 멈춘다. starter는 이것을 +예약하지 않는다: scheduler를 가지지 않고 어느 replica가 돌려야 하는지 알 수 없으며, 예약된 bean은 모든 +배포에 task scheduler를 강요하게 된다. 채택하는 쪽이 자기 scheduler에서 부른다(예: 한 시간마다). +지우기가 잠긴 행을 건너뛰므로 여러 replica에서 동시에 돌려도 안전하다. 한 번도 돌리지 않아도 안전하지만 +테이블이 끝없이 커진다. -The commit must be recorded in the mutation's transaction and the TTL must be longer than the slowest -keyed method; both reasons are in ADR-GRPC-004. +커밋은 변경의 트랜잭션 안에서 기록해야 하고 TTL은 키가 필요한 가장 느린 메서드보다 길어야 한다. 두 +이유는 모두 ADR-GRPC-004에 있다. diff --git a/src/platforms/messaging/CLAUDE.md b/src/platforms/messaging/CLAUDE.md index eda4b578..807a5890 100644 --- a/src/platforms/messaging/CLAUDE.md +++ b/src/platforms/messaging/CLAUDE.md @@ -1,6 +1,6 @@ -# messaging — local authority for the messaging platform family +# messaging — 메시징 플랫폼 family의 지역 정본 -이 문서는 messaging family의 **local authority**다. leaf 목록·gradle path·허용 의존성은 +이 문서는 messaging family의 **지역 정본(local authority)**이다. leaf 목록·gradle path·허용 의존성은 `src/config/architecture/modules.json`이 SSOT이며 이 문서는 그것을 복제하지 않는다. 여기서 정하는 것은 registry가 표현할 수 없는 것들이다: family별 framework 규칙, public surface 정책, Stable 승격에 필요한 증거, runtime membership이 비어 있다는 사실의 의미. @@ -40,7 +40,7 @@ JDBC이고 SQL은 `jsonb` · `FOR UPDATE SKIP LOCKED` · `ON CONFLICT` · `TIMES registry edge를 주면 그 경계가 깨진다. 복사본을 고칠 때(키 길이 검사, constant-time 비교 등)는 `shared-contract`의 정본과 같은 규칙인지 함께 본다. -### Publish retryability of authentication and authorization +### 인증·인가 거부의 발행 재시도 여부 (Publish retryability of authentication and authorization) 이 제품 안에는 같은 category에 대한 재시도 규칙이 둘 있다. 의도다. @@ -52,7 +52,8 @@ registry edge를 주면 그 경계가 깨진다. 복사본을 고칠 때(키 길 publish를 거부한 뒤 멈추기 때문이다. `retryable`을 믿는 publisher가 그 몇 분 동안의 레코드를 영구 보류하지 않게 하려는 것이다. -06-01 수정이 이 제품에서 바꾼 것(모두 publish 경로, 소비 경로 동작은 그대로): +다시 시도하면 될 거부를 relay가 즉시 DEAD로 보내던 결함의 수정(2026-11-01 성숙도 리뷰 뒤)이 이 제품에서 바꾼 것(모두 +publish 경로, 소비 경로 동작은 그대로): - `KafkaPublishFailureClassifier`: 인증·인가 거부를 `retryable = true`로. - `DefaultMessagePublisher`: runtime이 없을 때의 거부(`PUBLISH_RUNTIME_UNAVAILABLE`)를 `retryable = true`로. diff --git a/src/platforms/optional-build/README.md b/src/platforms/optional-build/README.md index e6bce651..8df221e1 100644 --- a/src/platforms/optional-build/README.md +++ b/src/platforms/optional-build/README.md @@ -1,13 +1,13 @@ -# Optional gRPC platforms +# optional gRPC 플랫폼 -The default application does not depend on `grpc/*` or `grpc-advanced/*`, so those projects (the -registry entries with `"build": "optional-grpc"`) are kept out of the main multi-project build. This build preserves their existing project paths and -internal project dependencies while making their configuration opt-in. +기본 애플리케이션은 `grpc/*`나 `grpc-advanced/*`에 의존하지 않는다. 그래서 이 프로젝트들(registry에서 +`"build": "optional-grpc"`인 항목)은 주 멀티 프로젝트 빌드에서 뺀다. 이 빌드는 그 프로젝트들의 원래 +프로젝트 경로와 내부 프로젝트 의존을 그대로 두면서, 그 설정을 고를 때만 켜지게 한다. ```bash ./gradlew -p platforms/optional-build ci ./gradlew -p platforms/optional-build :grpc:grpc-testkit:grpcInProcessContractTest ``` -`adapter:inbound:grpc` remains in the main application build because it is an application adapter; -the reusable gRPC platform libraries are optional capability code and live here. +`adapter:inbound:grpc`는 애플리케이션 어댑터라서 주 애플리케이션 빌드에 남는다. 다시 쓰는 gRPC +플랫폼 라이브러리는 optional capability 코드이고 여기 있다. diff --git a/src/shared-contract/CLAUDE.md b/src/shared-contract/CLAUDE.md index 3739e420..6722710c 100644 --- a/src/shared-contract/CLAUDE.md +++ b/src/shared-contract/CLAUDE.md @@ -1,72 +1,68 @@ -# shared-contract — skeleton-wide operational contract +# shared-contract — 골격 전체가 쓰는 운영 계약 -## Registered identity +## 등록 정보 -- Module ID: `shared-contract` -- Gradle path: `:shared-contract` -- Focused test (derived from Gradle path): `./gradlew :shared-contract:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `shared-contract` +- Gradle 경로: `:shared-contract` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :shared-contract:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.shared`. +패키지 루트: `dev.caskeleton.shared`. -Design decisions previously kept as code comments (error-code classification, response -envelope shape, metric cardinality bounds, tracing seam, domain-context propagation) live in -[README.md](README.md). This file stays the SSOT for module rules. +예전에 코드 주석에 두던 설계 결정(오류 코드 분류, 응답 envelope 모양, metric cardinality 한계, +tracing 이음매, domain-context 전파)은 [README.md](README.md)에 있다. 이 파일은 모듈 규칙의 정본으로 +남는다. -## Responsibility -- Response envelope (`response/Envelope`, `response/ApiError`, `response/BulkEnvelope`, `response/BulkItemResult`). -- Error code contract (`error/ApiErrorCode` interface, `error/OperationalError` enum, - `error/ApiErrorCarrier`) and the one client-facing wording table (`error/ClientErrorMessages`, - Korean, one message per `Category`, used by every transport). -- Cross-cutting mapper sentinel (`error/MappingException`). -- Request value contract (`request/Patch`). -- Tracing contract types (`tracing/TraceParent`, `tracing/SpanErrorRecorder`) — W3C - `traceparent` value type and the span-error-recording seam (feature-distributed-tracing-contract; the OTel - tracer runtime is a fork-activated seam, so these stay Java-stdlib-only). -- Stdlib helpers every leaf used to copy (moved here in the 2026-09-25 review follow-up): `digest/Sha256` (the - SHA-256 digest value and the one `MessageDigest.getInstance("SHA-256")`), `digest/HmacSha256` - (sign and constant-time verify), `retry/Backoff` (capped exponential ceiling; "full jitter" means - `U[0, ceiling]` and nothing else). Vendored `messaging:*` and the optional gRPC build do not depend - on this module and keep their own copies; each family's CLAUDE.md says why (a different product, - decided after the 2026-08-14 messaging module review). Every template leaf that needs one of these has the `shared-contract` edge and uses them - instead of copying: identifier, persistence-mongo, application-objectstorage and redis-sdk took the - edge for exactly this (decided 2026-11-03), each with a test - that pins its output to a vector computed outside the JVM. -- `observability/MdcKeys`: the snake_case MDC key names (registry `docs/registries/mdc-keys.yaml`) - every transport puts a request's correlation under — web, GraphQL, STOMP and gRPC alike. -- `ratelimit/`: the provider-neutral edge rate-limit port (`EdgeRateLimitPort`) and its value types, - between the web edge and the Redis adapter (README 「ratelimit」). -- `security/Permission`: the `resource:action` permission value `AuthorizationPort` is asked about - (README 「security」). -- `concurrency/`: the domain-context propagation port and its `ThreadLocal` default (README - 「concurrency」). -- `runtime/RuntimeEnvironment`: the one runtime-profile vocabulary every leaf answers "is this - production?" with. -- `metrics/ForbiddenMetricTags`: the high-cardinality tag keys no metric may carry. -- These are the module's packages and the only ones it may have: - `ForbiddenApiArchitectureTest.SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES` refuses a - class in any other package below `dev.caskeleton.shared` or directly in the root, which holds only - its `package-info`. A new contract package goes into that test's `SHARED_CONTRACT_PACKAGES` and - into this list together; `SharedContractPackageRuleTest` fails when `SHARED_CONTRACT_PACKAGES` and - the module's packages differ. -- Registry-rule mirrors read only by contract tests live in `testFixtures`, not `main`: +## 책임 (Responsibility) +- 응답 envelope(`response/Envelope`, `response/ApiError`, `response/BulkEnvelope`, `response/BulkItemResult`). +- 오류 코드 계약(`error/ApiErrorCode` 인터페이스, `error/OperationalError` enum, + `error/ApiErrorCarrier`)과 클라이언트에 보여 줄 문구 표 하나(`error/ClientErrorMessages`. + 한국어이고 `Category`마다 문구 하나이며 모든 전송 계층이 쓴다). +- 계층을 가로지르는 mapper 표지 예외(`error/MappingException`). +- 요청 값 계약(`request/Patch`). +- tracing 계약 타입(`tracing/TraceParent`, `tracing/SpanErrorRecorder`) — W3C `traceparent` 값 타입과 + span 오류 기록 이음매(feature-distributed-tracing-contract. OTel tracer 런타임은 fork가 켜는 + 이음매라서 이 타입들은 Java 표준 라이브러리만 쓴다). +- 모든 leaf가 복사해 쓰던 표준 라이브러리 도우미(2026-09-25 리뷰 후속으로 여기로 옮겼다): + `digest/Sha256`(SHA-256 digest 값과 유일한 `MessageDigest.getInstance("SHA-256")`), + `digest/HmacSha256`(서명과 상수 시간 검증), `retry/Backoff`(상한 있는 지수 ceiling. "full jitter"는 + `U[0, ceiling]`이고 다른 뜻이 아니다). 들여온 `messaging:*`와 optional gRPC 빌드는 이 모듈에 + 의존하지 않고 자기 사본을 둔다. 각 제품의 CLAUDE.md가 이유를 적는다(다른 제품이다. 2026-08-14 메시징 + 모듈 리뷰 뒤에 정했다). 이 도우미가 필요한 템플릿 leaf는 모두 `shared-contract` edge를 두고 복사하지 + 않고 쓴다. identifier, persistence-mongo, application-objectstorage, redis-sdk가 바로 이 때문에 + edge를 받았고(2026-11-03에 정함), 각각 JVM 밖에서 계산한 벡터로 출력을 고정하는 시험이 있다. +- `observability/MdcKeys`: 모든 전송 계층(web, GraphQL, STOMP, gRPC)이 요청의 correlation을 넣는 + snake_case MDC 키 이름(registry `docs/registries/mdc-keys.yaml`). +- `ratelimit/`: web edge와 Redis 어댑터 사이에 있는 provider 중립 edge rate-limit 포트 + (`EdgeRateLimitPort`)와 그 값 타입(README 「ratelimit」). +- `security/Permission`: `AuthorizationPort`에 묻는 `resource:action` 권한 값(README 「security」). +- `concurrency/`: domain-context 전파 포트와 그 `ThreadLocal` 기본 구현(README 「concurrency」). +- `runtime/RuntimeEnvironment`: 모든 leaf가 「운영 환경인가?」에 답할 때 쓰는 유일한 runtime profile + 어휘. +- `metrics/ForbiddenMetricTags`: 어떤 metric도 실으면 안 되는 high-cardinality tag 키. +- 이 모듈의 패키지는 위가 전부이고 다른 패키지는 둘 수 없다: + `ForbiddenApiArchitectureTest.SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES`가 + `dev.caskeleton.shared` 아래 다른 패키지에 있는 클래스와 루트에 바로 있는 클래스를 거절한다. 루트에는 + `package-info`만 있다. 새 계약 패키지는 그 시험의 `SHARED_CONTRACT_PACKAGES`와 이 목록에 함께 + 넣는다. `SharedContractPackageRuleTest`는 `SHARED_CONTRACT_PACKAGES`와 모듈의 패키지가 다르면 + 실패한다. +- 계약 시험만 읽는 registry 규칙 사본은 `main`이 아니라 `testFixtures`에 둔다: `metrics/MetricNaming`, `metrics/CardinalityBounds`, `metrics/AlertSeverity`, - `tracing/BaggageAllowlist`. Move one to `main` only when production code consumes it. -- Generic messaging envelope schema resources under `contracts/messaging/envelope/`. - They own transport-neutral envelope metadata only; feature payload schemas remain in their - feature-owner modules. Resource presence is not runtime discovery or registration. + `tracing/BaggageAllowlist`. 운영 코드가 쓰게 될 때만 `main`으로 옮긴다. +- `contracts/messaging/envelope/` 아래의 범용 메시징 envelope schema 리소스. 전송 중립 envelope + metadata만 가진다. 기능 payload schema는 그 기능을 가진 모듈에 남는다. 리소스가 있다고 런타임에 + 찾아지거나 등록되는 것은 아니다. -## Allowed -- Java standard library ONLY. No Spring, no Jackson, no JPA imports. +## 허용 +- Java 표준 라이브러리**만**. Spring, Jackson, JPA import는 없다. -## Forbidden -- business/domain concept (domain error codes belong in the consuming module). -- framework imports (HTTP status is expressed as transport-neutral `int`; the web module maps it). -- claiming Draft 2020-12 validator compatibility before the messaging adapter's Task 6 validator - qualification exists. +## 금지 (Forbidden) +- 업무·도메인 개념(도메인 오류 코드는 그것을 쓰는 모듈에 둔다). +- 프레임워크 import(HTTP 상태는 전송 중립 `int`로 나타내고 web 모듈이 대응시킨다). +- 메시징 어댑터의 Task 6 validator 검증이 생기기 전에 Draft 2020-12 validator 호환을 주장하기. -## Test +## 테스트 ```bash cd src ./gradlew :shared-contract:test diff --git a/src/shared-contract/README.md b/src/shared-contract/README.md index a1d66198..b22731a4 100644 --- a/src/shared-contract/README.md +++ b/src/shared-contract/README.md @@ -508,7 +508,7 @@ Spring 배선(`DomainContextConfig`)은 `composition:service-runtime` 에 있고 흐르는 값도 없다. 도메인은 필요해질 때 자기 키를 선언한다(그 전까지 seam 은 관측 가능한 동작이 없다 — route 가 없는 `RateLimitKeyResolver` 와 같다). - **`ScopedValue`/`StructuredTaskScope` strategy:** Java 21 preview API 이고 빌드에 `--enable-preview` - 가 없어(빌드 사실 C1) 운영에서 컴파일되지 않는다. `domain_context_propagation_primitives_stay_unshipped` + 가 없어(빌드 사실 C1) 운영에서 컴파일되지 않는다. `DOMAIN_CONTEXT_PROPAGATION_PRIMITIVES_STAY_UNSHIPPED` ArchUnit 규칙(app-bootstrap `ForbiddenApiArchitectureTest`)이, 해당 구현이 추가되기 전까지 이를 운영 코드에서 배제한다. @@ -534,7 +534,7 @@ Spring 배선(`DomainContextConfig`)은 `composition:service-runtime` 에 있고 살고 inbound 필터가 virtual thread 에서 전파한다(B6 + D11). 이 propagator 는 **도메인 채널** — 별개의 관심사다. - **명시적 핸드오프(S3):** 구현은 스레드 간 암묵적 상속에 의존해선 안 된다(`InheritableThreadLocal` 은 - `no_inheritable_thread_local` ArchUnit 규칙으로 금지). 스레드/`fork()` 경계를 넘는 코드는 + `NO_INHERITABLE_THREAD_LOCAL` ArchUnit 규칙으로 금지). 스레드/`fork()` 경계를 넘는 코드는 `wrap()` 또는 `capture()`+`restore()` 로 컨텍스트를 명시적으로 재확립한다. ### 전략이 하나뿐인 이유 @@ -545,13 +545,13 @@ Spring 배선(`DomainContextConfig`)은 `composition:service-runtime` 에 있고 - `io.micrometer:context-propagation` 의 `ContextSnapshot`/`ContextRegistry`. 다중 키나 Reactor bridge 가 필요할 때 고른다(C7: 활성화 전에 virtual-thread 동작을 확인할 것). - Java 21 `ScopedValue`. PREVIEW 라 `--enable-preview` 가 필요한데 현재 빌드는 켜지 않는다(C1) → - `domain_context_propagation_primitives_stay_unshipped` ArchUnit 규칙으로 guard 된다. + `DOMAIN_CONTEXT_PROPAGATION_PRIMITIVES_STAY_UNSHIPPED` ArchUnit 규칙으로 guard 된다. ### ThreadLocalDomainContextPropagator (기본 구현) - plain `ThreadLocal` 이 현재 스레드의 도메인 컨텍스트 맵을 들고, 스레드 경계는 명시적 capture/restore 로 넘긴다(D4/D6). - **왜 plain `ThreadLocal` 인가:** `InheritableThreadLocal` 이 아니라서 pooled carrier 스레드 너머로 - 조용히 새지 않고 `no_inheritable_thread_local` ArchUnit 규칙(B6)을 지킨다. virtual thread 는 각자 + 조용히 새지 않고 `NO_INHERITABLE_THREAD_LOCAL` ArchUnit 규칙(B6)을 지킨다. virtual thread 는 각자 자기 copy 를 갖는다(Oracle Java 21 docs, TL-VT-C1) → 같은 스레드 read 는 동작하지만 fork 시 상속은 없다 — 그래서 핸드오프가 `wrap()`/`capture()` 로 **명시적**이어야 하는 것이다. - multi-key 고빈도 변경이나 Reactor bridging 용이 아니다 — 그건 context-propagation 기반 구현의 일이다. 이