docs!: 번역 네 묶음을 합치고 문서 검사 장치를 마무리한다 #3
@@ -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 검사를
|
||||
유지한다.
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
## What changed and why
|
||||
## 무엇을 왜 바꿨나
|
||||
|
||||
<!-- Summarize the behavior, architecture boundary, or policy being changed. -->
|
||||
<!-- 바꾼 동작, 아키텍처 경계, 정책을 요약한다. -->
|
||||
|
||||
## Verification
|
||||
## 검증
|
||||
|
||||
- [ ] I ran focused `:<changed-leaf>: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.
|
||||
- [ ] 바꾼 모듈마다 `:<changed-leaf>:check`를 돌렸다.
|
||||
- [ ] 저장소 구조·의존성·공개 경로를 건드렸으면 `cd src && ./gradlew architectureCheck verifyPublicPathSnapshot verifyDependencyLocks`를 돌렸다.
|
||||
- [ ] registry에 없는 production 모듈 의존을 더하지 않았다.
|
||||
- [ ] 의존성을 바꿨으면 다시 만든 `gradle.lockfile`과 strict lock 검증을 함께 넣었다.
|
||||
- [ ] Trivy 예외(suppression)에는 소유자가 검토한 이유와 90일 안의 만료일이 있다.
|
||||
- [ ] 간헐 실패 테스트는 격리하지 않고 고치거나 지웠다(격리 레지스트리는 없다).
|
||||
- [ ] 돌리지 못한 검사와 그 때문에 남은 위험을 적었다.
|
||||
|
||||
## Compatibility and operations
|
||||
## 호환성과 운영
|
||||
|
||||
<!-- Note public API/config changes, migration needs, rollout/rollback impact, and external blockers. -->
|
||||
<!-- 공개 API·설정 변경, 마이그레이션 필요 여부, 배포·되돌리기 영향, 외부 차단 요인을 적는다. -->
|
||||
|
||||
@@ -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$
|
||||
@@ -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가 실제로 실행하는
|
||||
|
||||
@@ -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 <gradle-path>: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 <FeatureName>`으로 만들고 [docs/manual/README.md](docs/manual/README.md) 순서대로 채운다. 모듈 이름과 경계는 그대로 둔다.
|
||||
5. 쓰는 capability의 `runtimeOnly` 줄만 켠다. 켜지 않은 capability leaf는 산출물에 들어가지 않으니 지우지 않아도 된다.
|
||||
|
||||
3. `CaSkeletonApplication`을 새 애플리케이션 이름으로 바꾸고, 목표 도메인의 엔티티·repository port·유스케이스·adapter를 production 모듈에 추가합니다. 새 업무 기능은 `scripts/new-feature.sh <FeatureName>`으로 만듭니다.
|
||||
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) 양식을 채운다.
|
||||
|
||||
+25
-29
@@ -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는 아무도
|
||||
시험하지 않는 두 번째 입구가 된다.
|
||||
|
||||
+55
-49
@@ -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://…/<VAR>` 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://…/<VAR>` 자격 증명 참조가 가리키는 변수
|
||||
|
||||
코드에 있는 참조(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://<account>@environment/<variable>` 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://<account>@environment/<variable>` 참조를 거치고, 그 변수가 위 fixture 비밀번호를 가진다.
|
||||
여기의 모든 계정이 `~prod:*`로 묶여 있어서, lane은 Redis namespace 환경을 `prod`로 두고 돈다.
|
||||
`scripts/verify-compose-profile-contracts.sh`가 Redis lane마다 참조·비밀번호·namespace를 이 파일의 계정 줄과
|
||||
비교한다. 그래서 lane을 고치지 않고 여기의 비밀번호나 key 패턴만 바꾸면, lane의 첫 명령이 아니라 그 검사가
|
||||
실패한다.
|
||||
|
||||
+96
-40
@@ -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
|
||||
<!-- 머리 블록: 이 블록을 빼면 원문이다. 형식은 docs/README.md 「기록 문서의 머리 블록」 -->
|
||||
@@ -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`에 더한다.
|
||||
|
||||
## 여기에 없는 것
|
||||
|
||||
|
||||
@@ -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 — 답은 세 번째 규약이 아니라 따로 둔 모듈이다.
|
||||
|
||||
@@ -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 경계 규칙
|
||||
옆에서 검사한다.
|
||||
|
||||
@@ -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를 본다.
|
||||
|
||||
@@ -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이 들어온 뒤가 아니라
|
||||
오늘 돈다.
|
||||
|
||||
@@ -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`는 그것을 푸는 일이 호출자에게 맡긴 숙제가 아니라
|
||||
지원하는 경로가 되게 하려고 있다.
|
||||
|
||||
@@ -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`으로 바꾼다.
|
||||
|
||||
@@ -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`가 누가 그것을 다르게 다시 쓸 법한 자리에서 그렇게 말한다.
|
||||
|
||||
@@ -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을 본다.
|
||||
|
||||
@@ -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.<capability>.enabled`, all off by
|
||||
default.
|
||||
**capability마다 flag 하나.** `ca-skeleton.grpc.advanced.<capability>.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가 조용히 넓어질 수 없다.
|
||||
|
||||
@@ -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<T, ID>`
|
||||
every aggregate inherits — or provide only the pieces domains assemble themselves.
|
||||
영속 플랫폼은 repository 추상 — 모든 aggregate가 상속하는 `GenericRepository<T, ID>` — 을 가질 수도 있고, 도메인이 스스로
|
||||
조립할 조각만 줄 수도 있다.
|
||||
|
||||
## 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`.
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -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`이기도 하다).
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -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`가 규칙 자신의 부정 경우를 시험한다.
|
||||
|
||||
@@ -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<T, ID>` 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<T, ID>`와 범용 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<T, ID>`.** 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<T, ID>`가 없다.** 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)를 본다.
|
||||
|
||||
@@ -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은 둘 다 사라진다.
|
||||
|
||||
@@ -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」.** 모든 트랜잭션 본문이 완전히 멱등이어야 한다. 표지 하나를 쓰는
|
||||
것보다 훨씬 강하고 훨씬 검사하기 어려운 성질이고, 누가 멱등이 아닌 단계를 처음 더하는 순간 소리 없이 깨진다.
|
||||
|
||||
@@ -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가
|
||||
실제 장치이고 애너테이션은 두 번째의 갈라진 정본이다.
|
||||
|
||||
@@ -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를 본다.
|
||||
|
||||
@@ -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으로 옮긴다.
|
||||
|
||||
@@ -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을 먹는 범인이 될 때까지 하나도
|
||||
보이지 않는다.
|
||||
|
||||
@@ -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 컴파일 단계를 건너뛴다.** 버렸다: 다른 단계가 놓치는 실패를 잡는 유일한 단계다.
|
||||
|
||||
@@ -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.
|
||||
**모듈을 강제 없는 패키지로 싣는다.** 가장 싸지만 경계를 주장으로 만든다. 구현 중에 찾은 위반 여섯 개가 그것에 반대하는 근거다.
|
||||
|
||||
@@ -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와 따로 쓴다.** 버렸다: 「누가 연결돼 있나」의 정본이 둘이면 어긋나고, 그 어긋남은 보이지 않는다 — 둘 다
|
||||
그럴듯해 보이고 아무것도 둘을 맞추지 않는다.
|
||||
|
||||
@@ -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는 문서가 된다.
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
<!-- 머리 블록: 이 블록을 빼면 원문이다. 형식은 docs/README.md 「기록 문서의 머리 블록」 -->
|
||||
> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다.
|
||||
|
||||
- 상태: 채택
|
||||
- 작성일: 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다. 비용은 「도착했나?」가 두 번째 질문이라는 것이다 — 그것이 정직한 질문 수다.
|
||||
@@ -0,0 +1,31 @@
|
||||
<!-- 머리 블록: 이 블록을 빼면 원문이다. 형식은 docs/README.md 「기록 문서의 머리 블록」 -->
|
||||
> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다.
|
||||
|
||||
- 상태: 채택
|
||||
- 작성일: 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이다.
|
||||
@@ -0,0 +1,42 @@
|
||||
<!-- 머리 블록: 이 블록을 빼면 원문이다. 형식은 docs/README.md 「기록 문서의 머리 블록」 -->
|
||||
> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다.
|
||||
|
||||
- 상태: 채택
|
||||
- 작성일: 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를 지원하면 맞춰 보기를 돌린다
|
||||
- 그렇지 않으면 전달을 멈추고 운영자를 기다린다
|
||||
|
||||
모호한 시도를 운영자가 다시 보내려면 중복 위험을 명시해 승인해야 한다.
|
||||
|
||||
## 결과
|
||||
|
||||
어떤 알림은 사람이나 맞춰 보기 한 바퀴가 필요한 상태에서 멈춘다. 그것이 의도한 거래다: 풀리지 않은 모름이 보장된 중복보다 싸고,
|
||||
상태는 어느 쪽으로든 소리 없이 풀리지 않고 보인다.
|
||||
@@ -0,0 +1,33 @@
|
||||
<!-- 머리 블록: 이 블록을 빼면 원문이다. 형식은 docs/README.md 「기록 문서의 머리 블록」 -->
|
||||
> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다.
|
||||
|
||||
- 상태: 채택
|
||||
- 작성일: 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가 한 경로를 바꿔도 다른 경로가 소리 없이 바뀌지 않는다. 비용은 문자열 필드보다 타입이 하나 더 필요하다는
|
||||
것이다.
|
||||
+4
-3
@@ -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개의 처분은 네 가지 중 하나다.
|
||||
|
||||
@@ -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.<capability>.enabled`.
|
||||
capability는 모두 기본으로 꺼져 있다. 스위치는 `app.grpc.advanced.<capability>.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를 올려도 다른 것의 등급은 바뀌지 않는다.
|
||||
|
||||
@@ -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에서 만들어지지 않고 정책으로 다스린다.
|
||||
|
||||
+138
-145
@@ -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)에 적었다.
|
||||
|
||||
@@ -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<String> 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<String> 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 위임 경로가 같은 실패에 다른 상태로 답하면 안 된다.
|
||||
|
||||
@@ -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에게 넘기지 않는다 |
|
||||
|
||||
@@ -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":["<from the dry run>"],"reasonCode":"ORPHAN_GROWTH_RUNBOOK"}'
|
||||
"expectedFingerprints":["<dry run이 보여 준 값>"],"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 <pod> -- 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=<name>`, then run the drift query again: the namespace must be gone
|
||||
from its result before writes resume.
|
||||
`psql -v namespace=<name>`으로 돌리고 drift query를 다시 돌린다. 쓰기를 다시 열기 전에 그 namespace가 결과에서
|
||||
사라져야 한다.
|
||||
|
||||
+53
-58
@@ -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 수준의 거부를 구분할 수 없다. 그래서 안전하다고
|
||||
증명할 수 없는 것은 모두 결과를 모르는 것으로 보고 맞춰 보기로 보낸다.
|
||||
|
||||
@@ -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를 다시 쓰는 저장소도 이것을 상속한다.
|
||||
|
||||
@@ -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) — 버전 사이에 바뀌는 것.
|
||||
|
||||
@@ -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
|
||||
```
|
||||
|
||||
@@ -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.<typo>`
|
||||
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.<typo>`는 아무것도 바인딩하지 않고 아무것도 실패시키지
|
||||
않았다. 이제 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 방어는 있고 맞지만 우회된다. 그래서
|
||||
이 조합은 지킬 수 없는 보장을 단 채 내주지 않고 거부한다.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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과 원격 오류 본문은 절대 속성으로 기록하지 않는다.
|
||||
|
||||
@@ -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에서 잰 숫자를 인증한 기준선처럼 내놓는 것은 기준선이 없는
|
||||
것보다 나쁘다.
|
||||
|
||||
@@ -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가 자동 구성하는 일은 없다.
|
||||
|
||||
@@ -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 의미.
|
||||
|
||||
@@ -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 허가도
|
||||
잡지 않는다.
|
||||
|
||||
+46
-53
@@ -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로만
|
||||
나온다.
|
||||
|
||||
@@ -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 호출만 돌린다.
|
||||
|
||||
@@ -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 상한을 단언한다. 지연 숫자는 단언하지 않는다 |
|
||||
|
||||
@@ -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는 데이터는 맞지만 성능 증거는 거짓이고, 그것은 기동이나
|
||||
호출 실패보다 알아채기 어렵다.
|
||||
|
||||
@@ -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<T, ID>` 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<T, ID>`도 플랫폼 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 타입 인자까지 확인한다.
|
||||
|
||||
@@ -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.
|
||||
막힌 상태 둘을 나누는 이유는 필요한 일이 달라서다. 하나는 증거가, 다른 하나는 결정이 필요하다.
|
||||
|
||||
@@ -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가 해야 할 것을 계속 단언한다. 배포가 돌리는 것이 그것이기 때문이다.
|
||||
|
||||
+131
-164
@@ -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.
|
||||
시나리오마다 스키마 버전만이 아니라 데이터 불변식을 단언한다. 열 이름을 바꾸면서 내용을 잃은 마이그레이션은 버전은 맞고
|
||||
데이터는 사라진 채로 남는다.
|
||||
|
||||
+35
-44
@@ -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가 된다.
|
||||
|
||||
@@ -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 뒤에 둘 것이 아니다.
|
||||
|
||||
@@ -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의 전형적인
|
||||
메모리 부족이다.
|
||||
|
||||
+102
-120
@@ -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=<major>`로 고른다. 계약 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<T, ID>` 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<T, ID>`도,
|
||||
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에 지웠다.
|
||||
|
||||
+50
-63
@@ -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 <invalid_index>;` 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 <invalid_index>;`를 돌리고, 인덱스 마이그레이션을
|
||||
다시 적용한다.
|
||||
|
||||
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 보장을 하나도 지킬 수 없다.
|
||||
|
||||
+33
-36
@@ -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.
|
||||
값은 늘 묶는다. 식별자는 늘 등록한다.
|
||||
|
||||
+81
-95
@@ -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).
|
||||
- 완료를 모르는 트랜잭션의 자동 맞추기. 플랫폼은 기록하고, 도메인이 푼다.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 테스트 결과에 생성된 테스트 클래스가 실행·통과로 남았는지 확인
|
||||
-> 임시 디렉터리 삭제
|
||||
```
|
||||
|
||||
@@ -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는 이 중 아무것도 인증하지 못한다. 아무것도 거부하지 않기 때문이다.
|
||||
|
||||
@@ -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<MongoTenantContext>` 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<MongoTenantContext>`를 받는다.
|
||||
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이다.
|
||||
|
||||
@@ -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이다.
|
||||
|
||||
@@ -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.
|
||||
여기 있는 파일은 검토를 했다고 주장한다. 검토 없이 파일만 더하는 것이 이 방식의 실패 모드다. 그것은
|
||||
검토 절차의 문제이고, 어떤 스크립트도 차이를 알 수 없다.
|
||||
|
||||
@@ -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을 잡음
|
||||
발생기로 만든다.
|
||||
|
||||
@@ -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에서도
|
||||
같은 뜻이다. 명령의 바이트 상한은 무엇이든 보내기 전에 그렇게 변환한 문서로 잰다.
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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<T, ID>` 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<T, ID>`는 명시적으로 지원하지 않는 목록(§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.
|
||||
모두 지금은 싸고, 나중에는 마이그레이션이다.
|
||||
|
||||
@@ -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)).
|
||||
|
||||
@@ -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`로 돌리거나, 이름으로 하나씩 돌린다.
|
||||
|
||||
@@ -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`가 되어
|
||||
시험하려던 「결과를 모름」과 정반대가 된다.
|
||||
|
||||
@@ -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 결과를 모를 때 본문을 다시 돌리지 않음을 단언한다.
|
||||
|
||||
@@ -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를 되돌리면 아직 절반의 인스턴스에서 도는 코드가 깨진다.
|
||||
|
||||
@@ -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 `<redacted>` — 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*`)은 `<redacted>`로 보인다. 인자에 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`가 서버가 방금 거부한 바로 그 권한을 이름으로 대는지 본다.
|
||||
|
||||
@@ -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<T, ID>`.
|
||||
- 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<T, ID>`.
|
||||
- 실행 중 임의의 `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`).
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
<!-- 머리 블록: 이 블록을 빼면 원문이다. 형식은 docs/README.md 「기록 문서의 머리 블록」 -->
|
||||
> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다.
|
||||
|
||||
- 상태: 채택
|
||||
- 작성일: 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.
|
||||
@@ -1,34 +0,0 @@
|
||||
<!-- 머리 블록: 이 블록을 빼면 원문이다. 형식은 docs/README.md 「기록 문서의 머리 블록」 -->
|
||||
> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다.
|
||||
|
||||
- 상태: 채택
|
||||
- 작성일: 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.
|
||||
@@ -1,46 +0,0 @@
|
||||
<!-- 머리 블록: 이 블록을 빼면 원문이다. 형식은 docs/README.md 「기록 문서의 머리 블록」 -->
|
||||
> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다.
|
||||
|
||||
- 상태: 채택
|
||||
- 작성일: 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.
|
||||
@@ -1,36 +0,0 @@
|
||||
<!-- 머리 블록: 이 블록을 빼면 원문이다. 형식은 docs/README.md 「기록 문서의 머리 블록」 -->
|
||||
> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다.
|
||||
|
||||
- 상태: 채택
|
||||
- 작성일: 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.
|
||||
@@ -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<String, Object>` 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<String, Object>`보다 확실히 낫다. 그러나 `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으로 둔다.
|
||||
|
||||
@@ -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를 위한 것이다.
|
||||
|
||||
@@ -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_<ID>_<FIELD>`).
|
||||
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_<ID>_<FIELD>`)으로 줄 수 있다. 내보내는 참조 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)를 본다.
|
||||
|
||||
@@ -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`를 주장할 수 없고, 어떤 제출 결과도
|
||||
전달 결과를 실을 수 없다.
|
||||
|
||||
@@ -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`의 「제거된 코드」 표에 있다.
|
||||
|
||||
@@ -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` 「제거된 코드」에 있다.
|
||||
|
||||
@@ -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 런타임 상태와 세대, 큐 깊이와 나이, 콜백과 맞추기 상태. 주소와 자격 증명은 절대 싣지 않는다.
|
||||
|
||||
@@ -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을
|
||||
여기에 함께 쓴다.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user