From c91cc3fb10128a36dfc32b4fc2646fca84a29a67 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 7 Nov 2026 17:07:16 +0900 Subject: [PATCH 1/6] =?UTF-8?q?docs(core):=20core=C2=B7=EC=A1=B0=EB=A6=BD?= =?UTF-8?q?=C2=B7=EB=B9=8C=EB=93=9C=C2=B7=ED=94=8C=EB=9E=AB=ED=8F=BC=20?= =?UTF-8?q?=EB=AA=A8=EB=93=88=20=EB=AC=B8=EC=84=9C=EB=A5=BC=20=ED=95=9C?= =?UTF-8?q?=EA=B5=AD=EC=96=B4=EB=A1=9C=20=EC=98=AE=EA=B8=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: core 계층(application·domain·shared-contract), app-bootstrap, composition, registry, build-logic, optional 빌드의 모듈 문서가 영어다. 세션이 처음 읽는 지역 규칙인데 소유자는 2026-11-07에 살아 있는 문서를 모두 한국어로 쓰기로 정했다. leaf CLAUDE.md 셋은 Spring Boot 버전을 4.0.0으로 복사해 두었는데 실제 버전(libs.versions.toml)과 다르다. 방법: 뜻을 그대로 옮기고 코드·명령·경로·식별자·표 구조는 원문으로 둔다. 버전은 `src/gradle/libs.versions.toml`을 가리키는 말로 바꾼다. 다른 문서·코드가 제목으로 가리키는 절(application-core의 Naming convention·Package ownership·Canonical use case shape·Allowed transactional shapes, shared-contract의 Responsibility·Forbidden, messaging의 발행 재시도 절)은 영어 원제를 괄호로 남겨 그 참조가 계속 찾아지게 한다. 참조하는 쪽을 고치는 것은 이 작업 범위 밖이다. 코드와 어긋난 주장은 코드에 맞춘다: TransactionPort 구현을 `adapter-persistence`에서 `adapter:outbound:persistence-jpa`의 `SpringTransaction`으로, registry README의 빈 의존 목록 예를 persistence-mongo(실제 목록은 application-core·shared-contract)에서 domain-core·shared-contract·messaging-core-api로 고친다. TemplatePackageOwnershipDocumentTest는 표 머리 문자열로 표를 찾으므로 머리 상수를 한국어 머리(`| 패키지 (...) |`)로 맞춘다. 표와 기계 사본을 대조하는 계약은 그대로다. 위험: 영어 원제를 괄호로 남긴 제목은 참조하는 문서가 한국어 제목으로 바뀌면 괄호를 지울 수 있다. 본문의 짧은 이력 번호(07-08, 06-01, 11-M9)는 뜻을 바꾸지 않으려고 그대로 옮겼다. 검증: python3 scripts/check-docs.py rc=0(번역한 파일의 language 줄 8개, number 줄 3개 지움), check-work-docs.py rc=0, --links(gates.md 범위) 깨진 링크 0, unittest discover scripts/tests 43개 통과. --- scripts/check-docs-exceptions.txt | 11 - src/app-bootstrap/CLAUDE.md | 205 ++++---- .../TemplatePackageOwnershipDocumentTest.java | 6 +- src/application-core/CLAUDE.md | 475 +++++++++--------- src/build-logic/README.md | 94 ++-- src/composition/outbox-relay/CLAUDE.md | 32 +- src/config/architecture/README.md | 21 +- src/domain-core/CLAUDE.md | 42 +- src/platforms/grpc-advanced/CLAUDE.md | 4 +- src/platforms/grpc/CLAUDE.md | 99 ++-- src/platforms/messaging/CLAUDE.md | 6 +- src/platforms/optional-build/README.md | 12 +- src/shared-contract/CLAUDE.md | 116 +++-- 13 files changed, 540 insertions(+), 583 deletions(-) diff --git a/scripts/check-docs-exceptions.txt b/scripts/check-docs-exceptions.txt index 1bff4f87..08f57e77 100644 --- a/scripts/check-docs-exceptions.txt +++ b/scripts/check-docs-exceptions.txt @@ -169,15 +169,7 @@ language src/adapter/outbound/persistence-notification/CLAUDE.md language src/adapter/outbound/redis-sdk/README.md language src/adapter/outbound/redis-sdk/compose/README.md language src/adapter/outbound/support/CLAUDE.md -language src/app-bootstrap/CLAUDE.md language src/app-bootstrap/src/test/resources/developer-experience/broken-readme.md -language src/application-core/CLAUDE.md -language src/build-logic/README.md -language src/composition/outbox-relay/CLAUDE.md -language src/config/architecture/README.md -language src/domain-core/CLAUDE.md -language src/platforms/optional-build/README.md -language src/shared-contract/CLAUDE.md # 참조: 지금 트리·registry에 없는 경로. 고치거나 「> 이력」 인용 블록으로 옮기면 지운다. reference AGENTS.md src/build-tools/ @@ -214,6 +206,3 @@ number src/adapter/outbound/objectstorage/CLAUDE.md Spring Boot 4.0.0 number src/adapter/outbound/persistence-jpa/CLAUDE.md Spring Boot 4.0.0 number src/adapter/outbound/persistence-mongo/CLAUDE.md Spring Boot 4.0.0 number src/adapter/outbound/support/CLAUDE.md Spring Boot 4.0.0 -number src/app-bootstrap/CLAUDE.md Spring Boot 4.0.0 -number src/domain-core/CLAUDE.md Spring Boot 4.0.0 -number src/shared-contract/CLAUDE.md Spring Boot 4.0.0 diff --git a/src/app-bootstrap/CLAUDE.md b/src/app-bootstrap/CLAUDE.md index e12f76f1..3ec72357 100644 --- a/src/app-bootstrap/CLAUDE.md +++ b/src/app-bootstrap/CLAUDE.md @@ -1,125 +1,118 @@ -# app-bootstrap — application entry point & composition root +# app-bootstrap — 애플리케이션 진입점과 조립 루트 -## Registered identity +## 등록 정보 -- Module ID: `app-bootstrap` -- Gradle path: `:app-bootstrap` -- Focused test (derived from Gradle path): `./gradlew :app-bootstrap:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `app-bootstrap` +- Gradle 경로: `:app-bootstrap` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :app-bootstrap:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.bootstrap`. +패키지 루트: `dev.caskeleton.bootstrap`. -## Responsibility +## 책임 -- Spring Boot entrypoint (`CaSkeletonApplication`). -- Runtime settings and logging bootstrap. -- Final cross-module wiring. -- Architecture tests that inspect all modules. +- Spring Boot 진입점(`CaSkeletonApplication`). +- 런타임 설정과 로깅 시작. +- 모듈을 가로지르는 마지막 배선. +- 모든 모듈을 들여다보는 아키텍처 시험. -## Allowed +## 허용 -- Runtime leaves explicitly declared by this module's Gradle dependencies and permitted by the - architecture registry. The resolved Gradle runtime graph is the runtime SSOT; do not duplicate a - membership list in metadata. -- Spring Boot startup/runtime dependencies. -- ArchUnit in tests. +- 이 모듈의 Gradle 의존성이 분명히 선언하고 아키텍처 registry가 허용한 런타임 leaf. 해석된 Gradle + runtime 그래프가 런타임의 정본이다. 구성원 목록을 metadata에 다시 적지 않는다. +- Spring Boot 시작·런타임 의존성. +- 시험에서 ArchUnit. -## Forbidden +## 금지 -- Concrete business policy. -- Controllers, use cases, repository adapters, or mappers authored directly under bootstrap. -- Settings classes that implement business logic. -- Implementing an `application-core` or `domain-core` port. A class that implements one is an - outbound adapter and belongs in an `adapter/outbound/*` leaf, however its dependencies are - configured — `CompositionRootBoundaryArchitectureTest` enforces this, with no exceptions. -- Raising a startup failure with `throw new IllegalStateException(...)`. Use `StartupFailures` - (`adapter:outbound:support`, package `support.startup`: `envValidation` / `profileMismatch` / - `requiredAdapterDisabled` / `migrationFailed`), so the - failure carries its sysexits exit code and structured log fields — - `StartupFailureContractArchitectureTest` enforces this. -- Answering "is this production?" locally. `dev.caskeleton.shared.runtime.RuntimeEnvironment` owns - the profile vocabulary for the whole repository. -- Depending on `org.testcontainers` from `src/test`. Real-service tests belong to - `src/integrationTest`; see `docs/testing/TESTING_STRATEGY.md`. +- 구체적인 업무 정책. +- bootstrap 아래에 직접 쓴 controller, 유스케이스, repository 어댑터, mapper. +- 업무 로직을 구현하는 설정 클래스. +- `application-core`나 `domain-core` 포트를 구현하기. 포트를 구현하는 클래스는 의존성을 어떻게 + 설정했든 outbound 어댑터이고 `adapter/outbound/*` leaf에 둔다 — + `CompositionRootBoundaryArchitectureTest`가 예외 없이 강제한다. +- 기동 실패를 `throw new IllegalStateException(...)`으로 내기. `StartupFailures` + (`adapter:outbound:support`, 패키지 `support.startup`: `envValidation` / `profileMismatch` / + `requiredAdapterDisabled` / `migrationFailed`)를 써서 실패가 sysexits 종료 코드와 구조화된 로그 + 필드를 싣게 한다 — `StartupFailureContractArchitectureTest`가 강제한다. +- 「운영 환경인가?」를 이 모듈 안에서 답하기. 저장소 전체의 profile 어휘는 + `dev.caskeleton.shared.runtime.RuntimeEnvironment`가 가진다. +- `src/test`에서 `org.testcontainers`에 의존하기. 실제 서비스를 쓰는 시험은 `src/integrationTest`에 + 둔다. `docs/testing/TESTING_STRATEGY.md`를 본다. -## Package layout +## 패키지 배치 -The rules below exist because their absence is what produced the drift this module was reviewed for -(`docs/reviews/2026-09-07-app-bootstrap-module-code-review.md`). Half the -capabilities lived under `autoconfigure/` and half at the package root; `Settings` classes were split -between a `settings/` package and their feature packages with no stated rule; and the same -decomposition problem was solved two different ways in the same leaf — Notification as nine focused -configurations, Redis as one 376-line class. +아래 규칙은 그것이 없어서 이 모듈의 리뷰 대상이 된 어긋남이 생겼기 때문에 있다 +(`docs/reviews/2026-09-07-app-bootstrap-module-code-review.md`). capability의 절반은 `autoconfigure/` +아래, 절반은 패키지 루트에 있었다. `Settings` 클래스는 규칙 없이 `settings/` 패키지와 각 기능 +패키지에 나뉘어 있었다. 그리고 같은 분해 문제를 같은 leaf에서 두 가지로 풀었다 — Notification은 작은 +설정 아홉 개로, Redis는 376줄 클래스 하나로. -- **A capability's assembly lives in the capability's own module**, registered by that module's - `AutoConfiguration.imports`, with its settings in the module's `config/module-defaults/*.yml`. - JPA (startup guards, Flyway strategy, lock decorator, readiness and full-off handling in - `JpaActivationEnvironmentPostProcessor`) is `adapter:outbound:persistence-jpa`; Redis (readiness) is - `adapter:outbound:cache-redis`; notification is `composition:notification-platform`. Every - capability is a commented `runtimeOnly` line in `build.gradle`; the default composition is web, - observability, the cores, support and identifier. This leaf keeps no list of capabilities: no - switch registry, no cross-capability dependency validator, no activation endpoint. Component scan - covers `dev.caskeleton.bootstrap` only; web (`WebAdapterAutoConfiguration`, `WebSecurityAutoConfiguration`, `WebMethodSecurityAutoConfiguration`) and support - (`OutboundSupportConfig`) arrive through their own `AutoConfiguration.imports`. What stays in `autoconfigure//` is application - composition every application needs: `common` (the clock). The outbox relay, the idempotency - executor and the durable operations (use cases and `/operations` endpoints, 07-08) are - `composition:outbox-relay`, `composition:idempotency` and `composition:durable-operation`, selected - by one `runtimeOnly` line each and building nothing until their ports exist. A capability's role→permission mapping ships in its own - `config/module-defaults` file, not in `config/security.yml`. The runtime wiring every composition root needs — - tracing, the metrics contract filters, domain-context propagation, user-principal pseudonymization - (`PrivacySettings`) and the actuator chain — is `composition:service-runtime`. -- **`Settings` lives beside its capability**, not in `settings/`. The `settings/` package - holds only settings that belong to no capability — `BootstrapSettings`, `RuntimeSafetySettings` — - bound strictly with `StrictSettingsBinder`, never scanned. Logging has no settings record: - `logback-spring.xml` reads `app.logging.*` itself and `LoggingConfigurationRule` refuses values - Logback cannot use. -- **`runtime/` holds guards about the application itself** — secrets, numeric bounds, error-detail - exposure, multi-instance coordination, the runtime-profile check (`RuntimeEnvironmentProfileValidator`). - A guard about a capability's settings (the JPA OSIV/DDL/pool/TLS/vendor guards, the Mongo - connection-source rule, the GraphQL deployment-mode rule) ships with that capability's module, so - it exists exactly when the capability does. -- **The startup failure vocabulary lives in `adapter:outbound:support`** (`support.startup`: phases, - error codes, exceptions, `StartupFailures`, `StartupValidationContext`, `StartupOrder`, - `ReadinessGroup`, `RuntimeWarnings`), so capability modules fail the same way without depending on - this leaf. `runtime/startup/` keeps only `StartupFailureExceptionReporter`. -- **An environment-only guard is a `StartupRule` bean** (`support.startup`): it returns violations, - and the one `StartupRuleRunner` raises them before any other singleton exists (declare it with a - `static` `@Bean` method that takes only the `Environment`, the bean factory or an `ObjectProvider` - of static `RequiredProductionSecrets`; in every profile the runner creates each rule and each - `RequiredProductionSecrets` before any rule runs, and fails the boot naming any other bean one of - them creates, and naming any whose runtime class has an `@Value`/`@Autowired`/ - `@Inject`/`@Resource` member, a `@PostConstruct`/`@PreDestroy` callback or a - `@ConfigurationProperties` binding — those are created before the post-processors and would stay - unset). A guard that needs another bean stays a bean. A - capability's production secrets are the capability's: its module contributes a - `RequiredProductionSecrets` bean, and `SecretSourceValidator` checks the names without knowing - which roles exist. +- **capability의 조립은 그 capability 자신의 모듈에 있다.** 그 모듈의 `AutoConfiguration.imports`가 + 등록하고, 설정은 그 모듈의 `config/module-defaults/*.yml`에 둔다. JPA(기동 guard, Flyway 전략, + lock decorator, readiness, `JpaActivationEnvironmentPostProcessor`의 완전히 끄기 처리)는 + `adapter:outbound:persistence-jpa`, Redis(readiness)는 `adapter:outbound:cache-redis`, 알림은 + `composition:notification-platform`이다. 모든 capability는 `build.gradle`에서 주석 처리한 + `runtimeOnly` 한 줄이다. 기본 조립은 web, 관측, core들, support, identifier다. 이 leaf는 capability + 목록을 두지 않는다: 스위치 registry도, capability 사이 의존 검증기도, 켜기 endpoint도 없다. + component scan은 `dev.caskeleton.bootstrap`만 본다. web(`WebAdapterAutoConfiguration`, + `WebSecurityAutoConfiguration`, `WebMethodSecurityAutoConfiguration`)과 support + (`OutboundSupportConfig`)는 자기 `AutoConfiguration.imports`로 들어온다. `autoconfigure//`에 + 남는 것은 모든 애플리케이션에 필요한 애플리케이션 조립인 `common`(시계)뿐이다. outbox relay, + 멱등성 executor, durable operation(유스케이스와 `/operations` endpoint, 07-08)은 + `composition:outbox-relay`, `composition:idempotency`, `composition:durable-operation`이다. 각각 + `runtimeOnly` 한 줄로 고르고, 자기 포트가 생기기 전에는 아무것도 만들지 않는다. capability의 + role → permission 대응은 `config/security.yml`이 아니라 그 capability의 `config/module-defaults` + 파일에 담긴다. 모든 조립 루트에 필요한 런타임 배선 — tracing, metric 계약 filter, domain-context + 전파, 사용자 principal 가명화(`PrivacySettings`), actuator chain — 은 `composition:service-runtime`이다. +- **`Settings`는 `settings/`가 아니라 그 capability 옆에 둔다.** `settings/` 패키지는 + 어느 capability에도 속하지 않는 설정 — `BootstrapSettings`, `RuntimeSafetySettings` — 만 담는다. + 이 설정은 `StrictSettingsBinder`로 엄격하게 바인딩하고 scan하지 않는다. 로깅에는 settings record가 + 없다. `logback-spring.xml`이 `app.logging.*`을 직접 읽고 `LoggingConfigurationRule`이 Logback이 쓸 + 수 없는 값을 거절한다. +- **`runtime/`은 애플리케이션 자체에 대한 guard를 담는다** — 비밀 값, 숫자 한계, 오류 상세 노출, + 여러 인스턴스 조율, runtime profile 검사(`RuntimeEnvironmentProfileValidator`). capability 설정에 + 대한 guard(JPA OSIV·DDL·pool·TLS·vendor guard, Mongo 연결 출처 규칙, GraphQL 배포 모드 규칙)는 그 + capability의 모듈과 함께 나간다. 그래야 capability가 있을 때만 정확히 존재한다. +- **기동 실패 어휘는 `adapter:outbound:support`에 있다**(`support.startup`: phase, 오류 코드, 예외, + `StartupFailures`, `StartupValidationContext`, `StartupOrder`, `ReadinessGroup`, `RuntimeWarnings`). + 그래서 capability 모듈은 이 leaf에 의존하지 않고 같은 방식으로 실패한다. `runtime/startup/`에는 + `StartupFailureExceptionReporter`만 남는다. +- **환경만 보는 guard는 `StartupRule` bean이다**(`support.startup`). 위반을 돌려주고, 유일한 + `StartupRuleRunner`가 다른 singleton이 생기기 전에 그것을 올린다(`Environment`, bean factory, 정적 + `RequiredProductionSecrets`의 `ObjectProvider`만 받는 `static` `@Bean` 메서드로 선언한다. 모든 + profile에서 runner는 어떤 규칙을 돌리기 전에 규칙마다, 그리고 `RequiredProductionSecrets`마다 하나씩 + 만든다. 그중 하나가 만드는 다른 bean이 있으면 그 이름을 대며 기동을 실패시킨다. runtime 클래스에 + `@Value`/`@Autowired`/`@Inject`/`@Resource` 멤버, `@PostConstruct`/`@PreDestroy` 콜백, + `@ConfigurationProperties` 바인딩이 있는 것도 이름을 대며 실패시킨다 — 그런 것은 post-processor보다 + 먼저 만들어져 값이 비어 있게 된다). 다른 bean이 필요한 guard는 bean으로 남는다. capability의 운영 + 비밀 값은 그 capability의 것이다: 그 모듈이 `RequiredProductionSecrets` bean을 내놓고, + `SecretSourceValidator`는 어떤 role이 있는지 모르는 채로 이름을 검사한다. -## Decomposition threshold +## 분해 기준 -State it rather than leaving it to taste, because "it felt long enough" is what produced two -different answers for the same question. +취향에 맡기지 않고 적어 둔다. 「충분히 길다고 느꼈다」가 같은 질문에 두 가지 답을 낳았기 때문이다. -- One `@Configuration` holds one assembly concern. Split when it passes roughly **eight `@Bean` - methods**, or as soon as it assembles two unrelated port families — whichever comes first. -- One `@ConfigurationProperties` class owns one capability namespace. -- A capability that needs more than one configuration gets a root class holding its `enabled` - condition, `@EnableConfigurationProperties`, and an `@Import` of the per-concern classes. Scan - nothing: `@Import` from a gated root is what keeps `enabled=false` load-bearing rather than advisory. - `cache-redis`'s `capability/RedisCapabilityConfig` is the reference example. Optional adapter - capabilities that own reusable Spring composition publish their own root instead. Notification - uses `adapter:outbound:notification`'s `NotificationPlatformAutoConfiguration` plus - `composition:notification-platform`'s `NotificationApplicationCompositionAutoConfiguration`; JPA uses the - package-private `PersistenceJpaAutoConfiguration`, `PersistenceJpaRuntimeConfig` and - `startup.JpaStartupAutoConfiguration` from `adapter:outbound:persistence-jpa`, which is not in the - default composition (`// runtimeOnly project(':adapter:outbound:persistence-jpa')` in - `build.gradle`). - Mongo follows the same rule: the persistence-mongo leaf owns MongoRootAutoConfiguration and its internal health bridge; bootstrap owns no Mongo-specific production health configuration. -- Shared helpers of a split capability get their own type named for what they are, not a `*Util` - bucket — `cache-redis`'s `capability/RedisKeys` is the reference. +- `@Configuration` 하나는 조립 관심사 하나를 담는다. 대략 **`@Bean` 메서드 여덟 개**를 넘거나, 서로 + 관계없는 포트 묶음 둘을 조립하게 되면 — 둘 중 먼저 오는 때에 — 나눈다. +- `@ConfigurationProperties` 클래스 하나는 capability namespace 하나를 가진다. +- 설정이 둘 이상 필요한 capability는 루트 클래스를 둔다. 루트가 `enabled` 조건, + `@EnableConfigurationProperties`, 관심사별 클래스의 `@Import`를 가진다. 아무것도 scan하지 않는다: + 조건이 걸린 루트에서 `@Import`해야 `enabled=false`가 권고가 아니라 실제로 끄는 스위치가 된다. + `cache-redis`의 `capability/RedisCapabilityConfig`가 참조 예다. 다시 쓸 Spring 조립을 가진 optional + 어댑터 capability는 자기 루트를 내놓는다. 알림은 `adapter:outbound:notification`의 + `NotificationPlatformAutoConfiguration`과 `composition:notification-platform`의 + `NotificationApplicationCompositionAutoConfiguration`을 쓴다. JPA는 + `adapter:outbound:persistence-jpa`의 package-private `PersistenceJpaAutoConfiguration`, + `PersistenceJpaRuntimeConfig`, `startup.JpaStartupAutoConfiguration`을 쓰고, 이 모듈은 기본 조립에 + 없다(`build.gradle`의 `// runtimeOnly project(':adapter:outbound:persistence-jpa')`). + Mongo도 같은 규칙을 따른다: persistence-mongo leaf가 MongoRootAutoConfiguration과 그 내부 health + bridge를 가지고, bootstrap은 Mongo 전용 운영 health 설정을 가지지 않는다. +- 나눈 capability의 공용 도우미는 `*Util` 바구니가 아니라 하는 일을 이름으로 단 자기 타입을 가진다 — + `cache-redis`의 `capability/RedisKeys`가 참조 예다. -## Test +## 테스트 ```bash cd src diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/architecture/TemplatePackageOwnershipDocumentTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/architecture/TemplatePackageOwnershipDocumentTest.java index 508b7d22..137c5a94 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/architecture/TemplatePackageOwnershipDocumentTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/architecture/TemplatePackageOwnershipDocumentTest.java @@ -31,8 +31,8 @@ class TemplatePackageOwnershipDocumentTest { private static final String RULE_BOOK = "src/application-core/CLAUDE.md"; private static final String REGISTRY = "src/config/architecture/modules.json"; - private static final String APPLICATION_TABLE = "| Package (`dev.caskeleton.application.*`) |"; - private static final String DOMAIN_TABLE = "| Package (`dev.caskeleton.domain.*`) |"; + private static final String APPLICATION_TABLE = "| 패키지 (`dev.caskeleton.application.*`) |"; + private static final String DOMAIN_TABLE = "| 패키지 (`dev.caskeleton.domain.*`) |"; private static final Pattern PACKAGE_NAME = Pattern.compile("`([a-z][a-z0-9]*)`"); private final Path root = RepositoryContractResources.fromSystemProperty().repositoryRoot(); @@ -83,7 +83,7 @@ class TemplatePackageOwnershipDocumentTest { // then assertThat(missing) .as( - "packages %s lists are not in the leaf its \"Owning leaf\" column names; a package was" + "packages %s lists are not in the leaf its \"소유 leaf\" column names; a package was" + " moved or removed without the table (and TemplatePackageOwnership) following it", RULE_BOOK) .isEmpty(); diff --git a/src/application-core/CLAUDE.md b/src/application-core/CLAUDE.md index 0d8b3171..fb6ecce2 100644 --- a/src/application-core/CLAUDE.md +++ b/src/application-core/CLAUDE.md @@ -1,180 +1,173 @@ -# application-core — application use cases +# application-core — 애플리케이션 유스케이스 -## Registered identity +## 등록 정보 -- Module ID: `application-core` -- Gradle path: `:application-core` -- Focused test (derived from Gradle path): `./gradlew :application-core:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: the Spring Boot 4.x version pinned by the shared version catalog. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `application-core` +- Gradle 경로: `:application-core` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :application-core:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준은 공용 버전 카탈로그(`src/gradle/libs.versions.toml`)가 고정한 Spring Boot 4.x다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.application`. +패키지 루트: `dev.caskeleton.application`. 코드 주석에서 덜어낸 **설계 결정의 근거**는 [README.md](README.md) 가 모아둔다 (이 문서는 모듈 규칙 SSOT). -## Responsibility +## 책임 (Responsibility) -- Use case inbound ports (`CommandUseCase`, `QueryUseCase`) and their command / query contracts. -- Outbound ports (`*Port` interfaces) the use cases depend on. -- Application exceptions and policy types. -- Coordinate domain models through ports. -- Own application transaction boundaries through the `TransactionPort` abstraction. -- Expose framework-free invocation context through ports such as `CorrelationIdPort`; adapters own - MDC or other concrete storage. -- Own the framework-free semantic integration-event draft, validated-event value contract and - exact typed payload contribution SPI. This is the messaging semantic contract R1 boundary only. +- 유스케이스 inbound 포트(`CommandUseCase`, `QueryUseCase`)와 그 command·query 계약. +- 유스케이스가 의존하는 outbound 포트(`*Port` 인터페이스). +- 애플리케이션 예외와 정책 타입. +- 포트를 거쳐 도메인 모델을 조율한다. +- `TransactionPort` 추상화로 애플리케이션 트랜잭션 경계를 가진다. +- `CorrelationIdPort` 같은 포트로 프레임워크 없는 호출 문맥을 내놓는다. MDC 같은 실제 저장소는 + 어댑터가 가진다. +- 프레임워크 없는 integration event 초안(semantic draft), 검증된 이벤트의 값 계약, 정확한 타입의 + payload를 내놓는 SPI를 가진다. 메시징 semantic contract R1 경계까지만이다. -## Allowed +## 허용 - `:domain-core` - `:shared-contract` -- Java standard library types. +- Java 표준 라이브러리 타입. -## Forbidden +## 금지 (Forbidden) -- `adapter-*` implementation classes. +- `adapter-*` 구현 클래스. - `app-bootstrap`. -- Controller request/response DTOs. -- JPA entities and Spring Data repositories. -- HTTP status, transport types (`org.springframework.web..`). -- `org.springframework.transaction.annotation.Transactional` (use `TransactionPort` instead). -- `org.springframework.context.ApplicationContext` — direct dependency forbidden - (`getBean(Class)` reflection-style bypass blocked by the ArchUnit rule `application_does_not_depend_on_application_context`). String-key - bean lookup / `Class.forName(String)` / `BeanFactory#getBeansOfType` remain - ArchUnit's static-analysis blind spot — guard via code review checklist. -- Lombok (`lombok..`) — also forbidden in `domain-core`. Within `application-core`, - Lombok is currently not in scope for the contract; if you intend to use it, - weigh the bytecode opacity cost first. -- Persistence-layer transaction annotations of any kind inside this module. -- Diagnostic frameworks (`org.slf4j`, `java.util.logging`, Logback, Log4j, Micrometer). Express - diagnostic intent through a specific outbound `*Port`; adapters own rendering. -- Messaging provider/runtime types: physical topic, Kafka record or metadata, JSON tree/raw JSON - payload, serializer/schema-validator implementation, security topology and publication epoch. +- controller의 요청·응답 DTO. +- JPA 엔티티와 Spring Data repository. +- HTTP 상태, 전송 타입(`org.springframework.web..`). +- `org.springframework.transaction.annotation.Transactional`(대신 `TransactionPort`를 쓴다). +- `org.springframework.context.ApplicationContext` — 직접 의존 금지 + (`getBean(Class)` 같은 리플렉션식 우회는 ArchUnit 규칙 `application_does_not_depend_on_application_context`가 막는다). 문자열 키로 + bean을 찾기, `Class.forName(String)`, `BeanFactory#getBeansOfType`은 ArchUnit 정적 분석이 + 보지 못하는 곳이다. 코드 리뷰 체크리스트로 막는다. +- Lombok(`lombok..`) — `domain-core`에서도 금지다. `application-core`에서는 지금 Lombok이 + 계약 범위에 없다. 쓰려면 바이트코드가 불투명해지는 비용을 먼저 따진다. +- 이 모듈 안의 영속 계층 트랜잭션 애너테이션은 종류를 가리지 않고 금지다. +- 진단 프레임워크(`org.slf4j`, `java.util.logging`, Logback, Log4j, Micrometer). 진단 의도는 + 전용 outbound `*Port`로 나타내고, 어떻게 남길지는 어댑터가 정한다. +- 메시징 provider·런타임 타입: 물리 topic, Kafka record나 metadata, JSON tree·raw JSON payload, + serializer·schema validator 구현, 보안 토폴로지, publication epoch. -## Contract types +## 계약 타입 -| Type | Purpose | +| 타입 | 용도 | |---|---| -| `usecase.UseCase` | Base type for inbound ports. Concrete inbound ports MUST extend `CommandUseCase` or `QueryUseCase`. | -| `usecase.CommandUseCase` | Inbound port for write use cases. Implementations MUST be annotated `@UseCaseCapability`. | -| `usecase.QueryUseCase` | Inbound port for read-only use cases. Implementations MUST declare `transactionMode = READ_ONLY` and `repositoryAccess = READ_REPOSITORY`. | -| `command.Command` | Marker for write intents. Plain immutable types built from domain values. | -| `query.Query` | Marker for read intents. Plain immutable types built from domain values. | -| `transaction.TransactionPort` | Outbound port for join-capable write/read, physical root-only write, and independent write boundaries. Implemented by `adapter-persistence`. | -| `secret.SecretSourcePort` | Framework-free outbound secret-resolution seam. Deployment selects a backend in app-bootstrap; concrete environment/cloud/vault readers belong to outbound adapter leaves. | -| `transaction.NestedRootTransactionRejectedException` | Fail-fast signal raised before action/provider side effects when `inRootWrite` detects an actual ambient transaction. | -| `transaction.TransactionMode` | `WRITE` / `READ_ONLY` / `REQUIRES_NEW`. `NESTED` and `NEVER` are intentionally absent. | -| `transaction.Isolation` | `READ_COMMITTED` (pinned default) / `REPEATABLE_READ` / `SERIALIZABLE`. `READ_UNCOMMITTED` is forbidden (not declared); the vendor default is never used (engine defaults differ — PostgreSQL READ COMMITTED vs MySQL InnoDB REPEATABLE READ). Routing the stricter levels through `TransactionPort` is a `planned` joint change with `feature-application-port-usecase-contract`; the shipped call path pins `READ_COMMITTED`. | -| `capability.UseCaseCapability` | Mandatory annotation on every concrete use case: declares `transactionMode`, `idempotency`, `repositoryAccess`, `externalOutboundAllowed`. | +| `usecase.UseCase` | inbound 포트의 기반 타입. 구체 inbound 포트는 반드시 `CommandUseCase`나 `QueryUseCase`를 상속한다. | +| `usecase.CommandUseCase` | 쓰기 유스케이스의 inbound 포트. 구현은 반드시 `@UseCaseCapability`를 단다. | +| `usecase.QueryUseCase` | 읽기 전용 유스케이스의 inbound 포트. 구현은 반드시 `transactionMode = READ_ONLY`와 `repositoryAccess = READ_REPOSITORY`를 선언한다. | +| `command.Command` | 쓰기 의도의 표지. 도메인 값으로 만든 평범한 불변 타입이다. | +| `query.Query` | 읽기 의도의 표지. 도메인 값으로 만든 평범한 불변 타입이다. | +| `transaction.TransactionPort` | 합류할 수 있는 쓰기·읽기, 물리 루트에서만 하는 쓰기, 독립 쓰기 경계를 내놓는 outbound 포트. `adapter:outbound:persistence-jpa`의 `SpringTransaction`이 구현한다. | +| `secret.SecretSourcePort` | 프레임워크 없는 outbound 비밀 해석 이음매. 배포가 app-bootstrap에서 backend를 고른다. 실제 환경 변수·클라우드·vault 리더는 outbound 어댑터 leaf에 둔다. | +| `transaction.NestedRootTransactionRejectedException` | `inRootWrite`가 실제로 열린 바깥 트랜잭션을 찾았을 때, action이나 provider 부작용 전에 바로 던지는 실패 신호. | +| `transaction.TransactionMode` | `WRITE` / `READ_ONLY` / `REQUIRES_NEW`. `NESTED`와 `NEVER`는 일부러 없다. | +| `transaction.Isolation` | `READ_COMMITTED`(고정 기본값) / `REPEATABLE_READ` / `SERIALIZABLE`. `READ_UNCOMMITTED`는 금지다(선언하지 않았다). vendor 기본값은 쓰지 않는다(엔진마다 기본값이 다르다 — PostgreSQL은 READ COMMITTED, MySQL InnoDB는 REPEATABLE READ). 더 엄격한 수준을 `TransactionPort`로 넘기는 일은 `feature-application-port-usecase-contract`와 함께 바꿀 `planned` 항목이다. 지금 호출 경로는 `READ_COMMITTED`로 고정한다. | +| `capability.UseCaseCapability` | 모든 구체 유스케이스에 반드시 다는 애너테이션: `transactionMode`, `idempotency`, `repositoryAccess`, `externalOutboundAllowed`를 선언한다. | | `capability.Idempotency` | `IDEMPOTENT` / `KEYED` / `NOT_IDEMPOTENT`. | | `capability.RepositoryAccess` | `NONE` / `READ_REPOSITORY` / `WRITE_REPOSITORY`. | -| `messaging.contract.IntegrationEventContractContribution

` | Closed exact-record payload type, canonical component order, local schema identity/hash and provider-neutral descriptor contribution. | -| `messaging.event.IntegrationEventDraft

` | Typed semantic event before local encoding; never JSON, Kafka or persistence state. Built only through `IntegrationEventDrafts` (`INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`). | -| `messaging.event.IntegrationEventDrafts` | The one way a feature builds a draft: contract id, version and destination from the contract, correlation from the request when canonical (else the event id), `SINGLE_TENANT_SCOPE` for a feature without tenants. | -| `messaging.event.IntegrationIdentity` | The one grammar and the length bounds of event, correlation/causation and aggregate ids. Test a value with `isCanonical(value, bound)`; never copy the pattern. | -| `messaging.event.ValidatedIntegrationEvent` | Stable semantic identities plus immutable exact encoded bytes and hashes, ready for a later durable append boundary. | -| `messaging.event.IntegrationEventEncoderPort` | Framework-free local draft-to-validated-event boundary implemented by an outbound adapter (the template's: `adapter:outbound:support` `JsonIntegrationEventEncoder`). | -| `outbox.OutboxAppendPort` | The one outbox append: a `ValidatedIntegrationEvent`, in the caller's write transaction. | -| `tenant.TenantId` | The tenant identifier and its one grammar (`[A-Za-z0-9][A-Za-z0-9_.-]{0,63}`); the web and GraphQL transport contexts both carry it. Built by a transport from verified authentication data only. | +| `messaging.contract.IntegrationEventContractContribution

` | 닫힌 정확한 record payload 타입, 정해진 component 순서, 로컬 schema identity·hash, provider 중립 descriptor 기여. | +| `messaging.event.IntegrationEventDraft

` | 로컬 인코딩 전의 타입 있는 semantic 이벤트. JSON·Kafka·영속 상태가 아니다. `IntegrationEventDrafts`로만 만든다(`INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`). | +| `messaging.event.IntegrationEventDrafts` | 기능이 초안을 만드는 유일한 길: contract id·version·destination은 contract에서, correlation은 요청 값이 정규형이면 그 값(아니면 event id), 테넌트가 없는 기능은 `SINGLE_TENANT_SCOPE`. | +| `messaging.event.IntegrationIdentity` | event id, correlation·causation id, aggregate id의 유일한 문법과 길이 한계. 값은 `isCanonical(value, bound)`로 시험한다. 패턴을 복사하지 않는다. | +| `messaging.event.ValidatedIntegrationEvent` | 안정된 semantic identity와 바뀌지 않는 정확한 인코딩 바이트·hash. 뒤의 durable append 경계로 넘길 준비가 된 값이다. | +| `messaging.event.IntegrationEventEncoderPort` | 프레임워크 없는 로컬 경계(초안 → 검증된 이벤트). outbound 어댑터가 구현한다(템플릿은 `adapter:outbound:support`의 `JsonIntegrationEventEncoder`). | +| `outbox.OutboxAppendPort` | 유일한 outbox append: `ValidatedIntegrationEvent` 하나를 호출자의 쓰기 트랜잭션 안에서 넣는다. | +| `tenant.TenantId` | 테넌트 식별자와 그 유일한 문법(`[A-Za-z0-9][A-Za-z0-9_.-]{0,63}`). web과 GraphQL 전송 문맥이 모두 이 값을 싣는다. 전송 계층이 검증된 인증 데이터로만 만든다. | -## Notification (NOTIF-ADR-005) +## 알림 (NOTIF-ADR-005) -None of the notification types are in this leaf. `..notification.platform..` and the simple -`NotificationPort`, `Notification` and `NotificationChannel` directly under -`dev.caskeleton.application.notification` all belong to leaf `application-notification`; the shared -package prefix is the only link. The R1 orchestration types were removed on 2026-09-25. +알림 타입은 이 leaf에 하나도 없다. `..notification.platform..`과 +`dev.caskeleton.application.notification` 바로 아래의 단순한 `NotificationPort`, `Notification`, +`NotificationChannel`은 모두 leaf `application-notification`의 것이다. 패키지 접두어가 같은 것이 +유일한 연결이다. R1 조율 타입은 2026-09-25에 지웠다. -## Naming convention +## 이름 규칙 (Naming convention) -This section is the repository's naming rule book. `NamingConventionTest` (app-bootstrap -architectureTest) enforces the machine-checkable rows; the rest are review rules, and a review checks -them against this table. A new feature follows the "new code" column; the "existing exceptions" are -named so nobody copies them by accident. +이 절이 저장소의 이름 규칙 정본이다. 기계로 볼 수 있는 행은 `NamingConventionTest`(app-bootstrap +architectureTest)가 강제한다. 나머지는 리뷰 규칙이고, 리뷰가 이 표와 대조한다. 새 기능은 「새 코드」 +열을 따른다. 「이미 있는 예외」는 누가 실수로 따라 하지 않게 이름을 적어 둔 것이다. -| Role | Name | Where | Existing exceptions (do not copy) | +| 역할 | 이름 | 위치 | 이미 있는 예외(따라 하지 않는다) | |---|---|---|---| -| Use case (inbound port implementation) | `UseCase`, enforced by ArchUnit | `application` package of the feature | `*ApplicationUseCase` (application-fileserver, application-notification), `*Service` (notification, fileserver) | -| Command / query record | `*Command` / `*Query` | next to its use case | — | -| Aggregate persistence (stores and returns whole aggregates) | `Repository` | **domain** package of the aggregate, owned by the domain | — | -| Technical store the application owns (outbox, idempotency, operation rows) | `StorePort` | application package | `*WritePort` (old onboarding fixture, removed) | -| Read model that returns projections, not aggregates | `QueryPort` | application package; returns projections only (ArchUnit) | — | -| Any other outbound port | `Port` | application package | — | -| Server-assigned id generation | `IdFactory extends IdFactory<Id>` | domain package; the id record `implements ResourceId` | `OutboxEventIdFactory` (sample; event ids are not resource ids) | -| Configuration binding | `*Settings` (operational) or `*Policy` (authorization / domain policy), enforced by ArchUnit | the leaf that binds it | — | -| Throwable | `*Exception`, enforced by ArchUnit | — | — | -| Contract test kit for a port | abstract `Contract` in the port owner's testFixtures; the fake's and each adapter's test extend it | testFixtures | value-type tests were once named `*ContractTest`; they are `*ValueTypesTest` now | +| 유스케이스(inbound 포트 구현) | `UseCase`, ArchUnit이 강제 | 기능의 `application` 패키지 | `*ApplicationUseCase`(application-fileserver, application-notification), `*Service`(notification, fileserver) | +| command·query record | `*Command` / `*Query` | 그 유스케이스 옆 | — | +| aggregate 영속(aggregate 전체를 저장하고 돌려준다) | `Repository` | aggregate의 **domain** 패키지, 도메인이 가진다 | — | +| 애플리케이션이 가진 기술 저장소(outbox, 멱등성, operation 행) | `StorePort` | application 패키지 | `*WritePort`(옛 onboarding fixture, 지움) | +| aggregate가 아니라 projection을 돌려주는 읽기 모델 | `QueryPort` | application 패키지. projection만 돌려준다(ArchUnit) | — | +| 그 밖의 outbound 포트 | `Port` | application 패키지 | — | +| 서버가 정하는 id 생성 | `IdFactory extends IdFactory<Id>` | domain 패키지. id record는 `implements ResourceId` | `OutboxEventIdFactory`(샘플. event id는 resource id가 아니다) | +| 설정 바인딩 | `*Settings`(운영) 또는 `*Policy`(인가·도메인 정책), ArchUnit이 강제 | 그것을 바인딩하는 leaf | — | +| Throwable | `*Exception`, ArchUnit이 강제 | — | — | +| 포트의 계약 시험 키트 | 포트 소유자의 testFixtures에 둔 추상 `Contract`. fake의 시험과 각 어댑터의 시험이 상속한다 | testFixtures | 값 타입 시험의 이름이 한때 `*ContractTest`였다. 지금은 `*ValueTypesTest`다 | -The one-line rule for stores: **if the domain would recognise the thing it stores, it is a -`Repository` in the domain; if it is plumbing the application needs, it is a `StorePort` in the -application.** +저장소의 한 줄 규칙: **도메인이 알아볼 만한 것을 저장하면 도메인의 `Repository`다. 애플리케이션에 +필요한 배관이면 application의 `StorePort`다.** -## Package ownership +## 패키지 소유 (Package ownership) -This section is the rule book for **which packages the template owns** and where a business feature -goes. `docs/manual/03-placement.md` points here. +이 절은 **템플릿이 어떤 패키지를 가지는지**와 업무 기능이 어디로 가는지의 정본이다. +`docs/manual/03-placement.md`가 이곳을 가리킨다. -- A business feature is `dev.caskeleton.application.` (and `dev.caskeleton.domain.`, - `...adapter.inbound.web.`, `...bootstrap.autoconfigure.`): one package per feature - directly under each root, no `command`/`usecase`/`port` sub-packages. -- `` is **not** one of the template package names below. A feature beside a template - package of the same name lands in the same package tree, and every upstream template update merges - into it. -- Template packages never import a feature package. Business code does not go into a template - package, even when the name fits. -- Everything under the two roots that is not listed here is a feature. A derived service adds - features without editing this list; the template edits it when it adds, renames or removes one of - its own packages. +- 업무 기능은 `dev.caskeleton.application.`다(그리고 `dev.caskeleton.domain.`, + `...adapter.inbound.web.`, `...bootstrap.autoconfigure.`). 루트마다 바로 아래에 + 기능 하나당 패키지 하나를 두고, `command`·`usecase`·`port` 하위 패키지를 두지 않는다. +- ``는 아래 템플릿 패키지 이름 중 하나가 **아니다**. 같은 이름의 템플릿 패키지 옆에 둔 + 기능은 같은 패키지 트리에 들어가고, upstream 템플릿 갱신이 올 때마다 그 기능에 섞여 들어간다. +- 템플릿 패키지는 기능 패키지를 import하지 않는다. 이름이 맞아도 업무 코드를 템플릿 패키지에 넣지 + 않는다. +- 두 루트 아래에서 여기 적히지 않은 것은 모두 기능이다. 파생 서비스는 이 목록을 고치지 않고 기능을 + 더한다. 템플릿은 자기 패키지를 더하거나, 이름을 바꾸거나, 지울 때 이 목록을 고친다. -| Package (`dev.caskeleton.application.*`) | Owning leaf | Holds | +| 패키지 (`dev.caskeleton.application.*`) | 소유 leaf | 담는 것 | |---|---|---| -| `usecase`, `command`, `query` | application-core | inbound port base types and the command/query markers | -| `capability` | application-core | `@UseCaseCapability` and its enums | -| `transaction` | application-core | `TransactionPort` and its modes | -| `security` | application-core | authorization port, `@RequiresPermission`, `@SystemInvoked`, `@SystemCaller`, `ObjectAccessPolicy` | +| `usecase`, `command`, `query` | application-core | inbound 포트 기반 타입과 command·query 표지 | +| `capability` | application-core | `@UseCaseCapability`와 그 enum | +| `transaction` | application-core | `TransactionPort`와 그 모드 | +| `security` | application-core | 인가 포트, `@RequiresPermission`, `@SystemInvoked`, `@SystemCaller`, `ObjectAccessPolicy` | | `tenant` | application-core | `TenantId` | | `observability` | application-core | `CorrelationIdPort`, `UserPrincipalPseudonymizerPort` | | `secret` | application-core | `SecretSourcePort`, `SecretReference` | -| `messaging` | application-core | the integration-event semantic contract | -| `outbox` | application-core | transactional outbox append and relay | -| `idempotency` | application-core | keyed idempotency executor and store port | -| `operation` | application-core | durable (long-running) operations | -| `lease`, `lock` | application-core | distributed lease and lock ports | -| `cache` | application-core | cache region port | -| `realtime` | application-core | live event replay port | -| `notification` | application-notification | notification capability | -| `fileserver` | application-fileserver | file server capability | -| `objectstorage` | application-objectstorage | object storage capability (its `content.CallBudget` is the call deadline it carries) | +| `messaging` | application-core | integration event semantic contract | +| `outbox` | application-core | 트랜잭션 outbox append와 relay | +| `idempotency` | application-core | 키 기반 멱등성 executor와 store 포트 | +| `operation` | application-core | durable(오래 걸리는) operation | +| `lease`, `lock` | application-core | 분산 lease·lock 포트 | +| `cache` | application-core | cache region 포트 | +| `realtime` | application-core | live event 재생 포트 | +| `notification` | application-notification | 알림 capability | +| `fileserver` | application-fileserver | 파일 서버 capability | +| `objectstorage` | application-objectstorage | 오브젝트 스토리지 capability(`content.CallBudget`은 그것이 싣는 호출 기한이다) | -| Package (`dev.caskeleton.domain.*`) | Owning leaf | Holds | +| 패키지 (`dev.caskeleton.domain.*`) | 소유 leaf | 담는 것 | |---|---|---| | `identifier` | domain-core | `ResourceId`, `IdFactory` | | `stereotype` | domain-core | `@AggregateRoot`, `@DomainEvent`, `@ValueObject` | -Enforcement: +강제하는 곳: -- `scripts/new-feature.sh` refuses a feature name that is already a package under any of the five - roots, in any leaf — every template package included. -- `NamingConventionTest.FEATURE_PACKAGES_DO_NOT_REUSE_TEMPLATE_PACKAGE_NAMES`: a feature package - under either root does not take a name from these tables. Every feature has a domain package, so a - feature named `operation` is caught at `dev.caskeleton.domain.operation`. -- `NamingConventionTest.TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES`: a feature class written - into a template package keeps the template's name but imports its own domain, and that import is - what fails. -- These tables are the rule book; the machine copy the rules read is `TemplatePackageOwnership` - (app-bootstrap `src/test`, so both the architecture suite and the document-contract lane see it). - `TemplatePackageOwnershipDocumentTest` (document-contract lane, `mainCheck`) fails when the tables - and that class differ in a package name or owning leaf, or when a listed package is not in the - leaf the table names; `TemplatePackageOwnershipRuleTest` (architectureTest) fails when a listed - name exists in no production class. A new template package joins both in the same change. -- Not caught: a new template package that nobody lists. Features are generated into the same leaves - (`scripts/new-feature.sh`), so an unlisted package is indistinguishable from a feature. Listing it - is part of adding it. -- Rejected alternatives: allowing only the listed top-level packages (every derived feature would - have to edit the template's list — a merge conflict per feature), and a separate - `application-platform` leaf for the platform packages (weighed in the 2026-11-01 maturity review: clearer - boundary, but more registry edges than a naming rule needs). +- `scripts/new-feature.sh`는 다섯 루트 중 어디든, 어느 leaf든 이미 패키지로 있는 기능 이름을 + 거절한다. 템플릿 패키지도 모두 여기 걸린다. +- `NamingConventionTest.FEATURE_PACKAGES_DO_NOT_REUSE_TEMPLATE_PACKAGE_NAMES`: 두 루트 아래의 기능 + 패키지는 이 표의 이름을 쓰지 않는다. 기능마다 domain 패키지가 있으므로 `operation`이라는 기능은 + `dev.caskeleton.domain.operation`에서 걸린다. +- `NamingConventionTest.TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES`: 템플릿 패키지 안에 쓴 + 기능 클래스는 템플릿 이름을 지니지만 자기 도메인을 import한다. 실패하는 것은 그 import다. +- 이 표가 정본이다. 규칙이 읽는 기계용 사본은 `TemplatePackageOwnership`이다(app-bootstrap + `src/test`에 있어서 architecture suite와 document-contract lane이 모두 본다). + `TemplatePackageOwnershipDocumentTest`(document-contract lane, `mainCheck`)는 표와 그 클래스의 + 패키지 이름이나 소유 leaf가 다르거나, 표에 적힌 패키지가 표가 말한 leaf에 없으면 실패한다. + `TemplatePackageOwnershipRuleTest`(architectureTest)는 적힌 이름이 운영 클래스 어디에도 없으면 + 실패한다. 새 템플릿 패키지는 같은 변경에서 둘 모두에 들어간다. +- 못 잡는 것: 아무도 적지 않은 새 템플릿 패키지. 기능은 같은 leaf에 생성되므로 + (`scripts/new-feature.sh`) 적히지 않은 패키지는 기능과 구별되지 않는다. 적는 것까지가 패키지를 + 더하는 일이다. +- 버린 대안: 적힌 최상위 패키지만 허용하기(파생 기능마다 템플릿 목록을 고쳐야 한다 — 기능마다 + 병합 충돌이 난다), 플랫폼 패키지용 `application-platform` leaf를 따로 두기(2026-11-01 성숙도 + 리뷰에서 따졌다: 경계는 더 분명하지만, 이름 규칙에 필요한 것보다 registry edge가 많아진다). -## Canonical use case shape +## 정해진 유스케이스 모양 (Canonical use case shape) ```java @RequiresPermission("user:register") @@ -201,135 +194,127 @@ public class RegisterUserUseCase implements CommandUseCase` / `Runnable` and cannot throw checked -exceptions. This matches Spring's `TransactionCallback` constraint. Wrap domain -checked exceptions into `RuntimeException` subclasses -(`DomainException extends RuntimeException`); `IOException` → `UncheckedIOException`; -`SQLException` is auto-translated by Spring's `DataAccessException` hierarchy. +`TransactionPort` 콜백은 `Supplier` / `Runnable`이라 checked 예외를 던지지 못한다. Spring +`TransactionCallback`의 제약과 같다. 도메인의 checked 예외는 `RuntimeException` 하위 클래스로 +감싼다(`DomainException extends RuntimeException`). `IOException`은 `UncheckedIOException`으로 +감싼다. `SQLException`은 Spring의 `DataAccessException` 계층이 자동으로 번역한다. -### `inNew` pool-sizing constraint +### `inNew` 풀 크기 제약 -`inNew` acquires a new physical JDBC connection. Pool size MUST satisfy: +`inNew`는 새 물리 JDBC 연결을 얻는다. 풀 크기는 반드시 다음을 만족한다. ``` hikari.maximumPoolSize >= (concurrent_threads × (1 + max_inNew_depth)) + 1 ``` -**Forbidden**: calling `tx.inNew(...)` inside a loop over many records — pool -exhaustion + deadlock risk. Batch records inside ONE `inNew` call, or move the -loop outside the transaction boundary. +**금지**: 많은 레코드를 도는 반복문 안에서 `tx.inNew(...)`를 부른다 — 풀이 바닥나고 교착이 생길 +수 있다. 레코드를 `inNew` 호출 **하나** 안에서 묶어 처리하거나, 반복문을 트랜잭션 경계 밖으로 뺀다. -## Idempotency (KEYED) — feature-rate-limit-idempotency-contract +## 멱등성 (KEYED) — feature-rate-limit-idempotency-contract -`@UseCaseCapability(idempotency = Idempotency.KEYED)` is **supported**. A KEYED use case wraps -its work with `dev.caskeleton.application.idempotency.IdempotencyExecutor` — the one owner-safe -generation; the V1 `IdempotencyScope`/`tryBegin` API is gone. +`@UseCaseCapability(idempotency = Idempotency.KEYED)`는 **지원한다**. KEYED 유스케이스는 자기 일을 +`dev.caskeleton.application.idempotency.IdempotencyExecutor`로 감싼다. 소유자를 안전하게 지키는 +유일한 세대다. V1 `IdempotencyScope`/`tryBegin` API는 없어졌다. -- **Scope**: the caller passes an `IdempotencyScopeDigest` — a versioned HMAC of - principal + client key + operation code, computed before the executor sees it. The raw - `Idempotency-Key` never reaches this layer or the store. -- **Store**: `IdempotencyStorePort`, contributed by exactly one provider selected with - `app.capabilities.idempotency.provider` (`redis` → `cache-redis`, `postgresql` → - `persistence-jpa`; default `disabled`). In-memory prod storage is forbidden. -- **Executor**: built once by `composition:idempotency` `IdempotencyAutoConfiguration` from - `IdempotencySettings` (processing lease 30s, replay TTL `APP_IDEMPOTENCY_TTL` 24h ≤72h and not - shorter than the lease, failure retention 24h and not shorter than the replay TTL). Do not - construct it in a use case or a service's own config. -- The action returns `IdempotentAction.Outcome` (`Success` / `RetryableNoEffect` / - `EffectUnknown`); a thrown exception counts as effect-unknown. In progress → 409 - `IDEMPOTENT_IN_FLIGHT`, fingerprint mismatch (SHA-256) → 422 `IDEMPOTENT_REQUEST_MISMATCH`; - `IdempotencyUnavailableException` and `IdempotencyRecoveryRequiredException` mean the store - could not prove the outcome, so do not blindly retry. -- Every store answers an execution whose processing lease ran out with `RecoveryRequired` and never - takes it over; only a claim that never started or a retryable failure is taken over. The answer - leaves the record to its holder: the holder's first late `complete`/`markFailed` is recorded, a - lease that ran out is not renewed and a claim whose lease ran out is not started — both answer - `LEASE_EXPIRED`, not `NOT_OWNER`, and the executor turns a refused start into "not applied" - (owner decision 2026-11-04). A record lives for the lease plus the replay TTL. `IdempotencyStoreContract` holds Redis and PostgreSQL to both on - real servers; the in-memory fake models no time, so it runs only the contract's time-free cases. -- Every transition names the operation its record was claimed under (`IdempotencyOwner.claimOperationId()`). - Another one is `OPERATION_CONFLICT` in every store and changes nothing; so is an inspection that - brings the owner token under another operation (owner decision 2026-11-06). -- A transition already applied is confirmed ("already …") only to the handle it was applied from — - the record one revision past it, moved there by that kind of transition. Any other handle is - `NOT_OWNER`, the same attempt's handle from before a takeover included, and so is a start through - the handle a renewal was applied from; a start through a released handle is `ABSENT` or - `NOT_OWNER` by whether the store keeps the released record (owner decision 2026-11-06, +- **범위(scope)**: 호출자가 `IdempotencyScopeDigest`를 넘긴다. principal + client key + operation + code의 버전 있는 HMAC이고, executor가 받기 전에 계산한다. 원본 `Idempotency-Key`는 이 계층에도 + store에도 닿지 않는다. +- **store**: `IdempotencyStorePort`. `app.capabilities.idempotency.provider`로 고른 provider 정확히 + 하나가 내놓는다(`redis` → `cache-redis`, `postgresql` → `persistence-jpa`, 기본값 `disabled`). + 운영에서 메모리 저장소는 금지다. +- **executor**: `composition:idempotency`의 `IdempotencyAutoConfiguration`이 `IdempotencySettings`로 + 한 번 만든다(처리 lease 30s, 재생 TTL `APP_IDEMPOTENCY_TTL` 24h ≤72h이고 lease보다 짧지 않다, 실패 + 보존 24h이고 재생 TTL보다 짧지 않다). 유스케이스나 서비스 자신의 설정에서 만들지 않는다. +- action은 `IdempotentAction.Outcome`(`Success` / `RetryableNoEffect` / `EffectUnknown`)을 + 돌려준다. 던진 예외는 효과를 모름(effect-unknown)으로 센다. 처리 중이면 409 + `IDEMPOTENT_IN_FLIGHT`, fingerprint(SHA-256)가 다르면 422 `IDEMPOTENT_REQUEST_MISMATCH`다. + `IdempotencyUnavailableException`과 `IdempotencyRecoveryRequiredException`은 store가 결과를 + 증명하지 못했다는 뜻이니 무턱대고 다시 시도하지 않는다. +- 모든 store는 처리 lease가 끝난 실행에 `RecoveryRequired`로 답하고 그 실행을 넘겨받지 않는다. + 넘겨받는 것은 시작하지 않은 claim이나 다시 시도할 수 있는 실패뿐이다. 이 답은 레코드를 가진 + 쪽에게 남긴다: 가진 쪽이 늦게 보낸 첫 `complete`/`markFailed`는 기록한다. lease가 끝난 것은 + 갱신하지 않고, lease가 끝난 claim은 시작하지 않는다. 둘 다 `NOT_OWNER`가 아니라 `LEASE_EXPIRED`로 + 답하고, executor는 거절된 시작을 「적용 안 됨」으로 바꾼다(소유자 결정 2026-11-04). 레코드는 + lease에 재생 TTL을 더한 만큼 산다. `IdempotencyStoreContract`가 Redis와 PostgreSQL을 실제 서버에서 + 둘 모두에 맞춘다. 메모리 fake는 시간을 모델링하지 않으니 계약 중 시간이 없는 경우만 돈다. +- 모든 전이는 그 레코드를 claim한 operation을 이름으로 댄다(`IdempotencyOwner.claimOperationId()`). + 다른 operation이면 모든 store에서 `OPERATION_CONFLICT`이고 아무것도 바꾸지 않는다. owner token을 + 다른 operation으로 가져온 조회도 같다(소유자 결정 2026-11-06). +- 이미 적용된 전이는 그것을 적용한 handle에게만 「already …」로 확인해 준다. 그 handle은 그 전이로 + 옮겨 간, 한 revision 뒤의 레코드다. 다른 handle은 모두 `NOT_OWNER`다. 넘겨받기 전의 같은 시도의 + handle도, 갱신을 적용한 handle로 하는 시작도 그렇다. 놓아준 handle로 하는 시작은 store가 놓아준 + 레코드를 남기느냐에 따라 `ABSENT`나 `NOT_OWNER`다(소유자 결정 2026-11-06, `IdempotencyStoreContract`). -- The applying handle resending `markFailed` with another disposition is `OPERATION_CONFLICT` and - the recorded failure stays; with only another retention it is `ALREADY_MARKED_SAME_OPERATION` and - the first retention stays — retention, like a completion's replay TTL, is not compared (owner - decision 2026-11-07). +- 적용한 handle이 다른 disposition으로 `markFailed`를 다시 보내면 `OPERATION_CONFLICT`이고 기록된 + 실패가 남는다. retention만 다르면 `ALREADY_MARKED_SAME_OPERATION`이고 처음 retention이 남는다 — + retention은 완료의 재생 TTL처럼 비교하지 않는다(소유자 결정 2026-11-07). -The former ArchUnit freeze rule `inbound_port_implementations_do_not_declare_keyed_idempotency` -and its fixture were removed when this branch merged. +예전 ArchUnit 동결 규칙 `inbound_port_implementations_do_not_declare_keyed_idempotency`와 그 fixture는 +이 브랜치가 병합될 때 지웠다. -## Read / query path (feature-application-query-bypass-contract) +## 읽기·query 경로 (feature-application-query-bypass-contract) -The read side has two equally-valid shapes; pick per read, do not force one: +읽기 쪽에는 똑같이 유효한 모양이 둘 있다. 읽기마다 고르고, 하나를 강요하지 않는다. -| Shape | Returns | When | How | +| 모양 | 돌려주는 것 | 언제 | 어떻게 | |---|---|---|---| -| **Through-aggregate** (default for simple reads) | domain aggregate via a `*Repository` port | read shape == write aggregate **and** the aggregate is the minimal invariant boundary (no lazy collections needed) | `QueryUseCase` → repository port → `Order` | -| **Projection (CQRS-lite)** | application-layer projection DTO via a `*QueryPort` | read shape ≠ write, or to skip aggregate hydration / lazy-collection joins | `QueryUseCase` → `*QueryPort` → `OrderSummary` (record); query via JPQL `SELECT new` / JdbcTemplate | +| **aggregate를 거쳐서**(단순 읽기의 기본) | `*Repository` 포트로 받은 도메인 aggregate | 읽기 모양 == 쓰기 aggregate **이고** aggregate가 최소 불변식 경계일 때(지연 컬렉션이 필요 없음) | `QueryUseCase` → repository 포트 → `Order` | +| **projection (CQRS-lite)** | `*QueryPort`로 받은 애플리케이션 계층 projection DTO | 읽기 모양 ≠ 쓰기, 또는 aggregate 수화·지연 컬렉션 join을 건너뛰려 할 때 | `QueryUseCase` → `*QueryPort` → `OrderSummary`(record). query는 JPQL `SELECT new` / JdbcTemplate | -- **Purity guardrail (core, machine-enforced):** a read port whose simple name ends - with `QueryPort` MUST return application-layer projection DTOs only — never a domain - aggregate, JPA entity, or web type, **including through generic type arguments** - (`List`). Enforced by ArchUnit `query_ports_do_not_leak_domain_jpa_or_web_types`. - Projection usage itself is **opt-in**, not a forced default. -- **Strict ceremony:** every read goes through a `QueryUseCase` bean. There is no thin - web→read-port path — that would bypass the mandatory `@UseCaseCapability` fitness function. -- **Transaction:** reads default to `TransactionPort.inRead`. A no-tx (autocommit) read - is an opt-in only when `spring.jpa.open-in-view=false` is confirmed **and** the read is - projection-only (no lazy access) **and** a single statement; otherwise keep `inRead`. -- **Capability:** a repository-backed projection read is still - `repositoryAccess = READ_REPOSITORY`. "Projection vs aggregate" is the return *shape* axis, - orthogonal to the repository-access *level* axis — no new enum. Outbound-HTTP reads (no - repository) stay `RepositoryAccess.NONE`. -- Full CQRS with a separate physical read store is out of scope — escalation only. +- **순수성 가드레일(core, 기계로 강제):** 단순 이름이 `QueryPort`로 끝나는 읽기 포트는 반드시 + 애플리케이션 계층 projection DTO만 돌려준다 — 도메인 aggregate, JPA 엔티티, web 타입은 **제네릭 + 타입 인자를 거쳐서도**(`List`) 안 된다. ArchUnit + `query_ports_do_not_leak_domain_jpa_or_web_types`가 강제한다. projection 사용 자체는 강요된 기본이 + 아니라 **선택**이다. +- **엄격한 절차:** 모든 읽기는 `QueryUseCase` bean을 거친다. web → 읽기 포트로 바로 가는 얇은 + 경로는 없다. 그런 경로는 필수인 `@UseCaseCapability` 적합성 검사를 건너뛴다. +- **트랜잭션:** 읽기의 기본은 `TransactionPort.inRead`다. 트랜잭션 없는(autocommit) 읽기는 + `spring.jpa.open-in-view=false`가 확인됐고 **그리고** 읽기가 projection만 쓰고(지연 접근 없음) + **그리고** 문장 하나일 때만 고를 수 있다. 아니면 `inRead`를 쓴다. +- **capability:** repository를 쓰는 projection 읽기도 `repositoryAccess = READ_REPOSITORY`다. + 「projection이냐 aggregate냐」는 돌려주는 *모양* 축이고, repository 접근 *수준* 축과 따로다 — 새 + enum이 없다. outbound HTTP 읽기(repository 없음)는 `RepositoryAccess.NONE`이다. +- 물리적으로 따로 둔 읽기 저장소를 쓰는 완전한 CQRS는 범위 밖이다. 올려서 정할 일이다. -## ArchUnit guardrails (enforced) +## ArchUnit 가드레일(강제됨) - `application_does_not_depend_on_adapters_or_transport` - `application_does_not_use_spring_transactional_annotation` @@ -337,9 +322,9 @@ The read side has two equally-valid shapes; pick per read, do not force one: - `APPLICATION_HAS_NO_DIAGNOSTIC_FRAMEWORK` - `inbound_port_implementations_end_with_use_case` - `inbound_port_implementations_declare_capability` -- `query_ports_do_not_leak_domain_jpa_or_web_types` (`*QueryPort` return purity) +- `query_ports_do_not_leak_domain_jpa_or_web_types`(`*QueryPort` 반환 순수성) -## Test +## 테스트 ```bash cd src @@ -347,5 +332,5 @@ cd src ./gradlew :app-bootstrap:architectureTest ``` -The messaging types above establish semantic contract R1 only. They do not claim JSON Schema -qualification, Kafka publication, durable outbox persistence or any messaging R2 capability. +위 메시징 타입은 semantic contract R1까지만 세운다. JSON Schema 검증, Kafka 발행, durable outbox +영속, 그 밖의 메시징 R2 capability를 주장하지 않는다. diff --git a/src/build-logic/README.md b/src/build-logic/README.md index 279ff8c3..cd9fe39b 100644 --- a/src/build-logic/README.md +++ b/src/build-logic/README.md @@ -1,69 +1,67 @@ # build-logic -The included build that holds this repository's Gradle conventions: the architecture core, the -conventions every leaf applies, and one test-lane mechanism. A check that is about one capability -(notification, Mongo, messaging, GraphQL, JPA) is not here — it is a test in the leaf that owns the -capability, and the files it reads are declared as that test task's inputs. +이 저장소의 Gradle 규약을 담은 included build다: 아키텍처 핵심, 모든 leaf가 적용하는 규약, 시험 lane +장치 하나. capability 하나에 대한 검사(알림, Mongo, 메시징, GraphQL, JPA)는 여기 없다 — 그것은 그 +capability를 가진 leaf의 시험이고, 그 시험이 읽는 파일은 그 시험 태스크의 입력으로 선언한다. -## What is here +## 여기 있는 것 -| Plugin | Owns | +| 플러그인 | 가지는 것 | | --- | --- | -| `ca.architecture-registry` (settings) | project inclusion, directory mapping, and the parsed registry every other reader shares | -| `ca.architecture` | `verifyCleanArchitectureDependencies` (per-module direction), `verifyApplicationCoreDependencyPurity` (domain-core, shared-contract, application-*), `verifyNoIgnoredSourcePackages`, `architectureCheck` | -| `ca.java-conventions` | Java toolchain/compiler baseline, dependency locking, the Mockito test agent, the per-leaf `mainCheck` lifecycle, the leaf version (release version only) and `sourceRevision` (`JavaConventionsPlugin.sourceRevision`, also what the root `verifyReleaseProvenance` checks) | -| `ca.quality-conventions` | Spotless, Checkstyle, Error Prone, SpotBugs/FindSecBugs wiring shared by Java leaves | -| `ca.java-library` / `ca.spring-library` / `ca.spring-config` | leaf-level composition of the Java/quality conventions for plain and Spring libraries | -| `ca.platform-module` / `ca.grpc-platform-module` | what a vendored platform leaf (`messaging:*`, `grpc:*`, `grpc-advanced:*`) is: `java-library`, plus the gRPC BOM for the leaves that had it | -| `ca.strict-test-lane` | the one "named tests ran, none skipped" mechanism: tagged / named / own-source-set `Test` lanes that fail when they execute nothing, miss a `requires` class, or (with `rejectSkipped`) skip anything. A `performance()` lane always rejects skips and runs with `performance.assertions.enabled=true`; a build (`-P`, `GRADLE_OPTS`) or lane that sets another value fails it before a test runs. `mainStage()` moves a tagged lane out of `test` into the leaf's `mainCheck`; `explicitOnly(reason)` keeps a lane that needs an outside input out of every aggregate, and the aggregate prints the reason. Extra test source sets are Gradle `jvm-test-suite` suites declared in the leaf (`testing { suites { … } }`); a lane named after its suite makes the suite's own `Test` task strict, and `ca.java-conventions` gives every suite the BOM's JUnit | -| `ca.strict-lane-stages` (root of each build with strict lanes: the main build and optional-platforms) | the other half of the lane mechanism: `verifyStrictLaneStages --dry-run` fails when a strict lane of that build that is not `explicitOnly` is in the task plan of no declared stage that a workflow executes, or when a declared stage is executed by no workflow. The workflows are read together (`WorkflowGradleInvocations.readAll`, so a reusable workflow is judged by its callers) and their `run:` scripts parsed as bash (`ShellScript`: quotes, comments, heredoc bodies, substitutions and compound commands are read as the shell reads them, so a `cd` in a heredoc or a string is data). A command does not count when Gradle runs no task with it — `--dry-run`/`-m` (also in a bundle such as `-qm`), `-v`/`--version`, `-h`/`-?`/`--help`, `--status`, `--stop`, `--foreground` (also in a bundle such as `-qv`) — or rejects it: a short-option bundle whose later letter takes a value (`-mx`: only the first letter of a bundle takes one), or a value given to an option that takes none (`-m=yes`). The reader follows Gradle 9.0's parser. `GradleCommandLineTest` holds its option tables to the `--help` of the Gradle that runs build-logic — an upgrade that adds an option, as 9.2 adds `--task-graph`, fails until the option is placed — and runs the launcher with each no-task option but `--stop` and `--foreground` (both return a daemon action, not a build, in Gradle's `BuildActionsFactory`); which options take a value was probed against 9.0.0 in round 9 and is not re-run. Nor does a command for another build count (the build a command starts is its step's `working-directory`, or the job's or workflow's `defaults.run.working-directory`, moved by each `cd ` the same `run:` shell surely ran before it — alone in its list, or before the command in the same `&&` list — then joined with `-p`; the plugin reads this build's own directory from where it sits under the repository that holds `.github/workflows`). Every other command that does not count gives one of three reasons. **Its failure may not fail its step**: `\|\| true`, `\|\| :` or any `\|\|` but `\|\| exit `, a pipe's left side without `pipefail` (on with `shell: bash` or a top-level `set -o pipefail`), `!`, `&`, an `if`/`while` condition, the part before `&&` of a list that is not the script's last command, after `set +e`, after a `trap` whose `EXIT` or `ERR` action may `exit` with status 0 (a bare `exit` keeps the status in an `EXIT` trap, not in an `ERR` one), and `continue-on-error`. **It may not run**: after `\|\|`, after `&&` in a list that is not the script's last command, inside `if`/`while`/`for`/`case` or a function body, after a top-level `exit`, `exec ` or `set -n`, after one elsewhere — in a compound command, an and-or list or a function the script calls — that may end the script with status 0 (`exit 0`, a bare `exit` other than right after `\|\|`, `exit "$code"`), replace it or stop it running commands (`set -o noexec`), under an `if:` other than `always()`/`success()`/`!cancelled()`, in a workflow that starts only on events someone or something asks for (`workflow_dispatch`, `repository_dispatch`, `issue_comment`, a pull request with `types: [labeled]`, `workflow_run`, …; `push`, `pull_request`, `pull_request_target`, `merge_group`, `schedule` and `release` count), in a workflow whose change-flow triggers all carry a `paths` or `paths-ignore` filter (a change outside those paths does not start it; owner decision 2026-11-06), for any stage but `:releaseCheck` in a workflow that starts without a request or a path filter only on the release flow — `release`, or a `push` with `tags`/`tags-ignore` and no `branches`/`branches-ignore`, which a branch push does not start (owner decision 2026-11-07; `:releaseCheck` is the tag-only stage) — in a reusable (`workflow_call`-only) workflow that no counted job calls with `uses: ./.github/workflows/`, and in a job that `needs`, directly or through other jobs, a job with such an `if:` or with `continue-on-error`, unless its own `if:` is `always()` or `!cancelled()`. **This check does not read it**, although its failure would fail the step (a false failure on purpose): `\|\| exit 1`, `\|\| { …; exit 1; }`, inside `{ }` or `( )`, `$( )`, `bash -c`, `gradlew` as another command's argument (`timeout 60 ./gradlew`), after a directory change the reader does not follow (`cd "$VAR"`, `cd -`, `cd ~`, an absolute path, `pushd`/`popd`, `builtin cd`, `eval`/`source`, a `cd` anywhere inside a compound command or a function body, one joined with `\|\|`, piped or in the background, and the lines after a `cd` that shares an `&&` list with other commands — not guessed), a step whose `shell:` is not `bash` or `sh`, and a step with no `shell:` in a job whose `runs-on` may be a Windows runner, whose default shell is `pwsh` (a Windows label, an expression such as `${{ matrix.os }}`, a self-hosted label set without `linux` or `macos`; Linux and macOS runners default to `bash -e` and a `container:` job to `sh -e`, which are read alike). An `exit` that fails the step — `exit 1`, or `cmd \|\| exit` — and one in an uncalled function, a `( )` subshell or `$( )` stop nothing after them from counting. The failure names every command that names the stage but does not execute it, with its reason or the other build it starts, and says to run the stage as `./gradlew` on a line of its own. A lane the command removes with `-x` is not covered — matched the way Gradle matches task and project names, abbreviations included (`TaskSelectors`, a copy of Gradle's internal `NameMatcher`). A `run:` input of a `uses:` step is not a command. The plan is Gradle's own; the workflows are read for their `run:` steps with YAML folding applied (review 2026-11-01 08-01, 2026-11-03 RR-06-03/04, 2026-11-04 RR2-04-04, owner decision 2026-11-04 on `cd`, RR5-02-01/02/03 in round 9, 2026-11-05 RR6-04-01..06, 2026-11-06 RR7-05-01, owner decision 2026-11-07 on the release flow) | -| `ca.redis-topology-lane` | the Redis topology lane (mode selection, `-P` property validation, per-mode required classes) the redis-sdk-topology workflow drives | -| `ca.api-surface` | read-only public API surface verification with a separate update task, wired into the leaf's `check` (owner decision 20); optionally holds other leaves' imports to a reviewed adopter subset (`adopterBaseline`) | -| `ca.config-contract` | app-bootstrap's `verifyEnvKeys` (moved from the deleted build-tools included build; owner decision 4 keeps the task in app-bootstrap) | -| `ca.bootrun-dotenv` | `bootRun`'s `.env` | +| `ca.architecture-registry` (settings) | 프로젝트 포함, 디렉터리 대응, 다른 모든 읽는 쪽이 같이 쓰는 파싱된 registry | +| `ca.architecture` | `verifyCleanArchitectureDependencies`(모듈별 방향), `verifyApplicationCoreDependencyPurity`(domain-core, shared-contract, application-*), `verifyNoIgnoredSourcePackages`, `architectureCheck` | +| `ca.java-conventions` | Java toolchain·컴파일러 기준, 의존성 잠금, Mockito 시험 agent, leaf별 `mainCheck` lifecycle, leaf 버전(릴리스 버전만)과 `sourceRevision`(`JavaConventionsPlugin.sourceRevision`. 루트 `verifyReleaseProvenance`가 검사하는 것도 이것이다) | +| `ca.quality-conventions` | Java leaf가 같이 쓰는 Spotless, Checkstyle, Error Prone, SpotBugs·FindSecBugs 배선 | +| `ca.java-library` / `ca.spring-library` / `ca.spring-config` | 평범한 라이브러리와 Spring 라이브러리를 위한 Java·품질 규약의 leaf 단위 조합 | +| `ca.platform-module` / `ca.grpc-platform-module` | 들여온 플랫폼 leaf(`messaging:*`, `grpc:*`, `grpc-advanced:*`)가 무엇인가: `java-library`, 그리고 원래 gRPC BOM을 쓰던 leaf에는 그 BOM | +| `ca.strict-test-lane` | 「이름 댄 시험이 돌았고 건너뛴 것이 없다」를 보는 유일한 장치: tag·이름·자기 source set으로 고른 `Test` lane이 아무것도 실행하지 않거나, `requires` 클래스를 빠뜨리거나, (`rejectSkipped`이면) 무엇이든 건너뛰면 실패한다. `performance()` lane은 언제나 건너뛰기를 거절하고 `performance.assertions.enabled=true`로 돈다. 빌드(`-P`, `GRADLE_OPTS`)나 lane이 다른 값을 넣으면 시험이 돌기 전에 실패한다. `mainStage()`는 tag로 고른 lane을 `test`에서 빼 leaf의 `mainCheck`로 옮긴다. `explicitOnly(reason)`는 바깥 입력이 필요한 lane을 모든 묶음 태스크에서 빼고, 묶음 태스크가 그 이유를 출력한다. 시험 source set을 더 두려면 leaf에 Gradle `jvm-test-suite` suite로 선언한다(`testing { suites { … } }`). suite 이름을 딴 lane은 그 suite 자신의 `Test` 태스크를 엄격하게 만들고, `ca.java-conventions`는 모든 suite에 BOM의 JUnit을 준다 | +| `ca.strict-lane-stages` (strict lane이 있는 각 빌드의 루트: 주 빌드와 optional-platforms) | lane 장치의 나머지 절반: `verifyStrictLaneStages --dry-run`은 그 빌드의 `explicitOnly`가 아닌 strict lane이 workflow가 실행하는 선언된 단계 어느 것의 태스크 계획에도 없거나, 선언된 단계를 실행하는 workflow가 없으면 실패한다. workflow는 함께 읽고(`WorkflowGradleInvocations.readAll`. 그래서 재사용 workflow는 그것을 부르는 쪽으로 판정한다) `run:` 스크립트는 bash로 파싱한다(`ShellScript`: 따옴표, 주석, heredoc 본문, 치환, 복합 명령을 셸이 읽듯 읽는다. 그래서 heredoc이나 문자열 안의 `cd`는 데이터다). Gradle이 태스크를 하나도 돌리지 않는 명령은 세지 않는다 — `--dry-run`/`-m`(`-qm` 같은 묶음 안도), `-v`/`--version`, `-h`/`-?`/`--help`, `--status`, `--stop`, `--foreground`(`-qv` 같은 묶음 안도) — Gradle이 거절하는 명령도 세지 않는다: 뒤 글자가 값을 받는 짧은 옵션 묶음(`-mx`: 묶음에서는 첫 글자만 값을 받는다), 값을 받지 않는 옵션에 준 값(`-m=yes`). 읽는 방식은 Gradle 9.0의 파서를 따른다. `GradleCommandLineTest`는 옵션 표를 build-logic을 돌리는 Gradle의 `--help`와 맞춘다 — 옵션을 더하는 업그레이드는(9.2가 `--task-graph`를 더하듯) 그 옵션을 자리에 넣기 전까지 실패한다 — 그리고 `--stop`과 `--foreground`를 뺀 태스크 없는 옵션마다 launcher를 돌린다(둘은 Gradle `BuildActionsFactory`에서 빌드가 아니라 daemon 동작을 돌려준다). 어떤 옵션이 값을 받는지는 round 9에 9.0.0으로 탐침했고 다시 돌리지 않는다. 다른 빌드를 위한 명령도 세지 않는다(명령이 시작하는 빌드는 그 step의 `working-directory`, 또는 job이나 workflow의 `defaults.run.working-directory`에서 시작해, 같은 `run:` 셸이 그 앞에서 반드시 돌린 `cd <리터럴 상대 경로>`마다 옮기고 — 혼자 있는 목록이거나 같은 `&&` 목록에서 그 명령 앞에 있을 때 — 그다음 `-p`로 이은 곳이다. 플러그인은 이 빌드 자신의 디렉터리를 `.github/workflows`를 가진 저장소 아래 어디에 있는지로 읽는다). 세지 않는 그 밖의 명령은 모두 세 이유 중 하나를 댄다. **실패해도 step이 실패하지 않을 수 있다**: `\|\| true`, `\|\| :`, `\|\| exit <0 아닌 값>`이 아닌 모든 `\|\|`, `pipefail` 없는 pipe의 왼쪽(`shell: bash`나 최상위 `set -o pipefail`이면 켜진다), `!`, `&`, `if`/`while` 조건, 스크립트의 마지막 명령이 아닌 목록에서 `&&` 앞부분, `set +e` 뒤, `EXIT`나 `ERR` 동작이 상태 0으로 `exit`할 수 있는 `trap` 뒤(`EXIT` trap 안의 맨 `exit`는 상태를 지키지만 `ERR` trap 안에서는 아니다), `continue-on-error`. **돌지 않을 수 있다**: `\|\|` 뒤, 스크립트의 마지막 명령이 아닌 목록에서 `&&` 뒤, `if`/`while`/`for`/`case` 안이나 함수 본문 안, 최상위 `exit`·`exec `·`set -n` 뒤, 다른 곳 — 복합 명령, and-or 목록, 스크립트가 부르는 함수 — 에서 스크립트를 상태 0으로 끝낼 수 있는 것(`exit 0`, `\|\|` 바로 뒤가 아닌 맨 `exit`, `exit "$code"`), 스크립트를 바꿔치는 것, 명령 실행을 멈추는 것(`set -o noexec`) 뒤, `always()`/`success()`/`!cancelled()`가 아닌 `if:` 아래, 누가 또는 무엇이 요청해야만 시작하는 이벤트(`workflow_dispatch`, `repository_dispatch`, `issue_comment`, `types: [labeled]`인 pull request, `workflow_run`, …. `push`, `pull_request`, `pull_request_target`, `merge_group`, `schedule`, `release`는 센다)로만 시작하는 workflow 안, 변경 흐름 트리거가 모두 `paths`나 `paths-ignore` 필터를 가진 workflow 안(그 경로 밖의 변경은 workflow를 시작하지 않는다. 소유자 결정 2026-11-06), 요청이나 경로 필터 없이 릴리스 흐름에서만 시작하는 workflow 안의 `:releaseCheck`가 아닌 단계 — 릴리스 흐름은 `release`, 또는 `tags`/`tags-ignore`가 있고 `branches`/`branches-ignore`가 없는 `push`로, 브랜치 push로는 시작하지 않는다(소유자 결정 2026-11-07. `:releaseCheck`가 태그 전용 단계다) — 센 job 어느 것도 `uses: ./.github/workflows/`로 부르지 않는 재사용(`workflow_call`만 있는) workflow 안, 그리고 그런 `if:`나 `continue-on-error`를 가진 job을 직접 또는 다른 job을 거쳐 `needs`하는 job 안(자기 `if:`가 `always()`나 `!cancelled()`이면 예외). **이 검사가 읽지 않는다**(실패하면 step이 실패하지만, 일부러 거짓 실패로 둔다): `\|\| exit 1`, `\|\| { …; exit 1; }`, `{ }`나 `( )` 안, `$( )`, `bash -c`, 다른 명령의 인자인 `gradlew`(`timeout 60 ./gradlew`), 읽는 쪽이 따라가지 않는 디렉터리 이동 뒤(`cd "$VAR"`, `cd -`, `cd ~`, 절대 경로, `pushd`/`popd`, `builtin cd`, `eval`/`source`, 복합 명령이나 함수 본문 안의 `cd`, `\|\|`로 이은 것, pipe나 background로 돌린 것, 다른 명령과 같은 `&&` 목록에 있는 `cd`의 뒤 줄 — 짐작하지 않는다), `shell:`이 `bash`나 `sh`가 아닌 step, `runs-on`이 Windows runner일 수 있는 job에서 `shell:`이 없는 step(기본 셸이 `pwsh`다. Windows label, `${{ matrix.os }}` 같은 표현식, `linux`나 `macos`가 없는 self-hosted label 집합. Linux·macOS runner의 기본은 `bash -e`, `container:` job의 기본은 `sh -e`이고 둘을 같이 읽는다). step을 실패시키는 `exit` — `exit 1`, `cmd \|\| exit` — 와 부르지 않는 함수, `( )` subshell, `$( )` 안의 `exit`는 그 뒤의 명령이 세지는 것을 막지 않는다. 실패 메시지는 단계 이름을 대지만 그 단계를 실행하지 않는 모든 명령을 그 이유나 그것이 시작하는 다른 빌드와 함께 대고, 단계를 혼자 있는 줄의 `./gradlew`로 돌리라고 말한다. 명령이 `-x`로 뺀 lane은 덮인 것이 아니다 — Gradle이 태스크·프로젝트 이름을 맞추는 방식(약어 포함)으로 맞춘다(`TaskSelectors`, Gradle 내부 `NameMatcher`의 사본). `uses:` step의 `run:` 입력은 명령이 아니다. 계획은 Gradle 자신의 것이다. workflow는 YAML folding을 적용해 `run:` step을 읽는다(review 2026-11-01 08-01, 2026-11-03 RR-06-03/04, 2026-11-04 RR2-04-04, `cd`에 대한 소유자 결정 2026-11-04, round 9의 RR5-02-01/02/03, 2026-11-05 RR6-04-01..06, 2026-11-06 RR7-05-01, 릴리스 흐름에 대한 소유자 결정 2026-11-07) | +| `ca.redis-topology-lane` | redis-sdk-topology workflow가 돌리는 Redis topology lane(모드 고르기, `-P` 속성 검증, 모드별 필수 클래스) | +| `ca.api-surface` | 읽기 전용 공개 API surface 검증과 따로 둔 갱신 태스크. leaf의 `check`에 배선한다(소유자 결정 20). 다른 leaf의 import를 리뷰한 adopter 부분집합(`adopterBaseline`)에 묶을 수도 있다 | +| `ca.config-contract` | app-bootstrap의 `verifyEnvKeys`(지운 build-tools included build에서 옮겼다. 소유자 결정 4가 그 태스크를 app-bootstrap에 둔다) | +| `ca.bootrun-dotenv` | `bootRun`의 `.env` | -Plain classes rather than plugins, because settings and projects load plugins through different -mechanisms and more than one caller needs each: +플러그인이 아니라 평범한 클래스로 둔 것. settings와 project는 플러그인을 서로 다른 방식으로 읽어 +들이고, 각각을 부르는 쪽이 둘 이상이기 때문이다: -| Class | Owns | +| 클래스 | 가지는 것 | | --- | --- | -| `dev.caskeleton.buildlogic.ModuleRegistry` | reading and validating `config/architecture/modules.json` | -| `dev.caskeleton.buildlogic.RequiredTestExecution` | the single decision "a test this build names must actually have run" | -| `dev.caskeleton.buildlogic.JavaPublicTypes` | public top-level types, parsed by javac rather than matched with a regular expression | +| `dev.caskeleton.buildlogic.ModuleRegistry` | `config/architecture/modules.json`을 읽고 검증하기 | +| `dev.caskeleton.buildlogic.RequiredTestExecution` | 「이 빌드가 이름을 댄 시험은 실제로 돌았어야 한다」는 단 하나의 판정 | +| `dev.caskeleton.buildlogic.JavaPublicTypes` | 공개 최상위 타입. 정규식으로 맞추지 않고 javac로 파싱한다 | -JMH benchmarks use the community `me.champeau.jmh` plugin; `ca.quality-conventions` only turns -Error Prone, `-Werror`, SpotBugs and Checkstyle off for benchmark and generated code. +JMH benchmark는 커뮤니티 플러그인 `me.champeau.jmh`를 쓴다. `ca.quality-conventions`는 benchmark와 +생성된 코드에서 Error Prone, `-Werror`, SpotBugs, Checkstyle을 끄기만 한다. -## What was removed, and what covers it +## 지운 것과 그것을 대신하는 것 -| Removed | Covered by | +| 지운 것 | 대신하는 것 | | --- | --- | -| `ca.runtime-membership` | the direction gate: nothing outside `allowed_dependencies` can reach a composition root | -| `ca.evidence`, `ca.conditional-transport-qualification`, `ca.strict-qualification` | `strictTestLanes` lanes with `requires` + `rejectSkipped`; the root `conditionalTransportQualification` and `verifyMessagingContracts` only aggregate them | -| `ca.dependency-policy` | a `componentSelection` rejection rule in the leaf (notification: YAML dataformat; messaging: Jackson 2 and any YAML module) and the registry (web-advanced has no allowed consumer). `rejectAll()` constraints were tried and do not fail: Spring's dependency management overrides the rejected version | -| `ca.graphql-platform` | the `graphqlStableTest` lane and `GraphQlProductionClassesTest` in the GraphQL leaf | -| `ca.jpa-test-lanes` | the lanes declared in `adapter/outbound/persistence-jpa/build.gradle` | -| `ca.test-jvm-agents`, `quarantineTest` | `ca.java-conventions`; the quarantine bucket had no tests | +| `ca.runtime-membership` | 방향 게이트: `allowed_dependencies` 밖의 것은 조립 루트에 닿을 수 없다 | +| `ca.evidence`, `ca.conditional-transport-qualification`, `ca.strict-qualification` | `requires` + `rejectSkipped`를 쓴 `strictTestLanes` lane. 루트 `conditionalTransportQualification`과 `verifyMessagingContracts`는 그 lane을 묶기만 한다 | +| `ca.dependency-policy` | leaf 안의 `componentSelection` 거절 규칙(notification: YAML dataformat, messaging: Jackson 2와 모든 YAML 모듈)과 registry(web-advanced는 허용된 소비자가 없다). `rejectAll()` 제약도 써 봤지만 실패하지 않는다: Spring의 의존성 관리가 거절한 버전을 덮어쓴다 | +| `ca.graphql-platform` | GraphQL leaf의 `graphqlStableTest` lane과 `GraphQlProductionClassesTest` | +| `ca.jpa-test-lanes` | `adapter/outbound/persistence-jpa/build.gradle`에 선언한 lane | +| `ca.test-jvm-agents`, `quarantineTest` | `ca.java-conventions`. quarantine 묶음에는 시험이 없었다 | | `ca.jmh-benchmarks` | `me.champeau.jmh` | -| build-tools `ca.jpa-evidence`, `ca.jpa-qualification` (+ `junit` evidence reader) | owner decision 4: persistence-jpa `JpaReadinessRegistryTest`, readiness lanes that require every cited scenario and reject skips, the leaf's `jpaReleaseQualification` aggregate over `config/jpa/release-registry.json` | -| build-tools `ca.config-contract` | moved here unchanged | -| `ca.public-path-snapshot` | app-bootstrap `PublicPathSnapshotTest` (lane `publicPathSnapshotTest`, root alias `verifyPublicPathSnapshot`) | -| `ca.archive-hygiene` | nothing to clean: leaf versions no longer carry the revision, so no stale traceable jar is produced | +| build-tools `ca.jpa-evidence`, `ca.jpa-qualification`(+ `junit` 증거 읽기) | 소유자 결정 4: persistence-jpa `JpaReadinessRegistryTest`, 인용한 시나리오를 모두 요구하고 건너뛰기를 거절하는 readiness lane, `config/jpa/release-registry.json`을 묶는 leaf의 `jpaReleaseQualification` | +| build-tools `ca.config-contract` | 바꾸지 않고 여기로 옮겼다 | +| `ca.public-path-snapshot` | app-bootstrap `PublicPathSnapshotTest`(lane `publicPathSnapshotTest`, 루트 별칭 `verifyPublicPathSnapshot`) | +| `ca.archive-hygiene` | 치울 것이 없다: leaf 버전이 더는 revision을 싣지 않으니 낡은 추적 가능 jar가 생기지 않는다 | | `ca.developer-bootstrap` | `scripts/bootstrap-local.sh` | -| `JpaAdopterApiSurfaceTest` (a regex import scan in persistence-jpa) | `ca.api-surface` `adopterBaseline` | +| `JpaAdopterApiSurfaceTest`(persistence-jpa의 정규식 import 검사) | `ca.api-surface` `adopterBaseline` | -## Testing a convention +## 규약 시험하기 ```bash cd src ./gradlew -p build-logic test --console=plain ``` -The lane and registry conventions are covered by Gradle TestKit against real builds rather than by -reading the plugin source, because the properties that matter — a lane that discovers nothing fails, -a lane reuses a result only when its classes and its lane policy (`rejectSkipped`, `requires`, tag, -category) are unchanged and it starts no server, a malformed registry is refused before any project is included — are -runtime behaviour rather than text in a script. Two of those tests exist because the obvious reading -of the Gradle documentation was wrong: `failOnNoDiscoveredTests` does not fire when a tag filter -matches nothing, and `failOnNoMatchingTests` does not fire when only *some* of the named tests are -missing. +lane과 registry 규약은 플러그인 소스를 읽는 대신 Gradle TestKit으로 실제 빌드에 대고 시험한다. +중요한 성질 — 아무것도 찾지 못한 lane은 실패한다, lane은 클래스와 lane 정책(`rejectSkipped`, +`requires`, tag, category)이 바뀌지 않았고 서버를 띄우지 않을 때만 결과를 다시 쓴다, 잘못된 registry는 +어떤 프로젝트도 포함하기 전에 거절된다 — 이 스크립트의 글이 아니라 런타임 동작이기 때문이다. 그중 +시험 둘은 Gradle 문서를 그대로 읽으면 틀렸기 때문에 있다: tag 필터가 아무것도 맞추지 못할 때 +`failOnNoDiscoveredTests`가 동작하지 않고, 이름을 댄 시험 중 *일부만* 없을 때 +`failOnNoMatchingTests`가 동작하지 않는다. diff --git a/src/composition/outbox-relay/CLAUDE.md b/src/composition/outbox-relay/CLAUDE.md index f63f9fa9..1f890d5f 100644 --- a/src/composition/outbox-relay/CLAUDE.md +++ b/src/composition/outbox-relay/CLAUDE.md @@ -1,21 +1,19 @@ # composition:outbox-relay -- Module ID `composition-outbox-relay`, Gradle path `:composition:outbox-relay`. Registry SSOT: +- 모듈 ID `composition-outbox-relay`, Gradle 경로 `:composition:outbox-relay`. registry 정본: `src/config/architecture/modules.json`. -- Responsibility: assemble and drive the application's outbox relay. It builds - `PublishPendingOutboxEventsUseCase` by hand from `app.outbox.*` (`OutboxSettings`, strict binding), - runs it from `OutboxRelayScheduler` (fixed-delay ticks, a `SmartLifecycle` that stops above the - messaging platform's admission phase), and owns the outbox metrics (`OutboxMetrics`: gauges on a - thread of their own, the cycle-outcome counter from the relay). -- Boundaries: it names ports only — `OutboxStorePort`, `OutboxMessagePublishPort`, - `OutboxRelayFailureReportPort`, `TransactionPort` — never a module type, so removing the - persistence or messaging line removes the relay. No business rule, no SQL, no broker type. The - relay use case is never a bean (`@SystemInvoked`, no permission gate). Allowed edges come only from - the registry entry. -- Startup refusals live here because only here do the settings meet the ports: a batch whose worst - case (`batch-size` × the publish port's `longestAttempt`) reaches `in-flight-timeout` fails startup. -- Tests: `./gradlew :composition:outbox-relay:check`. The shutdown order is pinned against the - platform's own phase constant (`OutboxRelayShutdownOrderTest`); the end-to-end relay → bridge → real - Kafka path is `:adapter:outbound:messaging-kafka:messagingKafkaRelayIntegrationTest`. -- Design and rejected alternatives: `README.md`. Operations: `docs/runbooks/outbox-publish-failed.md`, +- 책임: 애플리케이션의 outbox relay를 조립하고 돌린다. `app.outbox.*`(`OutboxSettings`, 엄격한 + 바인딩)로 `PublishPendingOutboxEventsUseCase`를 손으로 만들고, `OutboxRelayScheduler`(고정 지연 + tick, 메시징 플랫폼의 admission phase보다 위에서 멈추는 `SmartLifecycle`)에서 돌리며, outbox metric + (`OutboxMetrics`: 자기 스레드에서 도는 gauge, relay가 내는 cycle 결과 counter)을 가진다. +- 경계: 포트만 이름으로 댄다 — `OutboxStorePort`, `OutboxMessagePublishPort`, + `OutboxRelayFailureReportPort`, `TransactionPort`. 모듈 타입은 대지 않으니 persistence나 messaging + 줄을 지우면 relay도 빠진다. 업무 규칙, SQL, broker 타입이 없다. relay 유스케이스는 bean이 아니다 + (`@SystemInvoked`, 권한 검사 없음). 허용 edge는 registry 항목에서만 온다. +- 기동 거절은 여기 있다. 설정과 포트가 만나는 곳이 여기뿐이기 때문이다: 최악의 경우 + (`batch-size` × 발행 포트의 `longestAttempt`)가 `in-flight-timeout`에 닿는 batch는 기동에 실패한다. +- 시험: `./gradlew :composition:outbox-relay:check`. 종료 순서는 플랫폼 자신의 phase 상수에 맞춰 + 고정한다(`OutboxRelayShutdownOrderTest`). relay → bridge → 실제 Kafka로 가는 끝에서 끝까지 경로는 + `:adapter:outbound:messaging-kafka:messagingKafkaRelayIntegrationTest`다. +- 설계와 버린 대안: `README.md`. 운영: `docs/runbooks/outbox-publish-failed.md`, `docs/runbooks/outbox-dead-letter.md`. diff --git a/src/config/architecture/README.md b/src/config/architecture/README.md index 07a8d32b..b494cad8 100644 --- a/src/config/architecture/README.md +++ b/src/config/architecture/README.md @@ -1,13 +1,14 @@ -# Architecture module registry +# 아키텍처 모듈 registry -`modules.json` records Gradle project identity and the exact production project edges each leaf may -see. An empty `allowed_dependencies` list is meaningful: it means the leaf is intentionally -project-standalone, not that the registry entry is unfinished. +`modules.json`은 Gradle 프로젝트의 정체(id, Gradle 경로, 소스 경로)와 각 leaf가 볼 수 있는 운영 +프로젝트 edge를 정확히 적는다. 빈 `allowed_dependencies` 목록에도 뜻이 있다: 그 leaf가 일부러 다른 +프로젝트에 기대지 않는다는 뜻이지, registry 항목을 덜 채웠다는 뜻이 아니다. -`adapter-outbound-persistence-mongo` is the important example. That leaf owns the Mongo provider -implementation without importing application/domain project types; composition into application -ports is owned by the bootstrap/autoconfiguration side. Its empty dependency list is therefore an -explicit boundary and must remain empty until a real project edge is introduced and reviewed. +`domain-core`, `shared-contract`, 들여온 메시징 제품의 `messaging-core-api`가 그 예다. 빈 목록은 +분명한 경계이고, 실제 프로젝트 edge를 들여와 리뷰하기 전까지 비어 있어야 한다. 반대로 목록에 적힌 +edge는 빌드가 실제로 쓰는 것과 맞아야 한다. 예를 들어 `adapter-outbound-persistence-mongo`의 목록은 +`["application-core", "shared-contract"]`이고 `MongoRegistryPermissionParityTest`가 두 방향을 모두 +본다. -Runtime composition membership is derived from resolved runtime classpaths by the build logic; it is -not duplicated as a per-module field in this registry. +런타임 조립 구성원은 빌드 로직이 해석된 runtime classpath에서 얻는다. 이 registry에 모듈마다 칸으로 +다시 적지 않는다. diff --git a/src/domain-core/CLAUDE.md b/src/domain-core/CLAUDE.md index 7e32ff10..70bf470b 100644 --- a/src/domain-core/CLAUDE.md +++ b/src/domain-core/CLAUDE.md @@ -1,36 +1,36 @@ -# domain-core — pure domain layer +# domain-core — 순수 도메인 계층 -## Registered identity +## 등록 정보 -- Module ID: `domain-core` -- Gradle path: `:domain-core` -- Focused test (derived from Gradle path): `./gradlew :domain-core:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `domain-core` +- Gradle 경로: `:domain-core` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :domain-core:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.domain`. +패키지 루트: `dev.caskeleton.domain`. 코드 주석에서 덜어낸 **설계 결정의 근거**는 [README.md](README.md) 가 모아둔다 (이 문서는 모듈 규칙 SSOT). -## Responsibility +## 책임 -- Business concepts, entities, value objects, enums, domain events, domain services. -- Repository ports where this reference implementation still keeps domain-owned persistence contracts. -- Domain invariants and core rules. +- 업무 개념, 엔티티, 값 객체, enum, 도메인 이벤트, 도메인 서비스. +- 이 참조 구현이 아직 도메인 소유 영속 계약을 두는 곳의 repository 포트. +- 도메인 불변식과 핵심 규칙. -## Allowed +## 허용 -- Java standard library. -- Value-only shared operational types only if truly needed. +- Java 표준 라이브러리. +- 값만 담은 공용 운영 타입은 정말 필요할 때만. -## Forbidden +## 금지 -- Spring annotations. -- JPA annotations. -- Servlet/HTTP types. -- Adapter, application, bootstrap, or presentation DTO dependencies. +- Spring 애너테이션. +- JPA 애너테이션. +- Servlet·HTTP 타입. +- 어댑터, application, bootstrap, 표현 계층 DTO 의존. -## Test +## 테스트 ```bash cd src diff --git a/src/platforms/grpc-advanced/CLAUDE.md b/src/platforms/grpc-advanced/CLAUDE.md index 158830ae..d78e9d8d 100644 --- a/src/platforms/grpc-advanced/CLAUDE.md +++ b/src/platforms/grpc-advanced/CLAUDE.md @@ -1,6 +1,6 @@ -# grpc-advanced — local authority for the advanced gRPC capabilities +# grpc-advanced — 고급 gRPC capability의 지역 정본 -이 문서는 `grpc-advanced:*` family의 **local authority**다. leaf 목록·gradle path·허용 의존성은 +이 문서는 `grpc-advanced:*` family의 **지역 정본(local authority)**이다. leaf 목록·gradle path·허용 의존성은 `src/config/architecture/modules.json`이 SSOT다. Root 정책(`CLAUDE.md` / `AGENTS.md`)과 충돌하면 root가 이긴다. diff --git a/src/platforms/grpc/CLAUDE.md b/src/platforms/grpc/CLAUDE.md index 190f58d1..d79d4be7 100644 --- a/src/platforms/grpc/CLAUDE.md +++ b/src/platforms/grpc/CLAUDE.md @@ -1,6 +1,6 @@ -# grpc — local authority for the gRPC platform family +# grpc — gRPC 플랫폼 family의 지역 정본 -이 문서는 `grpc:*` family의 **local authority**다. gRPC platform은 기본 application build와 분리된 +이 문서는 `grpc:*` family의 **지역 정본(local authority)**이다. gRPC platform은 기본 application build와 분리된 `src/platforms/optional-build` build가 소유한다. 여기서 정하는 것은 family별 framework 규칙, 증거 등급, Stable 범위의 경계와 application에 채택될 때 필요한 계약이다. @@ -132,64 +132,61 @@ cd src (`GrpcMetricCardinalityPolicy`가 거부한다). -### Adoption-time observability gate +### 채택할 때의 관측 게이트 -The metric names implemented by `grpc-observability` are **not registered in -`docs/registries/metrics.yaml` yet** because this optional family is not a shipped runtime capability. -Do not present those names as repository-certified metrics until adoption adds registry entries with -the repository's `.seconds` / `.total` unit naming and the corresponding validation gate. +`grpc-observability`가 구현한 metric 이름은 **아직 `docs/registries/metrics.yaml`에 등록하지 +않았다**. 이 optional family는 출하하는 런타임 capability가 아니기 때문이다. 채택하면서 저장소의 +`.seconds` / `.total` 단위 이름 규칙에 맞는 registry 항목과 그에 맞는 검증 게이트를 더하기 전에는 그 +이름을 저장소가 인증한 metric처럼 내세우지 않는다. -### Durable operation ledger adoption +### durable operation 원장 채택 -`grpc-spring-boot-starter` does not pull the JPA ledger adapter transitively (11-M9). A deployment that -needs durable operation idempotency adds `:grpc:grpc-operation-ledger-jpa` explicitly, defines a -`GrpcOperationLedger` bean (`new JpaGrpcOperationLedger(repository)`), includes that adapter's Flyway -location `db/migration/grpc` (V001 table, V002 retention index, V003 claim attempt), and sets the flag below. A deployment -that does not adopt the ledger pays no Spring Data JPA classpath cost. +`grpc-spring-boot-starter`는 JPA 원장 어댑터를 전이 의존으로 끌어오지 않는다(11-M9). durable +operation 멱등성이 필요한 배포는 `:grpc:grpc-operation-ledger-jpa`를 직접 더하고, +`GrpcOperationLedger` bean(`new JpaGrpcOperationLedger(repository)`)을 정의하고, 그 어댑터의 Flyway +위치 `db/migration/grpc`(V001 테이블, V002 보존 index, V003 claim attempt)를 넣고, 아래 flag를 켠다. +원장을 채택하지 않는 배포는 Spring Data JPA classpath 비용을 내지 않는다. -| Key (`app.grpc.platform.*`) | Default | What it does | +| 키 (`app.grpc.platform.*`) | 기본값 | 하는 일 | | --- | --- | --- | -| `operation-ledger-enabled` | `false` | `true`: the starter assembles `GrpcIdempotencyInterceptor` (bean `grpcIdempotencyInterceptor`) and `GrpcOperationLedgerRetention` (bean `grpcOperationLedgerRetention`) over the deployment's `GrpcOperationLedger` bean, and refuses startup when there is none. `false`: neither bean exists, and a method that is `IDEMPOTENCY_KEY_REQUIRED` refuses startup | -| `operation-ledger-claim-ttl` | `5m` | How long an `IN_PROGRESS` claim is trusted to have a live owner. After it, a retry of the same request takes the claim over (`GrpcOperationLedger.reclaimStale`). Refused at startup unless longer than every keyed method's deadline | -| `operation-ledger-retention` | `24h` | How long a finished (`COMMITTED`/`FAILED_TERMINAL`) record is kept before `GrpcOperationLedgerRetention.purgeExpired` may delete it. `IN_PROGRESS` rows are never purged | +| `operation-ledger-enabled` | `false` | `true`: starter가 배포의 `GrpcOperationLedger` bean 위에 `GrpcIdempotencyInterceptor`(bean `grpcIdempotencyInterceptor`)와 `GrpcOperationLedgerRetention`(bean `grpcOperationLedgerRetention`)을 조립하고, 원장 bean이 없으면 기동을 거절한다. `false`: 두 bean 모두 없고, `IDEMPOTENCY_KEY_REQUIRED`인 메서드가 있으면 기동을 거절한다 | +| `operation-ledger-claim-ttl` | `5m` | `IN_PROGRESS` claim의 주인이 살아 있다고 믿는 시간. 지나면 같은 요청의 재시도가 claim을 넘겨받는다(`GrpcOperationLedger.reclaimStale`). 키가 필요한 모든 메서드의 deadline보다 길지 않으면 기동에서 거절한다 | +| `operation-ledger-retention` | `24h` | 끝난(`COMMITTED`/`FAILED_TERMINAL`) 레코드를 `GrpcOperationLedgerRetention.purgeExpired`가 지울 수 있게 되기 전까지 두는 시간. `IN_PROGRESS` 행은 지우지 않는다 | -Defaults: the 5-minute TTL is the value the ledger contract and interceptor tests certify, far beyond -a unary deadline, and short enough that a key whose owner died unblocks within a client's retry -patience. The 24-hour retention matches the HTTP idempotency replay TTL -(`app.capabilities.idempotency.replay-ttl`). A retry of a key after its record was purged is a new -operation, so the retention must exceed the callers' retry window. +기본값: 5분 TTL은 원장 계약 시험과 interceptor 시험이 인증한 값이다. unary deadline보다 훨씬 길고, +주인이 죽은 키가 클라이언트의 재시도 인내 안에 풀릴 만큼 짧다. 24시간 보존은 HTTP 멱등성 재생 TTL +(`app.capabilities.idempotency.replay-ttl`)과 같다. 레코드를 지운 뒤 같은 키로 하는 재시도는 새 +operation이므로, 보존 시간은 호출자의 재시도 창보다 길어야 한다. -These keys are not in `docs/registries/env-keys.yaml`: no `app.grpc.platform.*` key is, because the -optional build is not part of the shipped runtime. They join the registry when a composition root -adopts the platform. +이 키들은 `docs/registries/env-keys.yaml`에 없다. optional 빌드는 출하하는 런타임이 아니라서 +`app.grpc.platform.*` 키는 하나도 없다. 조립 루트가 플랫폼을 채택할 때 registry에 들어간다. -**Why the starter assembles the interceptor (option (b)), and not (a).** The 2026-11-01 maturity review proposed (a): -delete the flag and judge by whether a ledger bean exists. (b) was chosen on 2026-11-03 and is recorded in -ADR-GRPC-004: the flag stays and means what it says — when true, the -decision function is assembled and its TTL comes from configuration. (a) would have removed the false promise but left every adopter to rebuild the same -assembly and TTL validation by hand; (b) keeps that in one place. The interceptor bean has no -`@ConditionalOnMissingBean` on purpose: a replacement would silently ignore `operation-ledger-claim-ttl`. -Duplicates of a running operation are refused (`REJECT_IN_PROGRESS`), not told to wait; a -wait-and-poll option becomes a key when a keyed method needs it. +**starter가 interceptor를 조립하는 이유(선택지 (b)), (a)가 아닌 이유.** 2026-11-01 성숙도 리뷰는 +(a)를 제안했다: flag를 지우고 원장 bean이 있는지로 판단한다. 2026-11-03에 (b)를 골랐고 ADR-GRPC-004에 +적었다: flag를 남기고 flag는 말 그대로의 뜻이다 — true이면 판정 함수를 조립하고 그 TTL은 설정에서 +온다. (a)는 거짓 약속을 없앴겠지만 채택하는 쪽마다 같은 조립과 TTL 검증을 손으로 다시 만들게 +했다. (b)는 그것을 한곳에 둔다. interceptor bean에는 일부러 `@ConditionalOnMissingBean`이 없다: +바꿔 넣은 bean은 `operation-ledger-claim-ttl`을 소리 없이 무시하게 된다. 돌고 있는 operation의 +중복은 기다리라고 하지 않고 거절한다(`REJECT_IN_PROGRESS`). 기다렸다가 다시 묻는 선택지는 키가 +필요한 메서드가 그것을 필요로 할 때 키가 된다. -**Server wiring is still the adopter's, and stays a separate decision.** The starter builds no -server, so assembling the decision does not wire the platform into `adapter:inbound:grpc` (see "배선은 -별도 결정" above). `GrpcIdempotencyInterceptor` is a decision function, not an `io.grpc.ServerInterceptor`. -The adopter injects the bean by type and calls it from its own `IDEMPOTENCY` stage interceptor -(`GrpcServerInterceptorChain.builder().stage(GrpcServerInterceptorStage.IDEMPOTENCY, ...)`) or from -its typed service adapter: `decide(...)` before the mutation, `recordCommit(...)` inside the mutation's -transaction, `recordFailure(...)` on a terminal failure. Both record calls take the `GrpcClaimToken` -the `PROCEED` decision carried: a commit by an attempt whose claim was taken over is refused (its -transaction rolls back) and its failure is ignored, so a slow owner cannot write over the attempt that -took its claim (ADR-GRPC-004). +**서버 배선은 여전히 채택하는 쪽의 몫이고, 따로 정할 일로 남는다.** starter는 서버를 만들지 +않으므로, 판정을 조립한다고 플랫폼이 `adapter:inbound:grpc`에 배선되지는 않는다(위 "배선은 +별도 결정"을 본다). `GrpcIdempotencyInterceptor`는 판정 함수이고 `io.grpc.ServerInterceptor`가 +아니다. 채택하는 쪽은 bean을 타입으로 주입받아 자기 `IDEMPOTENCY` 단계 interceptor +(`GrpcServerInterceptorChain.builder().stage(GrpcServerInterceptorStage.IDEMPOTENCY, ...)`)나 자기 +typed service adapter에서 부른다: 변경 전에 `decide(...)`, 변경의 트랜잭션 안에서 +`recordCommit(...)`, 끝난 실패에 `recordFailure(...)`. 두 기록 호출은 모두 `PROCEED` 판정이 실어 온 +`GrpcClaimToken`을 받는다: claim을 넘겨준 시도의 커밋은 거절되고(그 트랜잭션은 롤백된다) 그 실패는 +무시된다. 그래서 느린 주인이 claim을 가져간 시도를 덮어쓰지 못한다(ADR-GRPC-004). -**Purge scheduling is the adopter's.** `GrpcOperationLedgerRetention.purgeExpired(now)` deletes -expired finished rows in bounded batches (500 per statement) until a batch comes back short. The -starter does not schedule it: it owns no scheduler and cannot know which replica should run it, and a -scheduled bean would force a task scheduler onto every deployment. The adopter calls it from its own -scheduler (for example hourly); concurrent runs on several replicas are safe because the delete skips -locked rows. Running it never is safe but lets the table grow without bound. +**지우기 일정은 채택하는 쪽의 몫이다.** `GrpcOperationLedgerRetention.purgeExpired(now)`는 기한이 지난 +끝난 행을 한계 있는 batch(문장 하나에 500)로 지우고, batch가 덜 차서 돌아오면 멈춘다. starter는 이것을 +예약하지 않는다: scheduler를 가지지 않고 어느 replica가 돌려야 하는지 알 수 없으며, 예약된 bean은 모든 +배포에 task scheduler를 강요하게 된다. 채택하는 쪽이 자기 scheduler에서 부른다(예: 한 시간마다). +지우기가 잠긴 행을 건너뛰므로 여러 replica에서 동시에 돌려도 안전하다. 한 번도 돌리지 않아도 안전하지만 +테이블이 끝없이 커진다. -The commit must be recorded in the mutation's transaction and the TTL must be longer than the slowest -keyed method; both reasons are in ADR-GRPC-004. +커밋은 변경의 트랜잭션 안에서 기록해야 하고 TTL은 키가 필요한 가장 느린 메서드보다 길어야 한다. 두 +이유는 모두 ADR-GRPC-004에 있다. diff --git a/src/platforms/messaging/CLAUDE.md b/src/platforms/messaging/CLAUDE.md index eda4b578..705cc3f3 100644 --- a/src/platforms/messaging/CLAUDE.md +++ b/src/platforms/messaging/CLAUDE.md @@ -1,6 +1,6 @@ -# messaging — local authority for the messaging platform family +# messaging — 메시징 플랫폼 family의 지역 정본 -이 문서는 messaging family의 **local authority**다. leaf 목록·gradle path·허용 의존성은 +이 문서는 messaging family의 **지역 정본(local authority)**이다. leaf 목록·gradle path·허용 의존성은 `src/config/architecture/modules.json`이 SSOT이며 이 문서는 그것을 복제하지 않는다. 여기서 정하는 것은 registry가 표현할 수 없는 것들이다: family별 framework 규칙, public surface 정책, Stable 승격에 필요한 증거, runtime membership이 비어 있다는 사실의 의미. @@ -40,7 +40,7 @@ JDBC이고 SQL은 `jsonb` · `FOR UPDATE SKIP LOCKED` · `ON CONFLICT` · `TIMES registry edge를 주면 그 경계가 깨진다. 복사본을 고칠 때(키 길이 검사, constant-time 비교 등)는 `shared-contract`의 정본과 같은 규칙인지 함께 본다. -### Publish retryability of authentication and authorization +### 인증·인가 거부의 발행 재시도 여부 (Publish retryability of authentication and authorization) 이 제품 안에는 같은 category에 대한 재시도 규칙이 둘 있다. 의도다. diff --git a/src/platforms/optional-build/README.md b/src/platforms/optional-build/README.md index e6bce651..8df221e1 100644 --- a/src/platforms/optional-build/README.md +++ b/src/platforms/optional-build/README.md @@ -1,13 +1,13 @@ -# Optional gRPC platforms +# optional gRPC 플랫폼 -The default application does not depend on `grpc/*` or `grpc-advanced/*`, so those projects (the -registry entries with `"build": "optional-grpc"`) are kept out of the main multi-project build. This build preserves their existing project paths and -internal project dependencies while making their configuration opt-in. +기본 애플리케이션은 `grpc/*`나 `grpc-advanced/*`에 의존하지 않는다. 그래서 이 프로젝트들(registry에서 +`"build": "optional-grpc"`인 항목)은 주 멀티 프로젝트 빌드에서 뺀다. 이 빌드는 그 프로젝트들의 원래 +프로젝트 경로와 내부 프로젝트 의존을 그대로 두면서, 그 설정을 고를 때만 켜지게 한다. ```bash ./gradlew -p platforms/optional-build ci ./gradlew -p platforms/optional-build :grpc:grpc-testkit:grpcInProcessContractTest ``` -`adapter:inbound:grpc` remains in the main application build because it is an application adapter; -the reusable gRPC platform libraries are optional capability code and live here. +`adapter:inbound:grpc`는 애플리케이션 어댑터라서 주 애플리케이션 빌드에 남는다. 다시 쓰는 gRPC +플랫폼 라이브러리는 optional capability 코드이고 여기 있다. diff --git a/src/shared-contract/CLAUDE.md b/src/shared-contract/CLAUDE.md index 3739e420..6722710c 100644 --- a/src/shared-contract/CLAUDE.md +++ b/src/shared-contract/CLAUDE.md @@ -1,72 +1,68 @@ -# shared-contract — skeleton-wide operational contract +# shared-contract — 골격 전체가 쓰는 운영 계약 -## Registered identity +## 등록 정보 -- Module ID: `shared-contract` -- Gradle path: `:shared-contract` -- Focused test (derived from Gradle path): `./gradlew :shared-contract:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `shared-contract` +- Gradle 경로: `:shared-contract` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :shared-contract:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.shared`. +패키지 루트: `dev.caskeleton.shared`. -Design decisions previously kept as code comments (error-code classification, response -envelope shape, metric cardinality bounds, tracing seam, domain-context propagation) live in -[README.md](README.md). This file stays the SSOT for module rules. +예전에 코드 주석에 두던 설계 결정(오류 코드 분류, 응답 envelope 모양, metric cardinality 한계, +tracing 이음매, domain-context 전파)은 [README.md](README.md)에 있다. 이 파일은 모듈 규칙의 정본으로 +남는다. -## Responsibility -- Response envelope (`response/Envelope`, `response/ApiError`, `response/BulkEnvelope`, `response/BulkItemResult`). -- Error code contract (`error/ApiErrorCode` interface, `error/OperationalError` enum, - `error/ApiErrorCarrier`) and the one client-facing wording table (`error/ClientErrorMessages`, - Korean, one message per `Category`, used by every transport). -- Cross-cutting mapper sentinel (`error/MappingException`). -- Request value contract (`request/Patch`). -- Tracing contract types (`tracing/TraceParent`, `tracing/SpanErrorRecorder`) — W3C - `traceparent` value type and the span-error-recording seam (feature-distributed-tracing-contract; the OTel - tracer runtime is a fork-activated seam, so these stay Java-stdlib-only). -- Stdlib helpers every leaf used to copy (moved here in the 2026-09-25 review follow-up): `digest/Sha256` (the - SHA-256 digest value and the one `MessageDigest.getInstance("SHA-256")`), `digest/HmacSha256` - (sign and constant-time verify), `retry/Backoff` (capped exponential ceiling; "full jitter" means - `U[0, ceiling]` and nothing else). Vendored `messaging:*` and the optional gRPC build do not depend - on this module and keep their own copies; each family's CLAUDE.md says why (a different product, - decided after the 2026-08-14 messaging module review). Every template leaf that needs one of these has the `shared-contract` edge and uses them - instead of copying: identifier, persistence-mongo, application-objectstorage and redis-sdk took the - edge for exactly this (decided 2026-11-03), each with a test - that pins its output to a vector computed outside the JVM. -- `observability/MdcKeys`: the snake_case MDC key names (registry `docs/registries/mdc-keys.yaml`) - every transport puts a request's correlation under — web, GraphQL, STOMP and gRPC alike. -- `ratelimit/`: the provider-neutral edge rate-limit port (`EdgeRateLimitPort`) and its value types, - between the web edge and the Redis adapter (README 「ratelimit」). -- `security/Permission`: the `resource:action` permission value `AuthorizationPort` is asked about - (README 「security」). -- `concurrency/`: the domain-context propagation port and its `ThreadLocal` default (README - 「concurrency」). -- `runtime/RuntimeEnvironment`: the one runtime-profile vocabulary every leaf answers "is this - production?" with. -- `metrics/ForbiddenMetricTags`: the high-cardinality tag keys no metric may carry. -- These are the module's packages and the only ones it may have: - `ForbiddenApiArchitectureTest.SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES` refuses a - class in any other package below `dev.caskeleton.shared` or directly in the root, which holds only - its `package-info`. A new contract package goes into that test's `SHARED_CONTRACT_PACKAGES` and - into this list together; `SharedContractPackageRuleTest` fails when `SHARED_CONTRACT_PACKAGES` and - the module's packages differ. -- Registry-rule mirrors read only by contract tests live in `testFixtures`, not `main`: +## 책임 (Responsibility) +- 응답 envelope(`response/Envelope`, `response/ApiError`, `response/BulkEnvelope`, `response/BulkItemResult`). +- 오류 코드 계약(`error/ApiErrorCode` 인터페이스, `error/OperationalError` enum, + `error/ApiErrorCarrier`)과 클라이언트에 보여 줄 문구 표 하나(`error/ClientErrorMessages`. + 한국어이고 `Category`마다 문구 하나이며 모든 전송 계층이 쓴다). +- 계층을 가로지르는 mapper 표지 예외(`error/MappingException`). +- 요청 값 계약(`request/Patch`). +- tracing 계약 타입(`tracing/TraceParent`, `tracing/SpanErrorRecorder`) — W3C `traceparent` 값 타입과 + span 오류 기록 이음매(feature-distributed-tracing-contract. OTel tracer 런타임은 fork가 켜는 + 이음매라서 이 타입들은 Java 표준 라이브러리만 쓴다). +- 모든 leaf가 복사해 쓰던 표준 라이브러리 도우미(2026-09-25 리뷰 후속으로 여기로 옮겼다): + `digest/Sha256`(SHA-256 digest 값과 유일한 `MessageDigest.getInstance("SHA-256")`), + `digest/HmacSha256`(서명과 상수 시간 검증), `retry/Backoff`(상한 있는 지수 ceiling. "full jitter"는 + `U[0, ceiling]`이고 다른 뜻이 아니다). 들여온 `messaging:*`와 optional gRPC 빌드는 이 모듈에 + 의존하지 않고 자기 사본을 둔다. 각 제품의 CLAUDE.md가 이유를 적는다(다른 제품이다. 2026-08-14 메시징 + 모듈 리뷰 뒤에 정했다). 이 도우미가 필요한 템플릿 leaf는 모두 `shared-contract` edge를 두고 복사하지 + 않고 쓴다. identifier, persistence-mongo, application-objectstorage, redis-sdk가 바로 이 때문에 + edge를 받았고(2026-11-03에 정함), 각각 JVM 밖에서 계산한 벡터로 출력을 고정하는 시험이 있다. +- `observability/MdcKeys`: 모든 전송 계층(web, GraphQL, STOMP, gRPC)이 요청의 correlation을 넣는 + snake_case MDC 키 이름(registry `docs/registries/mdc-keys.yaml`). +- `ratelimit/`: web edge와 Redis 어댑터 사이에 있는 provider 중립 edge rate-limit 포트 + (`EdgeRateLimitPort`)와 그 값 타입(README 「ratelimit」). +- `security/Permission`: `AuthorizationPort`에 묻는 `resource:action` 권한 값(README 「security」). +- `concurrency/`: domain-context 전파 포트와 그 `ThreadLocal` 기본 구현(README 「concurrency」). +- `runtime/RuntimeEnvironment`: 모든 leaf가 「운영 환경인가?」에 답할 때 쓰는 유일한 runtime profile + 어휘. +- `metrics/ForbiddenMetricTags`: 어떤 metric도 실으면 안 되는 high-cardinality tag 키. +- 이 모듈의 패키지는 위가 전부이고 다른 패키지는 둘 수 없다: + `ForbiddenApiArchitectureTest.SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES`가 + `dev.caskeleton.shared` 아래 다른 패키지에 있는 클래스와 루트에 바로 있는 클래스를 거절한다. 루트에는 + `package-info`만 있다. 새 계약 패키지는 그 시험의 `SHARED_CONTRACT_PACKAGES`와 이 목록에 함께 + 넣는다. `SharedContractPackageRuleTest`는 `SHARED_CONTRACT_PACKAGES`와 모듈의 패키지가 다르면 + 실패한다. +- 계약 시험만 읽는 registry 규칙 사본은 `main`이 아니라 `testFixtures`에 둔다: `metrics/MetricNaming`, `metrics/CardinalityBounds`, `metrics/AlertSeverity`, - `tracing/BaggageAllowlist`. Move one to `main` only when production code consumes it. -- Generic messaging envelope schema resources under `contracts/messaging/envelope/`. - They own transport-neutral envelope metadata only; feature payload schemas remain in their - feature-owner modules. Resource presence is not runtime discovery or registration. + `tracing/BaggageAllowlist`. 운영 코드가 쓰게 될 때만 `main`으로 옮긴다. +- `contracts/messaging/envelope/` 아래의 범용 메시징 envelope schema 리소스. 전송 중립 envelope + metadata만 가진다. 기능 payload schema는 그 기능을 가진 모듈에 남는다. 리소스가 있다고 런타임에 + 찾아지거나 등록되는 것은 아니다. -## Allowed -- Java standard library ONLY. No Spring, no Jackson, no JPA imports. +## 허용 +- Java 표준 라이브러리**만**. Spring, Jackson, JPA import는 없다. -## Forbidden -- business/domain concept (domain error codes belong in the consuming module). -- framework imports (HTTP status is expressed as transport-neutral `int`; the web module maps it). -- claiming Draft 2020-12 validator compatibility before the messaging adapter's Task 6 validator - qualification exists. +## 금지 (Forbidden) +- 업무·도메인 개념(도메인 오류 코드는 그것을 쓰는 모듈에 둔다). +- 프레임워크 import(HTTP 상태는 전송 중립 `int`로 나타내고 web 모듈이 대응시킨다). +- 메시징 어댑터의 Task 6 validator 검증이 생기기 전에 Draft 2020-12 validator 호환을 주장하기. -## Test +## 테스트 ```bash cd src ./gradlew :shared-contract:test From 5a3784be58590d78d43a3d8bc206adc6f19870e3 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 7 Nov 2026 17:12:03 +0900 Subject: [PATCH 2/6] =?UTF-8?q?docs(adapter-inbound):=20inbound=20?= =?UTF-8?q?=EC=96=B4=EB=8C=91=ED=84=B0=20=EB=AA=A8=EB=93=88=20=EB=AC=B8?= =?UTF-8?q?=EC=84=9C=EB=A5=BC=20=ED=95=9C=EA=B5=AD=EC=96=B4=EB=A1=9C=20?= =?UTF-8?q?=EC=98=AE=EA=B8=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: inbound 어댑터 leaf(messaging, web, web-advanced, websocket, graphql, grpc)의 CLAUDE.md가 영어이거나 영어 절이 섞여 있다. 다섯 CLAUDE.md는 Spring Boot 버전(4.0.0, 4.0.8)을, graphql README는 leaf 개수(19·24·43)를 복사해 두었고 그 수는 registry가 바뀌면 틀린다. 방법: 뜻을 그대로 옮기고 코드·명령·경로·식별자·설정 키·표 구조는 원문으로 둔다. 버전은 `src/gradle/libs.versions.toml`을, leaf 수는 registry를 가리키게 고친다. 번역하며 본 코드와 어긋난 주장은 코드에 맞춘다: web CLAUDE.md의 `adapter-persistence`(없는 이름)를 `adapter:outbound:persistence-jpa`로, Jackson 속성 위치를 `spring.jackson.serialization.*`·`generator.*`에서 실제 키 `spring.jackson.deserialization.*`·`spring.jackson.datatype.*`로, 「`WRITE_BIGDECIMAL_AS_PLAIN=true`로 고정」을 「설정 키가 아니라 `JacksonSerializationPolicyTest`가 지수 표기 없음을 단언」으로 고친다. 매뉴얼 장 번호만 쓴 참조는 경로와 절 제목으로 바꾼다. 위험: ArchUnit 규칙 이름의 대소문자(문서는 소문자, 코드는 대문자 상수)는 이 커밋에서 그대로 두고 다음 커밋에서 한꺼번에 맞춘다. 검증: python3 scripts/check-docs.py rc=0(language 줄 4개, number 줄 7개 지움), check-work-docs.py rc=0, --links(gates.md 범위) 깨진 링크 0. --- scripts/check-docs-exceptions.txt | 11 - src/adapter/inbound/graphql/CLAUDE.md | 56 ++-- src/adapter/inbound/graphql/README.md | 6 +- src/adapter/inbound/grpc/CLAUDE.md | 52 ++-- src/adapter/inbound/messaging/CLAUDE.md | 40 ++- src/adapter/inbound/web-advanced/CLAUDE.md | 66 ++--- src/adapter/inbound/web/CLAUDE.md | 315 +++++++++------------ src/adapter/inbound/web/README.md | 15 +- src/adapter/inbound/websocket/CLAUDE.md | 181 ++++++------ 9 files changed, 335 insertions(+), 407 deletions(-) diff --git a/scripts/check-docs-exceptions.txt b/scripts/check-docs-exceptions.txt index 08f57e77..2b41d107 100644 --- a/scripts/check-docs-exceptions.txt +++ b/scripts/check-docs-exceptions.txt @@ -146,10 +146,6 @@ language docs/web/runbook.md language docs/web/streaming-contract.md language docs/web/virtual-thread-profile.md language docs/websocket/runbook.md -language src/adapter/inbound/messaging/CLAUDE.md -language src/adapter/inbound/web-advanced/CLAUDE.md -language src/adapter/inbound/web/CLAUDE.md -language src/adapter/inbound/websocket/CLAUDE.md language src/adapter/outbound/cache-redis/CLAUDE.md language src/adapter/outbound/cache-redis/README.md language src/adapter/outbound/fileserver/CLAUDE.md @@ -189,13 +185,6 @@ number docs/jpa/repository-adaptation.md Spring Boot 4.0.8 number docs/manual/01-generator.md 5 leaf number docs/mongodb/repository-adaptation.md 19 leaf number docs/mongodb/repository-adaptation.md Spring Boot 4.0.8 -number src/adapter/inbound/graphql/CLAUDE.md Spring Boot 4.0.0 -number src/adapter/inbound/graphql/README.md 19개 leaf -number src/adapter/inbound/graphql/README.md 24개 leaf -number src/adapter/inbound/graphql/README.md 43개 leaf -number src/adapter/inbound/grpc/CLAUDE.md Spring Boot 4.0.0 -number src/adapter/inbound/web/CLAUDE.md Spring Boot 4.0.0 -number src/adapter/inbound/websocket/CLAUDE.md Spring Boot 4.0.8 number src/adapter/outbound/cache-redis/CLAUDE.md Spring Boot 4.0.0 number src/adapter/outbound/fileserver/CLAUDE.md Spring Boot 4.0.0 number src/adapter/outbound/httpclient/CLAUDE.md Spring Boot 4.0.0 diff --git a/src/adapter/inbound/graphql/CLAUDE.md b/src/adapter/inbound/graphql/CLAUDE.md index 89dd89bf..bec9db91 100644 --- a/src/adapter/inbound/graphql/CLAUDE.md +++ b/src/adapter/inbound/graphql/CLAUDE.md @@ -1,12 +1,12 @@ -# adapter:inbound:graphql — inbound GraphQL adapter (skeleton machinery) +# adapter:inbound:graphql — inbound GraphQL 어댑터(골격 장치) -## Registered identity +## 등록 정보 -- Module ID: `adapter-inbound-graphql` -- Gradle path: `:adapter:inbound:graphql` -- Focused test (derived from Gradle path): `./gradlew :adapter:inbound:graphql:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-inbound-graphql` +- Gradle 경로: `:adapter:inbound:graphql` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:inbound:graphql:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. Package root: `dev.caskeleton.adapter.inbound.graphql`. @@ -46,7 +46,7 @@ sub-package 사이의 경계(Stable↔Advanced 방향, 모듈 레코드)를 값 두 규칙 모두 위반 fixture 로 실제로 잡히는지 같은 테스트가 확인한다. `graphqlStableTest` 의 required-class 검사가 이 테스트가 조용히 사라지는 것을 막는다. -## Responsibility +## 책임 - GraphQL 전송 인프라만: 최소 health 스키마(`skeleton.graphqls`) + `HealthGraphqlController`, 프로토콜 에러 매핑(`error/GraphQlWireErrorMapper`). Spring for GraphQL 이 스키마와 컨트롤러를 @@ -62,28 +62,26 @@ required-class 검사가 이 테스트가 조용히 사라지는 것을 막는 실제 활성화 시 composition root 는 인증/인가·CORS 정책과 GraphiQL/introspection 운영 설정을 함께 명시해야 한다. -## Error-code ownership +## 오류 코드 소유 -`docs/registries/error-codes.yaml` is the skeleton-wide `OperationalError` SSOT; it is not a -catch-all registry for transport-specific presentation codes. GraphQL therefore keeps its own finite -platform wire-code catalogue in `GraphQlErrorCode`. +`docs/registries/error-codes.yaml`은 골격 전체의 `OperationalError` 정본이다. 전송 계층마다 다른 표현 +코드를 모두 받는 registry가 아니다. 그래서 GraphQL은 자기의 유한한 플랫폼 wire 코드 catalog를 +`GraphQlErrorCode`에 둔다. -- GraphQL platform mappers must use `GraphQlErrorCode.platform(...)`. An unregistered platform code - fails immediately. -- application/domain `ApiErrorCode` values remain a separate namespace and pass through with - `GraphQlErrorCode.of(...)`; GraphQL must not rename product errors. Only a registered - `ApiErrorCode` reaches the wire this way — a DataLoader per-key failure carries one, never a free - string (owner decision 2026-09-25). -- new GraphQL-owned platform codes use the `GRAPHQL_` prefix. The existing unprefixed platform - values are frozen legacy wire contracts and are listed explicitly by - `legacyUnprefixedPlatformCodes()`. -- modelled-only capability codes are not added to `platformCodes()` until that capability reaches - the shipped request path. +- GraphQL 플랫폼 mapper는 `GraphQlErrorCode.platform(...)`을 써야 한다. 등록되지 않은 플랫폼 코드는 바로 + 실패한다. +- application·domain `ApiErrorCode` 값은 별도 namespace로 남고 `GraphQlErrorCode.of(...)`로 그대로 지나간다. + GraphQL은 제품 오류의 이름을 바꾸면 안 된다. 이 길로 wire에 닿는 것은 등록된 `ApiErrorCode`뿐이다 — + DataLoader의 키별 실패도 그것을 싣고, 자유 문자열을 싣지 않는다(소유자 결정 2026-09-25). +- GraphQL이 가진 새 플랫폼 코드는 `GRAPHQL_` 접두어를 쓴다. 접두어 없는 기존 플랫폼 값은 얼려 둔 옛 wire + 계약이고 `legacyUnprefixedPlatformCodes()`가 하나씩 적는다. +- 모델만 있는 capability 코드는 그 capability가 출하하는 요청 경로에 닿기 전까지 `platformCodes()`에 + 더하지 않는다. -`GraphQlErrorCodeCatalogTest` pins the exact shipped catalogue, the prefix rule and the -application/platform namespace split. +`GraphQlErrorCodeCatalogTest`가 출하하는 catalog 전체, 접두어 규칙, application·플랫폼 namespace 분리를 +고정한다. -## Allowed +## 허용 - `:application-core`, `:domain-core`, `:shared-contract`. `:application-core` 는 선언만이 아니라 실제 의존이다 — object 인가의 **답하는 계약**(`dev.caskeleton.application.security.ObjectAccessPolicy`)이 @@ -107,7 +105,7 @@ application/platform namespace split. `@ConfigurationProperties` 이므로 `ca.spring-config` convention plugin이 주는 패리티 게이트가 이 선언을 요구한다. -## Forbidden +## 금지 - outbound 어댑터(`:adapter:outbound:*`)에 대한 직접 의존 — 인바운드는 application 아웃바운드 포트를 통해서만 persistence/messaging/cache/http 에 닿는다 (ArchUnit @@ -117,7 +115,7 @@ application/platform namespace split. `HealthcheckController` 와 동일 원칙). feature 스키마/컨트롤러/매퍼는 그 기능을 가진 서비스가 소유한다. - 모듈별 `yml` — 설정은 프레임워크 `spring.graphql.*` 로 composition-root `application.yml` 에 산다. -## Error mapping (`Category → ErrorType`) +## 오류 대응 (`Category → ErrorType`) 모든 client 에러는 `error/GraphQlWireErrorMapper` 하나를 거친다 — 전송 interceptor, 실행 전 pipeline(instrumentation), data fetcher resolver 세 곳이 같은 bean 을 받는다. 순서는 플랫폼 거부 @@ -181,7 +179,7 @@ health 스키마만 소유한다. (`docs/capability-status.md` 제거 표). 다시 필요하면 Spring GraphQL/graphql-java SPI 를 구현하는 형태로 새로 만든다. -## Test +## 테스트 ```bash cd src diff --git a/src/adapter/inbound/graphql/README.md b/src/adapter/inbound/graphql/README.md index ff9c7c63..98e59e89 100644 --- a/src/adapter/inbound/graphql/README.md +++ b/src/adapter/inbound/graphql/README.md @@ -176,15 +176,15 @@ composition root 는 이 leaf 를 채택할 때 인증/인가 및 CORS 정책을 ## 설계서의 "모듈"을 Gradle 모듈로 만들지 않은 이유 -설계서는 Stable 16 + Advanced 12 = 28개 Gradle 모듈을 전제한다. 구현 시점의 레지스트리 -(`src/config/architecture/modules.json`)는 19개 leaf 였고, 28개를 추가하는 것은 레지스트리· +설계서는 Stable 16 + Advanced 12 = 28개 Gradle 모듈을 전제한다. 그 28개를 구현 시점의 레지스트리 +(`src/config/architecture/modules.json`)에 추가하는 것은 레지스트리· `settings.gradle` fail-closed 검증·의존 게이트를 동시에 건드리는 변경이다. GraphQL 표면은 하나의 인바운드 전송 경계이므로 그 **내부** 분할을 레포 전역 SSOT 까지 밀어올리지 않기로 하고, **모듈 = bounded sub-package** 로 매핑했다(선례: httpclient leaf 가 366개 java 파일을 같은 방식으로 담는다). **정직하게 기록해 둘 반례:** 이후 main 에 통합된 자매 플랫폼 messaging 은 정반대로 -**24개 leaf 를 레지스트리에 등록**했다(현재 총 43개 leaf). 즉 레지스트리는 닫혀 있지 않았고, +**자기 leaf 를 레지스트리에 하나씩 등록**했다(지금의 leaf 목록과 수는 레지스트리가 정한다). 즉 레지스트리는 닫혀 있지 않았고, "확장하면 게이트가 깨진다"는 전제는 과했다. 두 플랫폼이 서로 다른 패턴을 쓰고 있으므로 **어느 쪽으로 통일할지는 미결 아키텍처 결정**이다. diff --git a/src/adapter/inbound/grpc/CLAUDE.md b/src/adapter/inbound/grpc/CLAUDE.md index 5c4dff1a..9b4ef61f 100644 --- a/src/adapter/inbound/grpc/CLAUDE.md +++ b/src/adapter/inbound/grpc/CLAUDE.md @@ -1,19 +1,19 @@ -# adapter:inbound:grpc — inbound gRPC adapter (skeleton machinery) +# adapter:inbound:grpc — inbound gRPC 어댑터(골격 장치) -## Registered identity +## 등록 정보 -- Module ID: `adapter-inbound-grpc` -- Gradle path: `:adapter:inbound:grpc` -- Focused test (derived from Gradle path): `./gradlew :adapter:inbound:grpc:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-inbound-grpc` +- Gradle 경로: `:adapter:inbound:grpc` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:inbound:grpc:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. Package root: `dev.caskeleton.adapter.inbound.grpc`. 코드 주석에서 덜어낸 **설계 결정의 근거**는 [README.md](README.md) 가 모아둔다 (이 문서는 모듈 규칙 SSOT). -## Responsibility +## 책임 - gRPC 전송 인프라만: 서버 수명주기(`GrpcServerRunner`), 타입드 설정(`GrpcServerSettings`), feature 인증 정책 경계, 프로토콜 에러 매핑(`GrpcStatusMapper` + @@ -22,13 +22,13 @@ Package root: `dev.caskeleton.adapter.inbound.grpc`. - feature-agnostic: 모든 `io.grpc.BindableService` 빈을 generic 하게 등록하며 구체 기능을 이름으로 알지 않는다. -## Allowed +## 허용 - `:application-core`, `:domain-core`, `:shared-contract`. - `io.grpc:*` (grpc-netty-shaded / grpc-protobuf / grpc-stub / grpc-services), `spring-boot-starter`, `spring-boot-starter-validation`. -## Forbidden +## 금지 - outbound 어댑터(`:adapter:outbound:*`)에 대한 직접 의존 — 인바운드는 application 아웃바운드 포트를 통해서만 persistence/messaging/cache/http 에 닿는다 (ArchUnit @@ -38,7 +38,7 @@ Package root: `dev.caskeleton.adapter.inbound.grpc`. - 프로덕션 feature RPC 를 스켈레톤에 두는 것 — health/reflection 표면만 (web 의 `HealthcheckController` 와 동일 원칙). -## Config knobs (`app.grpc.server.*`) +## 설정 손잡이 (`app.grpc.server.*`) 타입드 `@ConfigurationProperties` 만 두고, 값은 composition-root `application.yml` 에 산다 (모듈별 `yml` 없음). prefix가 `app.grpc`가 아니라 `.server`까지인 이유: 바인딩이 @@ -69,24 +69,22 @@ Package root: `dev.caskeleton.adapter.inbound.grpc`. `enabled=true`는 `allowInsecureLocal=true`와 실제 loopback `bindAddress`가 함께 없으면 configuration binding/startup 단계에서 실패한다. -## Adopting this capability +## 이 capability 채택하기 -gRPC is also a **build-composition opt-in**. The default bootJar does not contain this leaf. +gRPC도 **빌드 조립에서 고르는 것**이다. 기본 bootJar에는 이 leaf가 없다. -1. Add `:adapter:inbound:grpc` to the consuming composition and add the corresponding allowed - dependency edge in `config/architecture/modules.json`. -2. Register settings through the capability root; do not add - `dev.caskeleton.adapter.inbound.grpc` to the shipped `@ConfigurationPropertiesScan`. -3. Provide any feature `BindableService` plus exactly one `GrpcAuthenticationPolicy`. -4. Run `./gradlew :adapter:inbound:grpc:test :conditionalTransportQualification` before promotion. -5. Production adoption is incomplete until composition-owned configuration/env registry entries - exist for the selected runtime contract. +1. 쓰는 조립에 `:adapter:inbound:grpc`를 더하고 `config/architecture/modules.json`에 맞는 허용 의존 + edge를 더한다. +2. 설정은 capability 루트로 등록한다. 출하하는 `@ConfigurationPropertiesScan`에 + `dev.caskeleton.adapter.inbound.grpc`를 더하지 않는다. +3. 기능의 `BindableService`와 정확히 하나의 `GrpcAuthenticationPolicy`를 준다. +4. 승격 전에 `./gradlew :adapter:inbound:grpc:test :conditionalTransportQualification`을 돌린다. +5. 고른 런타임 계약에 대한 조립 소유의 설정·env registry 항목이 생기기 전에는 운영 채택이 끝난 것이 아니다. -**Current transport limit:** the P1 server is plaintext and deliberately permits only loopback -binding. It is therefore suitable for local-process or same-Pod sidecar communication only. It -cannot bind `0.0.0.0` for a normal Kubernetes Service, cannot accept cross-Pod traffic, and must -not be presented as a cluster-facing gRPC endpoint. Cluster exposure requires the deferred TLS/mTLS -credential path and a separately qualified non-loopback bind. +**지금 전송의 한계:** P1 서버는 평문이고 일부러 loopback bind만 허용한다. 그래서 같은 프로세스나 같은 +Pod sidecar 통신에만 맞다. 보통 Kubernetes Service를 위해 `0.0.0.0`에 bind할 수 없고, 다른 Pod의 트래픽을 +받을 수 없으며, 클러스터를 향한 gRPC endpoint로 내세우면 안 된다. 클러스터에 노출하려면 미뤄 둔 TLS/mTLS +credential 경로와 따로 검증한 loopback 아닌 bind가 필요하다. ## Feature 기여 방법 @@ -109,7 +107,7 @@ listener 시작이 실패한다. 정책은 `Optional authenticate(Met 이 증거는 local insecure unary qualification일 뿐 production-ready 근거가 아니다. TLS/mTLS, external bind, 메서드별 deadline, streaming/backpressure, generated protobuf 호환성은 P2로 남아 있다. -## Test +## 테스트 ```bash cd src diff --git a/src/adapter/inbound/messaging/CLAUDE.md b/src/adapter/inbound/messaging/CLAUDE.md index 11d9c1a2..e1637a6e 100644 --- a/src/adapter/inbound/messaging/CLAUDE.md +++ b/src/adapter/inbound/messaging/CLAUDE.md @@ -1,25 +1,23 @@ # adapter:inbound:messaging -- Module ID `adapter-inbound-messaging`, Gradle path `:adapter:inbound:messaging`. Registry SSOT: +- 모듈 ID `adapter-inbound-messaging`, Gradle 경로 `:adapter:inbound:messaging`. registry 정본: `src/config/architecture/modules.json`. -- Responsibility: the application's consume side of the vendored messaging platform — the inbox - parts the platform needs from the application (`JdbcInboxRepository` over the application - DataSource, a `TransactionRunner` over its `PlatformTransactionManager`, the inbox migration as - its own Flyway stream `MessagingInboxSchemaStream`) and the application's `MessageHandler` - implementations, each turning a delivery into one use case call. A handler registers nothing - else: the platform decodes what its `destination()` and `schemaVersions()` declare. -- Boundaries: no business rule in a handler (HARD-STOP 4); no persistence entity or repository; no - broker SDK type. Allowed edges come only from the registry entry. -- A handler that calls a write use case is `@SystemCaller(reason = ...)` and constructs the - `@SystemInvoked` use case itself; the use case is never a bean, and no user transport calls the - handler (manual 09 「소비」 step 4, manual 07 「시스템이 부르는 쓰기」, +- 책임: 들여온 메시징 플랫폼의 애플리케이션 소비 쪽이다 — 플랫폼이 애플리케이션에서 받아야 하는 + inbox 부품(애플리케이션 DataSource 위의 `JdbcInboxRepository`, 그 `PlatformTransactionManager` 위의 + `TransactionRunner`, 자기 Flyway stream `MessagingInboxSchemaStream`인 inbox migration)과 애플리케이션의 + `MessageHandler` 구현들이다. 핸들러 하나는 전달 하나를 유스케이스 호출 하나로 바꾼다. 핸들러는 그 밖에 + 아무것도 등록하지 않는다: 플랫폼이 그 `destination()`과 `schemaVersions()`가 선언한 것을 decode한다. +- 경계: 핸들러에 업무 규칙을 두지 않는다(HARD-STOP 4). 영속 엔티티나 repository가 없다. broker SDK 타입이 + 없다. 허용 edge는 registry 항목에서만 온다. +- 쓰기 유스케이스를 부르는 핸들러는 `@SystemCaller(reason = ...)`이고 `@SystemInvoked` 유스케이스를 직접 + 만든다. 유스케이스는 bean이 아니고, 사용자 전송 계층은 핸들러를 부르지 않는다 + (`docs/manual/09-outbox-events.md` 「소비 — 이벤트를 받는 쪽」 순서 4단계, + `docs/manual/07-authorization.md` 「시스템이 부르는 쓰기」, `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`, - `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`). The handler implements only project types - (`MessageHandler`), never `Runnable` or another type outside the project - (`SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`). -- Tests: focused auto-configuration and inbox behavior tests; `./gradlew :adapter:inbound:messaging:check`. - The real Kafka + PostgreSQL redelivery lane is `messagingInboxRedeliveryIntegrationTest` - (`:integrationCheck`). -- Coordinates: group `dev.caskeleton.adapter.inbound`, jar `adapter-inbound-messaging`. Do not drop them — - with the default group this project and `:adapter:outbound:messaging` are one module to Gradle. -- Design and rejected alternatives: `README.md`. + `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`). 핸들러는 프로젝트 타입(`MessageHandler`)만 구현하고, + `Runnable`이나 프로젝트 밖의 다른 타입은 구현하지 않는다(`SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`). +- 시험: 자동 구성과 inbox 동작을 보는 시험. `./gradlew :adapter:inbound:messaging:check`. + 실제 Kafka + PostgreSQL 재전달 lane은 `messagingInboxRedeliveryIntegrationTest`다(`:integrationCheck`). +- 좌표: group `dev.caskeleton.adapter.inbound`, jar `adapter-inbound-messaging`. 지우지 않는다 — 기본 + group이면 Gradle에게 이 프로젝트와 `:adapter:outbound:messaging`은 같은 모듈이 된다. +- 설계와 버린 대안: `README.md`. diff --git a/src/adapter/inbound/web-advanced/CLAUDE.md b/src/adapter/inbound/web-advanced/CLAUDE.md index 18d3212d..1f11e209 100644 --- a/src/adapter/inbound/web-advanced/CLAUDE.md +++ b/src/adapter/inbound/web-advanced/CLAUDE.md @@ -1,46 +1,42 @@ -# adapter:inbound:web-advanced — opt-in web library +# adapter:inbound:web-advanced — 골라 쓰는 web 라이브러리 -## Registered identity +## 등록 정보 -- Module ID: `adapter-inbound-web-advanced` -- Gradle path: `:adapter:inbound:web-advanced` -- Focused test (derived from Gradle path): `./gradlew :adapter:inbound:web-advanced:test --console=plain` -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-inbound-web-advanced` +- Gradle 경로: `:adapter:inbound:web-advanced` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:inbound:web-advanced:test --console=plain` +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.inbound.web.advanced`. What it provides, the one line a -service adds and the settings are in [README.md](README.md). +패키지 루트: `dev.caskeleton.adapter.inbound.web.advanced`. 무엇을 주는지, 서비스가 더하는 한 줄, +설정은 [README.md](README.md)에 있다. -## Responsibility +## 책임 -- Web library code that the servlet production path does not reach: streaming, virtual-thread - admission, JSON Patch / Merge Patch, CBOR/XML codecs, OpenAPI 3.2 generator and breaking-change - policy, URI/method policy, versioning, operation/budget/contract catalogs, security-context - bridge, idempotent response codec, route inventory. -- The three switched MVC capabilities (virtual threads, NDJSON, JSON sequence), each an - `@AutoConfiguration` listed in this leaf's `AutoConfiguration.imports` and off by default. +- servlet 운영 경로가 닿지 않는 web 라이브러리 코드: streaming, virtual thread admission, JSON Patch / + Merge Patch, CBOR·XML codec, OpenAPI 3.2 생성기와 breaking change 정책, URI·method 정책, versioning, + operation·budget·contract catalog, security context bridge, 멱등 응답 codec, route 목록. +- 스위치가 있는 MVC capability 셋(virtual thread, NDJSON, JSON sequence). 각각 이 leaf의 + `AutoConfiguration.imports`에 적힌 `@AutoConfiguration`이고 기본은 꺼져 있다. -## Rules +## 규칙 -- Not in any default composition. `app-bootstrap` main은 이 leaf에 의존하지 않는다; - `app-bootstrap` takes it `testRuntimeOnly` so the whole-repository ArchUnit import reads it. -- It depends on `adapter:inbound:web` (the `core` vocabulary), never the reverse. -- No component-scannable stereotype. A consuming application may scan the adapter packages - (서비스가 `dev.caskeleton.adapter.inbound.web`을 scan할 수 있다), so a - `@Configuration`/`@Component` here would be created whatever its switch says. Switched wiring is - `@AutoConfiguration` + an imports line; imported helpers carry no stereotype - (`MvcStreamingSupportConfiguration`). -- No setting that no code reads, no gate or evidence type in `main` that only tests call — the - release gate and OpenAPI promotion report were removed for exactly that - (`docs/capability-status.md`). -- One generation per feature. Nothing here may re-implement what the production web path already - does another way: forwarded headers (`server.forward-headers-strategy`), CORS/CSRF - (`CorsSettings`/`SecurityConfig`), cache headers (`CacheControlFilter`), the JSON mapper (Boot's - `JsonMapper`), OpenAPI customization (`OpenApiContractConfig`). Those duplicates and the WebFlux - `functional` package were removed on 2026-09-25 (`docs/capability-status.md`). -- Inbound adapter rules from `adapter:inbound:web` apply: no repository access, no business rules, - no DTO leaking into `application-core`/`domain-core`. +- 어떤 기본 조립에도 없다. `app-bootstrap` main은 이 leaf에 의존하지 않는다. + `app-bootstrap`은 저장소 전체 ArchUnit import가 이 leaf를 읽도록 `testRuntimeOnly`로만 받는다. +- `adapter:inbound:web`(`core` 어휘)에 의존하고, 그 반대는 없다. +- component scan에 걸리는 stereotype이 없다. 쓰는 애플리케이션은 어댑터 패키지를 scan할 수 있다 + (서비스가 `dev.caskeleton.adapter.inbound.web`을 scan할 수 있다). 그래서 여기 둔 `@Configuration`이나 + `@Component`는 스위치가 무엇을 말하든 만들어진다. 스위치가 있는 배선은 `@AutoConfiguration` + imports + 한 줄이다. import되는 도우미는 stereotype을 달지 않는다(`MvcStreamingSupportConfiguration`). +- 아무 코드도 읽지 않는 설정, 시험만 부르는 `main`의 gate·증거 타입을 두지 않는다 — 릴리스 gate와 + OpenAPI 승격 보고서를 바로 그 이유로 지웠다(`docs/capability-status.md`). +- 기능마다 세대 하나. 운영 web 경로가 이미 다른 방식으로 하는 일을 여기서 다시 구현하지 않는다: + forwarded header(`server.forward-headers-strategy`), CORS·CSRF(`CorsSettings`/`SecurityConfig`), cache + header(`CacheControlFilter`), JSON mapper(Boot의 `JsonMapper`), OpenAPI 손질(`OpenApiContractConfig`). + 그 중복과 WebFlux `functional` 패키지는 2026-09-25에 지웠다(`docs/capability-status.md`). +- `adapter:inbound:web`의 inbound 어댑터 규칙이 그대로 적용된다: repository 접근 없음, 업무 규칙 없음, + `application-core`·`domain-core`로 새는 DTO 없음. -## Test +## 테스트 ```bash cd src diff --git a/src/adapter/inbound/web/CLAUDE.md b/src/adapter/inbound/web/CLAUDE.md index 35c66ca8..f4903614 100644 --- a/src/adapter/inbound/web/CLAUDE.md +++ b/src/adapter/inbound/web/CLAUDE.md @@ -1,213 +1,170 @@ -# adapter:inbound:web — inbound HTTP adapter +# adapter:inbound:web — inbound HTTP 어댑터 -## Registered identity +## 등록 정보 -- Module ID: `adapter-inbound-web` -- Gradle path: `:adapter:inbound:web` -- Focused test (derived from Gradle path): `./gradlew :adapter:inbound:web:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-inbound-web` +- Gradle 경로: `:adapter:inbound:web` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:inbound:web:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.inbound.web`. +패키지 루트: `dev.caskeleton.adapter.inbound.web`. 코드 주석에서 덜어낸 **설계 결정의 근거**는 [README.md](README.md) 가 모아둔다 (이 문서는 모듈 규칙 SSOT). -## Responsibility +## 책임 -- HTTP controllers. -- Request/response DTOs. -- Request DTO to application command mapping. -- Authentication, validation, error mapping, filters, and web/security settings. -- Sanitized request correlation context exposed through application-owned `CorrelationIdPort`. -- Transport-owned OpenAPI customization that keeps `ApiError.details` as `type: object` without - leaking Swagger dependencies into `shared-contract`. +- HTTP controller. +- 요청·응답 DTO. +- 요청 DTO를 application command로 바꾸기. +- 인증, 검증, 오류 대응, filter, web·보안 설정. +- 애플리케이션이 가진 `CorrelationIdPort`로 내놓는, 걸러 낸 요청 correlation 문맥. +- `shared-contract`로 Swagger 의존을 새게 하지 않으면서 `ApiError.details`를 `type: object`로 두는, + 전송 계층이 가진 OpenAPI 손질. -Every service ships this leaf, so it holds only what the servlet production path reaches: its -`AutoConfiguration.imports` roots (`WebAdapterAutoConfiguration` imports the envelope, filters, -health and rate-limit beans; `WebSecurityAutoConfiguration` imports the JWT chain, so an application -with its own posture excludes only that root; `WebMethodSecurityAutoConfiguration` imports method -security and the permission port and stays when the chain is replaced; nobody scans -this leaf), and the types -`app-bootstrap`, `web-fileserver` and `composition:fileserver-platform` name — -plus their transitive references. Library code that no production path reaches (streaming, virtual -threads, patch, codecs, OpenAPI 3.2, URI/method policy, versioning, operation, budget, contract, -security-context bridge, `JsonIdempotentResponseCodec`, route inventory) lives in the opt-in leaf -`adapter:inbound:web-advanced`. A new type that nothing on the -production path uses belongs there, not here. This leaf never depends on it (Gradle registry + -ArchUnit `WEB-ARCH-ADV`). +모든 서비스가 이 leaf를 싣는다. 그래서 servlet 운영 경로가 닿는 것만 담는다: 그 `AutoConfiguration.imports` +루트(`WebAdapterAutoConfiguration`은 envelope, filter, health, rate-limit bean을 import한다. +`WebSecurityAutoConfiguration`은 JWT chain을 import하므로, 자기 보안 방식을 가진 애플리케이션은 그 루트만 +뺀다. `WebMethodSecurityAutoConfiguration`은 method security와 권한 포트를 import하고 chain을 바꿔도 남는다. +이 leaf를 scan하는 쪽은 없다), 그리고 `app-bootstrap`, `web-fileserver`, `composition:fileserver-platform`이 +이름을 대는 타입과 그것이 전이로 참조하는 것. 운영 경로가 닿지 않는 라이브러리 코드(streaming, virtual +thread, patch, codec, OpenAPI 3.2, URI·method 정책, versioning, operation, budget, contract, security context +bridge, `JsonIdempotentResponseCodec`, route 목록)는 골라 쓰는 leaf `adapter:inbound:web-advanced`에 있다. +운영 경로에서 아무도 쓰지 않는 새 타입은 여기가 아니라 거기에 둔다. 이 leaf는 그 leaf에 의존하지 않는다 +(Gradle registry + ArchUnit `WEB-ARCH-ADV`). -## Allowed +## 허용 - `:application-core` - `:domain-core` - `:shared-contract` -- `:adapter:outbound:support` — `StrictSettingsBinder` only. `app.security` (`SecuritySettings`, the - authentication mode included) is bound by the one strict binder every module uses (since - 2026-11-01); the ArchUnit inbound/outbound rules allow that class and nothing else from the - leaf. -- Spring Web/Security/Validation dependencies. +- `:adapter:outbound:support` — `StrictSettingsBinder`만. `app.security`(`SecuritySettings`, 인증 모드 포함)는 + 모든 모듈이 쓰는 엄격한 binder 하나로 바인딩한다(2026-11-01부터). ArchUnit inbound·outbound 규칙은 그 + leaf에서 이 클래스만 허용한다. +- Spring Web·Security·Validation 의존성. -## Forbidden +## 금지 -- Direct dependency on `adapter-persistence` or any other `adapter-outbound` type. -- Direct repository or JPA entity access from controllers. -- Core business rules in controller, filter, config, mapper, or settings code. -- DTO leakage into application or domain. +- `adapter:outbound:persistence-jpa`나 다른 `adapter:outbound:*` 타입에 직접 의존하기. +- controller에서 repository나 JPA 엔티티에 직접 접근하기. +- controller, filter, config, mapper, settings 코드 안의 핵심 업무 규칙. +- DTO가 application이나 domain으로 새는 것. -## Boundary validation & mapper contract +## 경계 검증과 mapper 계약 -`feature-boundary-validation-mapping-contract` (design record) fixes the -behaviour at this layer's boundaries. The repo-level guardrails (ArchUnit + -Jackson config + handler) only catch the static violations — the contract below -also drives the runtime patterns reference implementations must follow. +`feature-boundary-validation-mapping-contract`(설계 기록)가 이 계층 경계의 동작을 정한다. 저장소 단위 +가드레일(ArchUnit + Jackson 설정 + handler)은 정적 위반만 잡는다. 아래 계약은 참조 구현이 따라야 할 런타임 +패턴도 정한다. -- **B1 — Jackson policy at the request boundary.** `spring.jackson.deserialization` - pins `fail-on-unknown-properties`, `fail-on-null-for-primitives`, - `fail-on-ignored-properties` to `true` and `read-unknown-enum-values-as-null` - to `false`. Do NOT undo this per-DTO with class-level - `@JsonIgnoreProperties(ignoreUnknown = true)` — ArchUnit rule - `request_dtos_do_not_silence_unknown_fields` blocks it. Use wrapper types - (`Integer`, `Long`, `Boolean`, `Optional`) in request records so JSON - `null` cannot become primitive `0`. -- **B2 — PATCH semantics.** Do not adopt RFC 7396 `application/merge-patch+json` - (`null = deletion`). PATCH endpoints must distinguish *absent* (no change), - *explicit null* (clear field), and *value* (replace). Use - `org.openapitools:jackson-databind-nullable` (`JsonNullable`) or - `Optional` wrappers on request records. -- **B3 — Mapper-internal failures.** Map record canonical-constructor - `IllegalArgumentException`, MapStruct generated NPE, ACL normalization - failures, etc. by throwing `MappingException`; the global handler routes it to `MAPPING_FAILED` (HTTP 400), - never to `BAD_PARAMETER` or `INTERNAL_ERROR`. Plain `IllegalArgumentException` - remains `BAD_PARAMETER` for non-mapper callers. -- **B4 — Validation layering.** Class-level Bean Validation constraints belong - to the *syntax* layer (request DTO). Domain invariants belong to - `application-core` / `domain-core`. Use `@GroupSequence(...)` to short-circuit - invariant evaluation when syntax fails. Keep `@Valid` cascade depth ≤ 3. -- **B5 — Polymorphic deserialization.** Calling - `ObjectMapper.enableDefaultTyping()` / `activateDefaultTyping()` or - referencing `LaissezFaireSubTypeValidator` is the CVE-2019-14379 RCE entry - point and is blocked by ArchUnit (`no_jackson_laissez_faire_subtype_validator`, - `no_jackson_enable_default_typing_call`). Sealed `Command` types must use - `@JsonTypeInfo(use = NAME)` + `@JsonSubTypes`, or a - `BasicPolymorphicTypeValidator` allowlist. -- **B6 — Virtual thread context propagation.** With - `spring.threads.virtual.enabled=true`, do not use `InheritableThreadLocal` - (ArchUnit rule `no_inheritable_thread_local`). Filters and interceptors must - propagate `requestId` / `traceId` via SLF4J 2.0+ MDC or - `RequestContextHolder`. -- **B7 — Outbound ACL mapper scope.** Outbound HTTP / messaging adapter - responses must pass through an ACL mapper (normalization, masking, public - field selection) before reaching `application-core` or `domain-core` — the - same boundary contract as inbound. Raw external response types must not leak - into `domain-core`. -- **B8 — Bulk endpoint partial success.** Envelope `success = true` only when - every item succeeded. Partial failure responds with `success = false` + - `error.code = BATCH_PARTIAL_FAILURE` + `error.details[]` (per-item array) — - a different shape from the single-item endpoint. Document the shape divergence - in the OpenAPI spec. +- **B1 — 요청 경계의 Jackson 정책.** `spring.jackson.deserialization`이 `fail-on-unknown-properties`, + `fail-on-null-for-primitives`, `fail-on-ignored-properties`를 `true`로, `read-unknown-enum-values-as-null`을 + `false`로 고정한다. 클래스 수준 `@JsonIgnoreProperties(ignoreUnknown = true)`로 DTO마다 이것을 되돌리지 + **않는다** — ArchUnit 규칙 `request_dtos_do_not_silence_unknown_fields`가 막는다. 요청 record에는 + wrapper 타입(`Integer`, `Long`, `Boolean`, `Optional`)을 써서 JSON `null`이 primitive `0`이 되지 못하게 + 한다. +- **B2 — PATCH 뜻.** RFC 7396 `application/merge-patch+json`(`null = 삭제`)을 쓰지 않는다. PATCH endpoint는 + *없음*(바꾸지 않음), *명시한 null*(필드 비움), *값*(바꿈)을 구별해야 한다. 요청 record에 + `org.openapitools:jackson-databind-nullable`(`JsonNullable`)이나 `Optional` wrapper를 쓴다. +- **B3 — mapper 안의 실패.** record 정규 생성자의 `IllegalArgumentException`, MapStruct가 생성한 NPE, ACL + 정규화 실패 등은 `MappingException`을 던져 대응시킨다. 전역 handler가 그것을 `MAPPING_FAILED`(HTTP 400)로 + 보내고, `BAD_PARAMETER`나 `INTERNAL_ERROR`로 보내지 않는다. mapper가 아닌 호출자의 평범한 + `IllegalArgumentException`은 계속 `BAD_PARAMETER`다. +- **B4 — 검증 층.** 클래스 수준 Bean Validation 제약은 *문법* 층(요청 DTO)에 속한다. 도메인 불변식은 + `application-core` / `domain-core`에 속한다. 문법이 실패하면 `@GroupSequence(...)`로 불변식 평가를 건너뛴다. + `@Valid` cascade 깊이는 3 이하로 둔다. +- **B5 — 다형 역직렬화.** `ObjectMapper.enableDefaultTyping()` / `activateDefaultTyping()`을 부르거나 + `LaissezFaireSubTypeValidator`를 참조하는 것은 CVE-2019-14379 RCE의 입구이고 ArchUnit이 막는다 + (`no_jackson_laissez_faire_subtype_validator`, `no_jackson_enable_default_typing_call`). sealed `Command` + 타입은 `@JsonTypeInfo(use = NAME)` + `@JsonSubTypes`나 `BasicPolymorphicTypeValidator` 허용 목록을 쓴다. +- **B6 — virtual thread 문맥 전파.** `spring.threads.virtual.enabled=true`이면 `InheritableThreadLocal`을 쓰지 + 않는다(ArchUnit 규칙 `no_inheritable_thread_local`). filter와 interceptor는 SLF4J 2.0+ MDC나 + `RequestContextHolder`로 `requestId` / `traceId`를 전파한다. +- **B7 — outbound ACL mapper 범위.** outbound HTTP·메시징 어댑터의 응답은 `application-core`나 `domain-core`에 + 닿기 전에 ACL mapper(정규화, 가리기, 공개 필드 고르기)를 거친다 — inbound와 같은 경계 계약이다. 외부 응답 + 원본 타입은 `domain-core`로 새면 안 된다. +- **B8 — bulk endpoint의 부분 성공.** envelope `success = true`는 모든 항목이 성공했을 때뿐이다. 일부가 + 실패하면 `success = false` + `error.code = BATCH_PARTIAL_FAILURE` + `error.details[]`(항목별 배열)로 + 답한다 — 단일 항목 endpoint와 모양이 다르다. 모양이 다르다는 것을 OpenAPI spec에 적는다. -Domain `@RestControllerAdvice` in a consuming module must be annotated -`@Order(Ordered.HIGHEST_PRECEDENCE)` (or otherwise ordered ahead of this -module's base `GlobalExceptionHandler`), because the base handler's catch-all -`@ExceptionHandler(Exception.class)` would otherwise resolve domain exceptions -to `INTERNAL_ERROR`. +이 모듈을 쓰는 모듈의 도메인 `@RestControllerAdvice`에는 `@Order(Ordered.HIGHEST_PRECEDENCE)`를 단다(또는 +다른 방법으로 이 모듈의 기본 `GlobalExceptionHandler`보다 앞에 둔다). 그렇지 않으면 기본 handler의 +catch-all `@ExceptionHandler(Exception.class)`가 도메인 예외를 `INTERNAL_ERROR`로 만든다. -The base operational handler (`error/GlobalExceptionHandler`), the error-code -contract (`dev.caskeleton.shared.error.ApiErrorCode` + `OperationalError`), the -`error/ErrorResponseFactory`, and the `envelope/EnvelopeBodyAdvice` now live in -production modules (`adapter:inbound:web` / `shared-contract`), so the running application -provides them. 기능 전용 예외 handler와 오류 코드는 그 기능을 가진 모듈에 둔다(`docs/manual/06-errors.md`). +기본 운영 handler(`error/GlobalExceptionHandler`), 오류 코드 계약 +(`dev.caskeleton.shared.error.ApiErrorCode` + `OperationalError`), `error/ErrorResponseFactory`, +`envelope/EnvelopeBodyAdvice`는 이제 운영 모듈(`adapter:inbound:web` / `shared-contract`)에 있어서, 돌아가는 +애플리케이션이 그것을 준다. 기능 전용 예외 handler와 오류 코드는 그 기능을 가진 모듈에 둔다(`docs/manual/06-errors.md`). -## Schema / serialization contract +## schema·직렬화 계약 -`feature-schema-serialization-contract` (design record) fixes the -*response producer* side of the wire contract — the sibling of the B1 *request -consumer* policy above. The deserialization switches (B1) and the -null/empty/missing 3-state (`Patch` + `JsonNullable`, B2) already cover the -inbound side; the rules below cover the outbound side. The Jackson properties -live in `app-bootstrap` (`application.yml` `spring.jackson.serialization.*` / -`spring.jackson.generator.*`); ArchUnit + effective-config tests live in -`app-bootstrap` (`JacksonSerializationPolicyTest`, `no_bigdecimal_double_constructor`). +`feature-schema-serialization-contract`(설계 기록)가 wire 계약의 *응답을 만드는* 쪽을 정한다 — 위 B1 +*요청을 받는* 정책의 짝이다. 역직렬화 스위치(B1)와 null·빈 값·없음 세 상태(`Patch` + `JsonNullable`, +B2)가 이미 inbound 쪽을 덮고, 아래 규칙이 outbound 쪽을 덮는다. Jackson 속성은 `app-bootstrap`의 +`application.yml`(`spring.jackson.deserialization.*`, `spring.jackson.datatype.*`)에 있다. ArchUnit과 실제 +설정 시험도 `app-bootstrap`에 있다(`JacksonSerializationPolicyTest`, `no_bigdecimal_double_constructor`). -- **S1 — Date / time / timezone.** `WRITE_DATES_AS_TIMESTAMPS=false` is - pinned, so `java.time` values serialize as ISO-8601 strings via `JavaTimeModule` - (`OffsetDateTime` → `"...Z"`, `LocalDate` → `"YYYY-MM-DD"`), never a numeric - epoch or `[y,m,d,...]` array. Server timezone is **UTC**: emit instants as - `OffsetDateTime`/`Instant` with a `Z` offset. Use `LocalDate` only for - date-only calendar fields. Do **not** put timezone-less `LocalDateTime` on a - response DTO — it serializes without an offset and breaks the contract. -- **S2 — Money / BigDecimal.** Default scale 2, rounding `HALF_UP` unless - the domain documents otherwise (KRW/JPY = scale 0 with a schema note). - `WRITE_BIGDECIMAL_AS_PLAIN=true` is pinned so values never serialize in - scientific notation. Pick **one** JSON representation per API and state it in - the OpenAPI schema: **string** (`@JsonSerialize(using = ToStringSerializer.class)`) - for public / financial endpoints (client parses, no precision loss), or - **number + plain** for internal service-to-service endpoints. Never rely on - the default — decide at endpoint design time. -- **S3 — `new BigDecimal(double)` is banned.** The `double`/`float` constructors - capture binary floating-point error (`new BigDecimal(0.1)` ≠ `0.1`). Build from - a `String` (`new BigDecimal("0.1")`) or `BigDecimal.valueOf(double)`. Enforced - by the `no_bigdecimal_double_constructor` ArchUnit rule. -- **S4 — Enum / null·empty·missing.** Request-side unknown enum → - `VALIDATION_FAILED` (B1 `read-unknown-enum-values-as-null=false`); legacy values - map through an explicit adapter, never a silent fallback. The - absent / explicit-null / value distinction is owned by the inbound web mapper - (Controller DTO → Command), expressed with `Patch` (B2); `domain-core` and - `application-core` receive the already-resolved 3-state, never a wire type. -- **S5 — Out of this branch's scope.** OpenAPI drift enforcement is owned by - the verification suite / api-contract-baseline; removed-field-reuse ban tooling - (`x-removed-fields` vs markdown catalog) is `needs-confirmation`; Avro - Schema Registry for outbox/event and response field rename/versioning - (`feature-api-compatibility-deprecation-contract`) are separate branches. +- **S1 — 날짜·시간·시간대.** `WRITE_DATES_AS_TIMESTAMPS=false`로 고정하므로 `java.time` 값은 + `JavaTimeModule`을 거쳐 ISO-8601 문자열로 직렬화한다(`OffsetDateTime` → `"...Z"`, `LocalDate` → + `"YYYY-MM-DD"`). 숫자 epoch나 `[y,m,d,...]` 배열이 되지 않는다. 서버 시간대는 **UTC**다: 시각은 `Z` + offset을 가진 `OffsetDateTime`/`Instant`로 낸다. 날짜만 있는 달력 필드에만 `LocalDate`를 쓴다. 시간대 + 없는 `LocalDateTime`을 응답 DTO에 넣지 **않는다** — offset 없이 직렬화되어 계약을 깬다. +- **S2 — 돈·BigDecimal.** 도메인이 따로 적지 않으면 기본 scale 2, 반올림 `HALF_UP`이다(KRW/JPY는 scale 0과 + schema 메모). 값은 지수 표기로 직렬화되지 않는다 — 설정 키로 고정하지 않고 `JacksonSerializationPolicyTest`가 + 큰 값과 끝자리 0을 단언한다. API마다 JSON 표현을 **하나** 고르고 OpenAPI schema에 적는다: 공개·금융 + endpoint는 **string**(`@JsonSerialize(using = ToStringSerializer.class)`. 클라이언트가 파싱하고 정밀도를 + 잃지 않는다), 내부 서비스 사이 endpoint는 **number + plain**. 기본값에 기대지 않는다 — endpoint를 설계할 + 때 정한다. +- **S3 — `new BigDecimal(double)`은 금지다.** `double`/`float` 생성자는 이진 부동소수점 오차를 담는다 + (`new BigDecimal(0.1)` ≠ `0.1`). `String`(`new BigDecimal("0.1")`)이나 `BigDecimal.valueOf(double)`로 + 만든다. ArchUnit 규칙 `no_bigdecimal_double_constructor`가 강제한다. +- **S4 — enum과 null·빈 값·없음.** 요청 쪽의 모르는 enum → `VALIDATION_FAILED`(B1 + `read-unknown-enum-values-as-null=false`). 옛 값은 명시한 어댑터로 대응시키고 소리 없는 대체값을 쓰지 + 않는다. 없음·명시한 null·값의 구별은 inbound web mapper(Controller DTO → Command)가 가지고 `Patch`(B2)로 + 나타낸다. `domain-core`와 `application-core`는 이미 풀린 세 상태를 받고 wire 타입은 받지 않는다. +- **S5 — 이 브랜치의 범위 밖.** OpenAPI drift 강제는 검증 suite / api-contract-baseline의 몫이다. 지운 + 필드 재사용 금지 도구(`x-removed-fields` 대 markdown catalog)는 `needs-confirmation`이다. outbox·event용 + Avro Schema Registry와 응답 필드 이름 바꾸기·versioning(`feature-api-compatibility-deprecation-contract`)은 + 다른 브랜치다. -## Business rule validation contract +## 업무 규칙 검증 계약 -`feature-business-rule-validation-contract` (design record) fixes **which -rule is validated at which boundary**, so "validation" does not collapse into the -controller DTO or a DB constraint. It sits on top of the boundary/mapping contract -above and is enforced by ArchUnit + contract tests (not new runtime mechanism). +`feature-business-rule-validation-contract`(설계 기록)는 **어떤 규칙을 어느 경계에서 검증하는지** 정해서, +「검증」이 controller DTO나 DB 제약 하나로 뭉개지지 않게 한다. 위 경계·대응 계약 위에 놓이고, ArchUnit과 +계약 시험이 강제한다(새 런타임 장치가 아니다). -| Layer | Owner | Validates | `error.category` | Enforced by | +| 층 | 소유 | 검증하는 것 | `error.category` | 강제하는 곳 | |---|---|---|---|---| -| syntax / shape | `adapter:inbound:web` request DTO (`@Valid` / `jakarta.validation`) | request shape, types, required fields | `VALIDATION` | `validation_constraints_stay_at_web_boundary` ArchUnit rule | -| use case policy | `application-core` | authorization, cross-aggregate policy, state preconditions | `AUTHZ` / `CONFLICT` | `BusinessRuleValidationContractTest` | -| domain invariant | `domain-core` model / value object **constructor** | business invariants (e.g. end ≥ start) | `CONFLICT` / `VALIDATION` | domain unit tests (e.g. `PeriodTest`) — constructor is the sole, immutable construction path | -| persistence integrity | `adapter-persistence` (translator owned by `feature-persistence-failure-baseline`) | unique / FK / check / serialization | `DATA_INTEGRITY` / `CONFLICT` | `BusinessRuleValidationContractTest` + leak test | +| 문법·모양 | `adapter:inbound:web` 요청 DTO(`@Valid` / `jakarta.validation`) | 요청 모양, 타입, 필수 필드 | `VALIDATION` | ArchUnit 규칙 `validation_constraints_stay_at_web_boundary` | +| 유스케이스 정책 | `application-core` | 인가, aggregate를 가로지르는 정책, 상태 전제 조건 | `AUTHZ` / `CONFLICT` | `BusinessRuleValidationContractTest` | +| 도메인 불변식 | `domain-core` 모델·값 객체 **생성자** | 업무 불변식(예: end ≥ start) | `CONFLICT` / `VALIDATION` | 도메인 단위 시험(예: `PeriodTest`) — 생성자가 유일하고 바뀌지 않는 생성 경로다 | +| 영속 무결성 | `adapter:outbound:persistence-jpa`(번역기는 `feature-persistence-failure-baseline`의 것) | unique / FK / check / serialization | `DATA_INTEGRITY` / `CONFLICT` | `BusinessRuleValidationContractTest` + 누출 시험 | -- **C1 — Validation annotations stay at the web boundary.** `jakarta.validation` - (`@NotNull`, `@Valid`, …) must appear only in `adapter:inbound:web`. `domain-core` and - `application-core` express invariants and policy as plain Java. The - `validation_constraints_stay_at_web_boundary` ArchUnit rule fails the build if a - Bean Validation annotation leaks into `..domain..` or `..application..`. -- **C2 — Business invariants live in the domain, un-bypassable.** Enforce invariants - in the value-object / entity **constructor** (the sole construction path) and keep - the type immutable, so no application-service or persistence path can hand out an - invariant-violating instance. A DB constraint is a backstop, never the only check - (Forbidden: "DB constraint as only invariant"). -- **C3 / C7 — Persistence integrity maps to an operational error, leak-free.** A - unique/FK/check/serialization failure maps to `DATA_INTEGRITY` / `CONFLICT` with a - **client-safe message only**. The raw SQL, constraint/index name, SQLState code, - exception class, and stack frame must never reach `error.message` or - `error.details`. The base `GlobalExceptionHandler` catch-all already replaces the - message with the opaque shared message (`ClientErrorMessages.OPAQUE`) and emits `null` details; the - category-correct mapping (23505 → `CONFLICT/DB_UNIQUE_VIOLATION`, …) is owned by - `feature-persistence-failure-baseline`'s persistence-adapter translator. -- **C8 — Duplicate validation needs a canonical owner.** The same rule MAY be - pre-checked at another layer for UX / performance (e.g. an application pre-check - mirroring a DB unique constraint), but the **canonical owner** of the rule must be - named in a code comment or the relevant `CLAUDE.md`. A duplicate validator with no - documented owner is a review failure (silent contradiction risk). This is a process - gate (PR review), not an automated rule — `needs-confirmation` until an owner-marker - annotation is justified. +- **C1 — 검증 애너테이션은 web 경계에 머문다.** `jakarta.validation`(`@NotNull`, `@Valid`, …)은 + `adapter:inbound:web`에만 나와야 한다. `domain-core`와 `application-core`는 불변식과 정책을 평범한 Java로 + 나타낸다. Bean Validation 애너테이션이 `..domain..`이나 `..application..`으로 새면 ArchUnit 규칙 + `validation_constraints_stay_at_web_boundary`가 빌드를 실패시킨다. +- **C2 — 업무 불변식은 도메인에 있고 우회할 수 없다.** 불변식은 값 객체·엔티티 **생성자**(유일한 생성 + 경로)에서 강제하고 타입을 불변으로 둔다. 그래서 어떤 application service나 영속 경로도 불변식을 어긴 + 인스턴스를 내줄 수 없다. DB 제약은 뒷받침일 뿐 유일한 검사가 아니다(금지: 「불변식을 DB 제약으로만 + 지키기」). +- **C3 / C7 — 영속 무결성은 새는 것 없이 운영 오류로 대응한다.** unique·FK·check·serialization 실패는 + **클라이언트에게 안전한 메시지만** 가진 `DATA_INTEGRITY` / `CONFLICT`로 대응한다. SQL 원문, 제약·index + 이름, SQLState 코드, 예외 클래스, stack frame은 `error.message`나 `error.details`에 닿으면 안 된다. 기본 + `GlobalExceptionHandler` catch-all이 이미 메시지를 불투명한 공용 메시지(`ClientErrorMessages.OPAQUE`)로 + 바꾸고 details를 `null`로 낸다. category가 맞는 대응(23505 → `CONFLICT/DB_UNIQUE_VIOLATION`, …)은 + `feature-persistence-failure-baseline`의 영속 어댑터 번역기가 가진다. +- **C8 — 중복 검증에는 정본 소유자가 있어야 한다.** UX나 성능을 위해 같은 규칙을 다른 층에서 미리 검사할 수 + 있다(예: DB unique 제약을 따라 하는 application 사전 검사). 단 그 규칙의 **정본 소유자**를 코드 주석이나 + 관련 `CLAUDE.md`에 적어야 한다. 소유자를 적지 않은 중복 검증기는 리뷰에서 실패다(소리 없이 서로 어긋날 + 위험). 자동 규칙이 아니라 절차 게이트(PR 리뷰)다 — 소유자 표지 애너테이션이 정당해질 때까지 + `needs-confirmation`이다. -Out of this branch's scope (cross-referenced, not re-implemented here): the -SQLState→code 9-row matrix and the `DataAccessException` translator -(`feature-persistence-failure-baseline`); the Jackson B1/B2 request-boundary switches -and mapper sentinel (`feature-boundary-validation-mapping-contract`); the envelope, -`Category` enum, and `OperationalError` codes +이 브랜치의 범위 밖(참조만 하고 여기서 다시 구현하지 않는다): SQLState → 코드 9행 표와 +`DataAccessException` 번역기(`feature-persistence-failure-baseline`), Jackson B1/B2 요청 경계 스위치와 mapper +표지 예외(`feature-boundary-validation-mapping-contract`), envelope, `Category` enum, `OperationalError` 코드 (`feature-operational-error-observability-foundation`). -## Test +## 테스트 ```bash cd src diff --git a/src/adapter/inbound/web/README.md b/src/adapter/inbound/web/README.md index 134acd95..a2d2830e 100644 --- a/src/adapter/inbound/web/README.md +++ b/src/adapter/inbound/web/README.md @@ -16,13 +16,12 @@ route inventory)는 opt-in leaf `adapter:inbound:web-advanced` 에 있다 --- -## OpenAPI contract stabilization +## OpenAPI 계약 고정 -Springdoc 3 represents an untyped Java `Object` as an unconstrained OAS 3.1 schema (`{}`). -`OpenApiContractConfig` owns the transport-specific correction for the shared `ApiError.details` -field and publishes it as `type: object`. This preserves the committed HTTP contract without adding -Swagger annotations or dependencies to `shared-contract`. Real-server OpenAPI tests import this -production configuration and compare the result with the committed snapshot. +Springdoc 3은 타입 없는 Java `Object`를 제약 없는 OAS 3.1 schema(`{}`)로 나타낸다. +`OpenApiContractConfig`가 공용 `ApiError.details` 필드에 대한 전송 계층 보정을 가지고 그 필드를 +`type: object`로 낸다. 그래서 `shared-contract`에 Swagger 애너테이션이나 의존성을 더하지 않고 커밋한 HTTP +계약을 지킨다. 실제 서버 OpenAPI 시험은 이 운영 설정을 import하고 결과를 커밋한 snapshot과 비교한다. --- @@ -374,7 +373,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML ## ratelimit -### provider-neutral edge contract +### provider 중립 edge 계약 - inbound web은 `shared-contract`의 `EdgeRateLimitPort`만 호출한다. Redis key, Lua, local counter와 provider 설정을 알지 못한다. @@ -579,7 +578,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML ## idempotency -### Ownership +### 소유 - `Idempotency-Key`는 HTTP 경계가 읽어 application command/context로 전달할 수 있지만, **claim / fingerprint / replay / in-flight arbitration은 application use case가 소유**한다. - web leaf에는 별도 DB replay 엔진을 두지 않는다. 같은 요청 의미를 web/application 두 계층이 서로 다른 diff --git a/src/adapter/inbound/websocket/CLAUDE.md b/src/adapter/inbound/websocket/CLAUDE.md index 4b54b060..cc19b9f8 100644 --- a/src/adapter/inbound/websocket/CLAUDE.md +++ b/src/adapter/inbound/websocket/CLAUDE.md @@ -1,127 +1,120 @@ -# adapter:inbound:websocket — conditional WebSocket/STOMP boundary +# adapter:inbound:websocket — 고를 때만 켜는 WebSocket·STOMP 경계 -## Registered identity +## 등록 정보 -- Module ID: `adapter-inbound-websocket` -- Gradle path: `:adapter:inbound:websocket` -- Focused test: `./gradlew :adapter:inbound:websocket:test --console=plain` -- Runtime baseline: Java 21, Spring Boot 4.0.8 -- Registry SSOT: `src/config/architecture/modules.json` +- 모듈 ID: `adapter-inbound-websocket` +- Gradle 경로: `:adapter:inbound:websocket` +- 이 모듈만 시험: `./gradlew :adapter:inbound:websocket:test --console=plain` +- 실행 기준: Java 21. Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json` -Package root: `dev.caskeleton.adapter.inbound.websocket`. +패키지 루트: `dev.caskeleton.adapter.inbound.websocket`. -## Responsibility +## 책임 -This leaf contains **two different scopes** and they must not be read as one deployed feature: +이 leaf에는 **서로 다른 범위 둘**이 있고, 배포되는 기능 하나로 읽으면 안 된다. -1. **Opt-in STOMP/SockJS channel** — `stomp/**` owns the Spring transport configuration, typed - `app.websocket.*` settings, handshake principal/origin checks, destination policy, - fixed client-safe STOMP `ERROR` mapping, and best-effort in-process event projection. -2. **Servlet handler library** — `servlet/`, `outbound/`, `budget/` plus the two id records - `core/WebSocketConnectionId` and `protocol/WebSocketMessageId`. No settings keys, no Spring - configuration: a service's own adapter leaf constructs `PlatformWebSocketHandler` and registers - it. README "라이브러리 API" lists the entry points and the wiring. +1. **골라 쓰는 STOMP·SockJS 채널** — `stomp/**`가 Spring 전송 설정, 타입 있는 `app.websocket.*` 설정, + handshake principal·origin 검사, destination 정책, 정해진 클라이언트 안전 STOMP `ERROR` 대응, 할 수 있는 + 만큼만 하는(best-effort) 프로세스 안 이벤트 projection을 가진다. +2. **servlet handler 라이브러리** — `servlet/`, `outbound/`, `budget/`과 id record 둘 + `core/WebSocketConnectionId`, `protocol/WebSocketMessageId`. 설정 키도 Spring 설정도 없다: 서비스 자신의 + 어댑터 leaf가 `PlatformWebSocketHandler`를 만들고 등록한다. README 「라이브러리 API」가 진입점과 배선을 + 적는다. -This leaf does not deduplicate commands and owns no storage SPI. The former `idempotency/` -package (command ledger, `WebSocketActorReference`, `WebSocketEndpointName`) was removed on -2026-09-25. A command that must run at most once goes through the application -`IdempotencyExecutor` inside its use case, with a scope that survives a reconnect (endpoint + actor -+ the client's own message id), never the connection id. +이 leaf는 command 중복을 걸러 내지 않고 저장소 SPI를 가지지 않는다. 예전 `idempotency/` 패키지(command +원장, `WebSocketActorReference`, `WebSocketEndpointName`)는 2026-09-25에 지웠다. 많아야 한 번 돌아야 하는 +command는 그 유스케이스 안에서 애플리케이션 `IdempotencyExecutor`를 거친다. 범위(scope)는 다시 연결해도 +살아남는 값(endpoint + actor + 클라이언트 자신의 message id)이고, connection id가 아니다. -The module itself is absent from both shipped runtime compositions. Being registered and tested -does not activate either scope. +이 모듈은 출하하는 런타임 조립 둘 어디에도 없다. 등록되고 시험된다고 두 범위 중 어느 것도 켜지지 않는다. -## Allowed +## 허용 -- Registered dependency on `:domain-core` for the `@DomainEvent` marker. -- Spring Boot WebSocket and validation starters, managed by the repository BOM. -- Test-only embedded Tomcat/Jetty/SockJS/STOMP clients and Testcontainers (Nginx lane). +- `@DomainEvent` 표지를 위한 `:domain-core` 등록 의존. +- 저장소 BOM이 관리하는 Spring Boot WebSocket·validation starter. +- 시험에서만: 내장 Tomcat·Jetty·SockJS·STOMP 클라이언트와 Testcontainers(Nginx lane). -## Forbidden +## 금지 -- Direct dependency on any `adapter:outbound:*` module. -- Repository, Spring Data, persistence entity, or business policy access. -- Raw `@DomainEvent` payload transmission or reflection-based event serialization. -- Wildcard/blank handshake origins when enabled. -- Anonymous handshakes, arbitrary topic subscriptions, or client sends to broker destinations. -- A production feature `@MessageMapping` in this skeleton leaf. -- A module-local YAML file; composition roots own property values. -- Settings keys, flags or catalogs for behaviour no code in this leaf performs. A bound that the - handler does not enforce is not a field of `WebSocketConnectionBudget`. -- Reactive (WebFlux) WebSocket code: the template is servlet-only. +- 어떤 `adapter:outbound:*` 모듈에든 직접 의존하기. +- repository, Spring Data, 영속 엔티티, 업무 정책 접근. +- `@DomainEvent` payload를 그대로 보내기, 리플렉션 기반 이벤트 직렬화. +- 켜져 있을 때 wildcard·빈 handshake origin. +- 익명 handshake, 아무 topic 구독, 클라이언트가 broker destination으로 보내기. +- 이 골격 leaf 안의 운영 기능 `@MessageMapping`. +- 모듈 안의 YAML 파일. 속성 값은 조립 루트가 가진다. +- 이 leaf의 어떤 코드도 하지 않는 동작을 위한 설정 키·flag·catalog. handler가 강제하지 않는 한계는 + `WebSocketConnectionBudget`의 필드가 아니다. +- reactive(WebFlux) WebSocket 코드: 템플릿은 servlet만 쓴다. -## Typed settings (`app.websocket.*`) +## 타입 있는 설정 (`app.websocket.*`) -There is one property tree and one operator env prefix: `app.websocket.*` ↔ `APP_WEBSOCKET_*`. -They configure the STOMP channel only. The default bootJar does not contain this leaf, so these -values matter only in a composition that adopts it. +속성 트리 하나와 운영자 env 접두어 하나가 있다: `app.websocket.*` ↔ `APP_WEBSOCKET_*`. STOMP 채널만 +설정한다. 기본 bootJar에는 이 leaf가 없으니, 이 값은 이 leaf를 채택한 조립에서만 뜻이 있다. -| property | env | default / role | +| 속성 | env | 기본값·역할 | | --- | --- | --- | -| `app.websocket.enabled` | `APP_WEBSOCKET_ENABLED` | `true`; `false` turns the STOMP/SockJS channel off | +| `app.websocket.enabled` | `APP_WEBSOCKET_ENABLED` | `true`. `false`이면 STOMP·SockJS 채널을 끈다 | | `app.websocket.endpoint` | `APP_WEBSOCKET_ENDPOINT` | `/ws` | -| `app.websocket.allowed-origins` | `APP_WEBSOCKET_ALLOWED_ORIGINS` | `http://localhost:3000`; explicit origins only | +| `app.websocket.allowed-origins` | `APP_WEBSOCKET_ALLOWED_ORIGINS` | `http://localhost:3000`. 명시한 origin만 | | `app.websocket.broadcast-destination` | `APP_WEBSOCKET_BROADCAST_DESTINATION` | `/topic/events` | -| `app.websocket.channel-queue-capacity` | `APP_WEBSOCKET_CHANNEL_QUEUE_CAPACITY` | `10000`; messages each STOMP channel (client inbound, client outbound, broker) queues before rejecting | -| `app.websocket.message-size-limit` | `APP_WEBSOCKET_MESSAGE_SIZE_LIMIT` | `64KB` (Spring default, now explicit) | -| `app.websocket.send-buffer-size-limit` | `APP_WEBSOCKET_SEND_BUFFER_SIZE_LIMIT` | `512KB` (Spring default, now explicit) | -| `app.websocket.send-time-limit` | `APP_WEBSOCKET_SEND_TIME_LIMIT` | `10s` (Spring default, now explicit) | -| `app.websocket.time-to-first-message` | `APP_WEBSOCKET_TIME_TO_FIRST_MESSAGE` | `60s` (Spring default, now explicit) | -| `app.websocket.max-connections` | `APP_WEBSOCKET_MAX_CONNECTIONS` | `1000`; STOMP sessions per node, the next is closed with 1013 | +| `app.websocket.channel-queue-capacity` | `APP_WEBSOCKET_CHANNEL_QUEUE_CAPACITY` | `10000`. STOMP 채널마다(클라이언트 inbound, 클라이언트 outbound, broker) 거절하기 전에 쌓아 두는 메시지 수 | +| `app.websocket.message-size-limit` | `APP_WEBSOCKET_MESSAGE_SIZE_LIMIT` | `64KB`(Spring 기본값을 이제 명시한다) | +| `app.websocket.send-buffer-size-limit` | `APP_WEBSOCKET_SEND_BUFFER_SIZE_LIMIT` | `512KB`(Spring 기본값을 이제 명시한다) | +| `app.websocket.send-time-limit` | `APP_WEBSOCKET_SEND_TIME_LIMIT` | `10s`(Spring 기본값을 이제 명시한다) | +| `app.websocket.time-to-first-message` | `APP_WEBSOCKET_TIME_TO_FIRST_MESSAGE` | `60s`(Spring 기본값을 이제 명시한다) | +| `app.websocket.max-connections` | `APP_WEBSOCKET_MAX_CONNECTIONS` | `1000`. 노드마다 STOMP 세션 수. 그다음 것은 1013으로 닫는다 | -`WebSocketSettings` is `@Validated`. Invalid enabled settings fail context startup. +`WebSocketSettings`는 `@Validated`다. 켜진 상태의 잘못된 설정은 context 기동을 실패시킨다. -## Adopting this capability +## 이 capability 채택하기 -WebSocket is a **build-composition opt-in**, not a dormant feature inside the default bootJar. +WebSocket은 기본 bootJar 안에 잠든 기능이 아니라 **빌드 조립에서 고르는 것**이다. -1. Add `:adapter:inbound:websocket` to the consuming composition's dependencies and add the - matching allowed edge in `config/architecture/modules.json`. -2. Keep settings registration with the capability root; do not add - `dev.caskeleton.adapter.inbound.websocket` back to the shipped - `@ConfigurationPropertiesScan`. -3. The STOMP/SockJS channel is registered by this leaf's own `AutoConfiguration.imports` and is on - whenever the leaf is on a servlet classpath; set a non-wildcard origin allowlist, and - `app.websocket.enabled=false` to turn it off. -4. For the handler library, follow README "라이브러리 API". The handler must be a bean so its - `SmartLifecycle` stop (1001 to every open connection) runs before the web server stops. -5. Run the leaf lanes and the repository conditional-transport aggregate before promoting the - composition: +1. 쓰는 조립의 의존성에 `:adapter:inbound:websocket`을 더하고 `config/architecture/modules.json`에 맞는 허용 + edge를 더한다. +2. 설정 등록은 capability 루트에 둔다. 출하하는 `@ConfigurationPropertiesScan`에 + `dev.caskeleton.adapter.inbound.websocket`을 다시 더하지 않는다. +3. STOMP·SockJS 채널은 이 leaf 자신의 `AutoConfiguration.imports`가 등록하고, leaf가 servlet classpath에 + 있으면 언제나 켜진다. wildcard가 아닌 origin 허용 목록을 정하고, 끄려면 `app.websocket.enabled=false`로 + 한다. +4. handler 라이브러리는 README 「라이브러리 API」를 따른다. handler는 bean이어야 한다. 그래야 그 + `SmartLifecycle` 멈춤(열린 모든 연결에 1001)이 web 서버가 멈추기 전에 돈다. +5. 조립을 승격하기 전에 leaf lane과 저장소 conditional-transport 묶음을 돌린다: `./gradlew :adapter:inbound:websocket:test :adapter:inbound:websocket:systemTest :conditionalTransportQualification`. -## Inbound policy (STOMP) +## inbound 정책 (STOMP) -- The HTTP upgrade must already have a nonblank `Principal`; the adapter does not authenticate - credentials itself. -- STOMP `SUBSCRIBE` is allowed only for the configured broadcast destination. -- Authenticated `SEND` is allowed only below `/app/**`. -- Client `SEND` to `/topic/**` and other destinations is rejected. -- Every client-visible processing failure becomes an ERROR frame with an empty payload and the - fixed `message` `WEBSOCKET_REQUEST_REJECTED`. Its `error-code` header is the carried - `ApiErrorCode` of the first `ApiErrorCarrier` in the cause chain (even behind an - `IllegalArgumentException`), `BAD_PARAMETER` for an `IllegalArgumentException`, and - `WEBSOCKET_REQUEST_REJECTED` otherwise. +- HTTP upgrade에는 이미 비어 있지 않은 `Principal`이 있어야 한다. 어댑터는 credential을 직접 인증하지 않는다. +- STOMP `SUBSCRIBE`는 설정한 broadcast destination에만 허용한다. +- 인증된 `SEND`는 `/app/**` 아래에만 허용한다. +- 클라이언트가 `/topic/**`나 다른 destination으로 보내는 `SEND`는 거절한다. +- 클라이언트에게 보이는 처리 실패는 모두 빈 payload와 정해진 `message` `WEBSOCKET_REQUEST_REJECTED`를 가진 + ERROR frame이 된다. 그 `error-code` header는 cause chain에서 처음 나오는 `ApiErrorCarrier`가 실은 + `ApiErrorCode`(`IllegalArgumentException` 뒤에 있어도), `IllegalArgumentException`이면 `BAD_PARAMETER`, 그 + 밖에는 `WEBSOCKET_REQUEST_REJECTED`다. -## Event projection contract +## 이벤트 projection 계약 -A future feature may contribute a `LiveEventProjector` bean for one exact `@DomainEvent` class. -The broadcaster sends only when exactly one projector matches. Zero or duplicate projectors, -projection failures, invalid event types, null fields, and over-limit maps are dropped. The wire -envelope contains only `type`, bounded string `fields`, and `occurredAt`. The broker channel has its -own bounded executor, so the simple broker's fan-out to subscribers never runs on the thread that -published the domain event; a full broker queue drops the event (best-effort, R1). +나중의 기능이 정확히 하나의 `@DomainEvent` 클래스에 대해 `LiveEventProjector` bean을 기여할 수 있다. +broadcaster는 projector가 정확히 하나 맞을 때만 보낸다. projector가 없거나 둘 이상이거나, projection이 +실패하거나, 이벤트 타입이 잘못됐거나, 필드가 null이거나, map이 한계를 넘으면 버린다. wire envelope에는 +`type`, 한계 있는 문자열 `fields`, `occurredAt`만 있다. broker 채널은 자기 한계 있는 executor를 가지므로, +simple broker가 구독자에게 퍼뜨리는 일은 도메인 이벤트를 발행한 스레드에서 돌지 않는다. broker queue가 차면 +이벤트를 버린다(best-effort, R1). 템플릿에는 WebSocket 이벤트를 발행하거나 projector를 기여하는 기능이 없다. -## Evidence and limits +## 증거와 한계 -| lane | what it proves | +| lane | 증명하는 것 | | --- | --- | -| `test` | STOMP settings/policy, queue/writer/budget, handler size and overflow closes | -| `systemTest` | real Tomcat: STOMP boundary (`WebSocketBoundaryQualificationTest`), handler runtime and abuse contracts, context close sends 1001 | -| `websocketJettyTest` | the handler runtime contract on Jetty | -| `websocketNginxTest` | upgrade/forwarding behind a real Nginx (Docker required; fails without it) | -| `websocketTransportQualificationTest` | no-skip execution of the STOMP boundary test | +| `test` | STOMP 설정·정책, queue·writer·budget, handler 크기와 넘침 종료 | +| `systemTest` | 실제 Tomcat: STOMP 경계(`WebSocketBoundaryQualificationTest`), handler 런타임과 남용 계약, context를 닫으면 1001을 보냄 | +| `websocketJettyTest` | Jetty에서 handler 런타임 계약 | +| `websocketNginxTest` | 실제 Nginx 뒤의 upgrade·forwarding(Docker 필요. 없으면 실패한다) | +| `websocketTransportQualificationTest` | STOMP 경계 시험을 건너뛰지 않고 실행 | -The simple broker is local, single-process, best-effort R1 evidence only. Broker relay, -multi-node/durable delivery, rollback-safe publication and replay/resume are not provided. +simple broker는 로컬·단일 프로세스·best-effort R1 증거일 뿐이다. broker relay, 여러 노드·durable 전달, +롤백에 안전한 발행, replay·resume은 주지 않는다. From 8813b02e5433e3403a1371104cd1c7b8d2219849 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 7 Nov 2026 17:24:11 +0900 Subject: [PATCH 3/6] =?UTF-8?q?docs(adapter-outbound):=20outbound=20?= =?UTF-8?q?=EC=96=B4=EB=8C=91=ED=84=B0=20=EB=AA=A8=EB=93=88=20=EB=AC=B8?= =?UTF-8?q?=EC=84=9C=EB=A5=BC=20=ED=95=9C=EA=B5=AD=EC=96=B4=EB=A1=9C=20?= =?UTF-8?q?=EC=98=AE=EA=B8=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: outbound 어댑터 leaf의 CLAUDE.md 열세 개와 README 아홉 개가 영어이거나 영어 절이 섞여 있다. 열 CLAUDE.md는 Spring Boot 버전 (4.0.0, 4.0.8)을 복사해 두었고 실제 버전(libs.versions.toml)과 다르다. 방법: 뜻을 그대로 옮기고 코드·명령·경로·식별자·설정 키·로그 문자열· 표 구조는 원문으로 둔다. 버전은 `src/gradle/libs.versions.toml`을 가리키게 고친다. 번역하며 본 코드와 어긋난 주장은 코드에 맞춘다: identifier CLAUDE.md의 `.claude/hooks/ca_import_gate.py`(저장소에 없는 hook)를 registry 방향 게이트로, cache-redis README의 「app-bootstrap `IdempotencySettings`」를 실제 위치 `composition:idempotency`로, redis-sdk compose README의 ACL 파일 위치 `acl/`을 lane이 실제로 mount하는 `compose/redis/acl/`로 고친다. persistence-mongo 문서에는 지운 namespace(`spring.data.mongodb.`)를 쓰지 않는다 (MongoNamespaceContractTest가 본다). 다른 영역 문서의 절 제목을 인용한 곳(`docs/jpa/migration-guide.md` "Bound the lock wait" 등)은 그 문서가 아직 영어라 원문 제목으로 둔다. 위험: 인용한 docs/jpa 절 제목은 그 문서를 번역하는 쪽이 제목을 바꾸면 낡는다. 통합 단계에서 맞춰야 한다. ArchUnit 규칙 이름의 대소문자는 다음 커밋에서 맞춘다. 검증: python3 scripts/check-docs.py rc=0(language 줄 19개, number 줄 10개 지움, src/** number 줄 0), check-work-docs.py rc=0, --links(gates.md 범위) 깨진 링크 0. --- scripts/check-docs-exceptions.txt | 29 - src/adapter/outbound/cache-redis/CLAUDE.md | 339 ++++++------ src/adapter/outbound/cache-redis/README.md | 512 ++++++++--------- src/adapter/outbound/fileserver/CLAUDE.md | 55 +- src/adapter/outbound/fileserver/README.md | 40 +- src/adapter/outbound/httpclient/CLAUDE.md | 143 +++-- src/adapter/outbound/httpclient/README.md | 118 ++-- src/adapter/outbound/identifier/CLAUDE.md | 74 ++- .../outbound/messaging-kafka/CLAUDE.md | 23 +- src/adapter/outbound/messaging/CLAUDE.md | 78 ++- src/adapter/outbound/messaging/README.md | 2 +- src/adapter/outbound/notification/CLAUDE.md | 79 ++- src/adapter/outbound/notification/README.md | 20 +- src/adapter/outbound/objectstorage/CLAUDE.md | 71 ++- src/adapter/outbound/objectstorage/README.md | 190 +++---- .../outbound/persistence-fileserver/CLAUDE.md | 100 ++-- .../outbound/persistence-jpa/CLAUDE.md | 516 ++++++++---------- .../outbound/persistence-jpa/README.md | 4 +- .../outbound/persistence-mongo/CLAUDE.md | 276 +++++----- .../persistence-notification/CLAUDE.md | 93 ++-- src/adapter/outbound/redis-sdk/README.md | 129 ++--- .../outbound/redis-sdk/compose/README.md | 170 +++--- src/adapter/outbound/support/CLAUDE.md | 68 ++- 23 files changed, 1420 insertions(+), 1709 deletions(-) diff --git a/scripts/check-docs-exceptions.txt b/scripts/check-docs-exceptions.txt index 2b41d107..173f1fd2 100644 --- a/scripts/check-docs-exceptions.txt +++ b/scripts/check-docs-exceptions.txt @@ -146,25 +146,6 @@ language docs/web/runbook.md language docs/web/streaming-contract.md language docs/web/virtual-thread-profile.md language docs/websocket/runbook.md -language src/adapter/outbound/cache-redis/CLAUDE.md -language src/adapter/outbound/cache-redis/README.md -language src/adapter/outbound/fileserver/CLAUDE.md -language src/adapter/outbound/fileserver/README.md -language src/adapter/outbound/httpclient/CLAUDE.md -language src/adapter/outbound/httpclient/README.md -language src/adapter/outbound/identifier/CLAUDE.md -language src/adapter/outbound/messaging-kafka/CLAUDE.md -language src/adapter/outbound/messaging/CLAUDE.md -language src/adapter/outbound/notification/CLAUDE.md -language src/adapter/outbound/objectstorage/CLAUDE.md -language src/adapter/outbound/objectstorage/README.md -language src/adapter/outbound/persistence-fileserver/CLAUDE.md -language src/adapter/outbound/persistence-jpa/CLAUDE.md -language src/adapter/outbound/persistence-mongo/CLAUDE.md -language src/adapter/outbound/persistence-notification/CLAUDE.md -language src/adapter/outbound/redis-sdk/README.md -language src/adapter/outbound/redis-sdk/compose/README.md -language src/adapter/outbound/support/CLAUDE.md language src/app-bootstrap/src/test/resources/developer-experience/broken-readme.md # 참조: 지금 트리·registry에 없는 경로. 고치거나 「> 이력」 인용 블록으로 옮기면 지운다. @@ -185,13 +166,3 @@ number docs/jpa/repository-adaptation.md Spring Boot 4.0.8 number docs/manual/01-generator.md 5 leaf number docs/mongodb/repository-adaptation.md 19 leaf number docs/mongodb/repository-adaptation.md Spring Boot 4.0.8 -number src/adapter/outbound/cache-redis/CLAUDE.md Spring Boot 4.0.0 -number src/adapter/outbound/fileserver/CLAUDE.md Spring Boot 4.0.0 -number src/adapter/outbound/httpclient/CLAUDE.md Spring Boot 4.0.0 -number src/adapter/outbound/identifier/CLAUDE.md Spring Boot 4.0.8 -number src/adapter/outbound/messaging/CLAUDE.md Spring Boot 4.0.8 -number src/adapter/outbound/notification/CLAUDE.md Spring Boot 4.0.0 -number src/adapter/outbound/objectstorage/CLAUDE.md Spring Boot 4.0.0 -number src/adapter/outbound/persistence-jpa/CLAUDE.md Spring Boot 4.0.0 -number src/adapter/outbound/persistence-mongo/CLAUDE.md Spring Boot 4.0.0 -number src/adapter/outbound/support/CLAUDE.md Spring Boot 4.0.0 diff --git a/src/adapter/outbound/cache-redis/CLAUDE.md b/src/adapter/outbound/cache-redis/CLAUDE.md index 79842ed2..b00bee92 100644 --- a/src/adapter/outbound/cache-redis/CLAUDE.md +++ b/src/adapter/outbound/cache-redis/CLAUDE.md @@ -1,211 +1,180 @@ -# adapter:outbound:cache-redis — cache and Redis adapter +# adapter:outbound:cache-redis — cache와 Redis 어댑터 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-cache-redis` -- Gradle path: `:adapter:outbound:cache-redis` -- Focused test (derived from Gradle path): `./gradlew :adapter:outbound:cache-redis:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-outbound-cache-redis` +- Gradle 경로: `:adapter:outbound:cache-redis` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:outbound:cache-redis:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.outbound.cache`. +패키지 루트: `dev.caskeleton.adapter.outbound.cache`. -## Responsibility +## 책임 -- Implement semantic cache ports from `application-core` without exposing Redis concepts to core. -- Own canonical physical keys, digesting, codec/envelope, program catalog, typed Redis atomic - facades, runtime client adaptation, and capability-specific failure semantics. -- Implement absolute soft/hard expiry, write conditions and key invalidation markers behind the - semantic cache port (`CacheRegionPort`). There is no TTL jitter and no stampede protection; - single-flight is the caller's. The revision order is the port's `CacheSourceRevisionOrder`; the - Lua copy is held to it by `CacheRegionContract` (application-core testFixtures), which - `RedisCacheRegionContractTest` and `LiveRedisCacheRegionContractTest` extend. -- Implement the provider-neutral `EdgeRateLimitPort` with dedicated coordination Redis settings, - connection/admission, private keys and versioned atomic programs. -- Keep the legacy cache router isolated while consumers migrate to semantic ports. -- Reuse `adapter:outbound:support` for shared outbound concerns. -- Depend on `:adapter:outbound:redis-runtime` for the shared topology client, connection lifecycle, - the eight `SemanticRedisCommands` and conditional Redis runtime composition used by the semantic - adapters. -- Keep the general-purpose typed SDK in the separate library leaf `:adapter:outbound:redis-sdk` - (see its `README.md`). This leaf does not depend on it in any configuration, tests included; the - SDK's tests and lanes live in that leaf. +- `application-core`의 semantic cache 포트를 구현하고, Redis 개념을 core에 드러내지 않는다. +- 정해진 물리 키, digest, codec·envelope, program catalog, 타입 있는 Redis 원자 창구, runtime client 연결, + capability별 실패 뜻을 가진다. +- semantic cache 포트(`CacheRegionPort`) 뒤에서 절대 soft·hard 만료, 쓰기 조건, 키 무효화 표지를 구현한다. TTL + jitter도 stampede 보호도 없다. single-flight는 호출자의 몫이다. revision 순서는 포트의 + `CacheSourceRevisionOrder`다. Lua 사본은 `CacheRegionContract`(application-core testFixtures)가 그 순서에 + 맞추고, `RedisCacheRegionContractTest`와 `LiveRedisCacheRegionContractTest`가 그 계약을 상속한다. +- provider 중립 `EdgeRateLimitPort`를 전용 조율 Redis 설정, 연결·admission, 전용 키, 버전 있는 원자 program으로 + 구현한다. +- 쓰는 쪽이 semantic 포트로 옮기는 동안 옛 cache router를 떼어 둔다. +- 공용 outbound 관심사는 `adapter:outbound:support`를 다시 쓴다. +- semantic 어댑터가 쓰는 공용 topology client, 연결 lifecycle, `SemanticRedisCommands` 여덟 개, 조건부 Redis + runtime 조립은 `:adapter:outbound:redis-runtime`에 의존한다. +- 범용 typed SDK는 따로 둔 라이브러리 leaf `:adapter:outbound:redis-sdk`에 둔다(그 `README.md`를 본다). 이 + leaf는 시험을 포함해 어떤 설정에서도 그것에 의존하지 않는다. SDK의 시험과 lane은 그 leaf에 있다. -## Redis runtime (`…cache.redis.runtime`) and optional typed SDK (`…cache.redis.sdk`) +## Redis 런타임과 골라 쓰는 typed SDK (`…cache.redis.runtime`, `…cache.redis.sdk`) -Two registered leaves, two packages, one direction: the SDK builds on the runtime, the runtime knows -nothing of the SDK (`RedisRuntimePackageBoundaryTest` in the runtime holds that direction). +등록된 leaf 둘, 패키지 둘, 방향 하나: SDK는 runtime 위에 서고, runtime은 SDK를 모른다(runtime 안의 +`RedisRuntimePackageBoundaryTest`가 그 방향을 지킨다). -- `:adapter:outbound:redis-runtime` is production substrate: `RedisRuntimeSettings` binding, - credential resolution, topology clients, `RedisRuntimeOwner` with the runtime's own lanes - (`RedisConnectionKind.REGULAR`, `SCRIPT`), `SemanticRedisCommands` (the eight commands this leaf - and the health contributor send) and health. `cache-redis` depends on this leaf. -- `:adapter:outbound:redis-sdk` owns the optional general-purpose typed API: `RedisCommandGateway` - (extends `SemanticRedisCommands`), command catalog/policy, operation budgets, command guard, - raw/admin surfaces, programmability and extensions — and its own lanes (`RedisSdkLane`: blocking, - transaction, admin) and admin account, which a service contributes to the runtime as - `RedisLaneContribution`/`RedisAccountContribution` beans (`RedisSdkComposition`). `cache-redis` - does **not** depend on it, in production or in tests. -- The semantic cache/idempotency/rate-limit/lease adapters in this leaf send the runtime's - `SemanticRedisCommands` through their own closed semantic programs (`RegisteredLuaScript`). They - do not pass through `CommandPolicyGuard`, and `redis-command-policy.yml` does not control them. -- Which roles need Redis for correctness is this leaf's `RedisCorrectnessRoleSelectors`, registered - in `META-INF/spring.factories` as the runtime's `RedisCorrectnessRequirement`. +- `:adapter:outbound:redis-runtime`은 운영 기반이다: `RedisRuntimeSettings` 바인딩, credential 해석, topology + client, runtime 자신의 lane(`RedisConnectionKind.REGULAR`, `SCRIPT`)을 가진 `RedisRuntimeOwner`, + `SemanticRedisCommands`(이 leaf와 health contributor가 보내는 명령 여덟 개), health. `cache-redis`가 이 leaf에 + 의존한다. +- `:adapter:outbound:redis-sdk`는 골라 쓰는 범용 typed API를 가진다: `RedisCommandGateway`(`SemanticRedisCommands`를 + 상속), 명령 catalog·정책, operation 예산, 명령 guard, raw·admin surface, programmability, extension — 그리고 + 자기 lane(`RedisSdkLane`: blocking, transaction, admin)과 admin 계정. 서비스가 그것을 + `RedisLaneContribution`/`RedisAccountContribution` bean으로 runtime에 기여한다(`RedisSdkComposition`). + `cache-redis`는 운영에서도 시험에서도 그것에 의존하지 **않는다**. +- 이 leaf의 semantic cache·멱등성·rate-limit·lease 어댑터는 runtime의 `SemanticRedisCommands`를 자기의 닫힌 + semantic program(`RegisteredLuaScript`)으로 보낸다. `CommandPolicyGuard`를 지나지 않고, + `redis-command-policy.yml`이 그것을 다루지 않는다. +- 정확성을 위해 어떤 role에 Redis가 필요한지는 이 leaf의 `RedisCorrectnessRoleSelectors`가 정하고, + `META-INF/spring.factories`에 runtime의 `RedisCorrectnessRequirement`로 등록한다. -The typed SDK described in -`docs/design/2026-08-07-redis-wrapper-typed-api-design.md` remains an optional library -rather than part of the shipped semantic Redis adapter. Delivery status and adaptation history are -in `docs/history/plans/2026-08-07-redis-wrapper-typed-api-status.md`. +`docs/design/2026-08-07-redis-wrapper-typed-api-design.md`가 설명하는 typed SDK는 출하하는 semantic Redis 어댑터의 +일부가 아니라 골라 쓰는 라이브러리로 남는다. 전달 상태와 맞춘 이력은 +`docs/history/plans/2026-08-07-redis-wrapper-typed-api-status.md`에 있다. -- `sdk.api..` is the public contract. It must never import Spring, Lettuce, Micrometer, or any SDK - implementation package; Reactor is confined to `sdk.api.reactive`. -- `sdk.lettuce..` implements the contract; `sdk.config` owns properties, the capability probe, and - the permit authority. -- `:adapter:outbound:redis-sdk/src/main/resources/redis-sdk/redis-command-policy.yml` is the - optional typed SDK command-policy SSOT. A typed-SDK command that is not classified there is - refused. It is not a policy file for this leaf's semantic capability adapters. -- `sdk.lettuce.operations` implements the typed operations. Everything there goes through - `RedisCommandGateway`, the only seam that reaches Lettuce, and every call is admitted by - `CommandPolicyGuard` before it runs. Never call the driver from an operation directly. -- `sdk.cluster` owns client-side slot arithmetic and cluster observation. It depends on `sdk.api` - only and must never import Lettuce: the slot is computed before a command is built, which is what - lets `CommandPolicyGuard` refuse a cross-slot request instead of learning about it from a server - redirect. -- `sdk.programmability` owns transactions, registered Lua scripts, and deployed function calls. A - script body is never accepted at call time: `EVAL` is blocked in the catalog and only `EVALSHA` of - a `RedisScriptRegistry` digest is reachable. `FUNCTION LOAD` is admin-plane, never application. -- Transactions are `WATCH`/`MULTI`/`EXEC` and **never** roll back. `TransactionResult` reports only - "executed" or "a watched key changed, so nothing ran", and no type in this package offers a word - that suggests otherwise. A queued command returns a `QueuedReply` that throws when read before the - commit, because inside the window the server has answered `+QUEUED` and nothing else. Queued - commands pass the same `CommandPolicyGuard` admission as ordinary ones — a transaction is not a - way around the guard — and the window is closed on every exit path, including a callback that - threw, because a connection abandoned in `MULTI` state silently queues the next caller's command. - The queue is write-only on purpose: a read inside the window cannot be branched on, so the reads a - transaction depends on belong before it, under `WATCH`. -- `sdk.raw` is the approved raw command gateway. A command is reachable only when the catalog marks - it `RAW_ONLY` *and* the deployment registered an `ApprovedRawCommand` for it; keys are parsed back - out of the arguments and namespace-checked before anything is sent. Never add a method here that - takes a command name as a string. -- `sdk.admin` is the read-only diagnostic plane. It takes its own gateway (admin ACL account, own - connection), refuses any command the catalog does not classify `ADMIN_ONLY` and read-only, and - projects replies so a slow log or client listing never carries arguments, peer addresses, or - connection names. -- `sdk.extensions.*` holds the Redis 8 modules (JSON, Search, Time Series, Probabilistic). Every - bean is created through `ifSupported(...)` — the capability probe decides, the catalog minimum is - only a pre-filter — and all of them build commands through `ExtensionCommandRunner` so the guard - sees their keys. Search is the exception that proves it: an index is not a key, so its name is - namespaced by `LettuceRedisSearchOperations` itself. -- `RedisSdkModuleBoundaryTest` (in `redis-sdk`) scans the `redis-sdk` source root and enforces the - internal package graph, driver containment, the absence of an arbitrary string command surface, - and the designed module list. -- Decisions that must not be changed without revisiting the design: no unbounded `entries`, - `members`, `rangeAll`, or `keys`; no optional R2 permit or budget; no arbitrary command string - overload; no automatic retry of a non-idempotent write after a timeout; no real key in a metric or - trace tag. +- `sdk.api..`는 공개 계약이다. Spring, Lettuce, Micrometer, SDK 구현 패키지를 import하지 않는다. Reactor는 + `sdk.api.reactive` 안에만 둔다. +- `sdk.lettuce..`가 계약을 구현한다. `sdk.config`는 속성, capability probe, 허가 정본을 가진다. +- `:adapter:outbound:redis-sdk/src/main/resources/redis-sdk/redis-command-policy.yml`이 골라 쓰는 typed SDK의 명령 + 정책 정본이다. 거기 분류되지 않은 typed SDK 명령은 거절한다. 이 leaf의 semantic capability 어댑터를 위한 정책 + 파일이 아니다. +- `sdk.lettuce.operations`가 타입 있는 operation을 구현한다. 거기 있는 모든 것은 Lettuce에 닿는 유일한 이음매인 + `RedisCommandGateway`를 거치고, 모든 호출은 돌기 전에 `CommandPolicyGuard`의 허가를 받는다. operation에서 + driver를 직접 부르지 않는다. +- `sdk.cluster`는 client 쪽 slot 계산과 cluster 관찰을 가진다. `sdk.api`에만 의존하고 Lettuce를 import하지 + 않는다: slot을 명령을 만들기 전에 계산하므로 `CommandPolicyGuard`가 서버 redirect로 알게 되기 전에 cross-slot + 요청을 거절할 수 있다. +- `sdk.programmability`는 트랜잭션, 등록된 Lua script, 배포된 function 호출을 가진다. 호출 때 script 본문을 받지 + 않는다: catalog가 `EVAL`을 막고 `RedisScriptRegistry` digest의 `EVALSHA`만 닿을 수 있다. `FUNCTION LOAD`는 + 애플리케이션이 아니라 admin plane이다. +- 트랜잭션은 `WATCH`/`MULTI`/`EXEC`이고 **절대** 롤백하지 않는다. `TransactionResult`는 「실행됨」이나 「감시한 + 키가 바뀌어서 아무것도 돌지 않음」만 알리고, 이 패키지의 어떤 타입도 다른 뜻을 비치는 말을 주지 않는다. + 줄 세운 명령은 `QueuedReply`를 돌려주고, 커밋 전에 읽으면 던진다. 그 창 안에서 서버는 `+QUEUED`만 답했기 + 때문이다. 줄 세운 명령도 보통 명령과 같은 `CommandPolicyGuard` 허가를 지난다 — 트랜잭션은 guard를 피하는 길이 + 아니다 — 그리고 창은 던진 callback을 포함해 모든 출구에서 닫는다. `MULTI` 상태로 버려진 연결은 다음 호출자의 + 명령을 소리 없이 줄 세우기 때문이다. queue는 일부러 쓰기 전용이다: 창 안의 읽기로는 분기할 수 없으니, + 트랜잭션이 기대는 읽기는 그 앞에서 `WATCH` 아래에 둔다. +- `sdk.raw`는 승인된 raw 명령 gateway다. catalog가 `RAW_ONLY`로 표시했고 *그리고* 배포가 그 명령에 + `ApprovedRawCommand`를 등록했을 때만 닿을 수 있다. 보내기 전에 인자에서 키를 다시 파싱해 namespace를 검사한다. + 명령 이름을 문자열로 받는 메서드를 여기 더하지 않는다. +- `sdk.admin`은 읽기 전용 진단 plane이다. 자기 gateway(admin ACL 계정, 자기 연결)를 받고, catalog가 `ADMIN_ONLY`이자 + 읽기 전용으로 분류하지 않은 명령은 모두 거절하며, slow log나 client 목록이 인자·상대 주소·연결 이름을 싣지 + 않게 응답을 걸러 낸다. +- `sdk.extensions.*`는 Redis 8 모듈(JSON, Search, Time Series, Probabilistic)을 담는다. 모든 bean은 + `ifSupported(...)`로 만든다 — capability probe가 정하고, catalog 최소값은 앞 걸러내기일 뿐이다 — 그리고 모두 + `ExtensionCommandRunner`로 명령을 만들어 guard가 그 키를 본다. Search는 이것을 보여 주는 예외다: index는 키가 + 아니라서 그 이름은 `LettuceRedisSearchOperations`가 직접 namespace를 붙인다. +- `RedisSdkModuleBoundaryTest`(`redis-sdk` 안)가 `redis-sdk` 소스 루트를 scan해 내부 패키지 그래프, driver 가두기, + 아무 문자열 명령 surface 없음, 설계한 모듈 목록을 강제한다. +- 설계를 다시 보지 않고 바꾸면 안 되는 결정: 한계 없는 `entries`, `members`, `rangeAll`, `keys` 없음. 선택 사항인 + R2 허가·예산 없음. 아무 명령 문자열을 받는 overload 없음. timeout 뒤 멱등이 아닌 쓰기의 자동 재시도 없음. + metric이나 trace tag에 실제 키 없음. -## Boundaries +## 경계 -- Allowed dependency edges come only from the module's - `src/config/architecture/modules.json` entry. -- No inbound transport, persistence entity/repository, bootstrap, or sample dependency. -- Cache adapters do not decide business freshness, entitlement, or domain fallback rules. -- Physical Redis TTL must equal encoded hard expiry; future/corrupt schema must never collapse into - an ordinary miss. -- Application/domain code must not receive raw Redis keys, commands, Lua/Function names, SDK - objects, topology, or connection types. -- Cache fail-open behavior must not be reused for session, idempotency, strict quota, lease, or - fencing. -- Rate-limit composition must not reuse `app.cache.redis`, its connection, external client mode or - failure-open semantics; v1 is coordination-role and fail-closed only. -- The standalone runtime/cache service lane is R1 evidence only. Sentinel/Cluster, TLS/ACL, - persistence/restart, eviction and fault evidence are required separately for R2. +- 허용 의존 edge는 이 모듈의 `src/config/architecture/modules.json` 항목에서만 온다. +- inbound 전송, 영속 엔티티·repository, bootstrap, 샘플 의존이 없다. +- cache 어댑터는 업무상 신선도, 자격, 도메인 대체 규칙을 정하지 않는다. +- Redis 물리 TTL은 인코딩한 hard 만료와 같아야 한다. 미래·손상 schema가 보통 miss로 뭉개지면 안 된다. +- application·domain 코드는 raw Redis 키, 명령, Lua·Function 이름, SDK 객체, topology, 연결 타입을 받으면 안 된다. +- cache의 fail-open 동작을 session, 멱등성, 엄격한 quota, lease, fencing에 다시 쓰면 안 된다. +- rate-limit 조립은 `app.cache.redis`, 그 연결, 외부 client 모드, 실패하면 열리는 뜻을 다시 쓰면 안 된다. v1은 + 조율 role이고 실패하면 닫히는 것뿐이다. +- standalone runtime·cache 서비스 lane은 R1 증거일 뿐이다. Sentinel·Cluster, TLS·ACL, 영속·재시작, eviction, 장애 + 증거는 R2를 위해 따로 필요하다. -## Tests +## 테스트 -Focused tests drive the semantic adapters against `InMemorySemanticRedisCommands` from -`testFixtures(project(':adapter:outbound:redis-runtime'))`, the one fake of `SemanticRedisCommands`, -served through `StubRedisRuntimeClient`. R1/R2 promotion requires a separate real Redis service lane; it may never -be silently skipped when selected. +이 모듈만 보는 시험은 semantic 어댑터를 `testFixtures(project(':adapter:outbound:redis-runtime'))`의 +`InMemorySemanticRedisCommands`에 대고 돌린다. `SemanticRedisCommands`의 유일한 fake이고, `StubRedisRuntimeClient`를 +거쳐 쓴다. R1·R2 승격에는 따로 실제 Redis 서비스 lane이 필요하다. 그 lane을 골랐으면 소리 없이 건너뛰면 안 된다. -Two real-server lanes. `redisContainerContractTest` (integration category, in `integrationCheck` only — -not in this leaf's `mainCheck` too, which ran it twice per push to main) starts its own Redis with Testcontainers — the `redis` image of -`config/testing/container-images.properties`, loading `compose/redis/acl/lane-fixture-accounts.acl` — and -runs `LiveRedisCacheRegionContractTest`, `LiveRedisDistributedLeaseContractTest` and -`LiveRedisIdempotencyStoreContractTest` (the `application-core` port contracts the in-memory fakes -also pass), `LiveRedisSemanticPortsTest` and `LiveRedisSemanticScriptAclProbeTest`; a skip fails it -(since 2026-11-01). The idempotency contract was on the explicit-only topology lane alone -until 2026-11-03, so the Lua state machine's stale-handle, renew-refusal and -retry cases reached a real server in no gate. `RedisTestContainer` -starts the server only when that lane names the ACL file. +실제 서버 lane이 둘 있다. `redisContainerContractTest`(integration category, `integrationCheck`에만 있다 — 이 leaf의 +`mainCheck`에도 있었을 때는 main push마다 두 번 돌았다)는 Testcontainers로 자기 Redis를 띄운다 — +`config/testing/container-images.properties`의 `redis` image이고 `compose/redis/acl/lane-fixture-accounts.acl`을 +읽어 들인다 — 그리고 `LiveRedisCacheRegionContractTest`, `LiveRedisDistributedLeaseContractTest`, +`LiveRedisIdempotencyStoreContractTest`(메모리 fake도 통과하는 `application-core` 포트 계약), +`LiveRedisSemanticPortsTest`, `LiveRedisSemanticScriptAclProbeTest`를 돌린다. 건너뛰기가 있으면 실패한다 +(2026-11-01부터). 멱등성 계약은 2026-11-03까지 명시할 때만 도는 topology lane에만 있었다. 그래서 Lua 상태 기계의 +낡은 handle, 갱신 거절, 재시도 경우가 어느 게이트에서도 실제 서버에 닿지 않았다. `RedisTestContainer`는 그 lane이 +ACL 파일을 이름으로 댈 때만 서버를 띄운다. -`redisTopologyTest` is the external-topology lane, declared through `ca.redis-topology-lane`. This -leaf declares `standalone` and `cluster` (`LiveRedisSemanticPortsTest`, `LiveRedisSemanticScriptAclProbeTest`); `redis-runtime` and -`redis-sdk` declare their own lanes for their own classes. It is opt-in and fail-closed: the mode -must be one of `standalone`, `sentinel`, `cluster`, `tls` and one this leaf declares; the endpoint -properties must be present (`sentinel` additionally needs `redis.topology.master`, `tls` needs -`redis.topology.trust-material`); a run that discovers or executes zero tests fails (the -convention, not this leaf, owns that); the classes the leaf names in `redisTopologyLane` must -actually have run; and a skipped test fails the run rather than counting as executed. `tls` is a -lane, not a deployment mode — its shape is standalone and the task maps it so, because what it -qualifies is the transport. +`redisTopologyTest`는 외부 topology lane이고 `ca.redis-topology-lane`으로 선언한다. 이 leaf는 `standalone`과 +`cluster`(`LiveRedisSemanticPortsTest`, `LiveRedisSemanticScriptAclProbeTest`)를 선언한다. `redis-runtime`과 +`redis-sdk`는 자기 클래스에 대해 자기 lane을 선언한다. 고를 때만 돌고 실패하면 닫힌다: 모드는 `standalone`, +`sentinel`, `cluster`, `tls` 중 이 leaf가 선언한 것이어야 하고, endpoint 속성이 있어야 하며(`sentinel`은 +`redis.topology.master`가, `tls`는 `redis.topology.trust-material`이 더 필요하다), 시험을 하나도 찾지 못하거나 +돌리지 않은 실행은 실패하고(그것은 이 leaf가 아니라 규약이 가진다), leaf가 `redisTopologyLane`에 적은 클래스가 +실제로 돌았어야 하며, 건너뛴 시험은 실행한 것으로 세지 않고 실행을 실패시킨다. `tls`는 배포 모드가 아니라 +lane이다 — 모양은 standalone이고 태스크가 그렇게 대응시킨다. 검증하는 것이 전송이기 때문이다. -Two former checks are gone. A scan of the test sources for the literal text `@Tag("redis-topology")` -only improved the message for a failure `failOnNoDiscoveredTests` already produced, and a comment -containing the same text satisfied it. A hand-maintained per-mode floor on the executed count -(20/20/24/4) had to be edited whenever a case was added or removed, and the thing it failed on — -"coverage shrank" — is not a runtime, deployment, data, security or compile failure. +예전 검사 둘은 없어졌다. 시험 소스에서 글자 그대로 `@Tag("redis-topology")`를 찾는 scan은 +`failOnNoDiscoveredTests`가 이미 내는 실패의 메시지를 낫게 할 뿐이었고, 같은 글을 담은 주석으로도 만족됐다. 손으로 +관리하던 모드별 실행 수 하한(20/20/24/4)은 경우를 더하거나 뺄 때마다 고쳐야 했고, 그것이 잡는 「덮는 범위가 +줄었다」는 런타임·배포·데이터·보안·컴파일 실패가 아니다. -## Composition +## 조립 -`RedisRuntimeAutoConfiguration` now belongs to `:adapter:outbound:redis-runtime`. It is the only -place Redis settings and the shared runtime substrate come into existence, and it exists only while -`app.redis.enabled` (env `APP_REDIS_ENABLED`, default `true` — the module is on when present) is -true. It builds the topology client, connection owner and health contributors; `RedisCapabilityConfig` -in this leaf (its own `AutoConfiguration.imports`) composes the semantic ports on top of that runtime. +`RedisRuntimeAutoConfiguration`은 이제 `:adapter:outbound:redis-runtime`의 것이다. Redis 설정과 공용 runtime 기반이 +생기는 유일한 곳이고, `app.redis.enabled`(env `APP_REDIS_ENABLED`, 기본 `true` — 모듈이 있으면 켜진다)가 true인 +동안에만 있다. topology client, 연결 owner, health contributor를 만든다. 이 leaf의 `RedisCapabilityConfig`(자기 +`AutoConfiguration.imports`)가 그 runtime 위에 semantic 포트를 조립한다. -The optional `:adapter:outbound:redis-sdk` is not auto-composed by the shipped application. Its -`RedisStartupProbe` is a library API, not an implicit production guard. In particular there is no -`APP_REDIS_ACKNOWLEDGED_WRITE_LOSS_ACCEPTED` switch: accepting that trade must be an explicit -argument at the probe call site rather than a public setting with no production caller. +골라 쓰는 `:adapter:outbound:redis-sdk`는 출하하는 애플리케이션이 자동으로 조립하지 않는다. 그 +`RedisStartupProbe`는 라이브러리 API이고 숨은 운영 guard가 아니다. 특히 `APP_REDIS_ACKNOWLEDGED_WRITE_LOSS_ACCEPTED` +스위치는 없다: 그 거래를 받아들이는 것은 운영 호출자가 없는 공개 설정이 아니라 probe를 부르는 곳의 명시한 인자여야 +한다. -Every capability renders its keys under the one namespace from `app.redis.namespace` — -`{environment}:{service}:{domain}` — through `CapabilityKeyspace`. Never give a capability its own -prefix tokens: four capabilities each joining two free-form strings produced four different key -shapes, and the deployment's ACL pattern matched none of them. +모든 capability는 `CapabilityKeyspace`를 거쳐 `app.redis.namespace`의 namespace 하나 — +`{environment}:{service}:{domain}` — 아래에 키를 만든다. capability에 자기 접두어 token을 주지 않는다: capability 넷이 +각자 자유 문자열 둘을 이어 붙였더니 키 모양이 넷이 됐고, 배포의 ACL pattern은 그중 어느 것과도 맞지 않았다. -Lanes authenticate as different accounts. `RedisLane.account()` names the lane's `RedisAccount`, -and the topology factory builds one client per *configured* account — so a single-account -deployment still gets exactly one client and one event loop. The `SCRIPT` lane is -the reason it exists: `SCRIPT LOAD` and `EVALSHA` belong to the advanced account, so the account -that reads a cache entry cannot execute a script. +lane은 서로 다른 계정으로 인증한다. `RedisLane.account()`가 lane의 `RedisAccount`를 이름으로 대고, topology factory는 +*설정한* 계정마다 client를 하나 만든다 — 그래서 계정이 하나인 배포는 여전히 client 하나와 event loop 하나만 가진다. +`SCRIPT` lane이 그것이 있는 이유다: `SCRIPT LOAD`와 `EVALSHA`는 advanced 계정의 것이라서, cache 항목을 읽는 계정은 +script를 실행할 수 없다. -The cache's conditional writes run on the same account but on a lane of their own, -`CacheScriptLane.CACHE_SCRIPT` (`app.capabilities.cache.maximum-script-connections`, contributed by -`RedisCacheConfig` as a `RedisLaneContribution`). Do not move them back to `SCRIPT`: that lane is the -idempotency, rate-limit and lease budget, and a cache under load must not take it (decided -2026-11-03). Each lane's wait, refusals and reconnects are meters of `redis-runtime` -(`RedisLaneMetrics`, `redis.lane.*`, tag `lane`), so whether the cache stays off `SCRIPT` is a query, -not an assumption. The `DEGRADED` health order ships with `redis-runtime`, which reports the -status (`config/module-defaults/redis-runtime.yml`). +cache의 조건부 쓰기는 같은 계정이지만 자기 lane `CacheScriptLane.CACHE_SCRIPT`에서 돈다 +(`app.capabilities.cache.maximum-script-connections`, `RedisCacheConfig`가 `RedisLaneContribution`으로 기여한다). +`SCRIPT`로 되돌리지 않는다: 그 lane은 멱등성·rate-limit·lease의 예산이고, 부하를 받는 cache가 그것을 가져가면 +안 된다(2026-11-03에 정함). lane마다 기다림, 거절, 재연결은 `redis-runtime`의 meter(`RedisLaneMetrics`, `redis.lane.*`, +tag `lane`)이다. 그래서 cache가 `SCRIPT`를 쓰지 않는지는 짐작이 아니라 조회로 안다. `DEGRADED` health 순서는 +`redis-runtime`과 함께 나가고, 그 leaf가 상태를 알린다(`config/module-defaults/redis-runtime.yml`). -A Cluster transaction runs on one node, so the SDK's `RedisTransactionRunner` derives a routing key -from the watched keys (or an explicit `RedisSlotTag`) and borrows `RedisSdkLane.TRANSACTION`, which -is pinned to its key's owner, on the node that owns that slot. Routed leases are never pooled: a pooled connection is pinned to the previous caller's -node. +Cluster 트랜잭션은 노드 하나에서 돈다. 그래서 SDK의 `RedisTransactionRunner`는 감시한 키(또는 명시한 +`RedisSlotTag`)에서 routing 키를 끌어내고, 그 slot을 가진 노드에서 키의 주인에 고정된 `RedisSdkLane.TRANSACTION`을 +빌린다. route된 lease는 pool에 두지 않는다: pool에 둔 연결은 앞 호출자의 노드에 고정되어 있다. -Settings binding is a recorded exception to capability criterion 4 (one prefix, `StrictSettingsBinder`; -decided 2026-11-03): `app.redis.*` is bound by `redis-runtime` with setters and `validate()`, -because that leaf has no project dependencies and cannot reach `StrictSettingsBinder` (support); -`app.capabilities.*` (cache, lease, rate-limit provider) is bound strictly by this leaf under the -shared capability-selector root; `app.rate-limit.*` is the HTTP boundary's switch that this leaf only -reads. Renaming the keys would break every deployment's environment for no behavioural gain, so the -three trees stay; a new Redis setting goes into one of them, never a fourth. +설정 바인딩은 capability 기준 4(접두어 하나, `StrictSettingsBinder`)의 기록된 예외다(2026-11-03에 정함): +`app.redis.*`는 `redis-runtime`이 setter와 `validate()`로 바인딩한다. 그 leaf는 프로젝트 의존이 없어서 +`StrictSettingsBinder`(support)에 닿을 수 없기 때문이다. `app.capabilities.*`(cache, lease, rate-limit provider)는 이 +leaf가 공용 capability 선택 루트 아래에서 엄격하게 바인딩한다. `app.rate-limit.*`은 이 leaf가 읽기만 하는 HTTP +경계의 스위치다. 키 이름을 바꾸면 동작 이득 없이 모든 배포의 환경이 깨지니 세 트리를 그대로 둔다. 새 Redis 설정은 +그중 하나에 넣고, 네 번째 트리를 만들지 않는다. -`RedisRuntimeSettings` -must never carry a class-level `@ConfigurationProperties`: `RedisRuntimeAutoConfiguration` binds it, so -`APP_REDIS_ENABLED=false` binds no Redis configuration at all. A properties scan that reached this -package would bind it regardless (bootstrap's `@ConfigurationPropertiesScan` lists only -`dev.caskeleton.bootstrap.*` packages). Role selectors (cache binding, session auth-mode, idempotency/lease/rate-limit provider) -choose which capabilities compose; none of them activates Redis, and with the global switch off -this module contributes no bean at all. +`RedisRuntimeSettings`에는 클래스 수준 `@ConfigurationProperties`를 달면 안 된다: `RedisRuntimeAutoConfiguration`이 +그것을 바인딩하므로 `APP_REDIS_ENABLED=false`이면 Redis 설정을 하나도 바인딩하지 않는다. 이 패키지에 닿는 +properties scan은 그래도 그것을 바인딩하게 된다(bootstrap의 `@ConfigurationPropertiesScan`은 +`dev.caskeleton.bootstrap.*` 패키지만 적는다). role 선택자(cache 바인딩, session 인증 모드, 멱등성·lease·rate-limit +provider)는 어떤 capability를 조립할지 고른다. 그중 어느 것도 Redis를 켜지 않고, 전역 스위치가 꺼져 있으면 이 +모듈은 bean을 하나도 기여하지 않는다. diff --git a/src/adapter/outbound/cache-redis/README.md b/src/adapter/outbound/cache-redis/README.md index 515dc06e..47e879e3 100644 --- a/src/adapter/outbound/cache-redis/README.md +++ b/src/adapter/outbound/cache-redis/README.md @@ -1,372 +1,321 @@ -# Redis semantic adapters +# Redis semantic 어댑터 -This module is the **semantic Redis capability adapter**, not a general Redis SDK. +이 모듈은 범용 Redis SDK가 아니라 **semantic Redis capability 어댑터**다. -The Redis implementation is deliberately split into three Gradle leaves: +Redis 구현은 일부러 Gradle leaf 셋으로 나눈다: -- `:adapter:outbound:redis-runtime` (`dev.caskeleton.adapter.outbound.cache.redis.runtime`) — - shipped connection/topology/settings substrate: `RedisRuntimeSettings`, the lane owner, and the - eight `SemanticRedisCommands` this module sends. It knows nothing of the typed SDK. -- `:adapter:outbound:cache-redis` — shipped application-facing cache, rate-limit, lease and - idempotency adapters. -- `:adapter:outbound:redis-sdk` — optional typed/general-purpose SDK. It is not on the default - application runtime graph. +- `:adapter:outbound:redis-runtime`(`dev.caskeleton.adapter.outbound.cache.redis.runtime`) — 출하하는 연결· + topology·설정 기반: `RedisRuntimeSettings`, lane owner, 이 모듈이 보내는 `SemanticRedisCommands` 여덟 개. typed + SDK를 모른다. +- `:adapter:outbound:cache-redis` — 출하하는, 애플리케이션을 향한 cache·rate-limit·lease·멱등성 어댑터. +- `:adapter:outbound:redis-sdk` — 골라 쓰는 typed·범용 SDK. 기본 애플리케이션 runtime 그래프에 없다. -The default application therefore does not acquire the optional SDK's command policy merely by -selecting a semantic Redis capability. Semantic adapters call the runtime's `SemanticRedisCommands` -directly and own their own correctness rules. +그래서 기본 애플리케이션은 semantic Redis capability를 골랐다는 이유만으로 골라 쓰는 SDK의 명령 정책을 얻지 +않는다. semantic 어댑터는 runtime의 `SemanticRedisCommands`를 직접 부르고 자기 정확성 규칙을 스스로 가진다. -## Using it as a capability module — what it provides, the one line, the env keys +## capability 모듈로 쓰기 — 주는 것, 한 줄, env 키 -The web-only default composition does not ship this module: `app-bootstrap/build.gradle` lists it -as a commented `runtimeOnly` line. A service selects it by uncommenting that one line, and deleting -the line removes everything below: +web만 있는 기본 조립은 이 모듈을 싣지 않는다: `app-bootstrap/build.gradle`이 이것을 주석 처리한 `runtimeOnly` 줄로 +적는다. 서비스는 그 한 줄의 주석을 풀어 고르고, 그 줄을 지우면 아래 것이 모두 빠진다: ```groovy runtimeOnly project(':adapter:outbound:cache-redis') // brings :adapter:outbound:redis-runtime ``` -**Provides**, all registered by this module itself: +**주는 것**. 모두 이 모듈이 스스로 등록한다: -- the port implementations the role selectors ask for — `CacheRegionPort` (cache), - `EdgeRateLimitPort` (rate limit), `DistributedLeasePort` (lease), `IdempotencyStorePort` - (idempotency; the application builds the executor over it); -- `RedisCapabilityConfig` (`AutoConfiguration.imports`, after `RedisRuntimeAutoConfiguration`). With - `APP_REDIS_ENABLED=false` neither it nor redis-runtime's `RedisRuntimeAutoConfiguration` contributes a - bean — no settings, client, connection, thread or health contributor. The module pulls no Spring - Data Redis, so there is no Boot Redis auto-configuration to exclude; -- the readiness contribution `RedisReadinessGroupPostProcessor` (this module's `spring.factories`): - `redisRequired` joins the readiness group only when a correctness role selects Redis. Which roles - those are is this module's `RedisCorrectnessRoleSelectors`, registered in the same file as the - runtime's `RedisCorrectnessRequirement` — the runtime asks, it does not list selectors; -- the shipped settings `config/module-defaults/cache-redis.yml` — `app.redis.enabled`, - `app.rate-limit.*`, and the Redis parts of `app.capabilities.*` (cache, lease, rate-limit, - the Redis idempotency store's tuning). The support leaf's `ModuleDefaultsEnvironmentPostProcessor` - loads it below every application setting. +- role 선택자가 요구하는 포트 구현 — `CacheRegionPort`(cache), `EdgeRateLimitPort`(rate limit), + `DistributedLeasePort`(lease), `IdempotencyStorePort`(멱등성. 애플리케이션이 그 위에 executor를 만든다); +- `RedisCapabilityConfig`(`AutoConfiguration.imports`, `RedisRuntimeAutoConfiguration` 뒤). `APP_REDIS_ENABLED=false`이면 + 그것도 redis-runtime의 `RedisRuntimeAutoConfiguration`도 bean을 기여하지 않는다 — 설정, client, 연결, 스레드, + health contributor가 없다. 이 모듈은 Spring Data Redis를 끌어오지 않으니 뺄 Boot Redis 자동 구성도 없다; +- readiness 기여 `RedisReadinessGroupPostProcessor`(이 모듈의 `spring.factories`): 정확성 role이 Redis를 고를 때만 + `redisRequired`가 readiness group에 들어간다. 어떤 role인지는 이 모듈의 `RedisCorrectnessRoleSelectors`가 정하고, + 같은 파일에 runtime의 `RedisCorrectnessRequirement`로 등록한다 — runtime은 묻기만 하고 선택자를 적지 않는다; +- 출하하는 설정 `config/module-defaults/cache-redis.yml` — `app.redis.enabled`, `app.rate-limit.*`, + `app.capabilities.*`의 Redis 부분(cache, lease, rate-limit, Redis 멱등성 store의 조정). support leaf의 + `ModuleDefaultsEnvironmentPostProcessor`가 모든 애플리케이션 설정보다 아래 우선순위로 읽는다. -The application provides `SecretSourcePort` and `Clock`. +애플리케이션이 `SecretSourcePort`와 `Clock`을 준다. -**Env keys** (`src/.env.example`, registry `docs/registries/env-keys.yaml`): +**env 키**(`src/.env.example`, registry `docs/registries/env-keys.yaml`): -| Purpose | Keys | +| 용도 | 키 | |---|---| -| Switch | `APP_REDIS_ENABLED` (default true; `false` turns the present module off) | -| Connection | `APP_REDIS_MODE`, `APP_REDIS_NODES`, `APP_REDIS_DATABASE`, `APP_REDIS_SENTINEL_*`, `APP_REDIS_TLS_*`, `APP_REDIS_AUTHENTICATION_*` (credential references) | -| Namespace | `APP_REDIS_NAMESPACE_ENVIRONMENT`, `APP_REDIS_NAMESPACE_SERVICE`, `APP_REDIS_NAMESPACE_DOMAIN` | -| Roles | `APP_CACHE_CANONICAL_DEFAULT_PROVIDER`, `APP_RATE_LIMIT_PROVIDER`, `APP_LEASE_PROVIDER`, `APP_IDEMPOTENCY_PROVIDER=redis` | -| Role tuning | `APP_CACHE_REDIS_*`, `APP_RATE_LIMIT_*`, `APP_LEASE_REDIS_*`, `APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT` | -| Prod secrets (per selected role) | `APP_CACHE_REDIS_PASSWORD`, `APP_CACHE_REDIS_KEY_HMAC_SECRET`, `APP_RATE_LIMIT_REDIS_PASSWORD`, `APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET`, `APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET`, `APP_LEASE_REDIS_KEY_HMAC_SECRET` | +| 스위치 | `APP_REDIS_ENABLED`(기본 true. `false`이면 있는 모듈을 끈다) | +| 연결 | `APP_REDIS_MODE`, `APP_REDIS_NODES`, `APP_REDIS_DATABASE`, `APP_REDIS_SENTINEL_*`, `APP_REDIS_TLS_*`, `APP_REDIS_AUTHENTICATION_*`(credential 참조) | +| namespace | `APP_REDIS_NAMESPACE_ENVIRONMENT`, `APP_REDIS_NAMESPACE_SERVICE`, `APP_REDIS_NAMESPACE_DOMAIN` | +| role | `APP_CACHE_CANONICAL_DEFAULT_PROVIDER`, `APP_RATE_LIMIT_PROVIDER`, `APP_LEASE_PROVIDER`, `APP_IDEMPOTENCY_PROVIDER=redis` | +| role 조정 | `APP_CACHE_REDIS_*`, `APP_RATE_LIMIT_*`, `APP_LEASE_REDIS_*`, `APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT` | +| 운영 비밀 값(고른 role마다) | `APP_CACHE_REDIS_PASSWORD`, `APP_CACHE_REDIS_KEY_HMAC_SECRET`, `APP_RATE_LIMIT_REDIS_PASSWORD`, `APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET`, `APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET`, `APP_LEASE_REDIS_KEY_HMAC_SECRET` | -## Activation and composition +## 켜기와 조립 -Redis is on when this module is present. It has one off switch: +이 모듈이 있으면 Redis가 켜진다. 끄는 스위치는 하나다: -`app.redis.enabled=false` / `APP_REDIS_ENABLED=false` (default `true`). +`app.redis.enabled=false` / `APP_REDIS_ENABLED=false`(기본 `true`). -A semantic role does **not** activate Redis by itself: with the switch off this module -contributes no bean at all, whatever a role selector says. Redis idempotency refuses -`app.capabilities.idempotency.key-version` other than 1 at startup (no dual-read yet). +semantic role 혼자서는 Redis를 켜지 **않는다**: 스위치가 꺼져 있으면 role 선택자가 무엇을 말하든 이 모듈은 bean을 +하나도 기여하지 않는다. Redis 멱등성은 기동 때 1이 아닌 `app.capabilities.idempotency.key-version`을 거절한다(아직 +이중 읽기가 없다). -Current role selectors are: +지금의 role 선택자: - cache: `app.capabilities.cache.bindings.default=redis` - rate limit: `app.capabilities.rate-limit.provider=redis` - lease: `app.capabilities.lease.provider=redis` -- idempotency: `app.capabilities.idempotency.provider=redis` +- 멱등성: `app.capabilities.idempotency.provider=redis` -Only selected capabilities contribute their application port bean. +고른 capability만 자기 애플리케이션 포트 bean을 기여한다. -All capabilities render below the single namespace in `app.redis.namespace.*`. Per-capability -namespace settings are deprecated because they made ACL fencing inconsistent. +모든 capability는 `app.redis.namespace.*`의 namespace 하나 아래에 키를 만든다. capability별 namespace 설정은 ACL +fencing을 들쭉날쭉하게 만들어서 폐기 예정이다. -## Runtime ownership +## runtime 소유 -`:adapter:outbound:redis-runtime` owns: +`:adapter:outbound:redis-runtime`이 가진다: -- topology selection (standalone / sentinel / cluster), -- role-aware credentials, -- connection lifecycle and bounded lane leasing, -- the low-level command gateway, +- topology 고르기(standalone / sentinel / cluster), +- role을 아는 credential, +- 연결 lifecycle과 한계 있는 lane 대여, +- 낮은 수준 명령 gateway, - health, -- TLS and connection/client timeouts. +- TLS와 연결·client timeout. -`RedisRuntimeOwner` stops admission before shutdown, drains outstanding leases within a bounded -budget, closes connections, then closes the client. +`RedisRuntimeOwner`는 종료 전에 admission을 멈추고, 한계 있는 예산 안에서 남은 lease를 비우고, 연결을 닫은 뒤 +client를 닫는다. -Connection lane limits and command queue limits are different contracts. In particular: +연결 lane 한계와 명령 queue 한계는 다른 계약이다. 특히: -- `app.redis.capacity.maximum-in-flight-commands` bounds the per-connection command queue. -- `app.redis.capacity.maximum-script-connections` bounds physical SCRIPT lane connections - (default 8). Idempotency, rate limiting and leases share them. -- `app.capabilities.cache.maximum-script-connections` (`APP_CACHE_REDIS_MAXIMUM_SCRIPT_CONNECTIONS`) - bounds the cache's own script lane (`CacheScriptLane`, default 4), contributed only when the cache - binding is `redis`. See "Why the cache has its own script lane" below. -- `app.redis.lifecycle.acquire-timeout` (default 2s) is how long a borrow waits for a returned - connection when its lane is full. +- `app.redis.capacity.maximum-in-flight-commands`는 연결마다 명령 queue를 묶는다. +- `app.redis.capacity.maximum-script-connections`는 SCRIPT lane의 물리 연결을 묶는다(기본 8). 멱등성, rate limit, + lease가 그것을 같이 쓴다. +- `app.capabilities.cache.maximum-script-connections`(`APP_CACHE_REDIS_MAXIMUM_SCRIPT_CONNECTIONS`)는 cache 자신의 + script lane(`CacheScriptLane`, 기본 4)을 묶고, cache 바인딩이 `redis`일 때만 기여한다. 아래 「cache가 자기 script + lane을 가지는 이유」를 본다. +- `app.redis.lifecycle.acquire-timeout`(기본 2s)은 lane이 찼을 때 대여가 돌아올 연결을 기다리는 시간이다. -The second limit exists so a burst of semantic Lua calls cannot turn a command-capacity number such -as 64 into 64 physical Redis sockets. It bounds connections, not callers: a lease holds a connection -for one script round trip, so the ninth concurrent caller waits for one to come back instead of -being refused. Only a borrow still waiting when the acquire timeout runs out is refused, and that -refusal is a `RedisCommandRejectedException` whose metadata is not ambiguous — no command was ever -sent. +두 번째 한계는 semantic Lua 호출이 몰려도 64 같은 명령 용량 숫자가 Redis 물리 socket 64개가 되지 않게 하려고 +있다. 호출자가 아니라 연결을 묶는다: lease는 script 왕복 한 번 동안 연결을 쥐니, 아홉 번째 동시 호출자는 거절되지 +않고 연결 하나가 돌아오기를 기다린다. acquire timeout이 다 됐을 때 아직 기다리는 대여만 거절하고, 그 거절은 +metadata가 모호하지 않은 `RedisCommandRejectedException`이다 — 명령을 한 번도 보내지 않았다. -## Script ACL startup probe +## script ACL 기동 probe -Rate limiting, distributed leases and Redis idempotency execute Lua programs. If any of those roles -select Redis, the composition root runs a startup probe on the SCRIPT lane: +rate limit, 분산 lease, Redis 멱등성은 Lua program을 실행한다. 그 role 중 하나라도 Redis를 고르면 조립 루트가 +SCRIPT lane에서 기동 probe를 돌린다: -1. `SCRIPT LOAD` a program that calls the commands the semantic scripts depend on — `TIME`, then - `HSET`/`PEXPIRE`/`HGET`/`DEL` on its own probe key, which it deletes; -2. execute it through `EVALSHA`; -3. require the expected reply (the value it wrote reads back). +1. semantic script가 기대는 명령을 부르는 program을 `SCRIPT LOAD`한다 — `TIME`, 그다음 자기 probe 키에 + `HSET`/`PEXPIRE`/`HGET`/`DEL`을 하고 그 키를 지운다; +2. `EVALSHA`로 실행한다; +3. 기대한 응답(쓴 값이 다시 읽힌다)을 요구한다. -Redis checks a script's inner commands against the ACL only when they run, so a probe that ran -nothing proved `EVALSHA` and nothing else: an account granted by category (`@read`/`@write`) lacks -`TIME` and failed every rate-limit and idempotency request after a clean start. A deployment whose -effective Redis account lacks script permissions fails during startup rather than at the first -request. +Redis는 script 안의 명령을 돌 때만 ACL과 대조한다. 그래서 아무것도 돌리지 않는 probe는 `EVALSHA`만 증명했다: +category로(`@read`/`@write`) 권한을 준 계정에는 `TIME`이 없었고, 깨끗하게 시작한 뒤 모든 rate-limit·멱등성 요청이 +실패했다. 실제 Redis 계정에 script 권한이 없는 배포는 첫 요청이 아니라 기동 중에 실패한다. -A cache-only deployment (`app.capabilities.cache.bindings.default=redis`, no correctness role) runs -a narrower probe: a program that calls only `SET`/`GET`, the commands the cache's conditional-write -programs use. A server that answers and refuses it fails startup — every conditional record would -otherwise come back degraded while plain reads looked healthy. A Redis that cannot be reached at -startup is logged as a warning and the pod starts: a cache outage degrades, it never stops a pod. +cache만 쓰는 배포(`app.capabilities.cache.bindings.default=redis`, 정확성 role 없음)는 더 좁은 probe를 돌린다: cache의 +조건부 쓰기 program이 쓰는 명령인 `SET`/`GET`만 부르는 program이다. 답은 하지만 그것을 거절하는 서버는 기동을 +실패시킨다 — 그렇지 않으면 보통 읽기는 건강해 보이는데 모든 조건부 기록이 degraded로 돌아온다. 기동 때 닿을 수 +없는 Redis는 경고로 남기고 pod를 시작한다: cache 장애는 성능을 떨어뜨릴 뿐 pod를 멈추지 않는다. -At runtime, `redisRequired` (redis-runtime) probes the SCRIPT lane too when a script role is -selected, so a broken advanced-account credential makes the pod unready instead of leaving the -regular-lane PING to report UP. +런타임에는 script role을 골랐으면 `redisRequired`(redis-runtime)가 SCRIPT lane도 probe한다. 그래서 advanced 계정 +credential이 깨지면 regular lane PING이 UP을 알리게 두지 않고 pod를 unready로 만든다. -## Cache semantics +## cache 뜻 -`RedisCacheRegionAdapter` implements the application cache port. +`RedisCacheRegionAdapter`가 애플리케이션 cache 포트를 구현한다. -Important contracts: +중요한 계약: -- value entries have soft and hard expiry; -- negative entries use the shorter negative TTL; -- Redis physical TTL is the hard expiry; -- cache outages degrade to the application's typed unavailable/degraded outcomes; -- identifiers are rendered through a keyed digest before entering the keyspace. +- 값 항목에는 soft·hard 만료가 있다; +- 부정 항목은 더 짧은 부정 TTL을 쓴다; +- Redis 물리 TTL은 hard 만료다; +- cache 장애는 애플리케이션의 타입 있는 unavailable·degraded 결과로 떨어진다; +- 식별자는 keyspace에 들어가기 전에 키 있는 digest를 거친다. -### Conditional replacement +### 조건부 바꾸기 -`ONLY_IF_OBSERVED` is an atomic server-side compare-and-replace. +`ONLY_IF_OBSERVED`는 서버 쪽 원자 compare-and-replace다. -Every lookup returns a `CacheWriteCondition` naming the state it saw — `absent`, `vacant:` -(an invalidation marker, an entry of an older region generation, an expired entry) or -`present:`. A record that carries the condition applies only while the key is still in that -state (registered program, cache script lane). This is what rejects a source load that began before an -invalidation and finished after it. +모든 조회는 본 상태를 이름으로 대는 `CacheWriteCondition`을 돌려준다 — `absent`, `vacant:`(무효화 표지, 옛 +region generation의 항목, 만료된 항목), `present:`. 그 조건을 실은 기록은 키가 아직 그 상태일 때만 적용한다 +(등록된 program, cache script lane). 무효화 전에 시작해 무효화 뒤에 끝난 source 읽기를 이것이 거절한다. -A hit also returns an opaque SHA-1 observation token over the stored bytes. SHA-1 here is **not a -security primitive**; it is used only because Redis Lua exposes `redis.sha1hex`, allowing the -script to perform: +hit는 저장된 바이트 위의 불투명한 SHA-1 관찰 token도 돌려준다. 여기서 SHA-1은 **보안 기본 장치가 아니다**. Redis +Lua가 `redis.sha1hex`를 내놓아서 script가 아래를 할 수 있기 때문에 쓴다: `GET current -> compare observation -> SET replacement PX ttl` -inside one Redis execution. A stale source load therefore cannot overwrite a value written between -observation and replacement. +이것을 Redis 실행 한 번 안에서 한다. 그래서 낡은 source 읽기는 관찰과 바꾸기 사이에 쓰인 값을 덮어쓸 수 없다. -`ONLY_IF_SOURCE_REVISION_NEWER` is an atomic server-side revision comparison. The order is the -port's `CacheSourceRevisionOrder` (application-core): a non-negative decimal integer without leading -zeros (a row version, an offset, epoch millis), compared numerically at any length. Any other -revision is refused by `CacheRecordMetadata` itself, for every provider, because text order would -rank revision `10` below `9`. The Lua program reimplements the order (the comparison and the write -must be one step); `CacheRegionContract`, run over the fixture and a real server, keeps it equal. The script reads the stored envelope's -schema version, revision and generation and writes only when: +`ONLY_IF_SOURCE_REVISION_NEWER`는 서버 쪽 원자 revision 비교다. 순서는 포트의 `CacheSourceRevisionOrder` +(application-core)다: 앞자리 0이 없는 음이 아닌 10진 정수(row version, offset, epoch millis)이고, 길이와 관계없이 +숫자로 비교한다. 그 밖의 revision은 모든 provider에서 `CacheRecordMetadata`가 직접 거절한다. 글자 순서로는 revision +`10`이 `9`보다 아래가 되기 때문이다. Lua program은 그 순서를 다시 구현한다(비교와 쓰기가 한 단계여야 한다). +fixture와 실제 서버에 대고 도는 `CacheRegionContract`가 둘을 같게 지킨다. script는 저장된 envelope의 schema version, +revision, generation을 읽고 다음일 때만 쓴다: -- nothing is stored, or the stored entry is from an older region generation (already invalidated); -- otherwise, the stored revision is a decimal integer and the caller's is strictly greater. +- 아무것도 저장돼 있지 않거나, 저장된 항목이 옛 region generation에서 왔다(이미 무효화됨); +- 아니면, 저장된 revision이 10진 정수이고 호출자의 것이 엄격하게 크다. -Everything else — an equal or smaller revision, a stored revision with no numeric order (for -example one written by `UPSERT` as `rev-1`), another schema version, a generation newer than the -writer knows — is `NOT_RECORDED_CONDITION`. +그 밖의 모든 것 — 같거나 작은 revision, 숫자 순서가 없는 저장 revision(예: `UPSERT`가 `rev-1`로 쓴 것), 다른 +schema version, 쓰는 쪽이 아는 것보다 새 generation — 은 `NOT_RECORDED_CONDITION`이다. -Both conditional intents, and any record carrying a write condition, run registered scripts, so -they run on the scripting account (the advanced account when one is configured, the application -account otherwise), on the cache's own script lane. The application account is not granted -`EVALSHA`; on the REGULAR lane every conditional write came back `INDETERMINATE`. Unconditioned -`UPSERT` and `ONLY_IF_ABSENT` stay on the REGULAR lane. +두 조건부 의도와, 쓰기 조건을 실은 모든 기록은 등록된 script를 돌리므로 script 계정(advanced 계정을 설정했으면 그 +계정, 아니면 애플리케이션 계정)으로, cache 자신의 script lane에서 돈다. 애플리케이션 계정에는 `EVALSHA`를 주지 +않는다. REGULAR lane에서는 모든 조건부 쓰기가 `INDETERMINATE`로 돌아왔다. 조건 없는 `UPSERT`와 `ONLY_IF_ABSENT`는 +REGULAR lane에 남는다. -### Why the cache has its own script lane +### cache가 자기 script lane을 가지는 이유 -Recording with the condition a lookup returned is the normal way to use this port, so nearly every -cache fill is a script. On the runtime's SCRIPT lane those fills shared eight connections per pod -with idempotency claims, rate-limit evaluations and lease calls, and a timed-out lease is discarded -rather than pooled, so each timeout also cost a reconnect. A slow Redis or a burst of misses after a -region invalidation filled the lane with cache work; an idempotency claim then waited out its -timeout and answered `UNAVAILABLE`, and a rate-limit call fell to its failure policy. The cache is a -speed feature that may degrade; idempotency, rate limiting and leases are correctness features that -must not (review 2026-11-03 README §4, RR-04-02). +조회가 돌려준 조건으로 기록하는 것이 이 포트를 쓰는 보통 방법이라서 거의 모든 cache 채우기가 script다. runtime의 +SCRIPT lane에서 그 채우기는 pod마다 연결 여덟 개를 멱등성 claim, rate-limit 평가, lease 호출과 같이 썼다. timeout이 +난 lease는 pool로 돌아가지 않고 버려지니, timeout마다 재연결 비용도 들었다. Redis가 느리거나 region 무효화 뒤 miss가 +몰리면 lane이 cache 일로 찼다. 그러면 멱등성 claim은 timeout까지 기다렸다가 `UNAVAILABLE`로 답했고, rate-limit +호출은 실패 정책으로 떨어졌다. cache는 성능이 떨어져도 되는 속도 기능이고, 멱등성·rate limit·lease는 떨어지면 안 +되는 정확성 기능이다(review 2026-11-03 README §4, RR-04-02). -So `CacheScriptLane.CACHE_SCRIPT` is a lane of its own — the same scripting account, its own -connections, its own ceiling (`app.capabilities.cache.maximum-script-connections`, default 4). A cache -that runs out of them degrades (`DEGRADED_UNAVAILABLE`, nothing sent) without touching the SCRIPT -lane. Alternatives not taken: a per-capability permit cap inside the shared SCRIPT lane (still one -pool of connections and one reconnect cost), and running the cache programs on the REGULAR lane -(grants the application account `EVALSHA`, which the account split exists to withhold). +그래서 `CacheScriptLane.CACHE_SCRIPT`는 자기 lane이다 — 같은 script 계정, 자기 연결, 자기 상한 +(`app.capabilities.cache.maximum-script-connections`, 기본 4). 연결이 바닥난 cache는 SCRIPT lane을 건드리지 않고 +성능을 떨어뜨린다(`DEGRADED_UNAVAILABLE`, 보낸 것 없음). 고르지 않은 대안: 공용 SCRIPT lane 안의 capability별 허가 +상한(여전히 연결 pool 하나와 재연결 비용 하나), cache program을 REGULAR lane에서 돌리기(애플리케이션 계정에 +`EVALSHA`를 준다. 계정을 나눈 것은 바로 그것을 주지 않으려는 것이다). -Whether the split holds under load is visible per lane. With a `MeterRegistry` in the context, -`redis-runtime` registers these for every lane it pools — `REGULAR`, `SCRIPT`, `CACHE_SCRIPT` and the -typed SDK's — tagged `lane=` (`RedisLaneMetrics`; rows in `docs/registries/metrics.yaml`): +부하 아래에서 이 분리가 지켜지는지는 lane마다 보인다. context에 `MeterRegistry`가 있으면 `redis-runtime`이 pool로 두는 +모든 lane — `REGULAR`, `SCRIPT`, `CACHE_SCRIPT`, typed SDK의 lane — 에 대해 아래를 `lane=` tag로 등록한다 +(`RedisLaneMetrics`. 행은 `docs/registries/metrics.yaml`): -| Meter | Type | Read it as | +| meter | 타입 | 읽는 법 | | --- | --- | --- | -| `redis.lane.acquire.wait.seconds` (`outcome` = `admitted`/`refused`) | timer, histogram | how long a borrow queued for a connection; a growing admitted p99 comes before refusals | -| `redis.lane.acquire.refused.total` (`reason` = `saturated`/`closing`/`interrupted`/`connect_failed`) | counter | a borrow that got no connection, nothing sent; `saturated` on `SCRIPT` is the starvation this lane exists to prevent | -| `redis.lane.connections.opened.total` | counter | new connections; after warm-up a pooled lane opens one only to replace a discarded one. A routed lease (a Cluster `TRANSACTION` borrow) is opened for each borrow and closed after it without being counted as discarded, so on that lane a steady rate is normal use, not reconnects | -| `redis.lane.connections.discarded.total` (`reason` = `invalidated`/`broken`) | counter | connections closed instead of pooled — `invalidated` is a timed-out or failed call (the lease is not reused), and is what the reconnects replace | -| `redis.lane.connections.active`, `redis.lane.connections.pending` | gauge | connections lent out now; borrows waiting now | +| `redis.lane.acquire.wait.seconds`(`outcome` = `admitted`/`refused`) | timer, histogram | 대여가 연결을 얼마나 기다렸나. 거절보다 먼저 admitted p99가 늘어난다 | +| `redis.lane.acquire.refused.total`(`reason` = `saturated`/`closing`/`interrupted`/`connect_failed`) | counter | 연결을 얻지 못한 대여, 보낸 것 없음. `SCRIPT`의 `saturated`가 이 lane이 막으려는 굶주림이다 | +| `redis.lane.connections.opened.total` | counter | 새 연결. 데운 뒤에는 pool로 두는 lane이 버린 연결을 대신할 때만 연다. route된 lease(Cluster `TRANSACTION` 대여)는 대여마다 열고 그 뒤에 닫지만 버린 것으로 세지 않는다. 그래서 그 lane에서 꾸준한 비율은 재연결이 아니라 보통 사용이다 | +| `redis.lane.connections.discarded.total`(`reason` = `invalidated`/`broken`) | counter | pool로 두지 않고 닫은 연결 — `invalidated`는 timeout이 났거나 실패한 호출(그 lease는 다시 쓰지 않는다)이고, 재연결이 대신하는 것이 이것이다 | +| `redis.lane.connections.active`, `redis.lane.connections.pending` | gauge | 지금 빌려준 연결, 지금 기다리는 대여 | -Every counter series exists from startup at zero, so an alert on "refusals above zero" sees the first -one. A lane refusal is also logged, per call, by `RedisSemanticFailureLogger`. +모든 counter series는 기동 때부터 0으로 있으니, 「거절이 0보다 많다」 경보가 첫 거절을 본다. lane 거절은 +`RedisSemanticFailureLogger`도 호출마다 남긴다. -### Key invalidation +### 키 무효화 -`invalidate(key)` writes a short-lived marker (`GET`, then `SET … PX softTtl` on the REGULAR lane) -instead of deleting the key. While the marker lives, a record whose condition came from an earlier -lookup, an unconditioned `ONLY_IF_ABSENT`, and an unconditioned `ONLY_IF_SOURCE_REVISION_NEWER` are -`NOT_RECORDED_CONDITION`; a fresh lookup returns a `vacant:` condition that records normally; -unconditioned `UPSERT` overwrites it. Limit: the marker lives for the soft TTL, so a source load -slower than that, carrying an `absent` condition, can still land after it. +`invalidate(key)`는 키를 지우지 않고 짧게 사는 표지를 쓴다(REGULAR lane에서 `GET`, 그다음 `SET … PX softTtl`). 표지가 +사는 동안 앞 조회에서 온 조건을 실은 기록, 조건 없는 `ONLY_IF_ABSENT`, 조건 없는 `ONLY_IF_SOURCE_REVISION_NEWER`는 +`NOT_RECORDED_CONDITION`이다. 새 조회는 보통으로 기록되는 `vacant:` 조건을 돌려준다. 조건 없는 `UPSERT`는 표지를 +덮어쓴다. 한계: 표지는 soft TTL 동안 산다. 그래서 그보다 느리고 `absent` 조건을 실은 source 읽기는 여전히 그 뒤에 +들어올 수 있다. -### Stampede +### stampede -There is no stampede protection and no TTL jitter. Concurrent misses on one key each load from the -source. Single-flight, where a source cannot take the burst, is the caller's. +stampede 보호도 TTL jitter도 없다. 한 키에 동시에 난 miss는 각자 source에서 읽는다. source가 몰림을 감당하지 못하면 +single-flight는 호출자의 몫이다. -### Region invalidation +### region 무효화 -Region invalidation increments a generation key; it never scans/deletes the keyspace. +region 무효화는 generation 키를 올린다. keyspace를 scan하거나 지우지 않는다. -Each adapter instance caches the observed generation only for the positive soft TTL. After that -bounded interval it rechecks the server generation. This keeps ordinary cache hits from paying an -extra Redis round trip while ensuring an invalidation issued by another process eventually becomes -visible to every instance. +어댑터 인스턴스마다 본 generation을 양의 soft TTL 동안만 cache한다. 그 한계 있는 시간이 지나면 서버 generation을 다시 +본다. 그래서 보통 cache hit는 Redis 왕복을 더 치르지 않으면서, 다른 프로세스가 낸 무효화도 결국 모든 인스턴스에 +보이게 된다. -## Rate-limit semantics +## rate-limit 뜻 -The rate-limit adapter supports the configured fixed-window, sliding-counter and token-bucket -policies through registered Lua scripts. +rate-limit 어댑터는 설정한 fixed-window, sliding-counter, token-bucket 정책을 등록된 Lua script로 지원한다. -Time is taken from Redis `TIME`, not the caller JVM clock. Multiple application nodes therefore -make the same distributed decision even if their local clocks differ. +시간은 호출자 JVM 시계가 아니라 Redis `TIME`에서 가져온다. 그래서 애플리케이션 노드 여럿의 로컬 시계가 달라도 같은 +분산 판단을 한다. -Script TTLs are computed as integer milliseconds in Java and passed as exact Lua arguments. -`cleanup-grace` is part of the physical state TTL. There is no exposed -`maximum-clock-regression` knob because Redis is the time authority for this state. +script TTL은 Java에서 정수 밀리초로 계산해 정확한 Lua 인자로 넘긴다. `cleanup-grace`는 물리 상태 TTL의 일부다. 이 +상태의 시간 정본은 Redis이므로 `maximum-clock-regression` 손잡이는 내놓지 않는다. -Rate-limit failures remain fail-closed according to the application contract. A connection that -could not be opened is `UNAVAILABLE_BEFORE_SEND` (nothing was sent). The caller's remaining -deadline bounds the lane wait and the reply wait; opening a new connection is still bounded only by -the driver's connect timeout. +rate-limit 실패는 애플리케이션 계약대로 실패하면 닫힌다. 열지 못한 연결은 `UNAVAILABLE_BEFORE_SEND`다(보낸 것 없음). +호출자의 남은 deadline이 lane 대기와 응답 대기를 묶는다. 새 연결 열기는 여전히 driver의 connect timeout만 묶는다. -Evaluation deduplication is **not implemented**: `RateLimitRequest.evaluationId` is ignored, so a -retry after `NO_MUTATION_CONFIRMED` is charged again. Policies default to -`RateLimitEvaluationDedupPolicy.disabled()`, and the adapter refuses a policy that enables it. +평가 중복 제거는 **구현하지 않았다**: `RateLimitRequest.evaluationId`는 무시하므로 `NO_MUTATION_CONFIRMED` 뒤의 +재시도는 다시 센다. 정책 기본값은 `RateLimitEvaluationDedupPolicy.disabled()`이고, 어댑터는 그것을 켠 정책을 +거절한다. -## Idempotency semantics +## 멱등성 뜻 -The Redis idempotency adapter stores owner-safe claim state and executes claim/transition/release -programs atomically. `RedisIdempotencyConfig` contributes only the `IdempotencyStorePort`; the -`IdempotencyExecutor` and its lifecycle policy (lease, replay TTL, retention, codec id, policy -revision) come from app-bootstrap `IdempotencySettings`. This leaf reads only `key-version` and -`command-timeout` under `app.capabilities.idempotency`. +Redis 멱등성 어댑터는 소유자를 안전하게 지키는 claim 상태를 저장하고 claim·전이·놓아주기 program을 원자적으로 +실행한다. `RedisIdempotencyConfig`는 `IdempotencyStorePort`만 기여한다. `IdempotencyExecutor`와 그 lifecycle 정책 +(lease, 재생 TTL, 보존, codec id, 정책 revision)은 `composition:idempotency`의 `IdempotencySettings`에서 온다. 이 +leaf는 `app.capabilities.idempotency` 아래의 `key-version`과 `command-timeout`만 읽는다. -`renew` has its own program rather than the generic transition. Renewal keeps the record in -`EXECUTING`, and the transition answers "already in the target state" before it reads the revision -(that answer exists for a retry whose first reply was lost), so a renewal sent through it was always -`ALREADY_RENEWED_SAME_OPERATION` and never moved the lease. That answer is given only to the handle -the transition was applied from — the record one revision past it, with `lastKind` (written by the -claim, renew and transition programs) naming that transition. Another handle of the same -attempt (one from before a takeover, or the current one a replayed claim returned) used to be told a -start was applied and ran the action a second time (round6 RR6-02-01), and to be told a completion -or failure that followed a takeover was its own (owner decision 2026-11-06); it is now `NOT_OWNER` -or `NOT_CLAIMED`/`NOT_IN_PROGRESS`, as in the PostgreSQL store. Without the kind, a start through the -handle a renewal was applied from was confirmed too — renewal leaves the record `EXECUTING` one -revision past that handle (round8 RR8-04-02); it is `NOT_OWNER`. A failure from the handle that -applied one, asking for the other disposition, is `OPERATION_CONFLICT` (it fell through to -`NOT_OWNER`); the record keeps no retention, so another retention is confirmed (owner decision -2026-11-07). The renew program checks owner, -operation, revision and state, then extends `leaseUntil` from Redis `TIME` and bumps the revision. -A lost renewal reply is recognised by what the renewal recorded — the revision it started from and -the lease it asked for: the same lease is `ALREADY_RENEWED_SAME_OPERATION` with the current handle, -a different lease is `OPERATION_CONFLICT`. +`renew`는 범용 전이가 아니라 자기 program을 가진다. 갱신은 레코드를 `EXECUTING`에 두고, 전이는 revision을 읽기 전에 +「이미 목표 상태다」로 답한다(그 답은 첫 응답을 잃은 재시도를 위해 있다). 그래서 전이를 거쳐 보낸 갱신은 언제나 +`ALREADY_RENEWED_SAME_OPERATION`이었고 lease를 옮기지 못했다. 그 답은 전이를 적용한 handle에게만 준다 — 그 handle은 +한 revision 뒤의 레코드이고, `lastKind`(claim·renew·전이 program이 쓴다)가 그 전이를 이름으로 댄다. 같은 시도의 +다른 handle(넘겨받기 전의 것, 또는 재생된 claim이 돌려준 지금의 것)은 예전에 시작이 적용됐다는 답을 받아 action을 +두 번 돌렸고(round6 RR6-02-01), 넘겨받기 뒤에 온 완료나 실패를 자기 것이라고 들었다(소유자 결정 2026-11-06). 이제는 +PostgreSQL store처럼 `NOT_OWNER`나 `NOT_CLAIMED`/`NOT_IN_PROGRESS`다. kind가 없으면 갱신을 적용한 handle로 하는 +시작도 확인받았다 — 갱신은 레코드를 그 handle보다 한 revision 뒤의 `EXECUTING`에 둔다(round8 RR8-04-02). 이제는 +`NOT_OWNER`다. 실패를 적용한 handle이 다른 disposition을 요구하면 `OPERATION_CONFLICT`다(예전에는 `NOT_OWNER`로 +떨어졌다). 레코드는 retention을 두지 않으므로 다른 retention은 확인해 준다(소유자 결정 2026-11-07). renew program은 +owner, operation, revision, 상태를 검사한 뒤 Redis `TIME`으로 `leaseUntil`을 늘리고 revision을 올린다. 잃은 갱신 +응답은 그 갱신이 기록한 것 — 시작한 revision과 요청한 lease — 으로 알아본다: 같은 lease면 지금 handle과 함께 +`ALREADY_RENEWED_SAME_OPERATION`, 다른 lease면 `OPERATION_CONFLICT`다. -Every program compares the operation a call names with the one the record was claimed under, right -after the owner token: another operation is `OPERATION_CONFLICT` and changes nothing. The PostgreSQL -store and the in-memory fake used to apply it; they now answer the same (owner decision 2026-11-06, -`IdempotencyStoreContract`). The release program also checks the handle's revision, as the -transition does: owner token and operation alone let the handle from before the same attempt took -its claim over release the claim it holds now. A release deletes the record, so a release that finds -no record — its own retry, an expired record, one never claimed — is `ABSENT`; it used to be -confirmed as `ALREADY_RELEASED_SAME_OPERATION`, which the store cannot know. +모든 program은 owner token 바로 뒤에서 호출이 댄 operation과 레코드를 claim한 operation을 비교한다: 다른 operation이면 +`OPERATION_CONFLICT`이고 아무것도 바꾸지 않는다. PostgreSQL store와 메모리 fake는 예전에 그것을 적용했다. 이제 같은 +답을 한다(소유자 결정 2026-11-06, `IdempotencyStoreContract`). 놓아주기 program도 전이처럼 handle의 revision을 +검사한다: owner token과 operation만으로는 같은 시도가 claim을 넘겨받기 전의 handle이 지금 쥔 claim을 놓아줄 수 +있었다. 놓아주기는 레코드를 지우므로, 레코드를 찾지 못한 놓아주기 — 자기 재시도, 만료된 레코드, claim한 적 없는 +것 — 는 `ABSENT`다. 예전에는 store가 알 수 없는 `ALREADY_RELEASED_SAME_OPERATION`으로 확인해 줬다. -A lease that runs out is taken over only from a claim that never started or an attempt marked -retryable — by whoever claims next, the holder's own attempt included: the claim program checks for -a takeover before it replays a same-owner claim, so an attempt whose start was refused takes its -claim over when it claims again instead of being replayed the claim and refused until the record -expired (round6 RR6-02-01). A record still `EXECUTING` when its lease ran out has an unknown effect: the claim -program answers `RECOVERY_REQUIRED` and leaves the record as it is, because the holder may still be -running. The holder's late completion or failure goes through the transition program as it would -have inside the lease, and the next claim replays or retries it; only the lease is final — `RENEW` -refuses one that has run out with `LEASE_EXPIRED` (not `NOT_OWNER`: the holder still completes the -record, re-review 2026-11-04 RR5-01-02), and `INSPECT` reports somebody else's expired execution as -`RECOVERY_REQUIRED`. The transition program reads the lease for a start only: a claim whose lease -ran out is answered `LEASE_EXPIRED` and not started, so nothing runs and the next claim takes it -over (it used to start, and every other request was then told "recovery required" for work that -had just begun; README 15). The PostgreSQL store answers the same; the shared `IdempotencyStoreContract` -holds both to it on a real server (re-review 2026-11-04 RR-01-11 — this store used to take the -record over and run the work a second time; owner decision 2026-11-04 — both stores then abandoned -the record, and a holder that outlived its lease lost its result). +lease가 끝나면 시작하지 않은 claim이나 재시도할 수 있다고 표시한 시도에서만 넘겨받는다 — 다음에 claim하는 누구든, +쥔 쪽 자신의 시도도 포함한다: claim program은 같은 owner의 claim을 재생하기 전에 넘겨받기를 검사한다. 그래서 시작이 +거절된 시도는 다시 claim할 때 레코드가 만료될 때까지 claim을 재생받고 거절당하는 대신 자기 claim을 넘겨받는다 +(round6 RR6-02-01). lease가 끝났을 때 아직 `EXECUTING`인 레코드는 효과를 모른다: claim program은 +`RECOVERY_REQUIRED`로 답하고 레코드를 그대로 둔다. 쥔 쪽이 아직 돌고 있을 수 있기 때문이다. 쥔 쪽의 늦은 완료나 +실패는 lease 안이었을 때처럼 전이 program을 거치고, 다음 claim이 그것을 재생하거나 다시 시도한다. 끝난 것은 +lease뿐이다 — `RENEW`는 끝난 lease를 `LEASE_EXPIRED`로 거절하고(`NOT_OWNER`가 아니다: 쥔 쪽이 여전히 레코드를 +완료한다, re-review 2026-11-04 RR5-01-02), `INSPECT`는 남의 만료된 실행을 `RECOVERY_REQUIRED`로 알린다. 전이 +program은 시작할 때만 lease를 읽는다: lease가 끝난 claim은 `LEASE_EXPIRED`로 답하고 시작하지 않는다. 그래서 아무것도 +돌지 않고 다음 claim이 넘겨받는다(예전에는 시작했고, 그 뒤 다른 모든 요청이 막 시작한 일에 대해 「복구 필요」를 +들었다. README 15). PostgreSQL store도 같은 답을 한다. 공용 `IdempotencyStoreContract`가 둘을 실제 서버에서 거기에 +맞춘다(re-review 2026-11-04 RR-01-11 — 이 store는 예전에 레코드를 넘겨받아 일을 두 번 돌렸다. 소유자 결정 +2026-11-04 — 그 뒤 두 store 모두 레코드를 버렸고, lease보다 오래 산 쥔 쪽은 결과를 잃었다). -The record key lives for the processing lease plus the replay TTL (`afterLease`, kept on the record), -and a renewal stretches it to the new lease plus that margin. With the replay TTL alone, a replay -TTL shorter than the lease dropped the key of a running operation and the next claim ran it again, -and one equal to the lease left no record to answer `RECOVERY_REQUIRED` from (RR-03-11). +레코드 키는 처리 lease에 재생 TTL을 더한 만큼 산다(`afterLease`, 레코드에 둔다). 갱신은 그것을 새 lease에 그 여유를 +더한 만큼 늘린다. 재생 TTL만으로 두면, lease보다 짧은 재생 TTL은 돌고 있는 operation의 키를 버려 다음 claim이 그것을 +다시 돌렸고, lease와 같은 재생 TTL은 `RECOVERY_REQUIRED`로 답할 레코드를 남기지 않았다(RR-03-11). -Redis `TIME` determines lease deadlines. A failure after a command may have executed is returned -as an indeterminate outcome; the adapter does not convert an ambiguous write into a clean -unavailable result that would invite duplicate execution. +lease 기한은 Redis `TIME`이 정한다. 명령이 실행됐을 수 있는 뒤의 실패는 결과를 모름으로 돌려준다. 어댑터는 모호한 +쓰기를 중복 실행을 부르는 깨끗한 unavailable 결과로 바꾸지 않는다. -## Lease semantics +## lease 뜻 -The distributed lease adapter uses owner/operation-safe Lua programs for acquire, inspect, renew and -release. +분산 lease 어댑터는 acquire, inspect, renew, release에 owner·operation을 안전하게 지키는 Lua program을 쓴다. -Unknown mutation outcomes remain indeterminate. Local validity is shortened by the configured drift -budget; a successful renew is the only event that extends it. +결과를 모르는 변경은 모름으로 남는다. 로컬 유효 시간은 설정한 drift 예산만큼 줄인다. 그것을 늘리는 일은 성공한 +renew 하나뿐이다. -## Failure visibility +## 실패 보이기 -Semantic adapters intentionally translate Redis failures into typed application outcomes, but those -translations are not silent. +semantic 어댑터는 Redis 실패를 일부러 타입 있는 애플리케이션 결과로 바꾸지만, 그 번역은 소리 없지 않다. -`RedisSemanticFailureLogger` records only: +`RedisSemanticFailureLogger`는 다음만 남긴다: - capability, - semantic operation, -- exception class. +- 예외 클래스. -It never logs Redis keys, values, command arguments, exception messages or credentials. The first -occurrence of a capability/operation/failure-type combination is WARN; repeats are DEBUG to avoid -turning a Redis outage into a log-flood outage. +Redis 키, 값, 명령 인자, 예외 메시지, credential은 남기지 않는다. capability·operation·실패 타입 조합의 첫 발생은 +WARN이고, 되풀이는 DEBUG다. Redis 장애가 로그 홍수 장애로 번지지 않게 하려는 것이다. -## Optional typed SDK +## 골라 쓰는 typed SDK -`:adapter:outbound:redis-sdk` contains the broader typed command surface, command policy, raw/admin -and extension machinery. It is a separate library leaf that service code takes with -`implementation`; see `src/adapter/outbound/redis-sdk/README.md`. This leaf does not depend on it, -in production or in tests. +`:adapter:outbound:redis-sdk`에는 더 넓은 typed 명령 surface, 명령 정책, raw·admin, extension 장치가 있다. 서비스 +코드가 `implementation`으로 받는 따로 둔 라이브러리 leaf다. `src/adapter/outbound/redis-sdk/README.md`를 본다. 이 +leaf는 운영에서도 시험에서도 그것에 의존하지 않는다. -Its policy file and optional startup/library probes apply only when that SDK is deliberately added -to a composition. Do not infer SDK command-policy enforcement from the presence of a semantic cache -or rate-limit adapter. +그 정책 파일과 골라 쓰는 기동·라이브러리 probe는 그 SDK를 일부러 조립에 더했을 때만 적용된다. semantic cache나 +rate-limit 어댑터가 있다고 SDK 명령 정책이 강제된다고 짐작하지 않는다. -## Verification +## 검증 -Useful focused checks: +쓸 만한 이 모듈 검사: ```bash ./gradlew :adapter:outbound:cache-redis:check @@ -377,18 +326,16 @@ Useful focused checks: ./gradlew architectureCheck ``` -`redisContainerContractTest` runs the cache-region, lease and idempotency-store port contracts (the -ones the in-memory fakes pass; the idempotency contract's timed cases run here on the server's own -clock, and in `test` over the command fake's clock, which proves the fixture's copies of the -programs rather than the programs) and the live semantic-port tests against a Redis it starts itself, under the standalone -topology's ACL file. It is in `integrationCheck` (integration-main.yml's `integration-check` job), and -only there: listing it in `mainCheck` as well ran it twice on every push to main. The image is -`config/testing/container-images.properties` `redis`. +`redisContainerContractTest`는 cache-region, lease, 멱등성 store 포트 계약(메모리 fake가 통과하는 것. 멱등성 계약의 +시간 있는 경우는 여기서 서버 자신의 시계로 돌고, `test`에서는 명령 fake의 시계로 돈다 — 후자는 program 자체가 아니라 +fixture가 가진 program 사본을 증명한다)과 살아 있는 semantic 포트 시험을, standalone topology의 ACL 파일 아래에서 스스로 +띄운 Redis에 대고 돌린다. `integrationCheck`(integration-main.yml의 `integration-check` job)에 있고 거기에만 있다: +`mainCheck`에도 적었을 때는 main push마다 두 번 돌았다. image는 `config/testing/container-images.properties`의 +`redis`다. -Live Redis/topology qualification remains separate from fast unit tests. A release claim for a -specific Redis topology or ACL layout requires the corresponding live qualification lane; the -in-memory gateway is for deterministic contract tests, not evidence that an external Redis -deployment accepts the same network/TLS/ACL configuration. +살아 있는 Redis·topology 검증은 빠른 단위 시험과 따로다. 특정 Redis topology나 ACL 배치에 대한 릴리스 주장에는 그에 +맞는 살아 있는 검증 lane이 필요하다. 메모리 gateway는 결정적인 계약 시험을 위한 것이지, 외부 Redis 배포가 같은 +network·TLS·ACL 설정을 받아들인다는 증거가 아니다. ## 아직 내보내지 않는 지표 @@ -398,4 +345,3 @@ inflight.total, readiness.total, lifecycle.drain.total)는 redis-production-capa 것처럼 적고 있어서, 2026-11-03 재리뷰 수정에서 레지스트리에서 빼고 runbook을 지금 내보내는 `redis.lane.*`(redis-runtime, lane별 대기·거절·연결) 기준으로 고쳤다. capability 단위 지표가 필요해지면 operation 결과를 아는 semantic adapter(이 leaf)에서 내보내고, 그때 레지스트리에 다시 넣는다. - diff --git a/src/adapter/outbound/fileserver/CLAUDE.md b/src/adapter/outbound/fileserver/CLAUDE.md index 2f89dd43..fbece082 100644 --- a/src/adapter/outbound/fileserver/CLAUDE.md +++ b/src/adapter/outbound/fileserver/CLAUDE.md @@ -1,42 +1,39 @@ -# adapter:outbound:fileserver — module rules +# adapter:outbound:fileserver — 모듈 규칙 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-fileserver` -- Gradle path: `:adapter:outbound:fileserver` -- Focused test (derived from Gradle path): `./gradlew :adapter:outbound:fileserver:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-outbound-fileserver` +- Gradle 경로: `:adapter:outbound:fileserver` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:outbound:fileserver:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.outbound.fileserver.platform`. Driven (outbound) adapter for -the HTTP Fileserver platform: it implements the `application-fileserver` ports (content storage, -verification, identifiers, audit, metrics). Design rationale lives in [README.md](README.md). +패키지 루트: `dev.caskeleton.adapter.outbound.fileserver.platform`. HTTP 파일 서버 플랫폼의 driven +(outbound) 어댑터다: `application-fileserver` 포트(내용 저장, 검증, 식별자, 감사, metric)를 구현한다. +설계 근거는 [README.md](README.md)에 있다. -## Responsibility +## 책임 -- Local filesystem content storage, verification, identifiers, audit and metrics behind - `application-fileserver` ports. -- Activated only through `app.fileserver-platform.*` (default off), from - `platform.autoconfigure.FileserverCapabilityAutoConfiguration` registered in this leaf's - `AutoConfiguration.imports`. -- Detailed transport/security/operations contracts live under `docs/fileserver/`; certified - behavior is listed in `docs/fileserver/support-matrix.md`. +- `application-fileserver` 포트 뒤의 로컬 파일 시스템 내용 저장, 검증, 식별자, 감사, metric. +- `app.fileserver-platform.*`(기본 꺼짐)으로만 켠다. 이 leaf의 `AutoConfiguration.imports`에 등록한 + `platform.autoconfigure.FileserverCapabilityAutoConfiguration`에서 켜진다. +- 자세한 전송·보안·운영 계약은 `docs/fileserver/` 아래에 있다. 인증된 동작은 + `docs/fileserver/support-matrix.md`가 적는다. -## Allowed +## 허용 -- Project deps: SSOT is the `adapter-outbound-fileserver` entry in - `src/config/architecture/modules.json`; `src/build.gradle` enforces it. No `:domain-core`. -- External runtime: JDK filesystem, `spring-boot-autoconfigure`, `micrometer-core` and `slf4j-api`. +- 프로젝트 의존: 정본은 `src/config/architecture/modules.json`의 `adapter-outbound-fileserver` 항목이고 + `src/build.gradle`이 강제한다. `:domain-core`는 없다. +- 외부 런타임: JDK 파일 시스템, `spring-boot-autoconfigure`, `micrometer-core`, `slf4j-api`. -## Forbidden +## 금지 -- Inbound adapters, persistence, `app-bootstrap` (ArchUnit - `OUTBOUND_ADAPTERS_*` family rules). -- Leaking filesystem, stream, framework, or provider types across the application ports. -- Advertising a platform feature as implemented unless `docs/fileserver/support-matrix.md` lists it. -- Fully-qualified inline type references; more than one public top-level type per file. +- inbound 어댑터, 영속, `app-bootstrap`(ArchUnit `OUTBOUND_ADAPTERS_*` 규칙 묶음). +- 파일 시스템·stream·프레임워크·provider 타입을 application 포트 너머로 새게 하기. +- `docs/fileserver/support-matrix.md`가 적지 않은 플랫폼 기능을 구현됐다고 내세우기. +- 줄 안에 완전한 이름으로 쓴 타입 참조, 파일 하나에 공개 최상위 타입 둘 이상. -## Tests +## 테스트 ```bash cd src diff --git a/src/adapter/outbound/fileserver/README.md b/src/adapter/outbound/fileserver/README.md index dca317a9..39e29bfc 100644 --- a/src/adapter/outbound/fileserver/README.md +++ b/src/adapter/outbound/fileserver/README.md @@ -1,31 +1,29 @@ -# adapter:outbound:fileserver — design-decision reference +# adapter:outbound:fileserver — 설계 결정 참고 -Outbound (driven) adapter for the HTTP Fileserver platform. Package root: -`dev.caskeleton.adapter.outbound.fileserver.platform`. It implements the `application-fileserver` -ports: local filesystem content storage, upload verification, identifiers, audit and metrics. +HTTP 파일 서버 플랫폼의 outbound(driven) 어댑터다. 패키지 루트: +`dev.caskeleton.adapter.outbound.fileserver.platform`. `application-fileserver` 포트를 구현한다: 로컬 파일 +시스템 내용 저장, 업로드 검증, 식별자, 감사, metric. -The allowed/forbidden production dependency policy is owned by the -`adapter-outbound-fileserver` entry in `src/config/architecture/modules.json`; root Gradle -verification reads that registry. Module rules live in [CLAUDE.md](CLAUDE.md). +허용·금지 운영 의존 정책은 `src/config/architecture/modules.json`의 `adapter-outbound-fileserver` 항목이 +가진다. 루트 Gradle 검증이 그 registry를 읽는다. 모듈 규칙은 [CLAUDE.md](CLAUDE.md)에 있다. -Transport, security, configuration and operations contracts live in `docs/fileserver/`. For the -repository-level choice between this Fileserver platform and Object Storage, see -[`docs/storage-capability-boundary.md`](../../../../docs/storage-capability-boundary.md). +전송·보안·설정·운영 계약은 `docs/fileserver/`에 있다. 이 파일 서버 플랫폼과 Object Storage 중 무엇을 +고를지에 대한 저장소 단위 선택은 +[`docs/storage-capability-boundary.md`](../../../../docs/storage-capability-boundary.md)를 본다. -## Activation +## 켜기 -`app.fileserver-platform.enabled=true` (default `false`). While it is off, the auto-configuration -that binds the block is not processed, so nothing is created. See -`docs/fileserver/configuration.md` for the keys. +`app.fileserver-platform.enabled=true`(기본 `false`). 꺼져 있는 동안은 그 블록을 바인딩하는 자동 구성을 +처리하지 않으니 아무것도 만들지 않는다. 키는 `docs/fileserver/configuration.md`를 본다. -## Tests +## 테스트 -- `platform/**`: auto-configuration, local storage, security and verification tests. -- `testkit/`: content-store contract (this adapter's internal `BlockingContentStore` SPI), - crash-recovery matrix, large-file memory bound and the NFS/PVC certification helpers. -- Port contracts come from `application-fileserver` testFixtures (`testFixtures(project( - ':application-fileserver'))`): `LocalUploadStorageContractTest` extends `UploadStoragePortContract`, - the same contract the application's `FakeUploadStorageGateway` passes. +- `platform/**`: 자동 구성, 로컬 저장, 보안, 검증 시험. +- `testkit/`: 내용 저장 계약(이 어댑터 내부의 `BlockingContentStore` SPI), crash 복구 표, 큰 파일 메모리 + 한계, NFS/PVC 인증 도우미. +- 포트 계약은 `application-fileserver` testFixtures(`testFixtures(project( + ':application-fileserver'))`)에서 온다: `LocalUploadStorageContractTest`가 `UploadStoragePortContract`를 + 상속한다. 애플리케이션의 `FakeUploadStorageGateway`가 통과하는 것과 같은 계약이다. ```bash cd src diff --git a/src/adapter/outbound/httpclient/CLAUDE.md b/src/adapter/outbound/httpclient/CLAUDE.md index 2a9a3149..f1e67aab 100644 --- a/src/adapter/outbound/httpclient/CLAUDE.md +++ b/src/adapter/outbound/httpclient/CLAUDE.md @@ -1,93 +1,86 @@ -# adapter:outbound:httpclient — HTTP Client Platform +# adapter:outbound:httpclient — HTTP client 플랫폼 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-httpclient` -- Gradle path: `:adapter:outbound:httpclient` -- Focused test (derived from Gradle path): `./gradlew :adapter:outbound:httpclient:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-outbound-httpclient` +- Gradle 경로: `:adapter:outbound:httpclient` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:outbound:httpclient:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.outbound.httpclient`. +패키지 루트: `dev.caskeleton.adapter.outbound.httpclient`. -## Design authority +## 설계 정본 -The implementation follows -`docs/design/2026-08-08-httpclient-platform-design.md`. -The design assumes 19 separate Gradle modules; this repository's fail-closed registry -outranks that layout, so those modules are **packages** here. The mapping, and every other -deliberate substitution, is recorded in `docs/httpclient/repository-adaptation.md`. Read it before -moving a type between packages. +구현은 `docs/design/2026-08-08-httpclient-platform-design.md`를 따른다. 설계는 Gradle 모듈 19개를 따로 두는 +것을 전제한다. 이 저장소의 실패하면 닫히는 registry가 그 배치보다 앞서므로, 그 모듈들은 여기서 **패키지**다. +그 대응과 그 밖에 일부러 바꾼 것은 모두 `docs/httpclient/repository-adaptation.md`에 적혀 있다. 타입을 다른 +패키지로 옮기기 전에 그것을 읽는다. -## Responsibility +## 책임 -- Own the public call surfaces: H1 typed service clients (default), H2 generic exchange, H3 dynamic - target. H4 native engine access stays internal to `apache`, `jdk`, and `http3`. -- Blocking only: calls run on the caller's (virtual) thread through `RestClient`. The reactive stack - (`WebClient`, Reactor Netty) was removed by the 2026-09-25 owner decision; do not add it back. -- Own Named Client Profiles, runtime generations, transport SPI, deadlines, evidence-based retry, - resilience, authentication, TLS, SSRF defence, streaming lifecycle, and observability. -- Adapt external HTTP calls behind application/domain ports. -- Reuse `adapter:outbound:support` for shared outbound concerns. +- 공개 호출 surface를 가진다: H1 typed service client(기본), H2 generic exchange, H3 dynamic target. H4 native + engine 접근은 `apache`, `jdk`, `http3` 안에 머문다. +- blocking만: 호출은 `RestClient`를 거쳐 호출자의 (virtual) 스레드에서 돈다. reactive stack(`WebClient`, + Reactor Netty)은 2026-09-25 소유자 결정으로 지웠다. 다시 들이지 않는다. +- Named Client Profile, runtime generation, transport SPI, deadline, 증거 기반 재시도, resilience, 인증, TLS, + SSRF 방어, streaming lifecycle, 관측을 가진다. +- 외부 HTTP 호출을 application·domain 포트 뒤에 맞춘다. +- 공용 outbound 관심사는 `adapter:outbound:support`를 다시 쓴다. -## Package boundaries +## 패키지 경계 -`HttpClientModuleBoundaryTest` and `PublicApiArchitectureTest` enforce the design's module table: +`HttpClientModuleBoundaryTest`와 `PublicApiArchitectureTest`가 설계의 모듈 표를 강제한다: -- `api` depends on nothing else in the platform, and on no Spring, Apache, Jetty, or Resilience4j - type. -- `profile` depends publicly only on `api`. -- transport packages never reach back into the gateways. -- `resilience` never depends on a transport — retry eligibility is transport-neutral. -- no production package depends on the reusable testkit. It lives in Gradle - `testFixtures` (`src/testFixtures/java`) and is consumed explicitly by the ordinary tests, - integration/performance lanes, and JMH. Its dependencies stay on test-fixture/test configurations, - so production still cannot reach it. `PlatformClasses` is the single definition of "production - classes" the boundary rules import. -- Stable code never references `http3`. -- no class uses `org.springframework.web.service.registry` or `RestTemplate`. +- `api`는 플랫폼 안의 다른 어떤 것에도, Spring·Apache·Jetty·Resilience4j 타입에도 의존하지 않는다. +- `profile`은 공개적으로 `api`에만 의존한다. +- transport 패키지는 gateway로 거슬러 닿지 않는다. +- `resilience`는 transport에 의존하지 않는다 — 재시도 자격은 transport와 무관하다. +- 운영 패키지는 다시 쓰는 testkit에 의존하지 않는다. testkit은 Gradle `testFixtures` + (`src/testFixtures/java`)에 있고, 보통 시험, integration·performance lane, JMH가 명시적으로 쓴다. 그 의존은 + test-fixture·test 설정에 머물러서 운영 코드는 여전히 닿지 못한다. 경계 규칙이 import하는 「운영 클래스」의 + 유일한 정의는 `PlatformClasses`다. +- Stable 코드는 `http3`를 참조하지 않는다. +- 어떤 클래스도 `org.springframework.web.service.registry`나 `RestTemplate`를 쓰지 않는다. -## Boundaries +## 경계 -- Allowed dependency edges come only from this module's `src/config/architecture/modules.json` entry. -- No inbound controller/DTO, persistence, bootstrap, or sample dependency. -- Retry and circuit-breaker code is technical resilience; business compensation and use-case - sequencing stay in application/domain layers. -- Application/domain code must not import this module's gateways, operation descriptors, URI types, - Spring HTTP types, engine clients, retry types, or wire DTOs. The repository-level Gradle - dependency gate in `config/architecture/modules.json` enforces that direction; this leaf's - ArchUnit rules only govern boundaries inside the leaf. -- Normal calls use a registered profile and a profile-relative template. Absolute URLs are H3 only. -- Composition is capability-owned under `dev.caskeleton.adapter.outbound.httpclient.autoconfigure`: - profile binding, startup validation, transport registration, service gateways, dynamic targets, - and the actuator endpoint live in this leaf and are published through Boot auto-configuration - metadata. `HttpClientPlatformAutoConfiguration` is gated on `app.httpclient.enabled=true`. While - the switch is off the capability has no beans at all — not an empty registry, nothing. -- `app-bootstrap` must not import HTTP-client implementation or auto-configuration classes from - production code. Build inclusion is decided separately from this runtime activation switch. +- 허용 의존 edge는 이 모듈의 `src/config/architecture/modules.json` 항목에서만 온다. +- inbound controller·DTO, 영속, bootstrap, 샘플 의존이 없다. +- 재시도와 circuit breaker 코드는 기술적 resilience다. 업무 보상과 유스케이스 순서는 application·domain 계층에 + 남는다. +- application·domain 코드는 이 모듈의 gateway, operation descriptor, URI 타입, Spring HTTP 타입, engine client, + 재시도 타입, wire DTO를 import하면 안 된다. 그 방향은 `config/architecture/modules.json`의 저장소 단위 Gradle + 의존 게이트가 강제한다. 이 leaf의 ArchUnit 규칙은 leaf 안의 경계만 다룬다. +- 보통 호출은 등록된 profile과 profile 기준 template을 쓴다. 절대 URL은 H3만 쓴다. +- 조립은 `dev.caskeleton.adapter.outbound.httpclient.autoconfigure` 아래에서 capability가 가진다: profile 바인딩, + 기동 검증, transport 등록, service gateway, dynamic target, actuator endpoint가 이 leaf에 있고 Boot 자동 구성 + metadata로 나간다. `HttpClientPlatformAutoConfiguration`은 `app.httpclient.enabled=true`일 때만 켜진다. + 스위치가 꺼져 있으면 capability에는 bean이 하나도 없다 — 빈 registry가 아니라 아무것도 없다. +- `app-bootstrap`은 운영 코드에서 HTTP client 구현이나 자동 구성 클래스를 import하면 안 된다. 빌드에 넣을지는 + 이 런타임 켜기 스위치와 따로 정한다. -## Tests +## 테스트 -Default lane: `./gradlew :adapter:outbound:httpclient:test`. Additional lanes, all fail-closed: +기본 lane: `./gradlew :adapter:outbound:httpclient:test`. 추가 lane은 모두 실패하면 닫힌다: -| Lane | Purpose | +| lane | 용도 | |---|---| -| `httpClientStableContractTest` | one semantic contract across Apache and JDK | -| `httpClientSecurityTest` | SSRF matrix, credential stripping, tag cardinality | -| `httpClientFailureInjectionTest` | Toxiproxy faults; **requires Docker and fails without it** | -| `httpClientPerformanceTest` | pool, streaming, retry, rotation resource bounds | -| `spring62ApiSurfaceScan` | Spring 6.2 API-surface confinement | -| `spring70CompatibilityTest` | contract suite on the repository baseline | -| `jmh` | per-call overhead benchmarks | +| `httpClientStableContractTest` | Apache와 JDK에 걸친 semantic 계약 하나 | +| `httpClientSecurityTest` | SSRF 표, credential 걷어내기, tag cardinality | +| `httpClientFailureInjectionTest` | Toxiproxy 장애. **Docker가 필요하고 없으면 실패한다** | +| `httpClientPerformanceTest` | pool, streaming, 재시도, 교체의 자원 한계 | +| `spring62ApiSurfaceScan` | Spring 6.2 API surface 가두기 | +| `spring70CompatibilityTest` | 저장소 기준 버전 위의 계약 suite | +| `jmh` | 호출당 부담 benchmark | -A selected lane never skips silently: the fault lane throws without Docker, the contract lane throws -on an empty or unknown transport selection, and the performance lane asserts every bound in every -run — the strict-lane convention fails it when the build sets `performance.assertions.enabled` to -anything but `true` or when one of its tests is skipped. +고른 lane은 소리 없이 건너뛰지 않는다: 장애 lane은 Docker가 없으면 던지고, 계약 lane은 transport 선택이 +비었거나 모르는 것이면 던지고, performance lane은 실행마다 모든 한계를 단언한다 — 빌드가 +`performance.assertions.enabled`에 `true` 아닌 값을 넣거나 그 시험 하나가 건너뛰어지면 strict lane 규약이 +실패시킨다. -The transport port (`BlockingTransportProvider`) has one abstract contract in the test fixtures, -`testkit/BlockingTransportProviderContract`. The engines pass it over a real socket -(`StableTransportProviderContractTest`, the contract lane, once per selected transport) and the -scripted fake the gateway tests stand on passes it in the default lane -(`ScriptedTransportContractTest`). A new transport, or a change to `ScriptedTransport`, inherits the -same class rather than a copy (AGENTS.md rule 6). +transport 포트(`BlockingTransportProvider`)에는 test fixtures에 추상 계약 하나 +`testkit/BlockingTransportProviderContract`가 있다. engine은 실제 socket 위에서 그것을 통과하고 +(`StableTransportProviderContractTest`, 계약 lane, 고른 transport마다 한 번), gateway 시험이 딛고 서는 각본 +fake는 기본 lane에서 그것을 통과한다(`ScriptedTransportContractTest`). 새 transport나 `ScriptedTransport`의 +변경은 사본이 아니라 같은 클래스를 상속한다(AGENTS.md 규칙 6). diff --git a/src/adapter/outbound/httpclient/README.md b/src/adapter/outbound/httpclient/README.md index a0d50646..90a11685 100644 --- a/src/adapter/outbound/httpclient/README.md +++ b/src/adapter/outbound/httpclient/README.md @@ -1,21 +1,20 @@ # adapter:outbound:httpclient -The outbound HTTP Client Platform: a single contract for how this service talks to anything over -HTTP. It is not a wrapper around `RestClient` — it owns the target, the connection resources, the -time budget, the evidence of what actually executed, retry safety, authentication, TLS, SSRF -defence, and observability. +outbound HTTP client 플랫폼이다: 이 서비스가 HTTP로 무엇과든 말하는 방법을 정한 계약 하나. `RestClient`를 감싼 +것이 아니다 — 대상, 연결 자원, 시간 예산, 실제로 무엇이 실행됐는지의 증거, 재시도 안전성, 인증, TLS, SSRF +방어, 관측을 가진다. -Design: `docs/design/2026-08-08-httpclient-platform-design.md` -Adaptation to this repository: `docs/httpclient/repository-adaptation.md` +설계: `docs/design/2026-08-08-httpclient-platform-design.md` +이 저장소에 맞춘 내용: `docs/httpclient/repository-adaptation.md` -## Choosing a surface +## surface 고르기 -| Surface | Use it when | What it fixes for you | +| surface | 이럴 때 쓴다 | 대신 정해 주는 것 | |---|---|---| -| **H1 typed client** (`HttpServiceRegistry`) | almost always | URL, timeout, auth, retry, limits, metrics | -| **H2 generic exchange** (`GenericHttpGateway`, `BlockingStreamingGateway`) | method, path, or body must vary at runtime | scheme, host, port, TLS, credentials, hard limits | -| **H3 dynamic target** (`DynamicTargetGateway`) | the URL comes from a user | full SSRF validation; inherits no credential | -| **H4 native engine** | never, from application code | — | +| **H1 typed client**(`HttpServiceRegistry`) | 거의 언제나 | URL, timeout, 인증, 재시도, 한계, metric | +| **H2 generic exchange**(`GenericHttpGateway`, `BlockingStreamingGateway`) | method, path, body가 런타임에 바뀌어야 할 때 | scheme, host, port, TLS, credential, 단단한 한계 | +| **H3 dynamic target**(`DynamicTargetGateway`) | URL이 사용자에게서 올 때 | SSRF 검증 전체. credential을 물려받지 않는다 | +| **H4 native engine** | 애플리케이션 코드에서는 쓰지 않는다 | — | ```java @HttpClientProfile("users") @@ -28,48 +27,42 @@ public interface UsersClient { } ``` -The interface fails startup unless it names a profile, gives every method a stable operation name, -declares idempotency explicitly, and supplies a key parameter when the operation requires one. +인터페이스가 profile 이름을 대고, 모든 메서드에 안정된 operation 이름을 주고, 멱등성을 명시하고, operation이 +키를 요구하면 키 매개변수를 주지 않으면 기동이 실패한다. -Every call is blocking and runs on the caller's thread — a virtual thread in this template. There is -no reactive (`WebClient`/Reactor Netty) surface; it was removed on 2026-09-25 (decision 9). +모든 호출은 blocking이고 호출자의 스레드에서 돈다 — 이 템플릿에서는 virtual thread다. reactive +(`WebClient`/Reactor Netty) surface는 없다. 2026-09-25에 지웠다(결정 9). -## What the platform decides for you +## 플랫폼이 대신 정하는 것 -- **Time.** One effective deadline covers pool acquire, DNS, connect, TLS, write, read, and every - retry backoff. It is checked before each attempt and also ends an attempt still in flight: Apache - cancels the request at the deadline, the JDK transport bounds its exchange timeout by the time - left, the experimental Jetty HTTP/3 transport aborts the request, and the caller gets - `HttpDeadlineExceededException`. A streaming download's setup (up to the response headers) runs - inside the same deadline; after hand-over each body gap is bounded by `read-idle` and nothing else, - on both transports — on the JDK transport, which has no socket read timeout, a per-stream watchdog - bounds each read's wait. The watchdogs share one daemon thread (`httpclient-jdk-read-idle`): the - first stream that needs it starts it, it ends 60 s after the last wake it had queued, and the next - stream starts it again. It inherits no thread-locals from the request thread that starts it and - uses this module's class loader as its context loader, so it pins neither a request's state nor a - redeployed application's loader. A body that fails - after hand-over throws `HttpBodyReadException`, an `IOException` as `InputStream.read` promises, - whose `failure()` is the same stable exception a buffered call throws - (`HttpResponseTimeoutException` for a stalled body, `HttpResponseTruncatedException` for a cut - one). -- **Evidence.** Each attempt reports `NOT_SENT`, `SENT_NO_RESPONSE`, `RESPONSE_RECEIVED`, or - `PARTIAL_RESPONSE`. `NOT_SENT` is only claimed when a stage failure proves it. -- **Retry.** Never from the HTTP method alone. Idempotency, body replayability, evidence, deadline, - and a per-upstream token budget all have to agree. A sent, non-idempotent request with no response - raises `HttpAmbiguousExecutionException` instead of being retried or reported as a plain failure. -- **Order.** Every physical attempt passes Circuit Breaker → Rate Limiter → Bulkhead, and holds no - permit while a backoff waits. -- **Circuit.** The breaker counts transport failures and 5xx, 408, and 429 against the upstream, - whether the call throws them or returns them as a result (`RETURN_RESULT`). Any other 4xx (404, - 409, 422 …) is a healthy answer, even when it reaches the caller as `HttpRemoteErrorException`. - Window, threshold and open-state wait are per profile under `clients[N].circuit-breaker.*` - (defaults are Resilience4j's; see `docs/httpclient/configuration-reference.md`). An attempt that - the caller's own deadline (`HttpOperation.deadline()`) ended is not counted at all: the caller ran - out of time, the upstream did not fail. An attempt the profile's `total-call` ended still counts. -- **Resources.** Connections and buffers are reclaimed after success, error, decode failure, size - rejection, and cancellation alike. -- **Secrets.** No URL, query value, path variable, token, cookie, or idempotency key reaches a log, - a metric label, or an exception message. +- **시간.** 유효 deadline 하나가 pool 획득, DNS, connect, TLS, 쓰기, 읽기, 모든 재시도 backoff를 덮는다. + 시도마다 그 전에 검사하고, 아직 진행 중인 시도도 끝낸다: Apache는 deadline에 요청을 취소하고, JDK + transport는 남은 시간으로 exchange timeout을 묶고, 실험용 Jetty HTTP/3 transport는 요청을 중단하며, 호출자는 + `HttpDeadlineExceededException`을 받는다. streaming 다운로드의 준비(응답 header까지)는 같은 deadline 안에서 + 돈다. 넘겨준 뒤에는 body 사이의 빈 시간을 두 transport 모두 `read-idle`만으로 묶는다 — socket 읽기 timeout이 + 없는 JDK transport에서는 stream마다 watchdog이 각 읽기의 기다림을 묶는다. watchdog들은 daemon 스레드 하나 + (`httpclient-jdk-read-idle`)를 같이 쓴다: 그것이 필요한 첫 stream이 시작하고, 마지막으로 줄 세운 깨우기 60 s + 뒤에 끝나며, 다음 stream이 다시 시작한다. 그것을 시작한 요청 스레드에서 thread-local을 물려받지 않고 이 + 모듈의 class loader를 context loader로 쓰므로, 요청의 상태도 다시 배포된 애플리케이션의 loader도 붙잡지 + 않는다. 넘겨준 뒤 실패한 body는 `InputStream.read`가 약속한 대로 `IOException`인 `HttpBodyReadException`을 + 던진다. 그 `failure()`는 buffer로 받는 호출이 던지는 것과 같은 안정된 예외다(멈춘 body는 + `HttpResponseTimeoutException`, 잘린 body는 `HttpResponseTruncatedException`). +- **증거.** 시도마다 `NOT_SENT`, `SENT_NO_RESPONSE`, `RESPONSE_RECEIVED`, `PARTIAL_RESPONSE` 중 하나를 알린다. + `NOT_SENT`는 단계 실패가 그것을 증명할 때만 주장한다. +- **재시도.** HTTP method만 보고 하지 않는다. 멱등성, body 재생 가능성, 증거, deadline, upstream별 token 예산이 + 모두 맞아야 한다. 보냈고 멱등이 아니고 응답이 없는 요청은 재시도하거나 평범한 실패로 알리지 않고 + `HttpAmbiguousExecutionException`을 올린다. +- **순서.** 물리 시도마다 Circuit Breaker → Rate Limiter → Bulkhead를 지나고, backoff를 기다리는 동안 허가를 + 쥐고 있지 않는다. +- **circuit.** breaker는 transport 실패와 5xx, 408, 429를 upstream의 실패로 센다. 호출이 그것을 던지든 + 결과로 돌려주든(`RETURN_RESULT`) 같다. 그 밖의 4xx(404, 409, 422 …)는 호출자에게 + `HttpRemoteErrorException`으로 닿아도 건강한 답이다. window, 문턱, 열린 상태의 대기는 profile마다 + `clients[N].circuit-breaker.*` 아래에 있다(기본값은 Resilience4j의 것이다. + `docs/httpclient/configuration-reference.md`를 본다). 호출자 자신의 deadline(`HttpOperation.deadline()`)이 + 끝낸 시도는 아예 세지 않는다: 호출자의 시간이 다 된 것이지 upstream이 실패한 것이 아니다. profile의 + `total-call`이 끝낸 시도는 계속 센다. +- **자원.** 연결과 buffer는 성공, 오류, decode 실패, 크기 거절, 취소 뒤에 똑같이 거둬들인다. +- **비밀 값.** URL, query 값, path 변수, token, cookie, 멱등 키는 로그, metric label, 예외 메시지에 닿지 않는다. ## 제공하는 것 · 추가할 한 줄 · env 키 @@ -93,13 +86,12 @@ no reactive (`WebClient`/Reactor Netty) surface; it was removed on 2026-09-25 (d (필드 전체는 `docs/httpclient/env-fields.yaml`). client가 없으면 `HTTPCLIENT_ACTIVE_WITHOUT_CLIENTS`로 기동이 실패한다. -## Configuration +## 설정 -Profiles live under `app.httpclient.clients[N]`; Dynamic Target policies under -`app.httpclient.dynamic-targets[N]`. Every startup guard, property, and violation code is listed in -`docs/httpclient/configuration-reference.md`. +profile은 `app.httpclient.clients[N]` 아래에, Dynamic Target 정책은 `app.httpclient.dynamic-targets[N]` 아래에 +있다. 모든 기동 guard, 속성, 위반 코드는 `docs/httpclient/configuration-reference.md`에 있다. -## Verification +## 검증 ```bash cd src @@ -110,13 +102,11 @@ cd src ./gradlew :adapter:outbound:httpclient:httpClientFailureInjectionTest --console=plain # needs Docker ``` -No lane skips silently. The fault lane fails without Docker, the contract lane fails on an empty or -unknown transport selection, and the performance lane asserts every bound in every run (it fails -when the build sets `performance.assertions.enabled` to anything but `true`, or when a test is -skipped). +어떤 lane도 소리 없이 건너뛰지 않는다. 장애 lane은 Docker가 없으면 실패하고, 계약 lane은 transport 선택이 +비었거나 모르는 것이면 실패하고, performance lane은 실행마다 모든 한계를 단언한다(빌드가 +`performance.assertions.enabled`에 `true` 아닌 값을 넣거나 시험이 건너뛰어지면 실패한다). -## Further reading +## 더 읽을 것 -`docs/httpclient/` holds the support matrix, configuration reference, retry and ambiguity guide, -security guide, streaming guide, operations runbook, performance baseline, and -release checklist. +`docs/httpclient/`에 support matrix, 설정 참고, 재시도와 모호함 안내, 보안 안내, streaming 안내, 운영 runbook, +성능 기준선, 릴리스 체크리스트가 있다. diff --git a/src/adapter/outbound/identifier/CLAUDE.md b/src/adapter/outbound/identifier/CLAUDE.md index bd2ac640..f3addd83 100644 --- a/src/adapter/outbound/identifier/CLAUDE.md +++ b/src/adapter/outbound/identifier/CLAUDE.md @@ -1,55 +1,51 @@ -# adapter:outbound:identifier — non-IO infrastructure-capability adapter +# adapter:outbound:identifier — IO 없는 기반 capability 어댑터 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-identifier` -- Gradle path: `:adapter:outbound:identifier` -- Focused test (derived from Gradle path): `./gradlew :adapter:outbound:identifier:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.8. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-outbound-identifier` +- Gradle 경로: `:adapter:outbound:identifier` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:outbound:identifier:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.outbound.identifier`. +패키지 루트: `dev.caskeleton.adapter.outbound.identifier`. -Design decisions previously kept as code comments (algorithm SSOT, salt origin, -build choices) live in [README.md](README.md). +예전에 코드 주석에 두던 설계 결정(알고리즘 정본, salt 출처, 빌드 선택)은 [README.md](README.md)에 있다. -## Responsibility +## 책임 -- `HmacUserPrincipalPseudonymizer` — the `UserPrincipalPseudonymizerPort` implementation - (HMAC-SHA-256 of the UTF-8 principal, lowercase hex). -- `UuidV7DurableOperationIdFactory` — `DurableOperationIdFactory` implementation (UUIDv7 via - `uuid-creator`). The operation id is also the submission event's id, and the messaging platform's - message id accepts only UUIDv7. Wired by `composition:durable-operation`. -- The leaf name says "identifier"; general-purpose clock and random sources are not here. - The name is kept because Gradle paths and consumers use it (README). -- Wiring is `composition/service-runtime` (`PseudonymizationConfig`), not this leaf. +- `HmacUserPrincipalPseudonymizer` — `UserPrincipalPseudonymizerPort` 구현(UTF-8 principal의 HMAC-SHA-256, + 소문자 hex). +- `UuidV7DurableOperationIdFactory` — `DurableOperationIdFactory` 구현(`uuid-creator`로 만든 UUIDv7). + operation id는 제출 이벤트의 id이기도 하고, 메시징 플랫폼의 message id는 UUIDv7만 받는다. + `composition:durable-operation`이 배선한다. +- leaf 이름은 「identifier」다. 범용 시계·난수 출처는 여기 없다. Gradle 경로와 쓰는 쪽이 이 이름을 쓰니 + 이름을 그대로 둔다(README). +- 배선은 이 leaf가 아니라 `composition/service-runtime`(`PseudonymizationConfig`)이다. -## Allowed +## 허용 -Declared in [build.gradle](build.gradle); the registry entry is the SSOT. +[build.gradle](build.gradle)에 선언한다. registry 항목이 정본이다. -- `:application-core` — the ports both classes implement. -- `:shared-contract`, for `HmacSha256` only. The pseudonym is the hex HMAC - of the principal; `HmacUserPrincipalPseudonymizerVectorTest` pins it to a vector computed outside - the JVM, because logs written before and after a release are joined on it. -- `:domain-core` — a feature's server-assigned id adapter implements its domain `*IdFactory` port - here (registry edge `adapter:outbound:identifier -> domain-core`; `docs/manual/02-new-feature.md`). -- `com.github.f4b6a3:uuid-creator` (`libs.uuid.creator`) — UUIDv7 for - `UuidV7DurableOperationIdFactory`. +- `:application-core` — 두 클래스가 구현하는 포트. +- `:shared-contract`, `HmacSha256`만. 가명은 principal의 hex HMAC이다. + `HmacUserPrincipalPseudonymizerVectorTest`가 그것을 JVM 밖에서 계산한 벡터에 고정한다. 릴리스 전후에 쓴 + 로그를 이 값으로 잇기 때문이다. +- `:domain-core` — 기능의 서버 지정 id 어댑터가 여기서 그 도메인 `*IdFactory` 포트를 구현한다(registry + edge `adapter:outbound:identifier -> domain-core`, `docs/manual/02-new-feature.md`). +- `com.github.f4b6a3:uuid-creator`(`libs.uuid.creator`) — `UuidV7DurableOperationIdFactory`의 UUIDv7. -## Forbidden +## 금지 -- Persistence or web technology (JPA/Hibernate/Spring Data/Spring Web) — ArchUnit - `identifier_adapter_does_not_depend_on_other_adapters_or_bootstrap`; - `.claude/hooks/ca_import_gate.py` G4 가 쓰기 시점에 차단. -- inbound adapters, persistence adapters, other outbound leaves, `app-bootstrap`. -- External IO (HTTP / messaging / cache / DB) — that belongs in `adapter-outbound`. +- 영속·web 기술(JPA/Hibernate/Spring Data/Spring Web) — ArchUnit + `identifier_adapter_does_not_depend_on_other_adapters_or_bootstrap`와 registry 방향 게이트가 막는다. +- inbound 어댑터, 영속 어댑터, 다른 outbound leaf, `app-bootstrap`. +- 외부 IO(HTTP / 메시징 / cache / DB) — 그것은 IO를 하는 outbound 어댑터 leaf에 둔다. -## Test +## 테스트 -Pure unit tests, no Spring context: `HmacUserPrincipalPseudonymizerTest` (including the RFC 4231 -known-answer vector), `HmacUserPrincipalPseudonymizerVectorTest` and -`UuidV7DurableOperationIdFactoryTest`. +Spring context 없는 순수 단위 시험: `HmacUserPrincipalPseudonymizerTest`(RFC 4231 known-answer 벡터 포함), +`HmacUserPrincipalPseudonymizerVectorTest`, `UuidV7DurableOperationIdFactoryTest`. ```bash cd src diff --git a/src/adapter/outbound/messaging-kafka/CLAUDE.md b/src/adapter/outbound/messaging-kafka/CLAUDE.md index 060cd2b3..7f2fa07a 100644 --- a/src/adapter/outbound/messaging-kafka/CLAUDE.md +++ b/src/adapter/outbound/messaging-kafka/CLAUDE.md @@ -1,14 +1,13 @@ # adapter:outbound:messaging-kafka -- Module ID `adapter-outbound-messaging-kafka`, Gradle path `:adapter:outbound:messaging-kafka`. - Registry SSOT: `src/config/architecture/modules.json`. -- Responsibility: the Kafka publishing capability as one `runtimeOnly` line. It has no production - code: it bundles `adapter:outbound:messaging` (the application's bridge) with - `messaging:messaging-spring-boot-starter-kafka` (the vendored platform and its Kafka transport) and - ships the module defaults in `config/module-defaults/messaging.yml`. -- Boundaries: add no code here. A publish rule belongs to the bridge (`adapter:outbound:messaging`), - a Kafka rule to the vendored product (`src/platforms/messaging/CLAUDE.md`); a class here would be a third - place. Allowed edges come only from the registry entry. -- Tests: activation tests (`./gradlew :adapter:outbound:messaging-kafka:test`) and the real-Kafka - lane `messagingKafkaRelayIntegrationTest` (relay → bridge → broker record bytes; `:integrationCheck`). -- Design: `README.md`. +- 모듈 ID `adapter-outbound-messaging-kafka`, Gradle 경로 `:adapter:outbound:messaging-kafka`. + registry 정본: `src/config/architecture/modules.json`. +- 책임: Kafka 발행 capability를 `runtimeOnly` 한 줄로 만든다. 운영 코드가 없다: + `adapter:outbound:messaging`(애플리케이션의 bridge)과 `messaging:messaging-spring-boot-starter-kafka`(들여온 + 플랫폼과 그 Kafka 전송)를 묶고, 모듈 기본값 `config/module-defaults/messaging.yml`을 싣는다. +- 경계: 여기 코드를 더하지 않는다. 발행 규칙은 bridge(`adapter:outbound:messaging`)에, Kafka 규칙은 들여온 + 제품(`src/platforms/messaging/CLAUDE.md`)에 속한다. 여기 클래스를 두면 세 번째 자리가 생긴다. 허용 edge는 + registry 항목에서만 온다. +- 시험: 켜기 시험(`./gradlew :adapter:outbound:messaging-kafka:test`)과 실제 Kafka lane + `messagingKafkaRelayIntegrationTest`(relay → bridge → broker record 바이트, `:integrationCheck`). +- 설계: `README.md`. diff --git a/src/adapter/outbound/messaging/CLAUDE.md b/src/adapter/outbound/messaging/CLAUDE.md index d7d4f08d..bfd3277d 100644 --- a/src/adapter/outbound/messaging/CLAUDE.md +++ b/src/adapter/outbound/messaging/CLAUDE.md @@ -1,50 +1,46 @@ -# adapter:outbound:messaging — messaging adapter +# adapter:outbound:messaging — 메시징 어댑터 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-messaging` -- Gradle path: `:adapter:outbound:messaging` -- Focused test (derived from Gradle path): `./gradlew :adapter:outbound:messaging:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.8. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-outbound-messaging` +- Gradle 경로: `:adapter:outbound:messaging` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:outbound:messaging:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.outbound.messaging`. +패키지 루트: `dev.caskeleton.adapter.outbound.messaging`. -## Responsibility +## 책임 -- Implement outbound message publication and broker integration behind application/domain ports. -- Own broker settings, disabled/fail-safe technical modes, and outbox publication adaptation. -- Own structured rendering of `OutboxRelayFailureReport` through the single unconditional - `Slf4jOutboxRelayFailureReportAdapter` bean. -- Reuse `adapter:outbound:support` for shared technical concerns. +- application·domain 포트 뒤에서 outbound 메시지 발행과 broker 연동을 구현한다. +- broker 설정, 꺼짐·안전 실패 기술 모드, outbox 발행 연결을 가진다. +- 조건 없이 하나만 있는 `Slf4jOutboxRelayFailureReportAdapter` bean으로 `OutboxRelayFailureReport`를 구조화해 + 남긴다. +- 공용 기술 관심사는 `adapter:outbound:support`를 다시 쓴다. -## Boundaries +## 경계 -- Allowed dependency edges come only from the module's - `src/config/architecture/modules.json` entry. -- No inbound DTO/controller, persistence repository/entity, bootstrap, or sample dependency. -- The canonical platform bridge may depend only on `messaging-core-api` (which also holds the - `schema` package); do not import `messaging-runtime-core`, transport SPI implementations, or - broker SDK types under `platformbridge/`. -- There is one publication path: `OutboxMessagePublishAdapter` → `IntegrationEventPublishPort` → - the platform bridge. The legacy `KafkaSender` / `MessageBroker` R0 seam and the fail-open - `MessagePublisher` were removed with the canonical outbox (2026-09-28); do not reintroduce a - second path. -- Canonical producer identity is explicit `app.messaging.producer-id`; never derive it from - `spring.application.name`, host, pod, or process identity. With the module on and no bridge, - startup is refused — the relay would have nothing to publish through. -- The template's `IntegrationEventEncoderPort` (`JsonIntegrationEventEncoder`) lives in - `adapter:outbound:support`, not here: a use case encodes before it appends, in compositions that - may not carry this module. The R1 contract/binding compilers and JSON Schema envelope encoder were - removed on 2026-09-25 (see `docs/capability-status.md`). -- No JSON Schema engine (NetworkNT) on the main classpath. The evidence manifest schema check and the - capability card check (`release/`) are this leaf's tests (`evidence/`); snakeyaml is - test-only (owner decision 2026-09-25). -- Do not hide use-case sequencing or business routing policy in broker adapters. -- `OutboxMessagePublishAdapter` is delegate-only and emits no dependency log. The confirmed - FAILED/DEAD transition owns the one canonical ERROR. +- 허용 의존 edge는 이 모듈의 `src/config/architecture/modules.json` 항목에서만 온다. +- inbound DTO·controller, 영속 repository·엔티티, bootstrap, 샘플 의존이 없다. +- 정해진 플랫폼 bridge는 `messaging-core-api`(`schema` 패키지도 담는다)에만 의존할 수 있다. + `platformbridge/` 아래에서 `messaging-runtime-core`, 전송 SPI 구현, broker SDK 타입을 import하지 않는다. +- 발행 경로는 하나다: `OutboxMessagePublishAdapter` → `IntegrationEventPublishPort` → 플랫폼 bridge. 옛 + `KafkaSender` / `MessageBroker` R0 이음매와 실패해도 열리는(fail-open) `MessagePublisher`는 정해진 outbox와 + 함께 지웠다(2026-09-28). 두 번째 경로를 다시 들이지 않는다. +- 정해진 producer identity는 명시한 `app.messaging.producer-id`다. `spring.application.name`, host, pod, + 프로세스 identity에서 끌어내지 않는다. 모듈이 켜져 있는데 bridge가 없으면 기동을 거절한다 — relay가 발행할 + 길이 없다. +- 템플릿의 `IntegrationEventEncoderPort`(`JsonIntegrationEventEncoder`)는 여기가 아니라 + `adapter:outbound:support`에 있다: 유스케이스는 append하기 전에 인코딩하는데, 이 모듈을 싣지 않는 조립도 + 있다. R1 contract·binding 컴파일러와 JSON Schema envelope 인코더는 2026-09-25에 지웠다 + (`docs/capability-status.md`). +- 주 classpath에 JSON Schema 엔진(NetworkNT)이 없다. 증거 manifest schema 검사와 capability card 검사 + (`release/`)는 이 leaf의 시험(`evidence/`)이다. snakeyaml은 시험에서만 쓴다(소유자 결정 2026-09-25). +- 유스케이스 순서나 업무 라우팅 정책을 broker 어댑터 안에 숨기지 않는다. +- `OutboxMessagePublishAdapter`는 위임만 하고 의존성 로그를 내지 않는다. 확정된 FAILED/DEAD 전이가 정해진 + ERROR 하나를 가진다. -## Tests +## 테스트 -Use unit/contract tests with a fake canonical publisher. No real network or broker is used in -focused tests; settings records receive binding/validation tests when configuration changes. +가짜 정해진 publisher로 단위·계약 시험을 쓴다. 이 모듈만 보는 시험은 실제 네트워크나 broker를 쓰지 않는다. +설정이 바뀌면 settings record에 바인딩·검증 시험을 더한다. diff --git a/src/adapter/outbound/messaging/README.md b/src/adapter/outbound/messaging/README.md index 433775e0..95aa5803 100644 --- a/src/adapter/outbound/messaging/README.md +++ b/src/adapter/outbound/messaging/README.md @@ -25,7 +25,7 @@ bridge는 broker SDK나 transport SPI를 직접 보지 않는다. legacy `KafkaS seam과 그 위의 `MessagePublisher`·`OutboxEnvelopeJson`은 outbox를 canonical 하나로 통일하면서 삭제했다(2026-09-28, 소유자 결정 7). -## canonical platform bridge +## 정해진 플랫폼 bridge `IntegrationEventPublishPort`는 `app.messaging.producer-id`가 명시되고 platform publisher bean이 있을 때만 생성된다. exact `ValidatedIntegrationEvent.envelopeBytes()`를 보존하고 platform의 중앙 diff --git a/src/adapter/outbound/notification/CLAUDE.md b/src/adapter/outbound/notification/CLAUDE.md index 2a7822de..16bd153e 100644 --- a/src/adapter/outbound/notification/CLAUDE.md +++ b/src/adapter/outbound/notification/CLAUDE.md @@ -1,52 +1,49 @@ -# adapter:outbound:notification — notification adapter +# adapter:outbound:notification — 알림 어댑터 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-notification` -- Gradle path: `:adapter:outbound:notification` -- Focused test (derived from Gradle path): `./gradlew :adapter:outbound:notification:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-outbound-notification` +- Gradle 경로: `:adapter:outbound:notification` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:outbound:notification:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.outbound.notification`. +패키지 루트: `dev.caskeleton.adapter.outbound.notification`. -## Responsibility +## 책임 -- Preserve the current raw notification router/provider seams only as the `R0 legacy` compatibility - baseline until the reviewed canonical cutover removes them. -- Implement future provider protocols behind application-owned ports without leaking SDK, transport, - bootstrap, or persistence types. -- Own provider settings, technical fallback mechanics, and provider adaptation; application policy - owns mode, eligibility, retry/fallback decisions and business failure semantics. -- Reuse `adapter:outbound:support` for shared outbound concerns. +- 지금의 raw 알림 router·provider 이음매는 리뷰를 거친 정해진 전환(cutover)이 지울 때까지 `R0 legacy` 호환 + 기준선으로만 지킨다. +- 앞으로의 provider 프로토콜은 애플리케이션이 가진 포트 뒤에서 구현하고, SDK·전송·bootstrap·영속 타입을 + 새게 하지 않는다. +- provider 설정, 기술적 대체 장치, provider 연결을 가진다. 모드, 자격, 재시도·대체 판단, 업무 실패의 뜻은 + 애플리케이션 정책이 가진다. +- 공용 outbound 관심사는 `adapter:outbound:support`를 다시 쓴다. -## Current R0 freeze +## 지금의 R0 동결 -- `RoutingNotifier` performs route-list fan-out over `(Channel, providerId)`. -- `FailOpenNotificationProvider` applies one global fail-open rule. -- `google-email`/`GoogleEmailClient` and `slack-webhook`/`SlackClient` are fake-only extension seams, - not production integrations or qualified provider cards. -- Checked-in provider selector keys drift from the router's `routes` + provider `enabled` grammar. - Preserve and document that drift until the canonical graph replaces it; do not silently reinterpret - the old keys. -- There are no feature/application production consumers and no real-provider, durable, receipt, - security, load, or rotation evidence. -- The exact legacy deletion inventory lives in [README.md](README.md). Do not add behavior to those - classes while building their canonical replacements. +- `RoutingNotifier`가 `(Channel, providerId)` 위에서 route 목록으로 퍼뜨린다. +- `FailOpenNotificationProvider`가 전역 fail-open 규칙 하나를 적용한다. +- `google-email`/`GoogleEmailClient`와 `slack-webhook`/`SlackClient`는 fake로만 쓰는 확장 이음매다. 운영 연동이나 + 검증된 provider card가 아니다. +- 커밋해 둔 provider 선택 키는 router의 `routes` + provider `enabled` 문법과 어긋나 있다. 정해진 그래프가 + 대신할 때까지 그 어긋남을 지키고 적어 둔다. 옛 키를 소리 없이 다르게 해석하지 않는다. +- 기능·애플리케이션 운영 소비자가 없고, 실제 provider·durable·수신 확인·보안·부하·교체 증거가 없다. +- 지울 옛 코드의 정확한 목록은 [README.md](README.md)에 있다. 정해진 대체물을 만드는 동안 그 클래스에 동작을 + 더하지 않는다. -## Boundaries +## 경계 -- Allowed dependency edges come only from the module's - `src/config/architecture/modules.json` entry. -- No inbound DTO/controller, persistence, bootstrap, or sample dependency. -- Provider selection may route configured channels but must not encode business eligibility rules. -- No fully-qualified inline type references. `adapter:outbound:fileserver` already forbids these and - this leaf did not, so the same construct was a defect in one capability and ordinary style in the - next; the platform auto-configurations had accumulated twenty-two of them. A parameter written as - `dev.caskeleton.application.notification.platform.dispatch.ReconciliationJobStorePort jobs` hides - from the import block exactly the cross-leaf edge the import block exists to make readable. +- 허용 의존 edge는 이 모듈의 `src/config/architecture/modules.json` 항목에서만 온다. +- inbound DTO·controller, 영속, bootstrap, 샘플 의존이 없다. +- provider 선택은 설정한 채널로 보낼 수 있지만 업무 자격 규칙을 담으면 안 된다. +- 줄 안에 완전한 이름으로 쓴 타입 참조가 없다. `adapter:outbound:fileserver`는 이미 이것을 금지했고 이 leaf는 + 아니었다. 그래서 같은 구문이 한 capability에서는 결함이고 다음 capability에서는 평범한 문체였다. 플랫폼 자동 + 구성에 그런 것이 스물두 개 쌓여 있었다. + `dev.caskeleton.application.notification.platform.dispatch.ReconciliationJobStorePort jobs`처럼 쓴 매개변수는 + import 블록이 읽기 쉽게 보여 주려고 있는 바로 그 leaf 사이 edge를 import 블록에서 숨긴다. -## Tests +## 테스트 -Use provider/client fakes and contract tests; no real webhook or email network calls. Settings changes -include binding/validation tests. +provider·client fake와 계약 시험을 쓴다. 실제 webhook이나 email 네트워크 호출이 없다. 설정을 바꾸면 +바인딩·검증 시험을 더한다. diff --git a/src/adapter/outbound/notification/README.md b/src/adapter/outbound/notification/README.md index d87708af..b1382322 100644 --- a/src/adapter/outbound/notification/README.md +++ b/src/adapter/outbound/notification/README.md @@ -1,4 +1,4 @@ -# adapter:outbound:notification — R0 legacy truth +# adapter:outbound:notification — R0 legacy의 사실 > 현재 구현 전체는 교체 전 호환성 기준선인 `R0 legacy`다. `GoogleEmailClient`와 > `SlackClient`는 project-supplied seam일 뿐 실제 Google Mail 또는 Slack 연동이 아니며, @@ -12,7 +12,7 @@ correlation / fail-open 의존성 로깅을 재사용한다. `adapter-outbound-notification` row가 SSOT다. 이 문서는 코드 주석에서 덜어낸 **설계 결정의 근거**와 canonical 구현 전 삭제 대상을 모아둔 참조용 기록이다. -## Task 1 R0 truth table +## Task 1 R0 사실 표 | 축 | 현재 사실 | 증거와 한계 | | --- | --- | --- | @@ -54,18 +54,16 @@ client 는 포킹 프로젝트가 채우는 seam 이다. `GoogleEmailProvider`, `SlackWebhookProvider`). `GoogleEmailClient`/`SlackClient` 는 포크가 구현하는 seam 이며 실패는 데코레이터가 fail-open 처리한다. -## Removed R1 outbound experiment +## 지운 R1 outbound 실험 -The old top-level `catalog/`, `provider/`, and `template/` graph was never assembled by production -and has been removed. Do not recreate it to reach the canonical platform. The application R1 public -contract remains governed separately by NOTIF-ADR-005; new runtime code belongs under -`..notification.platform..`. +예전 최상위 `catalog/`, `provider/`, `template/` 그래프는 운영에서 한 번도 조립되지 않았고 지웠다. 정해진 플랫폼에 +닿으려고 그것을 다시 만들지 않는다. 애플리케이션 R1 공개 계약은 따로 NOTIF-ADR-005가 다룬다. 새 런타임 코드는 +`..notification.platform..` 아래에 둔다. -The context-aware HTML safety that was stronger in `LocalEmailRenderer` was carried forward before -removal: `platform.template.TemplateSlotPolicy` now validates operator-authored HTML against the -reviewed tag/attribute subset after rendering. +`LocalEmailRenderer`에서 더 강했던 문맥 인식 HTML 안전 장치는 지우기 전에 옮겨 왔다: 이제 +`platform.template.TemplateSlotPolicy`가 렌더링 뒤에 운영자가 쓴 HTML을 리뷰한 tag·attribute 부분집합과 대조한다. -## Wave G deletion inventory +## Wave G 삭제 목록 다음 surface는 canonical-only cutover와 retained evidence 검증이 끝난 뒤 한 묶음으로 제거한다. 그 전에는 동작을 확장하지 않고 R0 회귀 기준선으로만 유지한다. diff --git a/src/adapter/outbound/objectstorage/CLAUDE.md b/src/adapter/outbound/objectstorage/CLAUDE.md index f7306d2f..49182c7c 100644 --- a/src/adapter/outbound/objectstorage/CLAUDE.md +++ b/src/adapter/outbound/objectstorage/CLAUDE.md @@ -1,51 +1,46 @@ -# adapter:outbound:objectstorage — module rules +# adapter:outbound:objectstorage — 모듈 규칙 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-objectstorage` -- Gradle path: `:adapter:outbound:objectstorage` -- Focused test: `./gradlew :adapter:outbound:objectstorage:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-outbound-objectstorage` +- Gradle 경로: `:adapter:outbound:objectstorage` +- 이 모듈만 시험: `./gradlew :adapter:outbound:objectstorage:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.outbound.objectstorage`. Design rationale and truthful -readiness live in [README.md](README.md) and -`docs/registries/object-storage-readiness.yaml`. +패키지 루트: `dev.caskeleton.adapter.outbound.objectstorage`. 설계 근거와 사실대로 적은 준비 상태는 +[README.md](README.md)와 `docs/registries/object-storage-readiness.yaml`에 있다. -## Responsibility +## 책임 -- Implement application-core semantic object publication, read, retirement, and operation - resolution ports behind provider-neutral bounded streaming and strict durable control records. -- Compile disabled-by-default `app.object-storage` settings into exact immutable - provider/destination/route/policy bindings before constructing selected resources. -- Provide `filesystem-local-dev` as an R1-only development provider. -- Keep scanner maintenance composition separate; unsupported capabilities contribute no bean. - There is no purge, direct-grant, or multipart port. +- application-core의 semantic object 게시·읽기·폐기·operation 해석 포트를 provider 중립의 한계 있는 streaming과 + 엄격한 durable 제어 레코드 뒤에서 구현한다. +- 기본 꺼짐인 `app.object-storage` 설정을, 고른 자원을 만들기 전에 정확하고 바뀌지 않는 + provider·destination·route·policy 바인딩으로 컴파일한다. +- R1 전용 개발 provider로 `filesystem-local-dev`를 준다. +- scanner 유지보수 조립은 따로 둔다. 지원하지 않는 capability는 bean을 기여하지 않는다. purge·direct-grant· + multipart 포트는 없다. -## Allowed +## 허용 -- Project dependencies are exactly those allowed by the `adapter-outbound-objectstorage` entry in - `src/config/architecture/modules.json`; currently application-core, shared-contract, - application-objectstorage and the registered support edge (`adapter:outbound:support`: its - descriptor-based `SecureFileAccess`/`SecureDirectoryWalk`, which every local-dev file access goes - through, and `StrictSettingsBinder` — the `app.object-storage` tree is bound strictly, environment - included, capability rule 4). -- Provider SDK/configuration types stay within this leaf. -- Provider contributions may describe support without side effects and may construct resources - only after exact selection. +- 프로젝트 의존은 `src/config/architecture/modules.json`의 `adapter-outbound-objectstorage` 항목이 허용한 것뿐이다. + 지금은 application-core, shared-contract, application-objectstorage, 그리고 등록된 support edge + (`adapter:outbound:support`: 모든 local-dev 파일 접근이 거치는 descriptor 기반 `SecureFileAccess`/ + `SecureDirectoryWalk`, 그리고 `StrictSettingsBinder` — `app.object-storage` 트리는 환경 변수까지 엄격하게 + 바인딩한다. capability 규칙 4)다. +- provider SDK·설정 타입은 이 leaf 안에 머문다. +- provider 기여는 부작용 없이 지원 내용을 설명할 수 있고, 정확히 골라진 뒤에만 자원을 만들 수 있다. -## Forbidden +## 금지 -- Inbound adapters, sibling outbound adapters, persistence, or app-bootstrap dependencies. -- Provider keys, paths, locators, SDK types, Spring types, or control-record types leaking into - application-core. -- A default provider/destination/namespace, local-dev in production, or startup mutation when the - capability is disabled. -- Normal routing types implementing the scanner maintenance port. -- Claims above the exact rows in `docs/registries/object-storage-readiness.yaml`. -- Adapting new semantic operations back to legacy caller-keyed overwrite semantics. +- inbound 어댑터, 이웃 outbound 어댑터, 영속, app-bootstrap 의존. +- provider 키·경로·locator·SDK 타입·Spring 타입·제어 레코드 타입이 application-core로 새는 것. +- 기본 provider·destination·namespace, 운영에서 local-dev, capability가 꺼져 있을 때 기동 중 변경. +- 보통 라우팅 타입이 scanner 유지보수 포트를 구현하기. +- `docs/registries/object-storage-readiness.yaml`의 정확한 행보다 높은 주장. +- 새 semantic operation을 옛 호출자 키 기반 덮어쓰기 뜻으로 되돌려 맞추기. -## Test +## 테스트 ```bash cd src diff --git a/src/adapter/outbound/objectstorage/README.md b/src/adapter/outbound/objectstorage/README.md index 0e85a8ba..696b97c3 100644 --- a/src/adapter/outbound/objectstorage/README.md +++ b/src/adapter/outbound/objectstorage/README.md @@ -1,35 +1,32 @@ -# adapter:outbound:objectstorage — design-decision reference +# adapter:outbound:objectstorage — 설계 결정 참고 -Object-storage driven adapter under -`dev.caskeleton.adapter.outbound.objectstorage`. It implements the semantic contracts in -`dev.caskeleton.application.objectstorage` and keeps provider keys, paths, SDK types, and control -records behind the application boundary. +`dev.caskeleton.adapter.outbound.objectstorage` 아래의 object storage driven 어댑터다. +`dev.caskeleton.application.objectstorage`의 semantic 계약을 구현하고, provider 키·경로·SDK 타입·제어 +레코드를 애플리케이션 경계 뒤에 둔다. -The allowed production dependencies are owned by -`src/config/architecture/modules.json`. Module rules live in [CLAUDE.md](CLAUDE.md), the full design -in `docs/design/2026-07-28-objectstorage-production-capability-design.md`, and exact -evidence claims in `docs/registries/object-storage-readiness.yaml`. +허용 운영 의존은 `src/config/architecture/modules.json`이 가진다. 모듈 규칙은 [CLAUDE.md](CLAUDE.md), 전체 +설계는 `docs/design/2026-07-28-objectstorage-production-capability-design.md`, 정확한 증거 주장은 +`docs/registries/object-storage-readiness.yaml`에 있다. -For when to use this capability rather than the HTTP Fileserver platform, see -[`docs/storage-capability-boundary.md`](../../../../docs/storage-capability-boundary.md). +HTTP 파일 서버 플랫폼 대신 이 capability를 언제 쓰는지는 +[`docs/storage-capability-boundary.md`](../../../../docs/storage-capability-boundary.md)를 본다. -## Current readiness +## 지금 준비 상태 -Batch B implements the provider-neutral namespace/control kernel and -`filesystem-local-dev` managed single upload/download at R1. R1 means bounded local functional -evidence only: +Batch B가 provider 중립 namespace·제어 핵심과 `filesystem-local-dev`의 관리형 단일 업로드·다운로드를 R1으로 +구현한다. R1은 한계 있는 로컬 기능 증거만 뜻한다: -- immutable streamed create with exact SHA-256 and exact version inspection; -- full/range bounded reads; -- strict canonical control-record codecs and single-process CAS; -- same-operation replay without invoking the producer again; -- restart/path/symlink/corruption/fault characterization; -- exactly-once selected-provider lifecycle. +- 정확한 SHA-256과 정확한 version 검사를 하는, 바뀌지 않는 streaming 생성; +- 전체·범위 지정의 한계 있는 읽기; +- 엄격한 정규형 제어 레코드 codec과 단일 프로세스 CAS; +- producer를 다시 부르지 않는 같은 operation의 재생; +- 재시작·경로·symlink·손상·장애 특성 확인; +- 고른 provider의 lifecycle을 정확히 한 번. -It does not prove multi-node CAS, power-loss durability, production credentials/TLS/IAM/encryption, -S3 response-loss behavior, or R2 readiness. Direct transfer, multipart, quarantine, retention, and -production reconciliation cards remain R0. Direct transfer and multipart have no code: the unassembled -implementation was removed (recovery path in `docs/capability-status.md` 「제거된 코드」). +여러 노드 CAS, 전원 상실 내구성, 운영 credential·TLS·IAM·암호화, S3 응답 유실 동작, R2 준비는 증명하지 +않는다. direct transfer, multipart, quarantine, retention, 운영 reconciliation card는 R0에 머문다. direct +transfer와 multipart는 코드가 없다: 조립되지 않은 구현을 지웠다(되살리는 길은 `docs/capability-status.md` +「제거된 코드」). ## 제공하는 것 · 추가할 한 줄 · env 키 @@ -49,110 +46,103 @@ implementation was removed (recovery path in `docs/capability-status.md` 「제 bean도 두지 않는다. - env 키: 전용 `APP_*` 키는 없다. provider·destination이 map 구조라 배포의 `application-*.yml`에 `app.object-storage.{default-destination, providers..*, destinations..*}`를 적는다(아래 - 「Activation and routing」). 빠지면 기동 시 binding compile이 실패한다. + 「켜기와 라우팅」). 빠지면 기동 시 binding compile이 실패한다. -## Activation and routing +## 켜기와 라우팅 -The canonical namespace is `app.object-storage`. It is on when the module is present and off only -with `app.object-storage.enabled=false`. On requires an explicit provider, exact provider version, -logical destination, route token, binding/policy revisions, and bounded sizes. Settings compile fully before any selected provider creates a -directory, client, thread, scheduler, or credential lookup. +정해진 namespace는 `app.object-storage`다. 모듈이 있으면 켜지고 `app.object-storage.enabled=false`일 때만 +꺼진다. 켜려면 명시한 provider, 정확한 provider version, 논리 destination, route token, binding·policy +revision, 한계 있는 크기가 필요하다. 고른 provider가 디렉터리, client, 스레드, scheduler, credential 조회를 +만들기 전에 설정을 모두 컴파일한다. -`filesystem-local-dev` is rejected under `prod`/`production`. Normal composition contributes only -managed publication, inspection/transfer, retirement, and operation-resolution ports. Scanner -maintenance composition stays separate. There is no purge or direct-grant port. +`filesystem-local-dev`는 `prod`/`production`에서 거절한다. 보통 조립은 관리형 게시, 조회·전송, 폐기, +operation 해석 포트만 기여한다. scanner 유지보수 조립은 따로 둔다. purge나 direct-grant 포트는 없다. -S3 retirement deletes the exact version a HEAD verified (`DeleteObject` with `versionId`). An -`If-Match` condition on DELETE is not used: the qualified MinIO release ignores it (the MinIO lane -shows a stale ETag still deleting), and the SDK documents it for directory buckets only. A version-id -DELETE cannot touch an overwrite that landed after the HEAD, so it is conditional without relying on -the vendor honouring a header. It needs a bucket with versioning enabled: an S3 operation profile -that claims `CONDITIONAL_RETIREMENT` makes startup read `GetBucketVersioning` and refuse anything -but `Enabled`, and a retire that finds no version id is refused rather than turned into a by-key -delete. +S3 폐기는 HEAD가 확인한 정확한 version을 지운다(`versionId`를 준 `DeleteObject`). DELETE에 `If-Match` 조건은 +쓰지 않는다: 검증한 MinIO 릴리스는 그것을 무시하고(MinIO lane에서 낡은 ETag로도 지워진다), SDK는 그것을 +directory bucket에만 적는다. version id를 준 DELETE는 HEAD 뒤에 들어온 덮어쓰기를 건드릴 수 없으니, vendor가 +header를 지키는지에 기대지 않고도 조건부다. versioning이 켜진 bucket이 필요하다: `CONDITIONAL_RETIREMENT`를 +주장하는 S3 operation profile은 기동 때 `GetBucketVersioning`을 읽고 `Enabled`가 아니면 거절한다. version id를 +찾지 못한 폐기는 키 기준 삭제로 바꾸지 않고 거절한다. -The local provider maps provider-neutral logical control keys to `.record` leaf files. This permits -object-store-valid pairs such as `reference` and `reference/lifecycle` without a filesystem -file/directory collision; callers and durable control records retain the canonical logical keys. +로컬 provider는 provider 중립 논리 제어 키를 `.record` leaf 파일에 대응시킨다. 그래서 `reference`와 +`reference/lifecycle`처럼 object store에서는 맞는 짝이 파일 시스템의 파일·디렉터리 충돌 없이 함께 있을 수 +있다. 호출자와 durable 제어 레코드는 정규 논리 키를 그대로 가진다. -## Provider and dependency scope +## provider와 의존 범위 -The AWS SDK v2 BOM stays module-scoped because Spring Boot does not manage -`software.amazon.awssdk:*`. The whole-`byte[]` `ObjectStoragePort` generation and its filesystem/S3 -adapters were removed; the canonical semantic ports are the only generation (recovery path in -`docs/capability-status.md` 「제거된 코드」). +Spring Boot가 `software.amazon.awssdk:*`를 관리하지 않으니 AWS SDK v2 BOM은 모듈 범위에 둔다. `byte[]` 전체를 +쓰던 `ObjectStoragePort` 세대와 그 파일 시스템·S3 어댑터는 지웠다. 정해진 semantic 포트가 유일한 세대다 +(되살리는 길은 `docs/capability-status.md` 「제거된 코드」). -## Verification +## 검증 -Focused contracts cover codecs/state machines, local provider behavior, fail-closed binding, -composition side effects/lifecycle, routing replay/read behavior, and the readiness registry. +이 모듈만 보는 계약이 codec·상태 기계, 로컬 provider 동작, 실패하면 닫히는 바인딩, 조립 부작용·lifecycle, +라우팅 재생·읽기 동작, readiness registry를 덮는다. ```bash cd src ./gradlew :adapter:outbound:objectstorage:check --console=plain ``` -### Provider contract for a new provider +### 새 provider를 위한 provider 계약 -`ObjectStorageProviderContract` is in this leaf's test fixtures, because the `ObjectStorageProvider` -SPI is this leaf's own. The local-dev provider (`LocalDevObjectStorageProviderTest`) and the S3 -provider against MinIO (`MinioS3ManagedObjectProviderContractTest`) both extend it. A provider a -derived service adds extends the same class instead of copying it: +`ObjectStorageProvider` SPI가 이 leaf의 것이므로 `ObjectStorageProviderContract`는 이 leaf의 test fixtures에 +있다. local-dev provider(`LocalDevObjectStorageProviderTest`)와 MinIO에 대고 도는 S3 provider +(`MinioS3ManagedObjectProviderContractTest`)가 모두 그것을 상속한다. 파생 서비스가 더하는 provider는 복사하지 +않고 같은 클래스를 상속한다: ```groovy testImplementation testFixtures(project(':adapter:outbound:objectstorage')) ``` -### MinIO qualification lanes +### MinIO 검증 lane -`objectStorageMinioContractTest` and `objectStorageMinioFaultTest` run a real MinIO and Toxiproxy. -They run in the root `integrationCheck` (main push and nightly) and in -`.github/workflows/object-storage-qualification.yml` on pull requests that touch object storage — -not in this leaf's `mainCheck`, which ran them a second time on every main push. Their images are read from one file, -`src/test/resources/object-storage/minio-provider-evidence.json`, whose `image` digest is the -release the `status`, `excludedProfiles` and `limitations` beside it were measured on. -`MinioQualificationImage` (in `src/test`, checked by the leaf's `test` without Docker) reads it. +`objectStorageMinioContractTest`와 `objectStorageMinioFaultTest`는 실제 MinIO와 Toxiproxy를 돌린다. 루트 +`integrationCheck`(main push와 nightly)와, object storage를 건드리는 pull request의 +`.github/workflows/object-storage-qualification.yml`에서 돈다 — 이 leaf의 `mainCheck`에서는 돌지 않는다. +거기서는 main push마다 두 번 돌았다. image는 파일 하나 +`src/test/resources/object-storage/minio-provider-evidence.json`에서 읽는다. 그 `image` digest는 옆에 적힌 +`status`, `excludedProfiles`, `limitations`를 잰 릴리스다. `MinioQualificationImage`(`src/test`에 있고, leaf의 +`test`가 Docker 없이 검사한다)가 그것을 읽는다. -- The image is pulled before any container is built. If it cannot be pulled the lane fails with - `pinned image unavailable: `: a supply failure, not an adapter defect. The lane does - not skip, because a skipped vendor lane would be green with no vendor evidence. -- A mirror of the same digest is set with `OBJECT_STORAGE_MINIO_IMAGE` or - `-PobjectStorageMinioImage=/@sha256:`. A value that does not end - in the evidence digest is refused: a different build is a new measurement, made by re-running the - lanes and rewriting the evidence file (image and findings together). -- The local compose runtime (`compose.yaml`, and the compose lanes' smoke client in `src/app-bootstrap/compose-lanes/lane-services.yaml`; `LOCAL_MINIO_IMAGE`) uses the same digest. - `ComposeMinioImageMatchesEvidenceTest` (leaf `test`) fails when the compose default and the - evidence disagree; change both together. -- The contract lane also runs `MinioS3ManagedObjectProviderContractTest`: the S3 adapter itself under - the provider contract the local-dev provider inherits, on the production client factory, over TLS - with a certificate made for the run (a binding only accepts HTTPS). Its first run found two adapter - defects the mocked unit tests could not: every create failed because the SDK cancels the request - body once it holds Content-Length bytes (and at once for an empty body), and every read with a - consumer chunk below the network buffer size failed because Netty delivers 8 KiB buffers. Both - are fixed (`S3AsyncRequestBodyBridge`, `S3AsyncResponseBodyBridge.TRANSPORT_BUFFER_CEILING_BYTES`). +- container를 만들기 전에 image를 받는다. 받지 못하면 lane은 `pinned image unavailable: `로 + 실패한다: 어댑터 결함이 아니라 공급 실패다. lane은 건너뛰지 않는다. 건너뛴 vendor lane은 vendor 증거 없이 + 초록이 되기 때문이다. +- 같은 digest의 mirror는 `OBJECT_STORAGE_MINIO_IMAGE`나 + `-PobjectStorageMinioImage=/@sha256:`로 정한다. 증거 digest로 끝나지 않는 + 값은 거절한다: 다른 build는 새 측정이고, lane을 다시 돌려 증거 파일(image와 측정 결과를 함께)을 다시 써서 + 만든다. +- 로컬 compose 런타임(`compose.yaml`, 그리고 compose lane의 smoke client + `src/app-bootstrap/compose-lanes/lane-services.yaml`. `LOCAL_MINIO_IMAGE`)도 같은 digest를 쓴다. + `ComposeMinioImageMatchesEvidenceTest`(leaf `test`)는 compose 기본값과 증거가 다르면 실패한다. 둘을 함께 + 바꾼다. +- contract lane은 `MinioS3ManagedObjectProviderContractTest`도 돌린다: S3 어댑터 자체를 local-dev provider가 + 상속하는 provider 계약 아래에서, 운영 client factory로, 그 실행을 위해 만든 인증서로 TLS 위에서 시험한다 + (binding은 HTTPS만 받는다). 첫 실행에서 mock 단위 시험이 찾지 못한 어댑터 결함 둘을 찾았다: SDK가 + Content-Length 바이트를 받으면 요청 body를 취소해서(빈 body이면 바로) 모든 생성이 실패했고, Netty가 8 KiB + buffer로 넘겨서 network buffer 크기보다 작은 소비자 chunk로 하는 모든 읽기가 실패했다. 둘 다 고쳤다 + (`S3AsyncRequestBodyBridge`, `S3AsyncResponseBodyBridge.TRANSPORT_BUFFER_CEILING_BYTES`). -#### Image source (review 05-09, measured 2026-11-02) +#### image 출처 (review 05-09, 2026-11-02 측정) -Docker Hub `minio/minio` and `quay.io/minio/minio` stopped serving MinIO, so the measured digest of -the old release (2024-01-16) could not be mirrored. Two maintained builds were pulled and measured -with the same requests (create-only PUT twice, stale and current `If-Match` PUT, create-only -multipart completion onto an existing key, stale `If-Match` DELETE): +Docker Hub `minio/minio`와 `quay.io/minio/minio`가 MinIO 제공을 멈춰서, 옛 릴리스(2024-01-16)의 측정한 digest를 +mirror할 수 없었다. 유지되는 build 둘을 받아 같은 요청(create-only PUT 두 번, 낡은·현재 `If-Match` PUT, 있는 +키 위의 create-only multipart 완료, 낡은 `If-Match` DELETE)으로 쟀다: -| Candidate | Result | Decision | +| 후보 | 결과 | 결정 | | --- | --- | --- | -| `pgsty/minio@sha256:b6bfe723…` (community fork on Docker Hub, `RELEASE.2026-08-04T00-00-00Z`) | 412 / 412, 200 / 412; DELETE ignores `If-Match` | **Chosen.** Named release tags, `pgsty/mc` with a shell for the compose bucket bootstrap, runs as root like the old image | -| `cgr.dev/chainguard/minio@sha256:0a011000…` (`RELEASE.2026-10-23T20-06-51Z`) | Same results | Rejected: the free tier offers only a moving `latest` tag, it runs as uid 65532 (the compose volume would need re-owning), and `cgr.dev/chainguard/minio-client` has no shell | +| `pgsty/minio@sha256:b6bfe723…`(Docker Hub의 커뮤니티 fork, `RELEASE.2026-08-04T00-00-00Z`) | 412 / 412, 200 / 412. DELETE는 `If-Match`를 무시한다 | **골랐다.** 이름 있는 릴리스 태그, compose bucket 준비용 셸이 있는 `pgsty/mc`, 옛 image처럼 root로 돈다 | +| `cgr.dev/chainguard/minio@sha256:0a011000…`(`RELEASE.2026-10-23T20-06-51Z`) | 같은 결과 | 버렸다: 무료 등급은 움직이는 `latest` 태그만 주고, uid 65532로 돌며(compose volume 소유자를 바꿔야 한다), `cgr.dev/chainguard/minio-client`에는 셸이 없다 | -The new release refuses create-only overwrites, which the old one accepted. So the evidence is now -`status: SUPPORTED` for the managed create-only profiles (`supportedProfiles`), the direct -(presigned) profiles stay excluded because they were not measured, and the adapter allowlist gained -the provider type `s3-compatible-minio-pgsty-release-2026-08-04t00-00-00z` (version -`release-2026-08-04t00-00-00z-sdk-2.30.0`). Only that release may claim `IMMUTABLE_CREATE`; no MinIO -release may claim `MULTI_NODE_LINEARIZABLE_CAS` or `RESPONSE_LOSS_RESOLUTION`, because the evidence -is one single-node container. The 2024-01-16 type stays for servers that still run it, with its -old restrictions. +새 릴리스는 옛 릴리스가 받아 주던 create-only 덮어쓰기를 거절한다. 그래서 증거는 이제 관리형 create-only +profile(`supportedProfiles`)에 대해 `status: SUPPORTED`이고, direct(presigned) profile은 재지 않았으니 계속 +빠지며, 어댑터 허용 목록에 provider 타입 `s3-compatible-minio-pgsty-release-2026-08-04t00-00-00z`(version +`release-2026-08-04t00-00-00z-sdk-2.30.0`)가 더해졌다. 그 릴리스만 `IMMUTABLE_CREATE`를 주장할 수 있다. 증거가 +단일 노드 container 하나이므로 어떤 MinIO 릴리스도 `MULTI_NODE_LINEARIZABLE_CAS`나 `RESPONSE_LOSS_RESOLUTION`을 +주장할 수 없다. 2024-01-16 타입은 아직 그것을 돌리는 서버를 위해 옛 제한과 함께 남는다. -The compose client `minio-init` uses `pgsty/mc` by digest (`LOCAL_MINIO_MC_IMAGE` overrides it). +compose client `minio-init`은 digest로 `pgsty/mc`를 쓴다(`LOCAL_MINIO_MC_IMAGE`가 덮어쓴다). ```bash cd src diff --git a/src/adapter/outbound/persistence-fileserver/CLAUDE.md b/src/adapter/outbound/persistence-fileserver/CLAUDE.md index 1df1b76c..bb4c0a83 100644 --- a/src/adapter/outbound/persistence-fileserver/CLAUDE.md +++ b/src/adapter/outbound/persistence-fileserver/CLAUDE.md @@ -1,67 +1,59 @@ # persistence-fileserver -Relational persistence for the Fileserver capability: entities, Spring Data repositories and the -store adapters that implement `application-fileserver` ports. Root `AGENTS.md` and -`adapter/outbound/persistence-jpa/CLAUDE.md` still apply; this file adds what is local. +파일 서버 capability의 관계형 영속이다: 엔티티, Spring Data repository, `application-fileserver` 포트를 구현하는 +store 어댑터. 루트 `AGENTS.md`와 `adapter/outbound/persistence-jpa/CLAUDE.md`도 그대로 적용된다. 이 파일은 이 +leaf에만 있는 것을 더한다. -## Packages +## 패키지 -- `entity/` — JPA rows only. Every entity extends `AssignedIdEntity`. -- `repository/` — Spring Data interfaces and the SQL text they run (`CleanupClaimSql`). -- package root — the store adapters (`Jpa*`), `FileEntityMapper`, and the `@Configuration` - classes that register them as beans. +- `entity/` — JPA 행만. 모든 엔티티는 `AssignedIdEntity`를 상속한다. +- `repository/` — Spring Data 인터페이스와 그것이 돌리는 SQL 글(`CleanupClaimSql`). +- 패키지 루트 — store 어댑터(`Jpa*`), `FileEntityMapper`, 그것들을 bean으로 등록하는 `@Configuration` + 클래스. -`persistence-notification` follows the same rule (`platform.entity`, `platform.repository`, adapters -in `platform`), so the two capability leaves read the same way. +`persistence-notification`도 같은 규칙(`platform.entity`, `platform.repository`, 어댑터는 `platform`)을 +따르므로 두 capability leaf를 같은 방식으로 읽는다. -## Rules +## 규칙 -- **Transactions.** A store never opens one. Every write starts with - `CallerTransaction.require(" ")`, so a use case that forgot - `TransactionPort.inWrite` fails instead of committing statement by statement. -- **New rows.** Ids are assigned before the insert, so an entity must say whether it is new: - extend `AssignedIdEntity` (`Persistable`). Without it `save` merges — a SELECT before every - insert, and a second insert under an existing id overwrites the row instead of failing on the - primary key. A new `@Version` column may stay primitive `long`; newness comes from - `Persistable`, not from the version. -- **No policy here.** Retry budgets, lease lengths and other decisions belong to - `application-fileserver` and arrive as port arguments. A claim token or other fence travels in - the port type (`CleanupItem.claimToken`), never in a field of the adapter. -- **Claims.** A queue claim is one statement: CTE + `FOR UPDATE SKIP LOCKED` + `RETURNING` - (`CleanupClaimSql`). Settlements match the claim token and update zero rows for a stale worker. +- **트랜잭션.** store는 트랜잭션을 열지 않는다. 모든 쓰기는 `CallerTransaction.require(" ")`로 + 시작한다. 그래서 `TransactionPort.inWrite`를 잊은 유스케이스는 문장마다 커밋하지 않고 실패한다. +- **새 행.** id를 insert 전에 정하므로 엔티티가 새것인지 스스로 말해야 한다: `AssignedIdEntity` + (`Persistable`)를 상속한다. 그렇지 않으면 `save`가 merge한다 — insert마다 SELECT가 앞서고, 이미 있는 id로 + 하는 두 번째 insert가 primary key에서 실패하지 않고 행을 덮어쓴다. 새 `@Version` 열은 primitive `long`으로 둬도 + 된다. 새것인지는 version이 아니라 `Persistable`이 정한다. +- **여기에 정책을 두지 않는다.** 재시도 예산, lease 길이 같은 판단은 `application-fileserver`의 것이고 포트 + 인자로 온다. claim token 같은 fence는 어댑터 필드가 아니라 포트 타입(`CleanupItem.claimToken`)에 실려 다닌다. +- **claim.** queue claim은 문장 하나다: CTE + `FOR UPDATE SKIP LOCKED` + `RETURNING`(`CleanupClaimSql`). 마무리 + 처리는 claim token을 맞춰 보고, 낡은 worker이면 0행을 update한다. -## Migrations +## migration -- `src/main/resources/db/migration/jpa/fileserver/V*.sql`, applied as the capability's own Flyway - stream (`flyway_jpa_fileserver_history`). -- An applied file is never edited. Add a new version and its hash to the immutability list; - `persistence-jpa`'s `AppliedMigrationImmutabilityTest` pins these files where they live. +- `src/main/resources/db/migration/jpa/fileserver/V*.sql`. capability 자신의 Flyway stream + (`flyway_jpa_fileserver_history`)으로 적용한다. +- 적용한 파일은 고치지 않는다. 새 버전과 그 hash를 불변 목록에 더한다. `persistence-jpa`의 + `AppliedMigrationImmutabilityTest`가 이 파일들을 있는 자리에서 고정한다. -## Tests +## 테스트 -- `src/test` — this leaf's own tests, no container. Run: +- `src/test` — container 없는 이 leaf 자신의 시험. 돌리기: `./gradlew :adapter:outbound:persistence-fileserver:test --console=plain`. - - `FileserverStoreCallerTransactionTest` — every guarded write of every store refuses without a - caller transaction before it touches a repository (the Transactions rule above, one case per - write; Spring Data repositories are mocks). - - `FileserverPersistenceActivationTest` — the scan covers this package only, behind - `app.fileserver-platform.enabled`, and runs before the JPA root auto-configuration. - - `repository.CleanupClaimSqlTest` — the claim's text keeps its one-statement shape (the Claims - rule); the locking itself is checked on PostgreSQL by - `PostgreSqlFileserverReclamationIntegrationTest`. - - `entity.AssignedIdEntityTest` — newness from `Persistable`, on Hibernate over H2. - A new store write adds its case to the guard test; a new auto-configuration adds its line to the - activation test. -- Port contracts live in `application-fileserver` testFixtures (`*PortContract`, and - `FileQuotaLedgerContract` for the three quota ports, which share one table). The in-memory fakes - and the PostgreSQL tests both extend them; every port this leaf implements has one - (`docs/testing/TESTING_STRATEGY.md` 9.3). The PostgreSQL side of the seven added on - 2026-11-03 is tagged `jpa-contract` and runs in persistence-jpa's - `jpaPlatformContractTest` lane on `FileserverPostgreSqlStack`, whose clock a case moves. -- The real-PostgreSQL tests are still in `persistence-jpa`'s `postgresqlIntegrationTest` source - set, which owns the container and Flyway wiring, and the JPA readiness card - (`persistence-jpa/release/readiness-cards.yaml`, checked by `JpaReadinessRegistryTest`) names them as that - leaf's tasks — moving them means moving the card's tasks and selectors with them: - `postgresqlFileserverMigrationIntegrationTest`, `postgresqlFileserverMetadataIntegrationTest`, - `postgresqlFileserverReclamationIntegrationTest` + - `FileserverStoreCallerTransactionTest` — 모든 store의 보호된 쓰기는 호출자 트랜잭션이 없으면 repository에 + 닿기 전에 거절한다(위 트랜잭션 규칙, 쓰기마다 경우 하나. Spring Data repository는 mock이다). + - `FileserverPersistenceActivationTest` — scan은 `app.fileserver-platform.enabled` 뒤에서 이 패키지만 덮고, + JPA 루트 자동 구성보다 먼저 돈다. + - `repository.CleanupClaimSqlTest` — claim 글이 문장 하나 모양을 지킨다(claim 규칙). 잠금 자체는 + `PostgreSqlFileserverReclamationIntegrationTest`가 PostgreSQL에서 본다. + - `entity.AssignedIdEntityTest` — H2 위의 Hibernate에서 `Persistable`로 새것인지 정한다. + 새 store 쓰기는 보호 시험에 자기 경우를 더한다. 새 자동 구성은 켜기 시험에 자기 줄을 더한다. +- 포트 계약은 `application-fileserver` testFixtures에 있다(`*PortContract`, 그리고 테이블 하나를 같이 쓰는 quota + 포트 셋의 `FileQuotaLedgerContract`). 메모리 fake와 PostgreSQL 시험이 모두 그것을 상속한다. 이 leaf가 구현하는 + 포트는 모두 계약이 있다(`docs/testing/TESTING_STRATEGY.md` 9.3절). 2026-11-03에 더한 일곱 개의 PostgreSQL + 쪽은 `jpa-contract` tag를 달고 persistence-jpa의 `jpaPlatformContractTest` lane에서 + `FileserverPostgreSqlStack` 위에 돈다. 경우마다 그 시계를 옮긴다. +- 실제 PostgreSQL 시험은 아직 `persistence-jpa`의 `postgresqlIntegrationTest` source set에 있다. 그 source set이 + container와 Flyway 배선을 가지고, JPA readiness card(`persistence-jpa/release/readiness-cards.yaml`, + `JpaReadinessRegistryTest`가 검사)가 그 시험을 그 leaf의 태스크로 이름 댄다 — 옮기려면 card의 태스크와 + selector도 함께 옮겨야 한다: `postgresqlFileserverMigrationIntegrationTest`, + `postgresqlFileserverMetadataIntegrationTest`, `postgresqlFileserverReclamationIntegrationTest` (`./gradlew :adapter:outbound:persistence-jpa: --console=plain`). diff --git a/src/adapter/outbound/persistence-jpa/CLAUDE.md b/src/adapter/outbound/persistence-jpa/CLAUDE.md index bf3622e6..a0ff79f3 100644 --- a/src/adapter/outbound/persistence-jpa/CLAUDE.md +++ b/src/adapter/outbound/persistence-jpa/CLAUDE.md @@ -1,112 +1,96 @@ -# adapter:outbound:persistence-jpa — JPA/PostgreSQL persistence adapter +# adapter:outbound:persistence-jpa — JPA·PostgreSQL 영속 어댑터 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-persistence-jpa` -- Gradle path: `:adapter:outbound:persistence-jpa` -- Focused test (derived from Gradle path): `./gradlew :adapter:outbound:persistence-jpa:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-outbound-persistence-jpa` +- Gradle 경로: `:adapter:outbound:persistence-jpa` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:outbound:persistence-jpa:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.outbound.persistence`. +패키지 루트: `dev.caskeleton.adapter.outbound.persistence`. -Design decisions previously kept as code comments (transaction templates, auditing capture, -failure-translation SPI, idempotency/outbox concurrency, distributed-lock TTL) live in -[README.md](README.md). This file stays the SSOT for module rules and contract tables. +예전에 코드 주석으로 두던 설계 결정(트랜잭션 template, 감사 값 잡기, 실패 번역 SPI, 멱등성·outbox 동시성, 분산 +lock TTL)은 [README.md](README.md)에 있다. 이 파일은 모듈 규칙과 계약 표의 정본으로 남는다. -This module is the RDBMS/JPA implementation base. It is not a datastore-neutral -core for MongoDB, Redis, DynamoDB, or other NoSQL stores. Future NoSQL persistence -adapters implement application/domain ports directly and must not depend on this module. +이 모듈은 RDBMS·JPA 구현 기반이다. MongoDB, Redis, DynamoDB나 다른 NoSQL 저장소를 위한 저장소 중립 core가 아니다. +앞으로의 NoSQL 영속 어댑터는 application·domain 포트를 직접 구현하고 이 모듈에 의존하면 안 된다. -## JPA relational persistence platform +## JPA 관계형 영속 플랫폼 -The platform in `docs/design/2026-08-11-jpa-persistence-platform-design.md` is -implemented here. The design models it as 18 Stable library modules; this repository's fail-closed -registry outranks that layout, so those modules are **packages** in this leaf and -`docs/jpa/repository-adaptation.md` records the mapping. Read it before moving a type between -packages. +`docs/design/2026-08-11-jpa-persistence-platform-design.md`의 플랫폼을 여기 구현했다. 설계는 그것을 Stable 라이브러리 +모듈 18개로 모델링한다. 이 저장소의 실패하면 닫히는 registry가 그 배치보다 앞서므로, 그 모듈들은 이 leaf의 +**패키지**이고 `docs/jpa/repository-adaptation.md`가 그 대응을 적는다. 타입을 다른 패키지로 옮기기 전에 그것을 읽는다. -| Platform package | Owns | +| 플랫폼 패키지 | 가지는 것 | |---|---| -| `autoconfigure` | package-private Boot composition root/runtime: vendor and optional-store imports and provider runtime beans. It is intentionally not exported as public API | -| `api` (+ `.capability`, `.error`, `.query`, `.transaction`) | framework-free contracts: operation and query names, the stable error hierarchy, commit-completion evidence, keyset cursors | -| `transaction` | `SpringTransaction`, the one transaction engine (`TransactionPort` over Spring's `PlatformTransactionManager`) | -| `springdata` | repository fragments, safe sort, fetch plans, keyset execution, stream guard | -| `hibernate` (+ `.batch`, `.bulk`, `.stateless`) | statement inspector, statistics, batch, bulk DML, stateless session | -| `postgresql` (+ `.error`, `.lock`, `.constraint`, `.json`, `.array`, `.range`, `.copy`) | SQLSTATE classification, lock options, JSONB, arrays and ranges, COPY | -| `migration` | `FlywaySchemaPolicy` (composed by the `startup` package's dangerous-configuration guard) | -| `startup` | package-private startup policy (`JpaStartupAutoConfiguration`): Flyway migration strategy, datasource env/product checks, OSIV/DDL/Hikari/TLS/H2 guards, the `jpaplatform` actuator view, the readiness `db` contribution. Moved here from app-bootstrap | -| `cache`, `envers`, `querydsl`, `security`, `observation` | opt-in library capabilities and the runtime-role verifier | -| `experimental` | multi-tenancy, RLS, schema/database tenancy, read replica — library code a deployment constructs itself; no flag turns it on | -| `testkit` (`src/testFixtures/java`) | ArchUnit rules, fixtures, query/plan assertions, PostgreSQL matrix, failure injection, Flyway validate gate, concurrent-index inspector and lock-wait inspector | +| `autoconfigure` | package-private Boot 조립 루트·런타임: vendor와 선택 저장소 import, provider runtime bean. 일부러 공개 API로 내놓지 않는다 | +| `api` (+ `.capability`, `.error`, `.query`, `.transaction`) | 프레임워크 없는 계약: operation·query 이름, 안정된 오류 계층, 커밋 완료 증거, keyset cursor | +| `transaction` | `SpringTransaction`, 유일한 트랜잭션 엔진(Spring `PlatformTransactionManager` 위의 `TransactionPort`) | +| `springdata` | repository fragment, 안전한 정렬, fetch plan, keyset 실행, stream guard | +| `hibernate` (+ `.batch`, `.bulk`, `.stateless`) | statement inspector, 통계, batch, bulk DML, stateless session | +| `postgresql` (+ `.error`, `.lock`, `.constraint`, `.json`, `.array`, `.range`, `.copy`) | SQLSTATE 분류, lock 옵션, JSONB, 배열과 범위, COPY | +| `migration` | `FlywaySchemaPolicy`(`startup` 패키지의 위험 설정 guard가 조립한다) | +| `startup` | package-private 기동 정책(`JpaStartupAutoConfiguration`): Flyway migration 전략, datasource env·제품 검사, OSIV·DDL·Hikari·TLS·H2 guard, `jpaplatform` actuator view, readiness `db` 기여. app-bootstrap에서 여기로 옮겼다 | +| `cache`, `envers`, `querydsl`, `security`, `observation` | 골라 쓰는 라이브러리 capability와 runtime role 검증기 | +| `experimental` | multi-tenancy, RLS, schema·database 테넌시, read replica — 배포가 스스로 만드는 라이브러리 코드. 켜는 flag가 없다 | +| `testkit`(`src/testFixtures/java`) | ArchUnit 규칙, fixture, query·plan 단언, PostgreSQL 표, 장애 주입, Flyway validate gate, concurrent index inspector, lock-wait inspector | -`springdata`, `hibernate` (`.batch`, `.bulk`, `.stateless`, statement inspector), `postgresql` -(`.error`, `.lock`, `.constraint`, `.json`, `.array`, `.range`, `.copy`), `api.query`, `envers`, -`querydsl`, `cache`, `observation` and `experimental` are **library API**: no configuration composes -them, and a service calls them from its own adapter leaf, which takes this leaf as `implementation`. -The entry points and the test that proves each one are listed in [README.md](README.md) -"라이브러리 API". +`springdata`, `hibernate`(`.batch`, `.bulk`, `.stateless`, statement inspector), `postgresql`(`.error`, `.lock`, +`.constraint`, `.json`, `.array`, `.range`, `.copy`), `api.query`, `envers`, `querydsl`, `cache`, `observation`, +`experimental`은 **라이브러리 API**다: 어떤 설정도 그것을 조립하지 않고, 서비스가 이 leaf를 `implementation`으로 받는 +자기 어댑터 leaf에서 부른다. 진입점과 각각을 증명하는 시험은 [README.md](README.md) 「라이브러리 API」에 있다. -### Spring composition ownership +### Spring 조립 소유 -`META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports` publishes two -package-private entries: `PersistenceJpaAutoConfiguration` and `PersistenceJpaRuntimeConfig`. -Because Boot loads those candidates independently, **both** require -`app.persistence-jpa.enabled=true`. The first owns vendor/entity/repository and -capability-store imports. The second contributes only the provider runtime beans -(`HibernateProviderPolicy`, `PostgreSqlRuntimeRoleVerifier`). The -transaction engine is `SpringTransaction` alone; the second engine -(`SpringJpaTransactionExecutor`/`FullTransactionRetryCoordinator`) was removed on 2026-09-25 — see -`docs/capability-status.md`. Never rely on the first candidate's condition to gate the sibling -import candidate. +`META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`는 package-private 항목 둘을 내놓는다: +`PersistenceJpaAutoConfiguration`과 `PersistenceJpaRuntimeConfig`. Boot가 그 후보를 따로따로 읽으므로 **둘 다** +`app.persistence-jpa.enabled=true`를 요구한다. 첫째는 vendor·entity·repository와 capability 저장소 import를 가진다. +둘째는 provider runtime bean(`HibernateProviderPolicy`, `PostgreSqlRuntimeRoleVerifier`)만 기여한다. 트랜잭션 엔진은 +`SpringTransaction` 하나뿐이다. 두 번째 엔진(`SpringJpaTransactionExecutor`/`FullTransactionRetryCoordinator`)은 +2026-09-25에 지웠다 — `docs/capability-status.md`를 본다. 첫째 후보의 조건이 이웃 import 후보를 막아 준다고 기대지 +않는다. -`enabled=false` is a full off, not a bean-only one: `JpaActivationEnvironmentPostProcessor` (this -leaf's `spring.factories`) appends Boot's `jdbc`/`hibernate`/`data.jpa`/`flyway` auto-configurations -to `spring.autoconfigure.exclude`, so no DataSource, pool, EntityManagerFactory or Flyway exists. +`enabled=false`는 bean만이 아니라 완전히 끄기다: `JpaActivationEnvironmentPostProcessor`(이 leaf의 `spring.factories`)가 +Boot의 `jdbc`/`hibernate`/`data.jpa`/`flyway` 자동 구성을 `spring.autoconfigure.exclude`에 붙인다. 그래서 DataSource, +pool, EntityManagerFactory, Flyway가 하나도 없다. -The same split applies to owner-safe PostgreSQL idempotency: this leaf constructs the concrete -PostgreSQL store behind `IdempotencyStorePort` (`PostgreSqlIdempotencyStoreConfig`, active only with -`app.capabilities.idempotency.provider=postgresql`), while `composition:idempotency` owns provider -selection, TTL/lease/codec policy, executor construction, and exclusivity validation. With that -provider the leaf also applies the `db/migration/jpa/core` + `db/migration/jpa/idempotency` Flyway -streams and activates the capability registry row at startup (`IdempotencySchemaStream`, skipped -when `app.runtime.migration-on-startup=false`), refuses a non-PostgreSQL data source, and -runs `IdempotencyReaper`. There is no V1/JDBC idempotency store and no `jdbc` provider value. +소유자를 안전하게 지키는 PostgreSQL 멱등성도 같은 분할을 쓴다: 이 leaf는 `IdempotencyStorePort` 뒤의 실제 PostgreSQL +store를 만들고(`PostgreSqlIdempotencyStoreConfig`, `app.capabilities.idempotency.provider=postgresql`일 때만 켜진다), +`composition:idempotency`가 provider 고르기, TTL·lease·codec 정책, executor 만들기, 배타성 검증을 가진다. 그 provider를 +고르면 leaf는 `db/migration/jpa/core` + `db/migration/jpa/idempotency` Flyway stream도 적용하고 기동 때 capability +registry 행을 켜며(`IdempotencySchemaStream`, `app.runtime.migration-on-startup=false`이면 건너뛴다), PostgreSQL이 아닌 +data source를 거절하고, `IdempotencyReaper`를 돌린다. V1·JDBC 멱등성 store도 `jdbc` provider 값도 없다. -This module is a capability selected by one build line (`runtimeOnly -project(':adapter:outbound:persistence-jpa')`); the template's default composition does not carry it. -Everything that only makes sense with a relational store therefore lives here and turns on with the -module: migration startup sequencing, resolved datasource/version validation, OSIV/DDL/pool/TLS/vendor -safety, the sanitized management endpoint/report (`startup`), the metered multi-instance lock -(`lock`), the readiness `db` contribution and the shipped settings -(`config/module-defaults/persistence-jpa.yml`). Use-case assembly does not: the outbox relay is -`composition:outbox-relay` because a driven adapter must not construct or call a use case. The leaf must have -zero imports from `dev.caskeleton.bootstrap`; startup failures go through `adapter:outbound:support` -(`support.startup`), and new composition helpers stay package-private so `verifyJpaApiSurface` does -not grow by wiring accident. +이 모듈은 빌드 한 줄(`runtimeOnly project(':adapter:outbound:persistence-jpa')`)로 고르는 capability다. 템플릿의 기본 +조립은 이것을 싣지 않는다. 그래서 관계형 저장소가 있을 때만 뜻이 있는 것은 모두 여기 있고 모듈과 함께 켜진다: +migration 기동 순서, 해석된 datasource·버전 검증, OSIV·DDL·pool·TLS·vendor 안전, 걸러 낸 관리 endpoint·보고 +(`startup`), metric을 단 다중 인스턴스 lock(`lock`), readiness `db` 기여, 출하하는 설정 +(`config/module-defaults/persistence-jpa.yml`). 유스케이스 조립은 아니다: driven 어댑터가 유스케이스를 만들거나 부르면 +안 되므로 outbox relay는 `composition:outbox-relay`다. leaf에는 `dev.caskeleton.bootstrap` import가 하나도 없어야 한다. +기동 실패는 `adapter:outbound:support`(`support.startup`)를 거치고, 새 조립 도우미는 package-private로 둬서 배선 +실수로 `verifyJpaApiSurface`가 늘지 않게 한다. -### Non-negotiables +### 양보할 수 없는 것 -- No `GenericRepository` and no platform base repository. Domains own their repositories. -- `TransactionCompletionUnknownException` is never retried. `JpaFailureContext` refuses to - represent a retryable completion-unknown failure, and `SpringTransaction` retries nothing. -- A caller that retries re-runs the whole use case in a new transaction and a new Persistence - Context. -- OSIV is false in every runtime profile; Flyway owns schema change and Hibernate only validates. -- A migration that locks a table already in use starts with `SET LOCAL lock_timeout = '5s';` - (`docs/jpa/migration-guide.md` "Bound the lock wait"). `MigrationLockWaitTest` refuses one - without it. Its list of migrations released before the rule never takes a new migration; it - grows only when the inspector learns a statement and finds it in a file already on `main`. -- Flyway holds its PostgreSQL migration lock for the session, never in an open transaction, or a - `CREATE INDEX CONCURRENTLY` migration waits for Flyway forever: `spring.flyway.postgresql.transactional-lock: - false` in the module defaults, and every Flyway built in code starts from - `FlywaySchemaPolicy.configure()` (`JpaProductionArchitectureTest` refuses `Flyway.configure()` and - constructing a Flyway configuration directly — `new FluentConfiguration()`, `new - ClassicConfiguration()`, a subclass; `docs/jpa/migration-guide.md` "Who may change the schema"). -- Metric tags, exception messages, and logs carry no SQL parameters, entity ids, tenant ids, or PII. -- Contracts run against real PostgreSQL. H2 never satisfies one. +- `GenericRepository`도 플랫폼 기반 repository도 없다. 도메인이 자기 repository를 가진다. +- `TransactionCompletionUnknownException`은 절대 재시도하지 않는다. `JpaFailureContext`는 재시도할 수 있는 + completion-unknown 실패를 나타내기를 거절하고, `SpringTransaction`은 아무것도 재시도하지 않는다. +- 재시도하는 호출자는 새 트랜잭션과 새 Persistence Context에서 유스케이스 전체를 다시 돌린다. +- OSIV는 모든 runtime profile에서 false다. schema 변경은 Flyway가 가지고 Hibernate는 검증만 한다. +- 이미 쓰이는 테이블을 잠그는 migration은 `SET LOCAL lock_timeout = '5s';`로 시작한다 + (`docs/jpa/migration-guide.md` "Bound the lock wait"). `MigrationLockWaitTest`가 그것이 없는 migration을 거절한다. 그 + 규칙 전에 릴리스한 migration 목록에는 새 migration을 넣지 않는다. 그 목록은 inspector가 문장을 새로 배우고 이미 + `main`에 있는 파일에서 그것을 찾았을 때만 늘어난다. +- Flyway는 PostgreSQL migration lock을 열린 트랜잭션이 아니라 세션 동안 쥔다. 아니면 `CREATE INDEX CONCURRENTLY` + migration이 Flyway를 영원히 기다린다: 모듈 기본값의 `spring.flyway.postgresql.transactional-lock: false`, 그리고 코드에서 + 만드는 모든 Flyway는 `FlywaySchemaPolicy.configure()`에서 시작한다(`JpaProductionArchitectureTest`가 + `Flyway.configure()`와 Flyway 설정을 직접 만드는 것 — `new FluentConfiguration()`, `new ClassicConfiguration()`, 하위 + 클래스 — 을 거절한다. `docs/jpa/migration-guide.md` "Who may change the schema"). +- metric tag, 예외 메시지, 로그는 SQL 매개변수, entity id, tenant id, 개인정보를 싣지 않는다. +- 계약은 실제 PostgreSQL에 대고 돈다. H2는 어떤 계약도 만족시키지 않는다. -### Platform lanes +### 플랫폼 lane ```bash cd src @@ -126,164 +110,144 @@ cd src :adapter:outbound:persistence-jpa:jpaPlatformPoolContractTest ``` -Every Docker-backed lane fails closed. A selected lane that discovers nothing, or a container that -cannot start, is an error rather than a skip — a skipped contract reports success for a database -nobody tested. +Docker를 쓰는 모든 lane은 실패하면 닫힌다. 고른 lane이 아무것도 찾지 못하거나 container가 시작하지 못하면 건너뛰기가 +아니라 오류다 — 건너뛴 계약은 아무도 시험하지 않은 데이터베이스에 대해 성공을 알린다. -## Responsibility +## 책임 -- JPA entities. -- Spring Data repositories. -- Persistence mappers. -- Repository adapter implementations. -- Outbox append: one model. `JpaOutboxStore` implements `OutboxAppendPort` and persists a - `ValidatedIntegrationEvent`'s exact envelope bytes and hashes; a claim restores the same event - from them. A row without complete canonical metadata is unreadable and goes to DEAD, never - published by guess. `V19` refuses unpublished pre-canonical rows. -- Outbox relay fencing: `claimBatch` records the claiming relay (`lease_owner`) and increments - `lease_token` under the claim's row lock (`V17`); `markPublished`/`markFailed`/`markDead` are one - conditional UPDATE on `event_id` + `IN_FLIGHT` + owner + token and return `APPLIED`/`STALE`. A - completion never loads and overwrites a row. The V2 outbox generation was deleted on 2026-09-25 - (`docs/capability-status.md`). -- `TransactionPort` implementation (`SpringTransaction`) — the bridge between - application transactional intent and Spring's `PlatformTransactionManager`. -- Audit-metadata base + actor seam (`audit/AuditableEntity`, `audit/AuditContextPort`, - `audit/DomainContextAuditContext`) — see "Persistence auditing contract" below. -- Vendor SPI extension points shared by all RDBMS vendors: - - `outbox/jpa/OutboxClaimRepository` — vendor module implements claim strategy (e.g. FOR UPDATE SKIP LOCKED); the implementations sit beside it in `outbox/postgresql` and `outbox/h2`. - - `failure/SqlStateErrorMapping` — vendor module contributes vendor-specific SQLState rows. +- JPA 엔티티. +- Spring Data repository. +- 영속 mapper. +- repository 어댑터 구현. +- outbox append: 모델 하나. `JpaOutboxStore`가 `OutboxAppendPort`를 구현하고 `ValidatedIntegrationEvent`의 정확한 envelope + 바이트와 hash를 저장한다. claim은 그것으로 같은 이벤트를 되살린다. 정해진 metadata가 다 갖춰지지 않은 행은 읽을 수 + 없고 DEAD로 간다. 짐작으로 발행하지 않는다. `V19`는 발행하지 않은 정해진 형식 이전 행을 거절한다. +- outbox relay fencing: `claimBatch`가 claim의 행 lock 아래에서 claim한 relay(`lease_owner`)를 기록하고 + `lease_token`을 올린다(`V17`). `markPublished`/`markFailed`/`markDead`는 `event_id` + `IN_FLIGHT` + owner + token에 + 대한 조건부 UPDATE 하나이고 `APPLIED`/`STALE`을 돌려준다. 완료는 행을 읽어서 덮어쓰지 않는다. V2 outbox 세대는 + 2026-09-25에 지웠다(`docs/capability-status.md`). +- `TransactionPort` 구현(`SpringTransaction`) — 애플리케이션의 트랜잭션 의도와 Spring `PlatformTransactionManager` 사이의 + 다리. +- 감사 metadata 기반 + actor 이음매(`audit/AuditableEntity`, `audit/AuditContextPort`, `audit/DomainContextAuditContext`) — + 아래 「영속 감사 계약」을 본다. +- 모든 RDBMS vendor가 같이 쓰는 vendor SPI 확장점: + - `outbox/jpa/OutboxClaimRepository` — vendor 모듈이 claim 전략(예: FOR UPDATE SKIP LOCKED)을 구현한다. 구현은 그 + 옆 `outbox/postgresql`과 `outbox/h2`에 있다. + - `failure/SqlStateErrorMapping` — vendor 모듈이 vendor 전용 SQLState 행을 기여한다. -## Vendor selection +## vendor 고르기 -Two vendor compositions live in this module, each in its own subpackage, each registering the same -two SPI beans (outbox claim, SQLState mapping): +vendor 조립 둘이 이 모듈에 있고, 각각 자기 하위 패키지에 있으며, 각각 같은 SPI bean 둘(outbox claim, SQLState 대응)을 +등록한다: -| Vendor | Package | Selected by | Schema owner | +| vendor | 패키지 | 고르는 것 | schema 소유 | | --- | --- | --- | --- | -| PostgreSQL | `.postgresql` | `app.persistence.vendor=postgresql` (also the default) | Flyway, `db/migration/postgresql` | -| H2 | `.h2` | `app.persistence.vendor=h2` | Hibernate `ddl-auto`, entities only | +| PostgreSQL | `.postgresql` | `app.persistence.vendor=postgresql`(기본값이기도 하다) | Flyway, `db/migration/postgresql` | +| H2 | `.h2` | `app.persistence.vendor=h2` | Hibernate `ddl-auto`, 엔티티만 | -The outbox and idempotency features keep their pieces together, by feature and then by vendor: -`outbox/{jpa,postgresql,h2}` and `idempotency/{jpa,postgresql}`. The vendor configurations above still -decide which claim repository is registered. None of those feature classes imports a driver type, so -`PERSISTENCE_RDBMS_STAYS_VENDOR_NEUTRAL` still holds with them outside `.postgresql`. +outbox와 멱등성 기능은 기능별, 그다음 vendor별로 조각을 모아 둔다: `outbox/{jpa,postgresql,h2}`와 +`idempotency/{jpa,postgresql}`. 어떤 claim repository를 등록할지는 여전히 위 vendor 설정이 정한다. 그 기능 클래스 중 +driver 타입을 import하는 것이 없으므로, 그것들이 `.postgresql` 밖에 있어도 +`PERSISTENCE_RDBMS_STAYS_VENDOR_NEUTRAL`이 계속 지켜진다. -`config/PersistenceVendorSettings` binds the selector to an enum, so an unknown value fails at -startup instead of loading neither composition and surfacing as a missing `OutboxClaimRepository`. -The module states the choice: its `config/module-defaults/persistence-jpa.yml` defaults the vendor to -PostgreSQL and `spring.flyway.enabled` to `APP_FLYWAY_ENABLED` (true) for every profile; the composition -root's profile files no longer restate them (07-08). H2 is an explicit developer opt-out selected by -the `bootRunH2` task. `PersistenceVendorProdSafetyValidator` (`startup`) refuses H2 under prod -whatever property source supplies it. Under `bootRunH2` the idempotency provider must be `disabled` -or `redis`: the `postgresql` provider refuses an H2 data source at startup. +`config/PersistenceVendorSettings`가 선택자를 enum으로 바인딩한다. 그래서 모르는 값은 두 조립 중 어느 것도 읽지 않고 +`OutboxClaimRepository`가 없다는 오류로 나타나는 대신 기동 때 실패한다. 선택은 모듈이 정한다: 그 +`config/module-defaults/persistence-jpa.yml`이 모든 profile에서 vendor를 PostgreSQL로, `spring.flyway.enabled`를 +`APP_FLYWAY_ENABLED`(true)로 기본 설정한다. 조립 루트의 profile 파일은 더는 그것을 다시 적지 않는다(07-08). H2는 +`bootRunH2` 태스크가 고르는, 개발자가 명시해서 빠지는 길이다. `PersistenceVendorProdSafetyValidator`(`startup`)는 어떤 +속성 출처가 주든 prod에서 H2를 거절한다. `bootRunH2`에서는 멱등성 provider가 `disabled`나 `redis`여야 한다: +`postgresql` provider는 기동 때 H2 data source를 거절한다. -H2 is the local-development datastore, not a second production target. It has no migration tree, so -tables that exist only in migrations — capability schema registry, the Spring Integration lock table — do not exist under it. Vendor concurrency and migration -fidelity stay with `postgresqlIntegrationTest`. +H2는 로컬 개발 저장소이지 두 번째 운영 대상이 아니다. migration 트리가 없으므로, migration에만 있는 테이블 — +capability schema registry, Spring Integration lock 테이블 — 은 H2에 없다. vendor 동시성과 migration 충실도는 +`postgresqlIntegrationTest`에 남는다. -The outbox claim is the one vendor statement H2 runs, and it is identical — H2 2.4.240 accepts -`FOR UPDATE SKIP LOCKED` and genuinely skips locked rows, so the claim keeps its meaning. -`H2ClaimSqlTest` executes it against a real H2. H2 has no idempotency store. +outbox claim은 H2가 돌리는 유일한 vendor 문장이고 내용이 같다 — H2 2.4.240은 `FOR UPDATE SKIP LOCKED`를 받고 잠긴 행을 +정말 건너뛰므로 claim이 뜻을 지킨다. `H2ClaimSqlTest`가 그것을 실제 H2에 대고 실행한다. H2에는 멱등성 store가 없다. -### Capability-gated stores +### capability로 막은 store -Adapters that serve one optional capability carry that capability's switch, unlike the rest of this -module. The `fileserver` package is the current case: every `Jpa*` adapter there is annotated -`@ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true")`. +선택 capability 하나를 위한 어댑터는 이 모듈의 나머지와 달리 그 capability의 스위치를 단다. 지금은 `fileserver` +패키지가 그 경우다: 거기 있는 모든 `Jpa*` 어댑터는 +`@ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true")`를 단다. -Without the gate a composition root that merely includes this module builds those beans, and each of -them needs collaborators only the Fileserver configuration supplies. 지운 샘플 모듈이 쓰지도 않는 -Fileserver 협력 객체 때문에 기동에 실패한 일이 그 예다. A store for a capability nobody enabled -should not exist. +그 막음이 없으면 이 모듈을 넣기만 한 조립 루트도 그 bean을 만들고, 각 bean에는 파일 서버 설정만 주는 협력 객체가 +필요하다. 지운 샘플 모듈이 쓰지도 않는 Fileserver 협력 객체 때문에 기동에 실패한 일이 그 예다. 아무도 켜지 않은 +capability의 store는 있으면 안 된다. -## Allowed +## 허용 - `:application-core` - `:domain-core` - `:shared-contract` -- `:adapter:outbound:support` (typed startup failures, EnvironmentPostProcessor order, readiness - group, module-defaults loader) -- Spring Data JPA and Spring transaction. +- `:adapter:outbound:support`(타입 있는 기동 실패, EnvironmentPostProcessor 순서, readiness group, module-defaults 읽기) +- Spring Data JPA와 Spring transaction. -## Forbidden +## 금지 (Forbidden) -- `adapter-web`, `app-bootstrap`, or any outbound adapter other than `adapter:outbound:support`. -- Presentation DTOs. -- Business policy decisions. -- Use case orchestration hidden inside persistence adapters. -- Repository adapters opening `@Transactional` around application workflows — the application - use case owns cross-port transactions via `TransactionPort`. Adapter-local transactions are - allowed only when the port method itself defines a storage protocol that must be atomic (for - example durable-operation claim/read or live-event position allocation + insert). See - [application-core/CLAUDE.md](../../../application-core/CLAUDE.md)). -- **DB drivers** (`org.postgresql..`, `org.h2..`) or **`org.flywaydb.database.postgresql..`** — - those are vendor-specific and belong only in this module's matching vendor package (`.postgresql`, - `.h2`); NoSQL-specific dependencies belong only in their own future modules. - This is enforced by ArchUnit - `PERSISTENCE_RDBMS_STAYS_VENDOR_NEUTRAL` and `PERSISTENCE_RDBMS_STAYS_NEUTRAL_OF_H2` in - `CleanArchitectureTest`. -- NoSQL adapter code. MongoDB/Redis/DynamoDB adapters are sibling modules, not children of this module. -- Any sibling persistence or inbound/outbound adapter not allowed by the registry. +- `adapter-web`, `app-bootstrap`, `adapter:outbound:support`를 뺀 다른 outbound 어댑터. +- 표현 계층 DTO. +- 업무 정책 판단. +- 영속 어댑터 안에 숨긴 유스케이스 조율. +- repository 어댑터가 애플리케이션 흐름을 감싸 `@Transactional`을 여는 것 — 포트를 가로지르는 트랜잭션은 애플리케이션 + 유스케이스가 `TransactionPort`로 가진다. 어댑터 안의 트랜잭션은 포트 메서드 자체가 원자적이어야 하는 저장 프로토콜을 + 정할 때만 허용한다(예: durable operation claim·읽기, live event 위치 할당 + insert). + [application-core/CLAUDE.md](../../../application-core/CLAUDE.md)를 본다. +- **DB driver**(`org.postgresql..`, `org.h2..`)나 **`org.flywaydb.database.postgresql..`** — vendor 전용이라 이 모듈의 + 맞는 vendor 패키지(`.postgresql`, `.h2`)에만 둔다. NoSQL 전용 의존은 앞으로 생길 자기 모듈에만 둔다. + `CleanArchitectureTest`의 ArchUnit `PERSISTENCE_RDBMS_STAYS_VENDOR_NEUTRAL`과 `PERSISTENCE_RDBMS_STAYS_NEUTRAL_OF_H2`가 + 강제한다. +- NoSQL 어댑터 코드. MongoDB·Redis·DynamoDB 어댑터는 이 모듈의 자식이 아니라 이웃 모듈이다. +- registry가 허용하지 않은 이웃 영속 어댑터나 inbound·outbound 어댑터. -## TransactionPort implementation contract +## TransactionPort 구현 계약 -`SpringTransaction` pre-builds one `TransactionTemplate` per mode: +`SpringTransaction`은 모드마다 `TransactionTemplate`을 하나씩 미리 만든다: -| Mode | Propagation | Isolation | Read-only | Timeout | +| 모드 | 전파 | 격리 | 읽기 전용 | timeout | |---|---|---|---|---| -| `inWrite` | `REQUIRED` | `READ_COMMITTED` (pool) | `false` | `app.persistence-jpa.transaction.write-timeout` (30 s) | -| `inRootWrite` | `REQUIRED` | `READ_COMMITTED` (pool) | `false` | same as `inWrite` | -| `inRead` | `REQUIRED` | `READ_COMMITTED` (pool) | `true` | `app.persistence-jpa.transaction.read-timeout` (30 s) | -| `inNew` | `REQUIRES_NEW` | `READ_COMMITTED` (pool) | `false` | 30 s, fixed | +| `inWrite` | `REQUIRED` | `READ_COMMITTED`(pool) | `false` | `app.persistence-jpa.transaction.write-timeout`(30 s) | +| `inRootWrite` | `REQUIRED` | `READ_COMMITTED`(pool) | `false` | `inWrite`와 같음 | +| `inRead` | `REQUIRED` | `READ_COMMITTED`(pool) | `true` | `app.persistence-jpa.transaction.read-timeout`(30 s) | +| `inNew` | `REQUIRES_NEW` | `READ_COMMITTED`(pool) | `false` | 30 s, 고정 | -Isolation is pinned on the pool, not on the templates: the templates use -`ISOLATION_DEFAULT`, the module defaults set `spring.datasource.hikari.transaction-isolation: -TRANSACTION_READ_COMMITTED` (applied once per physical connection), and -`HikariPoolConstraintValidator` refuses to boot with any other level. Naming the level per template -made Spring call `getTransactionIsolation()` at every begin, which pgjdbc answers with a -`SHOW TRANSACTION ISOLATION LEVEL` round trip. +격리 수준은 template이 아니라 pool에 고정한다: template은 `ISOLATION_DEFAULT`를 쓰고, 모듈 기본값이 +`spring.datasource.hikari.transaction-isolation: TRANSACTION_READ_COMMITTED`를 정하며(물리 연결마다 한 번 적용), +`HikariPoolConstraintValidator`가 다른 수준이면 기동을 거절한다. template마다 수준을 대면 Spring이 begin마다 +`getTransactionIsolation()`을 부르고, pgjdbc는 그것에 `SHOW TRANSACTION ISOLATION LEVEL` 왕복으로 답했다. -Every mode is time-bounded (since 2026-11-01). Spring hands the remaining time to each statement, so a -slow query or lock wait is cancelled by the server (`57014` → `DB_QUERY_CANCELED`), and a deadline -that passed before the next statement gets the same code: Spring's `TransactionTimedOutException` -on the JDBC path, and on the JPA path (`JpaTransactionManager`, production) Hibernate's own -`TransactionException`, which has no SQLState and is classified because `SpringTransaction` knows -its deadline passed (`translateAfterDeadline`). A business exception thrown after -the deadline is passed on unchanged. +모든 모드에는 시간 한계가 있다(2026-11-01부터). Spring이 남은 시간을 문장마다 넘기므로 느린 query나 lock 대기는 서버가 +취소하고(`57014` → `DB_QUERY_CANCELED`), 다음 문장 전에 기한이 지난 경우도 같은 코드를 받는다: JDBC 경로에서는 Spring의 +`TransactionTimedOutException`, JPA 경로(`JpaTransactionManager`, 운영)에서는 Hibernate 자신의 `TransactionException`이다. +후자는 SQLState가 없고, `SpringTransaction`이 기한이 지났음을 알기 때문에 분류된다(`translateAfterDeadline`). 기한 뒤에 +던진 업무 예외는 바꾸지 않고 넘긴다. -Pre-built templates are immutable after construction so concurrent callers cannot -observe each other's reconfiguration. `inRootWrite` reuses the pre-built write template, -but first checks `TransactionSynchronizationManager.isActualTransactionActive()`. -When an actual ambient transaction exists it MUST throw -`NestedRootTransactionRejectedException` before invoking either the action or the -`PlatformTransactionManager`. It MUST NOT use `NEVER` or `REQUIRES_NEW`. +미리 만든 template은 만든 뒤 바뀌지 않아서, 동시 호출자가 서로의 재설정을 볼 수 없다. `inRootWrite`는 미리 만든 쓰기 +template을 다시 쓰지만, 먼저 `TransactionSynchronizationManager.isActualTransactionActive()`를 검사한다. 실제 바깥 +트랜잭션이 있으면 action이나 `PlatformTransactionManager`를 부르기 전에 반드시 +`NestedRootTransactionRejectedException`을 던진다. `NEVER`나 `REQUIRES_NEW`를 쓰면 안 된다. -`inRootWrite` returns its action value only after `TransactionTemplate.execute` has -committed. A commit failure propagates the transaction exception and no success value -is returned to the caller. +`inRootWrite`는 `TransactionTemplate.execute`가 커밋한 뒤에만 action 값을 돌려준다. 커밋이 실패하면 트랜잭션 예외를 +올리고 호출자에게 성공 값을 돌려주지 않는다. -### `inNew` pool-sizing constraint (feature-application-port-usecase-contract) +### `inNew` 풀 크기 제약 (feature-application-port-usecase-contract) -`REQUIRES_NEW` acquires a NEW physical JDBC connection while pinning the outer -transaction's connection. Provision the pool to satisfy: +`REQUIRES_NEW`는 바깥 트랜잭션의 연결을 쥔 채 새 물리 JDBC 연결을 얻는다. pool은 다음을 만족하게 잡는다: ``` hikari.maximumPoolSize >= (concurrent_threads × (1 + max_inNew_depth)) + 1 ``` -Loop-per-record `inNew` calls are forbidden (pool exhaustion + deadlock risk). -Batch records inside ONE `inNew`, or move the loop outside the transaction. +레코드마다 `inNew`를 부르는 반복문은 금지다(pool 고갈 + 교착 위험). 레코드를 `inNew` **하나** 안에서 묶어 처리하거나, +반복문을 트랜잭션 밖으로 뺀다. -## Persistence failure translation contract (feature-persistence-failure-baseline) +## 영속 실패 번역 계약 (feature-persistence-failure-baseline) -A raw Spring `DataAccessException` (and the JPA exception / SQLState / constraint name -inside it) must never reach the presentation layer. The -`failure/PersistenceExceptionTranslator` classifies a `DataAccessException` by its -SQLState against the §SQLState → Error Code Matrix and returns a -framework-neutral `shared.error.PersistenceFailureException` carrying one of the -`DB_*` `OperationalError` codes. +날것의 Spring `DataAccessException`(과 그 안의 JPA 예외·SQLState·제약 이름)은 절대 표현 계층에 닿으면 안 된다. +`failure/PersistenceExceptionTranslator`가 `DataAccessException`을 SQLState로 아래 §SQLState → 오류 코드 표와 대조해 +분류하고, `DB_*` `OperationalError` 코드 하나를 실은 프레임워크 중립 `shared.error.PersistenceFailureException`을 돌려준다. -**Standard rows (core):** +**표준 행(core):** | SQLState | code | category | http | retryable | |---|---|---|---|---| @@ -294,81 +258,66 @@ framework-neutral `shared.error.PersistenceFailureException` carrying one of the | `23505` | `DB_UNIQUE_VIOLATION` | `CONFLICT` | 409 | false | | `23514` | `DB_CHECK_VIOLATION` | `DATA_INTEGRITY` | 409 | false | -**Vendor-specific rows (contributed by vendor module via `SqlStateErrorMapping` SPI):** +**vendor 전용 행(vendor 모듈이 `SqlStateErrorMapping` SPI로 기여):** | SQLState | code | vendor | |---|---|---| -| `40P01` | `DB_DEADLOCK` | PostgreSQL (`.postgresql` package) | +| `40P01` | `DB_DEADLOCK` | PostgreSQL(`.postgresql` 패키지) | | `55P03` | `DB_LOCK_TIMEOUT` | PostgreSQL | | `25P03` | `DB_IDLE_IN_TX_TIMEOUT` | PostgreSQL | | `57014` | `DB_QUERY_CANCELED` | PostgreSQL | -| `57P01`, `57P02` | `DB_UNAVAILABLE` (before commit; completion-unknown during it) | PostgreSQL | -| `23513` | `DB_CHECK_VIOLATION` | H2 (`.h2` package) — H2 reports CHECK as 23513, not the standard 23514 the core table maps | -| `HYT00` | `DB_QUERY_CANCELED` | H2 — H2 collapses statement and lock timeout into one state | +| `57P01`, `57P02` | `DB_UNAVAILABLE`(커밋 전. 커밋 중이면 completion-unknown) | PostgreSQL | +| `23513` | `DB_CHECK_VIOLATION` | H2(`.h2` 패키지) — H2는 CHECK를 core 표가 대응시키는 표준 23514가 아니라 23513으로 알린다 | +| `HYT00` | `DB_QUERY_CANCELED` | H2 — H2는 문장 timeout과 lock timeout을 상태 하나로 합친다 | -The PostgreSQL rows are not a second table: before 2026-11-01 a hand-kept second table had already drifted. `PostgreSqlSqlStateErrorMapping` derives -them from `PostgreSqlFailureClassifier` (SQLState → `FailureCategory`) and -`FailureCategory.operationalError()` (category → code) — the same classification the library -`PostgreSqlExceptionTranslator` uses — leaving out the standard rows above, categories with no -specific code (`INTERNAL_ERROR`) and `COMPLETION_UNKNOWN` (phase-dependent). To add a PostgreSQL -state, add it to `PostgreSqlState` and the classifier; `SqlStateClassificationParityTest` fails if -the two paths disagree on any state. +PostgreSQL 행은 두 번째 표가 아니다: 2026-11-01 전에는 손으로 관리하던 두 번째 표가 이미 어긋나 있었다. +`PostgreSqlSqlStateErrorMapping`이 그 행을 `PostgreSqlFailureClassifier`(SQLState → `FailureCategory`)와 +`FailureCategory.operationalError()`(category → 코드)에서 끌어낸다 — 라이브러리 `PostgreSqlExceptionTranslator`가 쓰는 +것과 같은 분류다 — 그리고 위 표준 행, 전용 코드가 없는 category(`INTERNAL_ERROR`), `COMPLETION_UNKNOWN`(단계에 +따라 다르다)을 뺀다. PostgreSQL 상태를 더하려면 `PostgreSqlState`와 classifier에 더한다. 두 경로가 어떤 상태에서든 +다르면 `SqlStateClassificationParityTest`가 실패한다. -**No SQLState, classified by type:** a lost `@Version` race (`OptimisticLockingFailureException`, -JPA `OptimisticLockException`) → `DB_OPTIMISTIC_CONFLICT` (409); an expired Spring -transaction deadline (`TransactionTimedOutException`) → `DB_QUERY_CANCELED`; any other persistence -failure (JPA, Spring data-access or Spring transaction exception) of a transaction -`SpringTransaction` began, once its deadline has passed → `DB_QUERY_CANCELED`. +**SQLState가 없고 타입으로 분류:** 진 `@Version` 경쟁(`OptimisticLockingFailureException`, JPA +`OptimisticLockException`) → `DB_OPTIMISTIC_CONFLICT`(409). 만료된 Spring 트랜잭션 기한(`TransactionTimedOutException`) +→ `DB_QUERY_CANCELED`. `SpringTransaction`이 시작한 트랜잭션의 기한이 지난 뒤의 다른 영속 실패(JPA, Spring +data-access, Spring transaction 예외) → `DB_QUERY_CANCELED`. -**Commit phase (`translateCommitFailure`, ADR-JPA-003):** once the action has returned and -`SpringTransaction` is committing a write transaction it began, a failure with `08*`, `40003`, a -vendor-contributed termination state (`SqlStateErrorMapping.commitOutcomeUnknownStates()`: -PostgreSQL `57P01`, `57P02`) or a transport break with no SQLState becomes -`TransactionCompletionUnknownException` → `DB_COMPLETION_UNKNOWN` (500, never retryable), not -`DB_UNAVAILABLE`: the server may already have committed. A commit the server definitely rejected -(e.g. a deferred `23505`) keeps its row above; a read-only commit keeps `DB_UNAVAILABLE`. +**커밋 단계(`translateCommitFailure`, ADR-JPA-003):** action이 돌아왔고 `SpringTransaction`이 자기가 시작한 쓰기 +트랜잭션을 커밋하는 중이면, `08*`, `40003`, vendor가 기여한 종료 상태(`SqlStateErrorMapping.commitOutcomeUnknownStates()`: +PostgreSQL `57P01`, `57P02`), SQLState 없는 전송 끊김을 가진 실패는 `DB_UNAVAILABLE`이 아니라 +`TransactionCompletionUnknownException` → `DB_COMPLETION_UNKNOWN`(500, 절대 재시도하지 않음)이 된다: 서버가 이미 커밋했을 +수 있다. 서버가 분명히 거절한 커밋(예: 미뤄진 `23505`)은 위 자기 행을 지킨다. 읽기 전용 커밋은 `DB_UNAVAILABLE`을 지킨다. -- A repository adapter that catches a `DataAccessException` calls - `translator.translate(ex)` and rethrows the carrier (`ifPresent(e -> { throw e; })`); - an empty result means an unknown SQLState — rethrow the original so the web catch-all - answers a generic `INTERNAL` envelope (no leak). -- The category SSOT is the 10-value `Category` enum — there is **no** `PERSISTENCE` - category (design record §Audit CATEGORY_DRIFT). +- `DataAccessException`을 잡는 repository 어댑터는 `translator.translate(ex)`를 부르고 carrier를 다시 던진다 + (`ifPresent(e -> { throw e; })`). 빈 결과는 모르는 SQLState라는 뜻이다 — 원래 예외를 다시 던져 web catch-all이 일반 + `INTERNAL` envelope으로 답하게 한다(새는 것 없음). +- category 정본은 값 10개의 `Category` enum이다 — `PERSISTENCE` category는 **없다**(설계 기록 §Audit CATEGORY_DRIFT). -## Persistence auditing contract (feature-persistence-auditing-contract) +## 영속 감사 계약 (feature-persistence-auditing-contract) -Audit metadata (`created_at` / `updated_at` / `created_by` / `updated_by`) is an -infrastructure concern that must never reach `domain-core`. It lives only on the -`audit/AuditableEntity` `@MappedSuperclass`; a domain aggregate persistence entity opts in -by extending it (생성 명령이 만드는 서비스 persistence leaf의 엔티티가 그렇게 한다). The domain aggregate itself carries -zero audit fields, enforced by ArchUnit `domain_is_pure` (no `jakarta.persistence..`) plus -`domain_entities_do_not_carry_audit_fields` (no `createdAt`/`updatedAt`/`createdBy`/`updatedBy` -fields under `..domain..`). +감사 metadata(`created_at` / `updated_at` / `created_by` / `updated_by`)는 기반 관심사이고 `domain-core`에 닿으면 안 된다. +`audit/AuditableEntity` `@MappedSuperclass`에만 있다. 도메인 aggregate의 영속 엔티티가 그것을 상속해서 고른다(생성 +명령이 만드는 서비스 persistence leaf의 엔티티가 그렇게 한다). 도메인 aggregate 자체는 감사 필드를 하나도 갖지 않는다. +ArchUnit `domain_is_pure`(`jakarta.persistence..` 없음)와 `domain_entities_do_not_carry_audit_fields`(`..domain..` 아래에 +`createdAt`/`updatedAt`/`createdBy`/`updatedBy` 필드 없음)가 강제한다. -- **Capture = Manual explicit-set (current default).** The repository adapter - constructor-injects `Clock` and `AuditContextPort` and stamps audit on `save`: - INSERT (null version) → `initializeAudit(now, actor)`; UPDATE (non-null version) → - carry the persisted `created_*` forward + `applyModification(now, actor)`. - `created_*` is `updatable = false`. -- **Actor seam.** `AuditContextPort.currentActor()` reads the runtime-context-propagation - seam and falls back to `"system"` when no principal is bound (scheduler / Flyway / anonymous). - The actor's value semantics are owned by feature-authentication-authorization-contract - (UNSUPPORTED here); the type is fixed to `String`. -- **Excluded.** Infra/immutable entities such as `IdempotencyRecordEntity` (own - `created_at`, no `updated_at`) do NOT extend `AuditableEntity`. `version`/optimistic-lock - is owned by feature-persistence-failure-baseline / feature-transaction-concurrency-contract, - not by this audit base. -- **Growth path (deferred).** There is no second auditing implementation in the tree. If - manual stamping becomes too error-prone, migrate the canonical `AuditableEntity` contract - atomically to Spring Data listeners while preserving its `created_*`/`updated_*` schema, actor - bound, `Clock`, and `AuditContextPort` semantics. Bulk/native `@Query` UPDATEs bypass listeners - too, so they must continue to stamp audit columns explicitly. +- **잡기 = 손으로 명시해 넣기(지금 기본).** repository 어댑터가 생성자로 `Clock`과 `AuditContextPort`를 받고 `save`에서 + 감사 값을 넣는다: INSERT(version null) → `initializeAudit(now, actor)`. UPDATE(version 있음) → 저장된 `created_*`를 그대로 + 넘기고 + `applyModification(now, actor)`. `created_*`는 `updatable = false`다. +- **actor 이음매.** `AuditContextPort.currentActor()`는 runtime-context 전파 이음매를 읽고, principal이 묶여 있지 않으면 + (scheduler / Flyway / 익명) `"system"`으로 물러선다. actor 값의 뜻은 + feature-authentication-authorization-contract가 가진다(여기서는 UNSUPPORTED). 타입은 `String`으로 고정한다. +- **빠지는 것.** `IdempotencyRecordEntity`(자기 `created_at`, `updated_at` 없음) 같은 기반·불변 엔티티는 `AuditableEntity`를 + 상속하지 **않는다**. `version`·낙관적 lock은 이 감사 기반이 아니라 feature-persistence-failure-baseline / + feature-transaction-concurrency-contract가 가진다. +- **자랄 길(미룸).** 트리에 두 번째 감사 구현은 없다. 손으로 넣는 것이 실수가 너무 잦아지면, 정해진 `AuditableEntity` + 계약을 `created_*`/`updated_*` schema, actor 한계, `Clock`, `AuditContextPort` 뜻을 지키면서 한 번에 Spring Data + listener로 옮긴다. bulk·native `@Query` UPDATE도 listener를 지나지 않으므로 계속 감사 열을 명시해 넣어야 한다. -## MapStruct generated mapper exemption (feature-architecture-enforcement-rules) +## MapStruct 생성 mapper 예외 (feature-architecture-enforcement-rules) -If MapStruct is introduced for persistence mappers, the generated mapper class will -be annotated with `javax.annotation.processing.Generated`. Architecture rules that -forbid mapper boundary violations MUST exempt generated code via ArchUnit predicate: +영속 mapper에 MapStruct를 들이면, 생성된 mapper 클래스에 `javax.annotation.processing.Generated`가 붙는다. mapper 경계 +위반을 금지하는 아키텍처 규칙은 반드시 ArchUnit predicate로 생성 코드를 뺀다: ```java import javax.annotation.processing.Generated; @@ -379,21 +328,17 @@ classes() .should() /* ... boundary rule ... */; ``` -> Note the annotation FQN: MapStruct uses -> `javax.annotation.processing.Generated`. Spring AOT uses -> `org.springframework.aot.generate.Generated` — do **not** mix the two. The -> exemption MUST scope to the specific annotation expected for the build step -> being exempted. +> 애너테이션 FQN에 주의한다: MapStruct는 `javax.annotation.processing.Generated`를 쓴다. Spring AOT는 +> `org.springframework.aot.generate.Generated`를 쓴다 — 둘을 섞지 **않는다**. 예외는 반드시 빼려는 빌드 단계가 기대하는 +> 바로 그 애너테이션으로 범위를 잡는다. -Current ca-tmpl mappers are hand-written so no MapStruct exemption is wired into -ArchUnit yet — when generation is added, follow the predicate above and add a -red/green test using a fixture mapper. +지금 ca-tmpl mapper는 손으로 쓴 것이라 ArchUnit에 MapStruct 예외를 아직 배선하지 않았다 — 생성을 더할 때 위 +predicate를 따르고, fixture mapper로 red/green 시험을 더한다. -## NoSQL extension rule +## NoSQL 확장 규칙 -Do not create `adapter-persistence-nosql-core` preemptively. NoSQL stores have different -models and operational contracts. When a real MongoDB, Redis, or DynamoDB adapter is needed, -create a sibling module: +`adapter-persistence-nosql-core`를 미리 만들지 않는다. NoSQL 저장소는 모델과 운영 계약이 서로 다르다. 실제 MongoDB, +Redis, DynamoDB 어댑터가 필요해지면 이웃 모듈을 만든다: ```text adapter-persistence-mongodb @@ -401,10 +346,9 @@ adapter-persistence-redis adapter-persistence-dynamodb ``` -Such modules implement application/domain ports directly and must not depend on -`adapter:outbound:persistence-jpa`. +그런 모듈은 application·domain 포트를 직접 구현하고 `adapter:outbound:persistence-jpa`에 의존하면 안 된다. -## Test +## 테스트 ```bash cd src diff --git a/src/adapter/outbound/persistence-jpa/README.md b/src/adapter/outbound/persistence-jpa/README.md index 5f07bbd6..35815116 100644 --- a/src/adapter/outbound/persistence-jpa/README.md +++ b/src/adapter/outbound/persistence-jpa/README.md @@ -387,7 +387,7 @@ PUBLISHED backlog 를 한 transaction 으로 지우면 그 사이 모든 row loc cadence 측정 필요). retention 한 값은 reaper-local 이라 `@Value` 로 받지만, canonical 6-property 문서는 app-bootstrap `OutboxSettings` / `application.yml` 에 있다. -## JPA production capability candidate +## JPA 운영 capability 후보 `src/adapter/outbound/persistence-jpa/release/readiness-cards.yaml`이 capability와 독립 schema stream의 machine-readable SSOT다(개수는 registry가 소유한다). `selected` base card와 `implemented-candidate` reliability card를 @@ -420,7 +420,7 @@ Flyway의 PostgreSQL 마이그레이션 잠금은 트랜잭션이 아니라 세 자기 location/history table을 사용하고 non-empty schema adoption 때 version 0 baseline을 명시한 뒤 V1부터 실행한다. -| Capability | Location | History table | 상태 | +| capability | 위치 | history 테이블 | 상태 | |---|---|---|---| | core/adoption | `db/migration/jpa/core` | `flyway_jpa_core_history` | selected candidate | | idempotency | `db/migration/jpa/idempotency` | `flyway_jpa_idempotency_history` | implemented-candidate | diff --git a/src/adapter/outbound/persistence-mongo/CLAUDE.md b/src/adapter/outbound/persistence-mongo/CLAUDE.md index 3936e48c..c3110014 100644 --- a/src/adapter/outbound/persistence-mongo/CLAUDE.md +++ b/src/adapter/outbound/persistence-mongo/CLAUDE.md @@ -1,185 +1,157 @@ -# adapter:outbound:persistence-mongo — module rules +# adapter:outbound:persistence-mongo — 모듈 규칙 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-persistence-mongo` -- Gradle path: `:adapter:outbound:persistence-mongo` -- Focused test (derived from Gradle path): `./gradlew :adapter:outbound:persistence-mongo:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-outbound-persistence-mongo` +- Gradle 경로: `:adapter:outbound:persistence-mongo` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:outbound:persistence-mongo:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.outbound.mongo`. Driven (outbound) adapter — opt-in MongoDB -Document Persistence Platform. Design rationale lives in [README.md](README.md); the mapping from the -design package's assumed module layout onto this leaf lives in -`docs/mongodb/repository-adaptation.md` and is the file to update when that mapping changes. +패키지 루트: `dev.caskeleton.adapter.outbound.mongo`. driven(outbound) 어댑터 — 골라 쓰는 MongoDB 문서 영속 +플랫폼이다. 설계 근거는 [README.md](README.md)에 있다. 설계 패키지가 가정한 모듈 배치를 이 leaf에 대응시킨 것은 +`docs/mongodb/repository-adaptation.md`에 있고, 그 대응이 바뀌면 고칠 파일이 그것이다. -## Responsibility +## 책임 -- Provide the opt-in Mongo client, template and **platform policy** surface without shipping a fake - business domain. Real forks add their own document, repository, mapper, and application/domain port - implementation. -- It does **not** reimplement idempotency / outbox / lock on Mongo (those stay JPA-only). -- On when present: `MongoRootAutoConfiguration` and everything it imports run unless - `app.persistence-mongo.enabled=false` (`matchIfMissing = true`; the shipped - `config/mongo.yml` maps `APP_PERSISTENCE_MONGO_ENABLED`, default `true`). Absent from the build is - the ordinary off state. The connection URI and database come from Spring's standard - `spring.mongodb.*` settings; platform profiles come from - `app.persistence-mongo.platform.*`. - The connection source is fail-closed: either `spring.mongodb.uri` / - `SPRING_MONGODB_URI` is non-blank, or the selected typed profile supplies `uri-secret` and the - deployment supplies `MongoCredentialResolver`. The typed profile is not documentation-only: - `MongoProfileClientSettingsAutoConfiguration` applies `MongoClientSettingsFactory` to Boot's actual - `MongoClientSettings.Builder` at lowest precedence, so its TLS, Stable API, timeout and pool - policy overrides generic defaults. Without a typed profile (URI-only), - `MongoUriOnlyClientDefaults` applies finite socket/connect/server-selection timeouts and a pool - bound **before** Boot applies the connection string, so URI parameters still win; there is no - setting key of its own. -- Consumers: a service's own adapter leaf takes this leaf as `implementation`. The procedure is - `docs/mongodb/consumer-leaf-guide.md`; the worked example (document, mapper, repository, port - implementation) is the test-source package `…mongo.example`, run by `mongoStableContractTest`. -- `MongoDefaultsEnvironmentPostProcessor`, registered through `META-INF/spring.factories`, loads - `config/mongo.yml` at lowest precedence and, on an explicit `enabled=false`, appends Boot 4's - Mongo auto-configurations (read from Boot's own registration files) to - `spring.autoconfigure.exclude`. -- Two kinds of surface. Auto-configured beans (listed in README.md "자동 구성") turn on with - `enabled=true`. Everything else is **library API** (README.md "라이브러리 API"): a service's own - adapter leaf takes this leaf as `implementation` and constructs the type. Library API is not - registered as a bean and has no property of its own. -- Mongo health integration is leaf-owned. MongoRootAutoConfiguration imports the internal MongoPlatformHealthConfiguration, which adapts MongoPlatformHealthIndicator to Boot's HealthIndicator SPI under the stable bean name mongoPlatformHealthContributor. Application Actuator exposure policy still decides external endpoint exposure. +- 가짜 업무 도메인을 싣지 않고, 골라 쓰는 Mongo client, template, **플랫폼 정책** surface를 준다. 실제 fork가 자기 + 문서, repository, mapper, application·domain 포트 구현을 더한다. +- 멱등성·outbox·lock을 Mongo 위에 다시 구현하지 **않는다**(그것은 JPA에만 남는다). +- 있으면 켜진다: `app.persistence-mongo.enabled=false`가 아니면 `MongoRootAutoConfiguration`과 그것이 import하는 + 모든 것이 돈다(`matchIfMissing = true`. 출하하는 `config/mongo.yml`이 `APP_PERSISTENCE_MONGO_ENABLED`를 대응시키고 + 기본은 `true`). 빌드에 없는 것이 보통의 꺼진 상태다. 연결 URI와 데이터베이스는 Spring의 표준 `spring.mongodb.*` + 설정에서 오고, 플랫폼 profile은 `app.persistence-mongo.platform.*`에서 온다. + 연결 출처는 실패하면 닫힌다: `spring.mongodb.uri` / `SPRING_MONGODB_URI`가 비어 있지 않거나, 고른 typed profile이 + `uri-secret`을 주고 배포가 `MongoCredentialResolver`를 줘야 한다. typed profile은 문서용만이 아니다: + `MongoProfileClientSettingsAutoConfiguration`이 `MongoClientSettingsFactory`를 Boot의 실제 + `MongoClientSettings.Builder`에 가장 낮은 우선순위로 적용하므로, 그 TLS, Stable API, timeout, pool 정책이 일반 + 기본값을 덮는다. typed profile이 없으면(URI만) `MongoUriOnlyClientDefaults`가 Boot가 connection string을 적용하기 + **전에** 유한한 socket·connect·server selection timeout과 pool 한계를 적용하므로, URI 매개변수가 여전히 이긴다. + 자기 설정 키는 없다. +- 쓰는 쪽: 서비스 자신의 어댑터 leaf가 이 leaf를 `implementation`으로 받는다. 절차는 + `docs/mongodb/consumer-leaf-guide.md`다. 작동하는 예(문서, mapper, repository, 포트 구현)는 시험 소스 패키지 + `…mongo.example`이고, `mongoStableContractTest`가 돌린다. +- `META-INF/spring.factories`로 등록한 `MongoDefaultsEnvironmentPostProcessor`가 `config/mongo.yml`을 가장 낮은 + 우선순위로 읽고, 명시한 `enabled=false`이면 Boot 4의 Mongo 자동 구성(Boot 자신의 등록 파일에서 읽는다)을 + `spring.autoconfigure.exclude`에 붙인다. +- surface는 두 가지다. 자동 구성 bean(README.md 「자동 구성」에 적힌 것)은 `enabled=true`로 켜진다. 나머지는 모두 + **라이브러리 API**다(README.md 「라이브러리 API」): 서비스 자신의 어댑터 leaf가 이 leaf를 `implementation`으로 + 받아 타입을 만든다. 라이브러리 API는 bean으로 등록하지 않고 자기 속성이 없다. +- Mongo health 연동은 leaf가 가진다. MongoRootAutoConfiguration이 내부 MongoPlatformHealthConfiguration을 import하고, + 그것이 MongoPlatformHealthIndicator를 안정된 bean 이름 mongoPlatformHealthContributor 아래 Boot의 HealthIndicator + SPI에 맞춘다. 바깥 endpoint 노출은 여전히 애플리케이션 Actuator 노출 정책이 정한다. -## Allowed +## 허용 -- Two project dependencies. `shared-contract` for the `Sha256` and `HmacSha256` helpers (tenant - observable key, admin command digest, credential fingerprint, keyset cursor tag; - `MongoDigestOutputTest` pins the outputs). `application-core`, for - `SecretSourcePort` only. The registry entry's `allowed_dependencies` is - `["application-core", "shared-contract"]`, matching what the build actually uses; the - bridge in `MongoProfileClientSettingsAutoConfiguration` resolves a typed profile's `uri-secret` - through the deployment's configured secret backend. `verifyCleanArchitectureDependencies` only - checks that resolved edges are a subset of the declared ones, so an unused permission passes every - run; `MongoRegistryPermissionParityTest` checks the other direction and fails when the two sets - differ. -- A service selects the leaf with one commented-out line in `app-bootstrap/build.gradle`, - `runtimeOnly project(':adapter:outbound:persistence-mongo')`; the default composition does not - carry it. The leaf is imperative only: the reactive twin (`reactive/**`, reactive - transactions/sessions), the change-stream consumer and the change-stream-to-messaging bridge were - removed on 2026-09-25 (see `docs/capability-status.md`), so the leaf carries neither the reactive - starter nor the reactive-streams driver (`MongoReactiveDriverAbsenceTest`). -- External includes the (sync) Mongo starter, spring-boot-autoconfigure, spring-boot-health, micrometer-core, slf4j-api, and the configuration processor. Jackson annotations are compile-only because Boot Health carries Jackson annotations while runtime JSON serialization remains application-owned. - Versions come from the shared Spring Boot BOM; never pin the driver directly. -- Test-only: ArchUnit, Testcontainers (`mongodb`, `toxiproxy`). +- 프로젝트 의존 둘. `Sha256`과 `HmacSha256` 도우미를 위한 `shared-contract`(테넌트 관찰 키, admin 명령 digest, + credential fingerprint, keyset cursor tag. `MongoDigestOutputTest`가 출력을 고정한다). `SecretSourcePort`만을 위한 + `application-core`. registry 항목의 `allowed_dependencies`는 `["application-core", "shared-contract"]`이고 빌드가 + 실제로 쓰는 것과 맞는다. `MongoProfileClientSettingsAutoConfiguration`의 bridge가 typed profile의 `uri-secret`을 + 배포가 설정한 비밀 값 backend로 해석한다. `verifyCleanArchitectureDependencies`는 해석된 edge가 선언된 것의 + 부분집합인지만 보므로 쓰지 않는 허가는 매번 통과한다. `MongoRegistryPermissionParityTest`가 반대 방향을 보고 두 + 집합이 다르면 실패한다. +- 서비스는 `app-bootstrap/build.gradle`에서 주석 처리한 한 줄 + `runtimeOnly project(':adapter:outbound:persistence-mongo')`로 이 leaf를 고른다. 기본 조립은 싣지 않는다. leaf는 + imperative만이다: reactive 쌍둥이(`reactive/**`, reactive 트랜잭션·세션), change-stream 소비자, change-stream → + 메시징 bridge는 2026-09-25에 지웠다(`docs/capability-status.md`). 그래서 leaf는 reactive starter도 + reactive-streams driver도 싣지 않는다(`MongoReactiveDriverAbsenceTest`). +- 외부 의존: (sync) Mongo starter, spring-boot-autoconfigure, spring-boot-health, micrometer-core, slf4j-api, + configuration processor. Boot Health가 Jackson 애너테이션을 싣지만 런타임 JSON 직렬화는 애플리케이션의 몫이라서 + Jackson 애너테이션은 compile 전용이다. 버전은 공용 Spring Boot BOM에서 온다. driver 버전을 직접 고정하지 않는다. +- 시험 전용: ArchUnit, Testcontainers(`mongodb`, `toxiproxy`). -## Forbidden +## 금지 (Forbidden) -- Inbound adapters, sibling outbound adapters, `app-bootstrap` (ArchUnit - `OUTBOUND_ADAPTERS_*` family rules). -- Shipping placeholder `Example*` document, repository, record, or adapter types in production. -- Adding idempotency/outbox/lock on Mongo without a separately approved contract. -- Fully-qualified inline type references; more than one public top-level type per file. +- inbound 어댑터, 이웃 outbound 어댑터, `app-bootstrap`(ArchUnit `OUTBOUND_ADAPTERS_*` 규칙 묶음). +- 운영 코드에 자리표시용 `Example*` 문서, repository, record, 어댑터 타입을 싣기. +- 따로 승인된 계약 없이 Mongo 위에 멱등성·outbox·lock을 더하기. +- 줄 안에 완전한 이름으로 쓴 타입 참조, 파일 하나에 공개 최상위 타입 둘 이상. -### Package-boundary rules (`MongoModuleBoundaryTest`) +### 패키지 경계 규칙 (`MongoModuleBoundaryTest`) -These reproduce the design's module dependency table. Breaking one fails the build: +설계의 모듈 의존 표를 그대로 옮긴 것이다. 하나라도 어기면 빌드가 실패한다: -- `…mongo.api..` must not import Spring, the MongoDB driver, BSON or Reactor. It is the - framework-free core contract; `api/package-info.java` records why. -- No Stable package may depend on `…mongo.advanced..`. -- No production package may depend on `…mongo.testkit..`. -- `query` ↛ `aggregation`, `schema` ↛ execution packages, `observation` ↛ execution packages, - `migration` ↛ `migration.flamingock`. +- `…mongo.api..`는 Spring, MongoDB driver, BSON, Reactor를 import하지 않는다. 프레임워크 없는 핵심 계약이다. + `api/package-info.java`가 이유를 적는다. +- Stable 패키지는 `…mongo.advanced..`에 의존하지 않는다. +- 운영 패키지는 `…mongo.testkit..`에 의존하지 않는다. +- `query` ↛ `aggregation`, `schema` ↛ 실행 패키지, `observation` ↛ 실행 패키지, `migration` ↛ `migration.flamingock`. -### Consistency-bound templates +### 일관성에 묶인 template -`MongoConsistencyBinder` derives one `MongoTemplate` per consistency profile. Spring Data exposes -setters and no getters for a template's supporting contract, so the parts that must travel — -write-concern resolver, write-result checking, lifecycle events, and the `ApplicationContext` that -supplies entity callbacks and auditing — are passed explicitly as a `MongoTemplateSupportContract`. -Reflection over private fields is forbidden here. A template configured with callbacks registered -programmatically outside a context cannot be reproduced by the bound path; that configuration is -unsupported rather than silently dropped. +`MongoConsistencyBinder`는 일관성 profile마다 `MongoTemplate`을 하나 끌어낸다. Spring Data는 template의 지원 계약에 +setter만 내놓고 getter를 내놓지 않는다. 그래서 따라가야 하는 부분 — write-concern resolver, 쓰기 결과 검사, +lifecycle 이벤트, entity callback과 auditing을 주는 `ApplicationContext` — 을 `MongoTemplateSupportContract`로 명시해 +넘긴다. 여기서 private 필드에 대한 리플렉션은 금지다. context 밖에서 프로그램으로 callback을 등록한 template은 +묶인 경로로 다시 만들 수 없다. 그 설정은 소리 없이 버리지 않고 지원하지 않는 것으로 둔다. -### Public surface +### 공개 surface -Every public top-level type in one jar means `public` is public to every adopter regardless of which -package it sits in. `verifyMongoApiSurface` (in `check`) compares the surface against -`docs/architecture/mongo-api-surface.txt`, which carries the count; growing it takes -`updateMongoApiSurface -PapproveMongoApiSurfaceChange`, which is a review decision. +jar 하나 안의 모든 공개 최상위 타입이므로, `public`은 어느 패키지에 있든 모든 채택자에게 공개다. +`verifyMongoApiSurface`(`check` 안)가 surface를 개수를 담은 `docs/architecture/mongo-api-surface.txt`와 비교한다. +늘리려면 `updateMongoApiSurface -PapproveMongoApiSurfaceChange`가 필요하고, 그것은 리뷰 결정이다. -The architecture rule catalogue (`…mongo.architecture`) is in the **testkit** source set, not -production: it is ArchUnit input, and shipping it put rule text on every consumer's runtime -classpath. Release gating is testkit-only for the same reason and is one implementation, not two: -`…mongo.testkit.release` reads the JUnit XML a lane wrote and is what -`scripts/verify-mongodb-platform.sh` and `src/adapter/outbound/persistence-mongo/release/release-contracts.json` drive. A second -pair on the production classpath — a hand-built set of category names and a gate that checked it — -had no caller outside its own test and no source of truth behind the categories; it is gone rather -than moved. +아키텍처 규칙 catalog(`…mongo.architecture`)는 운영이 아니라 **testkit** source set에 있다: ArchUnit 입력이고, 그것을 +싣으면 모든 쓰는 쪽의 runtime classpath에 규칙 글이 올라갔다. 같은 이유로 릴리스 gate도 testkit 전용이고, 구현은 +둘이 아니라 하나다: `…mongo.testkit.release`가 lane이 쓴 JUnit XML을 읽고, `scripts/verify-mongodb-platform.sh`와 +`src/adapter/outbound/persistence-mongo/release/release-contracts.json`이 그것을 돌린다. 운영 classpath에 있던 두 번째 +짝 — 손으로 만든 category 이름 집합과 그것을 검사한 gate — 은 자기 시험 말고는 호출자가 없었고 category 뒤에 정본도 +없었다. 옮기지 않고 없앴다. -Still pending, and deliberately not done as part of a review sweep: moving implementation packages -under an `internal` root and lowering visibility inside them. That is a mechanical change over ~200 -files and belongs in its own commit, after which the snapshot above is what proves the surface -actually shrank. +아직 남았고, 리뷰 정리의 일부로 일부러 하지 않은 것: 구현 패키지를 `internal` 루트 아래로 옮기고 그 안의 가시성을 +낮추는 일. 약 200개 파일에 걸친 기계적 변경이라 자기 커밋에 둔다. 그 뒤에는 위 snapshot이 surface가 실제로 +줄었다는 증거가 된다. -### Credentials and production profiles +### credential과 운영 profile -A production `MongoProfileProperties` must declare TLS, authentication, strict Stable API, a -non-standalone topology and finite positive timeouts; `validate()` enforces all of them. The URI is a -`secret://` reference and `MongoCredentialResolver` is the only thing that turns one into a -connection string — it hands the value to a caller-supplied function and never returns it, so the -credential is a local for one call rather than a field, a bean property or a log line. +운영 `MongoProfileProperties`는 TLS, 인증, 엄격한 Stable API, standalone이 아닌 topology, 유한한 양의 timeout을 +선언해야 한다. `validate()`가 그것을 모두 강제한다. URI는 `secret://` 참조이고, 그것을 connection string으로 바꾸는 +것은 `MongoCredentialResolver`뿐이다 — 값을 호출자가 준 함수에 넘기고 돌려주지 않으니, credential은 필드나 bean +속성이나 로그 줄이 아니라 호출 한 번의 지역 변수다. -When `platform.profiles` is non-empty, adoption is intentionally fail-closed. In one composition -change provide the data-plane `MongoCredentialResolver` plus `MongoTopologyProbe`, -`MongoSecurityProfile`, admin `MongoCredentialReference`, and `MongoSchemaVersionRange`; README.md -contains the complete 14-field production profile example. Supplying profiles piecemeal and -discovering these requirements one startup failure at a time is not an accepted adoption path. +`platform.profiles`가 비어 있지 않으면 채택은 일부러 실패하면 닫힌다. 조립 변경 하나에서 데이터 plane +`MongoCredentialResolver`와 함께 `MongoTopologyProbe`, `MongoSecurityProfile`, admin `MongoCredentialReference`, +`MongoSchemaVersionRange`를 준다. README.md에 필드 14개짜리 운영 profile 예가 다 있다. profile을 조금씩 주며 그 +요구를 기동 실패 하나씩으로 알아내는 것은 받아들인 채택 길이 아니다. -The default resolver is a bridge over `SecretSourcePort` (`MongoCredentialResolver.fromSecretSource`, -registered when that port has a bean and no other resolver exists); the key is the reference's last -path segment, as in the Redis and HTTP client modules. Not shipped: the TLS lane -(trusted CA, wrong CA, hostname mismatch, expired certificate) which needs a container with real -certificates. Rotation ordering — new generation ready, traffic switch, old lease drain, close — is -covered by `MongoClientGenerationConcurrencyTest`. +기본 resolver는 `SecretSourcePort` 위의 bridge다(`MongoCredentialResolver.fromSecretSource`. 그 포트에 bean이 있고 +다른 resolver가 없을 때 등록한다). 키는 Redis·HTTP client 모듈처럼 참조의 마지막 경로 조각이다. 싣지 않은 것: +실제 인증서를 가진 container가 필요한 TLS lane(믿는 CA, 틀린 CA, hostname 불일치, 만료된 인증서). 교체 순서 — 새 +generation 준비, traffic 전환, 옛 lease 비우기, 닫기 — 는 `MongoClientGenerationConcurrencyTest`가 덮는다. -### Platform invariants that are not stylistic +### 문체가 아닌 플랫폼 불변식 -- Transaction body retry and commit retry are **separate loops**: a new session per body attempt, and - commit-only retry on an unknown commit. The body is never replayed after a commit ambiguity - (`MongoTransactionRetryCoordinator`, ADR-MONGO-003). -- `MongoExecutionOutcome`'s two ambiguous values must not be collapsed into success or failure. -- BSON representations come from `MongoTypeRepresentationManifest`, never from a library default - (ADR-MONGO-002). -- Index and validator changes go through the manifest and the admin plane; ownership gates every drop - (ADR-MONGO-004). -- Every concrete Advanced type is annotated `@MongoAdvancedEntryPoint(capability)` or - `@MongoAdvancedPolicy`, and an entry point takes a `MongoAdvancedCapabilityGuard` and calls - `require` before it exists. `MongoAdvancedRules` enforces both halves; the classification rule is - what keeps "we gate the executable ones" from meaning "the ones somebody remembered". -- The flags have no configuration property. The Advanced types are library API: the adopter's - adapter builds `MongoAdvancedCapabilityFlags` and the guard in code. The Stable auto-configuration - must reference nothing under `..advanced..`. -- Every setting key this leaf binds must change behaviour. A key that nothing reads, or one whose - only effect is to fail startup, is deleted rather than documented (AGENTS.md capability rule 3); - `docs/capability-status.md` records what was removed and why. -- An interface ships only with an implementation in this leaf. Search, vector, time series and - GridFS were contract-only and were removed on 2026-09-25. -- Observation tags are limited to `MongoObservationConvention`'s allowlist. +- 트랜잭션 본문 재시도와 커밋 재시도는 **따로 도는 반복문**이다: 본문 시도마다 새 세션, 모르는 커밋에는 커밋만 + 재시도. 커밋이 모호해진 뒤에는 본문을 다시 돌리지 않는다(`MongoTransactionRetryCoordinator`, ADR-MONGO-003). +- `MongoExecutionOutcome`의 모호한 값 둘을 성공이나 실패로 뭉개면 안 된다. +- BSON 표현은 라이브러리 기본값이 아니라 `MongoTypeRepresentationManifest`에서 온다(ADR-MONGO-002). +- index와 validator 변경은 manifest와 admin plane을 거친다. 모든 drop은 소유권이 막는다(ADR-MONGO-004). +- 모든 구체 Advanced 타입은 `@MongoAdvancedEntryPoint(capability)`나 `@MongoAdvancedPolicy`를 단다. entry point는 + `MongoAdvancedCapabilityGuard`를 받고, 존재하기 전에 `require`를 부른다. `MongoAdvancedRules`가 두 절반을 강제한다. + 「실행되는 것은 막는다」가 「누가 기억해 낸 것은 막는다」가 되지 않게 하는 것이 분류 규칙이다. +- flag에는 설정 속성이 없다. Advanced 타입은 라이브러리 API다: 채택자의 어댑터가 코드로 + `MongoAdvancedCapabilityFlags`와 guard를 만든다. Stable 자동 구성은 `..advanced..` 아래의 어떤 것도 참조하면 안 + 된다. +- 이 leaf가 바인딩하는 모든 설정 키는 동작을 바꿔야 한다. 아무것도 읽지 않는 키나, 효과가 기동 실패뿐인 키는 + 문서로 남기지 않고 지운다(AGENTS.md capability 규칙 3). `docs/capability-status.md`가 무엇을 왜 지웠는지 적는다. +- 인터페이스는 이 leaf 안에 구현이 있을 때만 싣는다. Search, vector, time series, GridFS는 계약만 있었고 + 2026-09-25에 지웠다. +- observation tag는 `MongoObservationConvention`의 허용 목록으로 제한한다. -## Tests +## 테스트 -`MongoCapabilityActivationTest` boots a real `SpringApplication` and proves present = on and an -explicit `enabled=false` = no client, template or platform bean (Boot's Mongo auto-configuration -included). `MongoPersistenceConfigTest` covers typed enablement binding and enabled infrastructure -with a mock `MongoClient` plus a real `MongoTemplate` without a network connection. +`MongoCapabilityActivationTest`는 실제 `SpringApplication`을 띄워 있음 = 켜짐, 명시한 `enabled=false` = client· +template·플랫폼 bean 없음(Boot의 Mongo 자동 구성 포함)을 증명한다. `MongoPersistenceConfigTest`는 타입 있는 켜기 +바인딩과, 네트워크 연결 없이 mock `MongoClient`와 실제 `MongoTemplate`으로 켜진 기반을 덮는다. -Hermetic contract tests carry `@Tag("mongodb-contract")` and run in `mongoStableContractTest`, which -`check` depends on. Container lanes carry `mongodb-replicaset` / `mongodb-failover` and run only in -their own tasks; the default `test` task excludes them, because a lane that needs Docker inside -`check` teaches people to skip `check`. +밀폐된 계약 시험은 `@Tag("mongodb-contract")`를 달고 `check`가 의존하는 `mongoStableContractTest`에서 돈다. container +lane은 `mongodb-replicaset` / `mongodb-failover`를 달고 자기 태스크에서만 돈다. 기본 `test` 태스크는 그것을 뺀다. +`check` 안에 Docker가 필요한 lane이 있으면 사람들이 `check`를 건너뛰게 되기 때문이다. ```bash cd src ./gradlew :adapter:outbound:persistence-mongo:check --console=plain ``` -Release gates run from the repository root: `scripts/verify-mongodb-platform.sh` (Stable) and -`scripts/verify-mongodb-advanced.sh` (Advanced). +릴리스 gate는 저장소 루트에서 돈다: `scripts/verify-mongodb-platform.sh`(Stable)와 +`scripts/verify-mongodb-advanced.sh`(Advanced). diff --git a/src/adapter/outbound/persistence-notification/CLAUDE.md b/src/adapter/outbound/persistence-notification/CLAUDE.md index 156c57c2..9a34f725 100644 --- a/src/adapter/outbound/persistence-notification/CLAUDE.md +++ b/src/adapter/outbound/persistence-notification/CLAUDE.md @@ -1,57 +1,52 @@ -# adapter:outbound:persistence-notification — notification relational persistence +# adapter:outbound:persistence-notification — 알림 관계형 영속 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-persistence-notification`; Gradle path and allowed edges are in - `src/config/architecture/modules.json`. -- Focused test: `./gradlew :adapter:outbound:persistence-notification:test --console=plain`. -- Package root: `dev.caskeleton.adapter.outbound.persistence.notification`. The package rule is - the one `persistence-fileserver` uses, so both capability leaves read the same way: - - `platform.entity` — JPA rows only. - - `platform.repository` — Spring Data interfaces and the SQL text they run (`RecipientClaimSql`). - - `platform` — the store adapters (`Jpa*`, `Jdbc*`, the inbox's `JpaNotificationInbox` and its - outbox helpers), `NotificationRecordMapper` and the payload codec. - - `configuration` — the auto-configuration facade that registers the stores as beans; the leaf - root holds the scan configuration and the schema stream. - Entity constructors, accessors and mutators are public because the stores use them from another - package; an entity never leaves the leaf (the ports carry records). Visibility no longer says so, - so a rule does: `JpaArchitectureRules.entitiesAreUsedOnlyInsideTheirLeaf`, run over the production - graph by `JpaProductionArchitectureTest` (app-bootstrap `architectureTest`) for this leaf and - `persistence-fileserver`. +- 모듈 ID: `adapter-outbound-persistence-notification`. Gradle 경로와 허용 edge는 + `src/config/architecture/modules.json`에 있다. +- 이 모듈만 시험: `./gradlew :adapter:outbound:persistence-notification:test --console=plain`. +- 패키지 루트: `dev.caskeleton.adapter.outbound.persistence.notification`. 패키지 규칙은 + `persistence-fileserver`와 같아서 두 capability leaf를 같은 방식으로 읽는다: + - `platform.entity` — JPA 행만. + - `platform.repository` — Spring Data 인터페이스와 그것이 돌리는 SQL 글(`RecipientClaimSql`). + - `platform` — store 어댑터(`Jpa*`, `Jdbc*`, inbox의 `JpaNotificationInbox`와 그 outbox 도우미), + `NotificationRecordMapper`, payload codec. + - `configuration` — store를 bean으로 등록하는 자동 구성 창구. leaf 루트에는 scan 설정과 schema stream이 있다. + 엔티티 생성자·접근자·변경자는 store가 다른 패키지에서 쓰니 public이다. 엔티티는 leaf를 떠나지 않는다(포트는 + record를 싣는다). 가시성이 더는 그것을 말해 주지 않으므로 규칙이 말한다: + `JpaArchitectureRules.entitiesAreUsedOnlyInsideTheirLeaf`를 `JpaProductionArchitectureTest`(app-bootstrap + `architectureTest`)가 운영 그래프에 대고 이 leaf와 `persistence-fileserver`에 돌린다. -## Where the tests are +## 시험은 어디 있나 -| What | Where | Run | +| 무엇 | 어디 | 돌리기 | |---|---|---| -| Unit and wiring tests | this leaf, `src/test` | `:adapter:outbound:persistence-notification:test` | -| Real PostgreSQL tests of these stores | `persistence-jpa`, `src/postgresqlIntegrationTest/.../persistence/notification` (that lane owns the container and Flyway wiring) | `:adapter:outbound:persistence-jpa:postgresqlIntegrationTest --tests ''` | -| Port contracts the stores must pass | `application-notification` testFixtures, `*.testkit.*Contract` (preference, suppression, deduplication, request, reconciliation job, admin operation, template registry, recipient lease, recipient delivery, delivery attempt, attempt resolver, delivery projection, provider event ledger, contact point, and the side effect over the contact point and suppression stores) | the in-memory fake (`application-notification` test) and the `PostgreSql*ContractTest` in `persistence-jpa` both extend the contract; `jpaPlatformContractTest` runs the PostgreSQL side | -| Migration pins | `persistence-jpa/src/test/resources/db/applied-migrations.sha256` | `AppliedMigrationImmutabilityTest` in `:adapter:outbound:persistence-jpa:test` | +| 단위·배선 시험 | 이 leaf, `src/test` | `:adapter:outbound:persistence-notification:test` | +| 이 store들의 실제 PostgreSQL 시험 | `persistence-jpa`, `src/postgresqlIntegrationTest/.../persistence/notification`(그 lane이 container와 Flyway 배선을 가진다) | `:adapter:outbound:persistence-jpa:postgresqlIntegrationTest --tests ''` | +| store가 통과해야 하는 포트 계약 | `application-notification` testFixtures, `*.testkit.*Contract`(preference, suppression, deduplication, request, reconciliation job, admin operation, template registry, recipient lease, recipient delivery, delivery attempt, attempt resolver, delivery projection, provider event ledger, contact point, 그리고 contact point·suppression store 위의 부수 효과) | 메모리 fake(`application-notification` 시험)와 `persistence-jpa`의 `PostgreSql*ContractTest`가 모두 계약을 상속한다. PostgreSQL 쪽은 `jpaPlatformContractTest`가 돌린다 | +| migration 고정 | `persistence-jpa/src/test/resources/db/applied-migrations.sha256` | `:adapter:outbound:persistence-jpa:test`의 `AppliedMigrationImmutabilityTest` | -A store whose port has a contract in `application-notification` testFixtures is tested by a -PostgreSQL subclass of that contract, not by a separate hand-written PostgreSQL test. A case that is -about the vendor (a CHECK constraint, `@Version` on a bulk update) stays in the subclass. The ports -without a contract (the serving-state read model, consent, inbox), and why, are listed in -`docs/testing/TESTING_STRATEGY.md` §9.2. +`application-notification` testFixtures에 계약이 있는 포트의 store는 따로 손으로 쓴 PostgreSQL 시험이 아니라 +그 계약의 PostgreSQL 하위 클래스로 시험한다. vendor에 관한 경우(CHECK 제약, bulk update의 `@Version`)는 하위 +클래스에 남긴다. 계약이 없는 포트(serving-state 읽기 모델, 동의, inbox)와 그 이유는 +`docs/testing/TESTING_STRATEGY.md` 9.2절에 있다. -## Rules +## 규칙 -- **Every write joins the caller's transaction.** A store write starts with - `CallerTransaction.require("")`; the use case owns the transaction (owner decision 2026-09-25). -- **Migrations** live in `src/main/resources/db/migration/jpa/notification-platform` and run as - their own Flyway stream (`NotificationSchemaStream`, history table - `flyway_jpa_notification_history`). An applied file is never edited: add the next `V__`, pin - its SHA-256 in `applied-migrations.sha256`, and add it to `NotificationFixtures.migrations()`. - A migration that deletes rows states in a SQL comment which row survives and why. A migration - that locks an existing table starts with `SET LOCAL lock_timeout = '5s';` - (`docs/jpa/migration-guide.md` "Bound the lock wait"; `MigrationLockWaitTest` in persistence-jpa - refuses one without it). -- **Insert-or-update is decided by the database.** Never find-then-insert: insert with - `ON CONFLICT () DO NOTHING`, and when it inserted nothing, update the existing row - through the managed entity (`JpaSuppressionStore.upsert`, `JpaPolicyStores.Preferences.save`, - `DeduplicationClaims.insertOrFind`). The conflict target needs a unique constraint in a migration. -- **A bulk or native `UPDATE` of a `@Version` table advances the version** (`version = version + 1`) - and is `@Modifying(clearAutomatically = true, flushAutomatically = true)` when the caller may - re-read the row. `JpaVersionedBulkUpdateRule` (persistence-jpa testFixtures) enforces the - version part in `:app-bootstrap:architectureTest`. -- Repositories extend `Repository`, not `CrudRepository`, and expose only tenant-scoped finders. +- **모든 쓰기는 호출자의 트랜잭션에 합류한다.** store 쓰기는 `CallerTransaction.require("")`로 + 시작한다. 트랜잭션은 유스케이스가 가진다(소유자 결정 2026-09-25). +- **migration**은 `src/main/resources/db/migration/jpa/notification-platform`에 있고 자기 Flyway stream + (`NotificationSchemaStream`, history 테이블 `flyway_jpa_notification_history`)으로 돈다. 적용한 파일은 고치지 + 않는다: 다음 `V__`를 더하고, 그 SHA-256을 `applied-migrations.sha256`에 고정하고, + `NotificationFixtures.migrations()`에 더한다. 행을 지우는 migration은 어떤 행이 남고 왜인지 SQL 주석에 + 적는다. 이미 있는 테이블을 잠그는 migration은 `SET LOCAL lock_timeout = '5s';`로 시작한다 + (`docs/jpa/migration-guide.md` "Bound the lock wait". persistence-jpa의 `MigrationLockWaitTest`가 그것이 없는 + migration을 거절한다). +- **insert냐 update냐는 데이터베이스가 정한다.** 찾은 뒤 insert하지 않는다: `ON CONFLICT () DO + NOTHING`으로 insert하고, 아무것도 insert하지 않았으면 관리되는 엔티티로 있는 행을 update한다 + (`JpaSuppressionStore.upsert`, `JpaPolicyStores.Preferences.save`, `DeduplicationClaims.insertOrFind`). 충돌 + 대상에는 migration에 unique 제약이 있어야 한다. +- **`@Version` 테이블의 bulk·native `UPDATE`는 version을 올린다**(`version = version + 1`). 호출자가 그 행을 다시 + 읽을 수 있으면 `@Modifying(clearAutomatically = true, flushAutomatically = true)`다. version 부분은 + `JpaVersionedBulkUpdateRule`(persistence-jpa testFixtures)이 `:app-bootstrap:architectureTest`에서 강제한다. +- repository는 `CrudRepository`가 아니라 `Repository`를 상속하고, 테넌트 범위의 finder만 내놓는다. diff --git a/src/adapter/outbound/redis-sdk/README.md b/src/adapter/outbound/redis-sdk/README.md index cf641d16..84ff69be 100644 --- a/src/adapter/outbound/redis-sdk/README.md +++ b/src/adapter/outbound/redis-sdk/README.md @@ -1,35 +1,31 @@ -# adapter:outbound:redis-sdk — typed Redis SDK (library) +# adapter:outbound:redis-sdk — 타입 있는 Redis SDK (라이브러리) -A guarded, typed Redis API for service code that needs Redis data structures directly, beyond the -semantic ports `cache-redis` implements (cache, rate limit, lease, idempotency). +`cache-redis`가 구현하는 semantic 포트(cache, rate limit, lease, 멱등성)를 넘어 Redis 자료 구조를 직접 써야 하는 +서비스 코드를 위한, 보호 장치가 있는 타입 있는 Redis API다. -It is a **library, not a capability**. Nothing turns on because this leaf is on the classpath: it -has no `AutoConfiguration.imports`, creates no beans, and has no `enabled` switch of its own. Service -code calls its types directly, so it cannot be taken as `runtimeOnly` (AGENTS.md, library-type -exception to the capability rules). +**capability가 아니라 라이브러리다.** 이 leaf가 classpath에 있다고 켜지는 것은 없다: `AutoConfiguration.imports`가 +없고, bean을 만들지 않고, 자기 `enabled` 스위치가 없다. 서비스 코드가 그 타입을 직접 부르므로 `runtimeOnly`로 +받을 수 없다(AGENTS.md, capability 규칙의 라이브러리 타입 예외). -## Adding it +## 더하기 -In the service's own outbound adapter leaf — never in `domain-core` or `application-core`: +서비스 자신의 outbound 어댑터 leaf에 더한다 — `domain-core`나 `application-core`에는 더하지 않는다: ```groovy implementation project(':adapter:outbound:redis-sdk') ``` -`redis-runtime` comes with it: the SDK's public types extend and return runtime types -(`SemanticRedisCommands`, `RedisLaneContribution`, …), so the SDK declares the runtime as `api`. -The SDK itself also uses `shared-contract` (`HmacSha256` for permit signatures, review 2026-11-01 -01-11) as an `implementation` edge; a consumer does not see it. Register both edges in that leaf's -`allowed_dependencies` in -`src/config/architecture/modules.json` (HARD-STOP 5). Put the adapter behind an application-core -port, as for any other outbound capability. +`redis-runtime`이 함께 온다: SDK의 공개 타입이 runtime 타입(`SemanticRedisCommands`, `RedisLaneContribution`, …)을 +상속하고 돌려주므로 SDK는 runtime을 `api`로 선언한다. SDK 자신은 `shared-contract`(허가 서명용 `HmacSha256`, +review 2026-11-01 01-11)도 `implementation` edge로 쓴다. 쓰는 쪽에는 보이지 않는다. 두 edge 모두 그 leaf의 +`src/config/architecture/modules.json` `allowed_dependencies`에 등록한다(HARD-STOP 5). 다른 outbound capability와 +같이 어댑터를 application-core 포트 뒤에 둔다. -The connections come from `redis-runtime` (package `...cache.redis.runtime`, which knows nothing of -this SDK): its `RedisRuntimeAutoConfiguration` exists only while `APP_REDIS_ENABLED=true` and -provides `RedisRuntimeOwner`, which pools the runtime's own lanes (`REGULAR`, `SCRIPT`). The SDK's -blocking, transaction and admin lanes (`RedisSdkLane`) and its admin account are the SDK's: the -service contributes them to the runtime as beans, one per lane it uses, through -`RedisSdkComposition` — +연결은 `redis-runtime`(패키지 `...cache.redis.runtime`. 이 SDK를 모른다)에서 온다: 그 +`RedisRuntimeAutoConfiguration`은 `APP_REDIS_ENABLED=true`인 동안에만 있고, runtime 자신의 lane(`REGULAR`, +`SCRIPT`)을 pool로 두는 `RedisRuntimeOwner`를 준다. SDK의 blocking·transaction·admin lane(`RedisSdkLane`)과 그 +admin 계정은 SDK의 것이다: 서비스가 쓰는 lane마다 하나씩, `RedisSdkComposition`을 거쳐 bean으로 runtime에 +기여한다 — ```java @Bean RedisLaneContribution redisBlockingLane() { return RedisSdkComposition.blockingLane(32); } @@ -45,67 +41,62 @@ service contributes them to the runtime as beans, one per lane it uses, through } ``` -— and builds `LettuceRedisCommandGateway.over(lease.driver())` over a borrowed lease. The last bean -matters only with an admin account: under `prod`, `SecretSourceValidator` refuses a secret that holds -a lane fixture password (`fixture-admin` is in `compose/redis/acl`), but it learns which variables -are secrets from the registry, from `secret://` references in the environment and from -`RequiredProductionSecrets` beans — not from a reference held in code. Without the bean the admin -account could run in production on the public lane password (review 2026-11-04 RR3-04-03). The SDK -cannot contribute it itself: it depends on `redis-runtime` and `shared-contract` only. The service's -adapter composes the SDK objects it uses on top of that; `LiveRedisOperationsFixture` in this leaf's -tests is a complete worked composition (catalog, permit verifier, guard, executor, operations). +— 그리고 빌린 lease 위에 `LettuceRedisCommandGateway.over(lease.driver())`를 만든다. 마지막 bean은 admin 계정이 +있을 때만 뜻이 있다: `prod`에서 `SecretSourceValidator`는 lane fixture 비밀번호(`fixture-admin`은 +`compose/redis/acl`에 있다)를 가진 비밀 값을 거절한다. 하지만 어떤 변수가 비밀 값인지는 registry, 환경 안의 +`secret://` 참조, `RequiredProductionSecrets` bean에서 배운다 — 코드가 쥔 참조에서는 배우지 않는다. 그 bean이 +없으면 admin 계정이 공개된 lane 비밀번호로 운영에서 돌 수 있었다(review 2026-11-04 RR3-04-03). SDK는 그 bean을 +스스로 기여할 수 없다: `redis-runtime`과 `shared-contract`에만 의존한다. 서비스의 어댑터가 그 위에 자기가 쓰는 +SDK 객체를 조립한다. 이 leaf 시험의 `LiveRedisOperationsFixture`가 완전한 조립 예다(catalog, 허가 검증기, guard, +executor, operations). -## What it provides +## 주는 것 -| Package (`dev.caskeleton.adapter.outbound.cache.redis.sdk.*`) | Contents | +| 패키지 (`dev.caskeleton.adapter.outbound.cache.redis.sdk.*`) | 내용 | | --- | --- | -| `api.key` | typed keys (`ValueKey`, `HashKey`, `ListKey`, `SetKey`, `SortedSetKey`, `StreamKey`, `BitmapKey`, `GeoKey`, `HyperLogLogKey`), `TypedRedisKeys`, `RedisKeyRenderer`, `RedisSlotTag` | -| `api.operations` / `api.reactive` | per-structure operation interfaces, synchronous and Reactor: value, hash, hash-field expiration, list, blocking list, set, sorted set, bitmap, bitfield, HyperLogLog, geo, stream, blocking stream, stream deletion, key, batch. No pub/sub: the SDK has no subscription transport, and the catalog blocks those commands | -| `api.command`, `api.codec`, `api.error` | `OperationBudget`, permits (`MultiKeyPermit`, `AdvancedOperationPermit`), `RedisPolicyAuthority`; `RedisCodec`/`RedisPayloadCodec`; the typed exception family | -| `lettuce.operations` | the `Lettuce*Operations` implementations, `RedisOperationContext`, `RedisOperationLimits` | -| `lettuce.command` | `RedisCommandCatalog` (loaded from `redis-sdk/redis-command-policy.yml`), `CommandPolicyGuard` (every command is admitted here before it runs), exception translation, executors | -| `lettuce.codec` | UTF-8/long/double/bytes codecs, `VersionedJsonCodec`, `RedisCodecRegistry` | -| `lettuce.observability`, `lettuce.connection` | `RedisObservation` through a no-throw sink; `SentinelFailoverObserver`; `RedisSdkLane`, `RedisSdkComposition` (the SDK's lanes and admin account, contributed to the runtime) | +| `api.key` | 타입 있는 키(`ValueKey`, `HashKey`, `ListKey`, `SetKey`, `SortedSetKey`, `StreamKey`, `BitmapKey`, `GeoKey`, `HyperLogLogKey`), `TypedRedisKeys`, `RedisKeyRenderer`, `RedisSlotTag` | +| `api.operations` / `api.reactive` | 자료 구조별 operation 인터페이스, 동기와 Reactor: value, hash, hash 필드 만료, list, blocking list, set, sorted set, bitmap, bitfield, HyperLogLog, geo, stream, blocking stream, stream 삭제, key, batch. pub/sub는 없다: SDK에 구독 전송이 없고 catalog가 그 명령을 막는다 | +| `api.command`, `api.codec`, `api.error` | `OperationBudget`, 허가(`MultiKeyPermit`, `AdvancedOperationPermit`), `RedisPolicyAuthority`. `RedisCodec`/`RedisPayloadCodec`. 타입 있는 예외 묶음 | +| `lettuce.operations` | `Lettuce*Operations` 구현, `RedisOperationContext`, `RedisOperationLimits` | +| `lettuce.command` | `RedisCommandCatalog`(`redis-sdk/redis-command-policy.yml`에서 읽는다), `CommandPolicyGuard`(모든 명령은 돌기 전에 여기서 허가받는다), 예외 번역, executor | +| `lettuce.codec` | UTF-8·long·double·bytes codec, `VersionedJsonCodec`, `RedisCodecRegistry` | +| `lettuce.observability`, `lettuce.connection` | 던지지 않는 sink를 거친 `RedisObservation`. `SentinelFailoverObserver`. `RedisSdkLane`, `RedisSdkComposition`(runtime에 기여하는 SDK의 lane과 admin 계정) | | `cluster` | `SameSlotValidator`, `ClusterScanCursor`, `ClusterTopologyObserver` | | `config` | `ConfiguredRedisPolicyAuthority`, `ConfiguredRedisPermitVerifier`, `RedisCapabilityProbe`, `RedisStartupProbe` | -| `programmability` | `WATCH`/`MULTI`/`EXEC` transactions (never roll back), registered scripts (`EVALSHA` only), deployed functions | -| `raw` | `LettuceRedisRawGateway`: only commands the catalog marks `RAW_ONLY` **and** the service approves in `RawCommandApprovals` | -| `admin` | `LettuceRedisAdminOperations`: read-only diagnostics on the `ADMIN` lane, projected replies | -| `extensions.*` | Redis 8 modules: JSON, Search, Time Series, Probabilistic; each gated by the capability probe | +| `programmability` | `WATCH`/`MULTI`/`EXEC` 트랜잭션(롤백하지 않는다), 등록된 script(`EVALSHA`만), 배포된 function | +| `raw` | `LettuceRedisRawGateway`: catalog가 `RAW_ONLY`로 표시했고 **그리고** 서비스가 `RawCommandApprovals`에서 승인한 명령만 | +| `admin` | `LettuceRedisAdminOperations`: `ADMIN` lane 위의 읽기 전용 진단, 걸러 낸 응답 | +| `extensions.*` | Redis 8 모듈: JSON, Search, Time Series, Probabilistic. 각각 capability probe가 막는다 | -Configuration that is **code, not settings** — there is no `app.redis.*` key for any of these: -operation ceilings and timeouts (`RedisOperationLimits`), the enabled advanced policies -(`ConfiguredRedisPolicyAuthority`), raw command approvals (`RawCommandApprovals`) and registered -scripts (`RedisScriptRegistry`). The service passes them where it composes the SDK. +**설정이 아니라 코드**인 설정 — 아래 어느 것에도 `app.redis.*` 키가 없다: operation 상한과 timeout +(`RedisOperationLimits`), 켠 고급 정책(`ConfiguredRedisPolicyAuthority`), raw 명령 승인(`RawCommandApprovals`), +등록된 script(`RedisScriptRegistry`). 서비스가 SDK를 조립하는 곳에서 넘긴다. -Package rules (driver containment, no string command surface, the transaction and raw-gateway -invariants) are in `src/adapter/outbound/cache-redis/CLAUDE.md` under "Redis runtime and optional -typed SDK"; `RedisSdkModuleBoundaryTest` enforces them. +패키지 규칙(driver 가두기, 문자열 명령 surface 없음, 트랜잭션과 raw gateway의 불변식)은 +`src/adapter/outbound/cache-redis/CLAUDE.md`의 「Redis 런타임과 골라 쓰는 typed SDK」에 있다. +`RedisSdkModuleBoundaryTest`가 강제한다. -## Env keys +## env 키 -The SDK reads none itself. It runs on `redis-runtime`, whose rows in -`docs/registries/env-keys.yaml` (owner `adapter-outbound-redis-runtime`) are the contract: +SDK는 스스로 하나도 읽지 않는다. `redis-runtime` 위에서 돌고, `docs/registries/env-keys.yaml`의 그 행(소유 +`adapter-outbound-redis-runtime`)이 계약이다: -- Required: `APP_REDIS_ENABLED` left at its default `true`, `APP_REDIS_NODES`, `APP_REDIS_MODE`, +- 필수: 기본값 `true`로 둔 `APP_REDIS_ENABLED`, `APP_REDIS_NODES`, `APP_REDIS_MODE`, `APP_REDIS_NAMESPACE_ENVIRONMENT`, `APP_REDIS_NAMESPACE_SERVICE`, `APP_REDIS_NAMESPACE_DOMAIN`, - and `APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE` (or - `APP_REDIS_AUTHENTICATION_ANONYMOUS_ACCESS_ACCEPTED=true`). -- Per SDK surface used: `APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE` (scripts, - functions; falls back to the application account with a startup warning), - `APP_REDIS_CAPACITY_MAXIMUM_SCRIPT_CONNECTIONS`. The blocking, transaction and admin lane - ceilings and the admin account's credential reference are code (`RedisSdkComposition`), not - settings — like every other SDK knob. -- Topology: `APP_REDIS_SENTINEL_*` when `APP_REDIS_MODE=sentinel`, `APP_REDIS_TLS_*` for TLS. + `APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE`(또는 `APP_REDIS_AUTHENTICATION_ANONYMOUS_ACCESS_ACCEPTED=true`). +- 쓰는 SDK surface마다: `APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE`(script, function. 없으면 기동 + 경고와 함께 애플리케이션 계정으로 물러선다), `APP_REDIS_CAPACITY_MAXIMUM_SCRIPT_CONNECTIONS`. blocking· + transaction·admin lane 상한과 admin 계정의 credential 참조는 설정이 아니라 코드(`RedisSdkComposition`)다 — + 다른 모든 SDK 손잡이처럼. +- topology: `APP_REDIS_MODE=sentinel`이면 `APP_REDIS_SENTINEL_*`, TLS는 `APP_REDIS_TLS_*`. -## Tests +## 테스트 ```bash ./gradlew :adapter:outbound:redis-sdk:test --console=plain ``` -Contract tests run the operations against this leaf's own in-memory gateway -(`InMemoryRedisCommandGateway`, test sources); the topology endpoint helper comes from -`testFixtures(project(':adapter:outbound:redis-runtime'))`. The real-server lane is -`redisTopologyTest` (see [compose/README.md](compose/README.md)); this leaf declares `standalone`, `sentinel` -and `cluster` in `build.gradle`. `tls` is qualified by `redis-runtime`. +계약 시험은 이 leaf 자신의 메모리 gateway(`InMemoryRedisCommandGateway`, 시험 소스)에 대고 operation을 돌린다. +topology endpoint 도우미는 `testFixtures(project(':adapter:outbound:redis-runtime'))`에서 온다. 실제 서버 lane은 +`redisTopologyTest`다([compose/README.md](compose/README.md)를 본다). 이 leaf는 `build.gradle`에서 `standalone`, +`sentinel`, `cluster`를 선언한다. `tls`는 `redis-runtime`이 검증한다. diff --git a/src/adapter/outbound/redis-sdk/compose/README.md b/src/adapter/outbound/redis-sdk/compose/README.md index 291b8572..a990dff2 100644 --- a/src/adapter/outbound/redis-sdk/compose/README.md +++ b/src/adapter/outbound/redis-sdk/compose/README.md @@ -1,28 +1,25 @@ -# Redis SDK topology lanes +# Redis SDK topology lane -These lanes exist to answer the questions the deterministic in-memory gateway cannot: how Lettuce -actually behaves during a Sentinel promotion, what a Cluster resharding does to an in-flight -command, and whether the ACL accounts grant exactly what the SDK issues. +이 lane들은 결정적인 메모리 gateway가 답하지 못하는 질문에 답하려고 있다: Sentinel 승격 중에 Lettuce가 실제로 +어떻게 움직이는지, Cluster resharding이 진행 중인 명령에 무엇을 하는지, ACL 계정이 SDK가 내는 명령을 정확히 +허락하는지. -All four have now run on Redis 7.4 and the evidence is recorded in -`docs/redis/support-matrix.md`. `.github/workflows/redis-sdk-topology.yml` runs the standalone lane -on any pull request that touches the Redis leaf, the full supported-version x topology matrix -nightly, and the same matrix on demand for a release candidate. +넷 모두 Redis 7.4에서 돌았고 증거는 `docs/redis/support-matrix.md`에 적혀 있다. +`.github/workflows/redis-sdk-topology.yml`은 Redis leaf를 건드리는 pull request마다 standalone lane을, 매일 밤 +지원 버전 × topology 표 전체를, 릴리스 후보에는 요청할 때 같은 표를 돌린다. -TLS is a lane of that matrix rather than something to wire up by hand. It is `tls`, not a -deployment mode: its shape is standalone and what it qualifies is the transport, so -`redisTopologyTest` maps the lane name to `standalone` for the tests and keeps the tag filter and -the required trust material on the lane. +TLS는 손으로 배선할 것이 아니라 그 표의 lane 하나다. 배포 모드가 아니라 `tls`다: 모양은 standalone이고 검증하는 +것은 전송이다. 그래서 `redisTopologyTest`는 시험에서 lane 이름을 `standalone`으로 대응시키고, tag 필터와 필요한 +신뢰 자료는 lane에 둔다. -## The TLS lane +## TLS lane -`tls/compose.yml` is the standalone shape with the transport swapped. The plaintext port is turned -off entirely (`--port 0`), which is the only configuration that proves anything: a lane accepting -both would let a client that failed to negotiate TLS fall back silently and still pass. +`tls/compose.yml`은 전송만 바꾼 standalone 모양이다. 평문 port는 완전히 끈다(`--port 0`). 이것만이 무언가를 +증명하는 설정이다: 둘 다 받는 lane이면 TLS 협상에 실패한 client가 소리 없이 물러서고도 통과할 수 있다. -Certificates are generated at start-up into a named volume rather than checked in — a private key -in the repository is a private key in the repository, however the file is named — and they last a -day, so a stale lane fails visibly instead of drifting. +인증서는 저장소에 넣지 않고 기동 때 named volume 안에 만든다 — 파일 이름을 어떻게 붙이든 저장소 안의 개인 +키는 저장소 안의 개인 키다 — 그리고 하루 동안만 유효해서, 낡은 lane은 조용히 어긋나지 않고 눈에 띄게 +실패한다. ```bash REDIS_VERSION=7.4 docker compose -f src/adapter/outbound/redis-sdk/compose/tls/compose.yml up -d --wait @@ -33,43 +30,38 @@ cd src && ./gradlew :adapter:outbound:redis-runtime:redisTopologyTest \ -Predis.topology.mode=tls -Predis.topology.trust-material=/tmp/redis-lane-ca.pem ``` -The lane refuses to run without `redis.topology.trust-material`. A TLS lane that trusts anything -qualifies nothing, so "no CA configured" is an error rather than a client with verification off. +lane은 `redis.topology.trust-material` 없이는 돌기를 거절한다. 아무것이나 믿는 TLS lane은 아무것도 검증하지 +않으니, 「CA를 설정하지 않음」은 검증을 끈 client가 아니라 오류다. -## The ACL fixture +## ACL fixture -`acl/lane-fixture-accounts.acl` provisions the accounts every lane uses. Two things about it matter, and -neither can be written in the file itself — **Redis refuses to start if an `aclfile` contains a -comment line**, so the whole file is directives and the explanation lives here. +`compose/redis/acl/lane-fixture-accounts.acl`이 모든 lane이 쓰는 계정을 만든다(각 lane의 `compose.yml`이 저장소 +루트의 그 폴더를 mount한다). 중요한 점이 둘인데, 둘 다 그 파일 안에 쓸 수 없다 — **`aclfile`에 주석 줄이 있으면 +Redis가 시작을 거절한다.** 그래서 파일 전체가 지시문이고 설명은 여기 있다. -`user default off` is the first line and is deliberate. Redis ships `default` enabled and -passwordless; while it is on, every restriction in the remaining accounts can be bypassed by simply -not authenticating, which makes the fixture decorative. Disabling it is what forces a client — and -the compose healthchecks — to pick a named account. +첫 줄 `user default off`는 일부러 둔 것이다. Redis는 `default`를 켜고 비밀번호 없이 내놓는다. 그것이 켜져 있는 +동안에는 인증하지 않기만 해도 나머지 계정의 모든 제한을 우회할 수 있어서 fixture가 장식이 된다. 그것을 꺼야 +client가 — 그리고 compose healthcheck가 — 이름 있는 계정을 고르게 된다. -Every named account carries a real password — `>fixture-application`, `>fixture-advanced`, and so -on. They were `nopass`, which was the more dangerous kind of wrong: an account that accepts any -password made every assertion about authentication pass for the same reason a typo would have, so -the lane's coverage of AUTH, rotation and secret wiring was indistinguishable from no coverage. -`LiveRedisCompositionTest` now presents a wrong password on purpose and requires `WRONGPASS`, which -is only a meaningful assertion because the accounts enforce one. +이름 있는 모든 계정에는 진짜 비밀번호가 있다 — `>fixture-application`, `>fixture-advanced` 같은 것이다. 예전에는 +`nopass`였고, 그것이 더 위험한 쪽의 잘못이었다: 아무 비밀번호나 받는 계정에서는 인증에 대한 모든 단언이 오타가 +있어도 통과할 이유로 통과했다. 그래서 lane이 AUTH, 교체, 비밀 값 배선을 덮는 것과 덮지 않는 것을 구별할 수 +없었다. `LiveRedisCompositionTest`는 이제 일부러 틀린 비밀번호를 내고 `WRONGPASS`를 요구한다. 계정이 비밀번호를 +강제하기 때문에 뜻이 있는 단언이다. -The passwords are fixture values in a throwaway container and are **not** a deployment template: a -real deployment resolves each account's credential through `secret://` and never writes one into -configuration. +이 비밀번호는 버리는 container 안의 fixture 값이고 배포 template이 **아니다**: 실제 배포는 계정마다 credential을 +`secret://`로 해석하고 설정에 쓰지 않는다. -The accounts are also split by role, because that is how the SDK uses them. `ca-skeleton-application` -runs ordinary data commands and cannot execute a script; `ca-skeleton-application-advanced` holds -`SCRIPT LOAD` and `EVALSHA` and nothing else needs to. That separation is real rather than -decorative: `LiveRedisSemanticPortsTest` runs the rate limiter without the advanced account and -requires it to come back `Unavailable`. +계정은 role로도 나뉜다. SDK가 그렇게 쓰기 때문이다. `ca-skeleton-application`은 보통 데이터 명령을 돌리고 +script를 실행할 수 없다. `ca-skeleton-application-advanced`는 `SCRIPT LOAD`와 `EVALSHA`를 가지고, 다른 계정은 그것이 +필요 없다. 이 분리는 장식이 아니라 실제다: `LiveRedisSemanticPortsTest`는 advanced 계정 없이 rate limiter를 돌리고 +그것이 `Unavailable`로 돌아오기를 요구한다. -## Running one +## 하나 돌리기 -Each lane has its own endpoint, because the address a client is given is not the same kind of thing -in each topology. Standalone declares a data node; Sentinel declares a *sentinel*, from which the -primary is resolved and re-resolved when it is promoted; Cluster declares any node, from which the -rest of the topology is discovered. +lane마다 자기 endpoint가 있다. client에게 주는 주소가 topology마다 같은 종류가 아니기 때문이다. standalone은 +데이터 노드를 선언한다. Sentinel은 *sentinel*을 선언하고, 거기서 primary를 찾으며 승격되면 다시 찾는다. Cluster는 +아무 노드나 선언하고, 거기서 나머지 topology를 찾는다. ```bash # Standalone @@ -91,69 +83,61 @@ cd src && ./gradlew :adapter:outbound:redis-runtime:redisTopologyTest :adapter:o -Predis.topology.host=localhost -Predis.topology.port=7100 -Predis.topology.mode=cluster ``` -Each leaf owns the lanes its tests qualify, and names the classes each lane must run in its -`build.gradle` (`redisTopologyLane { requiredClasses ... }`). Selecting a mode a leaf does not -declare fails instead of running nothing, so run only the leaves listed for the lane: +leaf마다 자기 시험이 검증하는 lane을 가지고, lane마다 돌아야 하는 클래스를 `build.gradle`에 적는다 +(`redisTopologyLane { requiredClasses ... }`). leaf가 선언하지 않은 모드를 고르면 아무것도 돌리지 않는 대신 +실패한다. 그러니 lane에 적힌 leaf만 돌린다: -| Lane | `redis-runtime` | `redis-sdk` | `cache-redis` | +| lane | `redis-runtime` | `redis-sdk` | `cache-redis` | | --- | --- | --- | --- | | standalone | `LiveRedisCompositionTest` | `RedisTopologyContractTest`, `LiveRedisGuardrailTest` | `LiveRedisSemanticPortsTest`, `LiveRedisSemanticScriptAclProbeTest` | | sentinel | `LiveRedisCompositionTest` | `RedisTopologyContractTest`, `LiveRedisSentinelPromotionTest` | — | | cluster | `LiveRedisCompositionTest` | `LiveRedisClusterTest`, `LiveRedisClusterTransactionTest` | `LiveRedisSemanticPortsTest`, `LiveRedisSemanticScriptAclProbeTest` | | tls | `LiveRedisTlsTest` | — | — | -Tear a lane down with `docker compose -f src/adapter/outbound/redis-sdk/compose//compose.yml down -v`. +lane은 `docker compose -f src/adapter/outbound/redis-sdk/compose//compose.yml down -v`로 내린다. -| Lane | Ports | Notes | +| lane | port | 메모 | | --- | --- | --- | -| standalone | 6379 | bridge network, published port | -| sentinel | primary 7010, replica 7011, sentinels 27010–27012 | host network | -| cluster | nodes 7100–7105, bus 17100–17105 | host network; `ready` gates on `cluster_state:ok` | -| tls | 6390 | published port, no plaintext port at all; CA generated per run | +| standalone | 6379 | bridge network, 내놓은 port | +| sentinel | primary 7010, replica 7011, sentinel 27010–27012 | host network | +| cluster | 노드 7100–7105, bus 17100–17105 | host network. `ready`가 `cluster_state:ok`를 기다린다 | +| tls | 6390 | 내놓은 port, 평문 port는 아예 없음. 실행마다 CA를 만든다 | -## Why the Sentinel and Cluster lanes use host networking +## Sentinel과 Cluster lane이 host network를 쓰는 이유 -Neither topology proxies. Sentinel answers `SENTINEL get-master-addr-by-name` with the address it -monitors and the client dials that itself; a cluster client reads `CLUSTER SHARDS` and connects to -every node it names. On a bridge network those are container-internal addresses, so a client on the -host resolves a topology it cannot reach — and after a promotion it resolves a *different* one it -also cannot reach. Sharing the host network namespace makes the address the topology advertises the -address the client can use, which is the difference between testing the SDK and testing Docker's -network. +두 topology 모두 proxy를 하지 않는다. Sentinel은 `SENTINEL get-master-addr-by-name`에 자기가 감시하는 주소로 답하고 +client가 그 주소로 직접 연결한다. cluster client는 `CLUSTER SHARDS`를 읽고 거기 적힌 모든 노드에 연결한다. bridge +network에서는 그것이 container 안쪽 주소라서, host의 client는 닿을 수 없는 topology를 찾게 되고 — 승격 뒤에는 +역시 닿을 수 없는 *다른* topology를 찾는다. host network namespace를 같이 쓰면 topology가 알리는 주소가 client가 +쓸 수 있는 주소가 된다. 그것이 SDK를 시험하는 것과 Docker network를 시험하는 것의 차이다. -That is also why their ports are fixed rather than parameterised: the addresses are written into -Sentinel's and the cluster's own configuration at creation time, and a lane whose two halves can -disagree fails for reasons that are not the SDK's. +같은 이유로 그 port들은 매개변수로 두지 않고 고정한다: 주소는 만들 때 Sentinel과 cluster 자신의 설정에 쓰이고, +두 절반이 서로 어긋날 수 있는 lane은 SDK와 관계없는 이유로 실패한다. -## Selection is by lane, not by hand +## 고르기는 손이 아니라 lane으로 한다 -`redisTopologyTest` derives its JUnit tag expression from the declared mode: `redis-topology & -lane-`. A promotion test is meaningless without sentinels and a cross-slot test is meaningless -without a cluster, but expressing that as a runtime assumption would turn "the lane was never -started" into a green skip. Selecting by tag keeps it fail-closed — what a mode cannot prove is not -selected, and what is selected must pass. +`redisTopologyTest`는 선언한 모드에서 JUnit tag 식을 끌어낸다: `redis-topology & lane-`. 승격 시험은 +sentinel 없이는 뜻이 없고 cross-slot 시험은 cluster 없이는 뜻이 없다. 하지만 그것을 런타임 가정으로 나타내면 +「lane이 시작되지 않았다」가 초록 건너뛰기가 된다. tag로 고르면 실패하면 닫힌 상태가 된다 — 모드가 증명할 수 +없는 것은 고르지 않고, 고른 것은 통과해야 한다. -The lane also fails closed on its endpoint: selecting `redisTopologyTest` without host, port, and -mode (and `redis.topology.master` on the Sentinel lane) is an error, never a skip. A topology test -that silently passes because it did not connect is worse than no topology test. +lane은 endpoint에 대해서도 실패하면 닫힌다: host, port, mode(Sentinel lane이면 `redis.topology.master`도) 없이 +`redisTopologyTest`를 고르면 건너뛰기가 아니라 오류다. 연결하지 않아서 소리 없이 통과하는 topology 시험은 +topology 시험이 없는 것보다 나쁘다. -## `min-replicas-to-write` on the Sentinel lane +## Sentinel lane의 `min-replicas-to-write` -The Sentinel lane sets `min-replicas-to-write 1` and `min-replicas-max-lag 1`, and this is not -incidental configuration. Without them the lane measured a promotion in which the superseded primary -kept answering `+OK` for eleven seconds after it had been replaced: **2,086 writes acknowledged to -the caller and then discarded**, with exactly one command failing. With them the same promotion lost -one write and refused 2,020 with `NOREPLICAS`, which the SDK reports as a definite, non-ambiguous -failure a caller can act on. +Sentinel lane은 `min-replicas-to-write 1`과 `min-replicas-max-lag 1`을 정한다. 우연히 둔 설정이 아니다. 그것 +없이 잰 승격에서는 밀려난 primary가 대체된 뒤에도 11초 동안 `+OK`로 답했다: **호출자에게 확인해 준 쓰기 +2,086개가 버려졌고**, 실패한 명령은 정확히 하나였다. 그것을 두고 같은 승격을 재면 쓰기 하나를 잃고 2,020개를 +`NOREPLICAS`로 거절했다. SDK는 그것을 호출자가 대응할 수 있는, 모호하지 않은 확정 실패로 알린다. -Any deployment where an acknowledgement is supposed to mean something has to set these. See -`docs/redis/support-matrix.md` for the full record. +확인 응답에 뜻이 있어야 하는 배포는 모두 이것을 정해야 한다. 전체 기록은 `docs/redis/support-matrix.md`를 본다. -## ACL accounts +## ACL 계정 -`acl/` holds one file per `CommandAccess` level. They are deliberately narrower than the SDK's own -rules, so a mistake in the SDK is still refused by the server — the account is the last boundary and -a permit never widens it. +`compose/redis/acl/`에는 `CommandAccess` 수준마다 파일이 하나씩 있다. 일부러 SDK 자신의 규칙보다 좁게 둔다. 그래서 +SDK의 실수도 서버가 거절한다 — 계정이 마지막 경계이고, 허가는 그것을 넓히지 않는다. -Every lane loads the same file on every data node. Accounts are enforced per node, so "they exist on -one node" is not evidence that a topology enforces them. +모든 lane은 모든 데이터 노드에 같은 파일을 읽어 들인다. 계정은 노드마다 강제되므로 「한 노드에 있다」는 topology가 +그것을 강제한다는 증거가 아니다. diff --git a/src/adapter/outbound/support/CLAUDE.md b/src/adapter/outbound/support/CLAUDE.md index 3afa2f32..a68269c7 100644 --- a/src/adapter/outbound/support/CLAUDE.md +++ b/src/adapter/outbound/support/CLAUDE.md @@ -1,44 +1,42 @@ -# adapter:outbound:support — shared outbound support +# adapter:outbound:support — outbound 공용 지원 -## Registered identity +## 등록 정보 -- Module ID: `adapter-outbound-support` -- Gradle path: `:adapter:outbound:support` -- Focused test (derived from Gradle path): `./gradlew :adapter:outbound:support:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. -- Registry SSOT: `src/config/architecture/modules.json`. +- 모듈 ID: `adapter-outbound-support` +- Gradle 경로: `:adapter:outbound:support` +- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:outbound:support:test --console=plain` +- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다. +- registry 정본: `src/config/architecture/modules.json`. -Package roots: `dev.caskeleton.adapter.outbound` and -`dev.caskeleton.adapter.outbound.support`. +패키지 루트: `dev.caskeleton.adapter.outbound`와 `dev.caskeleton.adapter.outbound.support`. -## Responsibility +## 책임 -- Own reusable outbound correlation, fail-open dependency logging, and auto-configuration seams. -- Provide technical support used by registered messaging/cache/notification/httpclient leaves. -- Own the template's `IntegrationEventEncoderPort` (`messaging/JsonIntegrationEventEncoder`, - registered by `IntegrationEventEncoderAutoConfiguration` over every contract contribution bean, - backing off to a service's own encoder). It lives here because a use case encodes before it - appends to the outbox, in compositions that carry no messaging module; it is the application's - own envelope v1 format, not an external-system protocol. -- Own the descriptor-relative local filesystem primitive (`filesystem/SecureDirectoryWalk`, - `filesystem/SecureFileAccess`): open, create, delete, stat and move below a root one directory - descriptor at a time with `NOFOLLOW_LINKS`, refusing symbolic components and escapes with typed - `IOException`s. A storage capability translates those into its own failure vocabulary (the - Fileserver's `LocalStorageFailures`); nothing here knows an error code. -- Own `StrictSettingsBinder`, the one strict settings binding. It is also the only support class an - inbound leaf may use: `adapter:inbound:web` binds `app.security` with it (registry edge and a - class-named ArchUnit exemption, since 2026-11-01). An empty value for a setting the type - has (`APP_FILESERVER_PLATFORM_QUOTA_NAMESPACE_LIMIT=`) binds as unset; an empty value under a name - the type does not have is still refused (decided 2026-11-03). -- Keep feature-specific clients and routing policies in their owning leaf. +- 다시 쓰는 outbound correlation, fail-open 의존성 로그, 자동 구성 이음매를 가진다. +- 등록된 messaging·cache·notification·httpclient leaf가 쓰는 기술 지원을 준다. +- 템플릿의 `IntegrationEventEncoderPort`(`messaging/JsonIntegrationEventEncoder`)를 가진다. + `IntegrationEventEncoderAutoConfiguration`이 모든 contract contribution bean 위에 등록하고, 서비스 자신의 + 인코더가 있으면 물러선다. 여기 있는 이유는 유스케이스가 outbox에 append하기 전에 인코딩하는데, 메시징 모듈을 + 싣지 않는 조립도 있기 때문이다. 이것은 외부 시스템 프로토콜이 아니라 애플리케이션 자신의 envelope v1 + 형식이다. +- 디렉터리 descriptor 기준의 로컬 파일 시스템 기본 장치(`filesystem/SecureDirectoryWalk`, + `filesystem/SecureFileAccess`)를 가진다: root 아래에서 디렉터리 descriptor를 하나씩 따라가며 + `NOFOLLOW_LINKS`로 열기, 만들기, 지우기, stat, 옮기기를 하고, symbolic 경로 요소와 바깥으로 나가기를 타입 있는 + `IOException`으로 거절한다. 저장 capability가 그것을 자기 실패 어휘로 바꾼다(파일 서버의 + `LocalStorageFailures`). 여기는 오류 코드를 모른다. +- 유일한 엄격 설정 바인딩 `StrictSettingsBinder`를 가진다. inbound leaf가 쓸 수 있는 유일한 support + 클래스이기도 하다: `adapter:inbound:web`이 이것으로 `app.security`를 바인딩한다(registry edge와 클래스 이름을 + 댄 ArchUnit 예외, 2026-11-01부터). 타입에 있는 설정의 빈 값(`APP_FILESERVER_PLATFORM_QUOTA_NAMESPACE_LIMIT=`)은 + 설정 안 함으로 바인딩한다. 타입에 없는 이름 아래의 빈 값은 계속 거절한다(2026-11-03에 정함). +- 기능 전용 client와 라우팅 정책은 그것을 가진 leaf에 둔다. -## Boundaries +## 경계 -- Allowed project dependencies are registry-owned: application, domain, and shared contracts. -- No inbound transport, persistence, bootstrap, or sample dependencies. -- No business rules or external-system-specific protocol implementation. +- 허용 프로젝트 의존은 registry가 가진다: application, domain, shared 계약. +- inbound 전송, 영속, bootstrap, 샘플 의존이 없다. +- 업무 규칙이나 특정 외부 시스템 프로토콜 구현이 없다. -## Tests +## 테스트 -Use focused unit tests for support behavior. Do not start a Spring application context unless the -contract being tested is configuration wiring itself. +지원 동작은 이 모듈만 보는 단위 시험으로 본다. 시험할 계약이 설정 배선 자체가 아니면 Spring application +context를 띄우지 않는다. From b169ad88bf80649373a9a15b0bdd8f53b871b99b Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 7 Nov 2026 17:25:20 +0900 Subject: [PATCH 4/6] =?UTF-8?q?docs(src):=20=EB=AA=A8=EB=93=88=20=EB=AC=B8?= =?UTF-8?q?=EC=84=9C=EC=9D=98=20ArchUnit=20=EA=B7=9C=EC=B9=99=20=EC=9D=B4?= =?UTF-8?q?=EB=A6=84=EC=9D=84=20=EC=BD=94=EB=93=9C=20=EC=83=81=EC=88=98=20?= =?UTF-8?q?=EC=9D=B4=EB=A6=84=EC=97=90=20=EB=A7=9E=EC=B6=98=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 모듈 문서가 ArchUnit 규칙을 `domain_is_pure`, `query_ports_do_not_leak_domain_jpa_or_web_types` 같은 소문자 이름으로 가리킨다. 지금 코드의 규칙은 `DOMAIN_IS_PURE` 같은 대문자 `static final ArchRule` 상수이고 소문자 이름은 운영 코드 어디에도 없다. 문서의 이름으로 규칙을 찾으면 아무것도 나오지 않는다. 방법: `src/**`의 CLAUDE.md와 README에서 backtick으로 쓴 소문자 규칙 이름 중, 같은 이름의 대문자 ArchRule 상수가 코드에 있는 것만 그 상수 이름으로 바꾼다(31곳, 파일 8개). 지운 규칙을 적은 곳 (`inbound_port_implementations_do_not_declare_keyed_idempotency`)은 지웠다는 기록이라 그대로 둔다. 위험: shared-contract 운영 코드 Javadoc 두 곳 (`DomainContextPropagator`, `ThreadLocalDomainContextPropagator`)이 아직 소문자 `no_inheritable_thread_local`을 쓴다. 이 작업 범위(문서) 밖이라 고치지 않았다. 검증: 바꾼 이름마다 `static final ArchRule ` 또는 ` =`가 코드에 있는지 스크립트로 대조했다. python3 scripts/check-docs.py rc=0, check-work-docs.py rc=0. --- src/adapter/inbound/web/CLAUDE.md | 14 +++++++------- src/adapter/outbound/identifier/CLAUDE.md | 2 +- src/adapter/outbound/persistence-jpa/CLAUDE.md | 2 +- src/application-core/CLAUDE.md | 16 ++++++++-------- src/application-core/README.md | 4 ++-- src/composition/service-runtime/README.md | 2 +- src/domain-core/README.md | 10 +++++----- src/shared-contract/README.md | 8 ++++---- 8 files changed, 29 insertions(+), 29 deletions(-) diff --git a/src/adapter/inbound/web/CLAUDE.md b/src/adapter/inbound/web/CLAUDE.md index f4903614..b31212eb 100644 --- a/src/adapter/inbound/web/CLAUDE.md +++ b/src/adapter/inbound/web/CLAUDE.md @@ -59,7 +59,7 @@ bridge, `JsonIdempotentResponseCodec`, route 목록)는 골라 쓰는 leaf `adap - **B1 — 요청 경계의 Jackson 정책.** `spring.jackson.deserialization`이 `fail-on-unknown-properties`, `fail-on-null-for-primitives`, `fail-on-ignored-properties`를 `true`로, `read-unknown-enum-values-as-null`을 `false`로 고정한다. 클래스 수준 `@JsonIgnoreProperties(ignoreUnknown = true)`로 DTO마다 이것을 되돌리지 - **않는다** — ArchUnit 규칙 `request_dtos_do_not_silence_unknown_fields`가 막는다. 요청 record에는 + **않는다** — ArchUnit 규칙 `REQUEST_DTOS_DO_NOT_SILENCE_UNKNOWN_FIELDS`가 막는다. 요청 record에는 wrapper 타입(`Integer`, `Long`, `Boolean`, `Optional`)을 써서 JSON `null`이 primitive `0`이 되지 못하게 한다. - **B2 — PATCH 뜻.** RFC 7396 `application/merge-patch+json`(`null = 삭제`)을 쓰지 않는다. PATCH endpoint는 @@ -74,10 +74,10 @@ bridge, `JsonIdempotentResponseCodec`, route 목록)는 골라 쓰는 leaf `adap `@Valid` cascade 깊이는 3 이하로 둔다. - **B5 — 다형 역직렬화.** `ObjectMapper.enableDefaultTyping()` / `activateDefaultTyping()`을 부르거나 `LaissezFaireSubTypeValidator`를 참조하는 것은 CVE-2019-14379 RCE의 입구이고 ArchUnit이 막는다 - (`no_jackson_laissez_faire_subtype_validator`, `no_jackson_enable_default_typing_call`). sealed `Command` + (`NO_JACKSON_LAISSEZ_FAIRE_SUBTYPE_VALIDATOR`, `NO_JACKSON_ENABLE_DEFAULT_TYPING_CALL`). sealed `Command` 타입은 `@JsonTypeInfo(use = NAME)` + `@JsonSubTypes`나 `BasicPolymorphicTypeValidator` 허용 목록을 쓴다. - **B6 — virtual thread 문맥 전파.** `spring.threads.virtual.enabled=true`이면 `InheritableThreadLocal`을 쓰지 - 않는다(ArchUnit 규칙 `no_inheritable_thread_local`). filter와 interceptor는 SLF4J 2.0+ MDC나 + 않는다(ArchUnit 규칙 `NO_INHERITABLE_THREAD_LOCAL`). filter와 interceptor는 SLF4J 2.0+ MDC나 `RequestContextHolder`로 `requestId` / `traceId`를 전파한다. - **B7 — outbound ACL mapper 범위.** outbound HTTP·메시징 어댑터의 응답은 `application-core`나 `domain-core`에 닿기 전에 ACL mapper(정규화, 가리기, 공개 필드 고르기)를 거친다 — inbound와 같은 경계 계약이다. 외부 응답 @@ -101,7 +101,7 @@ catch-all `@ExceptionHandler(Exception.class)`가 도메인 예외를 `INTERNAL_ *요청을 받는* 정책의 짝이다. 역직렬화 스위치(B1)와 null·빈 값·없음 세 상태(`Patch` + `JsonNullable`, B2)가 이미 inbound 쪽을 덮고, 아래 규칙이 outbound 쪽을 덮는다. Jackson 속성은 `app-bootstrap`의 `application.yml`(`spring.jackson.deserialization.*`, `spring.jackson.datatype.*`)에 있다. ArchUnit과 실제 -설정 시험도 `app-bootstrap`에 있다(`JacksonSerializationPolicyTest`, `no_bigdecimal_double_constructor`). +설정 시험도 `app-bootstrap`에 있다(`JacksonSerializationPolicyTest`, `NO_BIGDECIMAL_DOUBLE_CONSTRUCTOR`). - **S1 — 날짜·시간·시간대.** `WRITE_DATES_AS_TIMESTAMPS=false`로 고정하므로 `java.time` 값은 `JavaTimeModule`을 거쳐 ISO-8601 문자열로 직렬화한다(`OffsetDateTime` → `"...Z"`, `LocalDate` → @@ -116,7 +116,7 @@ B2)가 이미 inbound 쪽을 덮고, 아래 규칙이 outbound 쪽을 덮는다. 때 정한다. - **S3 — `new BigDecimal(double)`은 금지다.** `double`/`float` 생성자는 이진 부동소수점 오차를 담는다 (`new BigDecimal(0.1)` ≠ `0.1`). `String`(`new BigDecimal("0.1")`)이나 `BigDecimal.valueOf(double)`로 - 만든다. ArchUnit 규칙 `no_bigdecimal_double_constructor`가 강제한다. + 만든다. ArchUnit 규칙 `NO_BIGDECIMAL_DOUBLE_CONSTRUCTOR`가 강제한다. - **S4 — enum과 null·빈 값·없음.** 요청 쪽의 모르는 enum → `VALIDATION_FAILED`(B1 `read-unknown-enum-values-as-null=false`). 옛 값은 명시한 어댑터로 대응시키고 소리 없는 대체값을 쓰지 않는다. 없음·명시한 null·값의 구별은 inbound web mapper(Controller DTO → Command)가 가지고 `Patch`(B2)로 @@ -134,7 +134,7 @@ B2)가 이미 inbound 쪽을 덮고, 아래 규칙이 outbound 쪽을 덮는다. | 층 | 소유 | 검증하는 것 | `error.category` | 강제하는 곳 | |---|---|---|---|---| -| 문법·모양 | `adapter:inbound:web` 요청 DTO(`@Valid` / `jakarta.validation`) | 요청 모양, 타입, 필수 필드 | `VALIDATION` | ArchUnit 규칙 `validation_constraints_stay_at_web_boundary` | +| 문법·모양 | `adapter:inbound:web` 요청 DTO(`@Valid` / `jakarta.validation`) | 요청 모양, 타입, 필수 필드 | `VALIDATION` | ArchUnit 규칙 `VALIDATION_CONSTRAINTS_STAY_AT_WEB_BOUNDARY` | | 유스케이스 정책 | `application-core` | 인가, aggregate를 가로지르는 정책, 상태 전제 조건 | `AUTHZ` / `CONFLICT` | `BusinessRuleValidationContractTest` | | 도메인 불변식 | `domain-core` 모델·값 객체 **생성자** | 업무 불변식(예: end ≥ start) | `CONFLICT` / `VALIDATION` | 도메인 단위 시험(예: `PeriodTest`) — 생성자가 유일하고 바뀌지 않는 생성 경로다 | | 영속 무결성 | `adapter:outbound:persistence-jpa`(번역기는 `feature-persistence-failure-baseline`의 것) | unique / FK / check / serialization | `DATA_INTEGRITY` / `CONFLICT` | `BusinessRuleValidationContractTest` + 누출 시험 | @@ -142,7 +142,7 @@ B2)가 이미 inbound 쪽을 덮고, 아래 규칙이 outbound 쪽을 덮는다. - **C1 — 검증 애너테이션은 web 경계에 머문다.** `jakarta.validation`(`@NotNull`, `@Valid`, …)은 `adapter:inbound:web`에만 나와야 한다. `domain-core`와 `application-core`는 불변식과 정책을 평범한 Java로 나타낸다. Bean Validation 애너테이션이 `..domain..`이나 `..application..`으로 새면 ArchUnit 규칙 - `validation_constraints_stay_at_web_boundary`가 빌드를 실패시킨다. + `VALIDATION_CONSTRAINTS_STAY_AT_WEB_BOUNDARY`가 빌드를 실패시킨다. - **C2 — 업무 불변식은 도메인에 있고 우회할 수 없다.** 불변식은 값 객체·엔티티 **생성자**(유일한 생성 경로)에서 강제하고 타입을 불변으로 둔다. 그래서 어떤 application service나 영속 경로도 불변식을 어긴 인스턴스를 내줄 수 없다. DB 제약은 뒷받침일 뿐 유일한 검사가 아니다(금지: 「불변식을 DB 제약으로만 diff --git a/src/adapter/outbound/identifier/CLAUDE.md b/src/adapter/outbound/identifier/CLAUDE.md index f3addd83..0d021b3a 100644 --- a/src/adapter/outbound/identifier/CLAUDE.md +++ b/src/adapter/outbound/identifier/CLAUDE.md @@ -38,7 +38,7 @@ ## 금지 - 영속·web 기술(JPA/Hibernate/Spring Data/Spring Web) — ArchUnit - `identifier_adapter_does_not_depend_on_other_adapters_or_bootstrap`와 registry 방향 게이트가 막는다. + `IDENTIFIER_ADAPTER_DOES_NOT_DEPEND_ON_OTHER_ADAPTERS_OR_BOOTSTRAP`와 registry 방향 게이트가 막는다. - inbound 어댑터, 영속 어댑터, 다른 outbound leaf, `app-bootstrap`. - 외부 IO(HTTP / 메시징 / cache / DB) — 그것은 IO를 하는 outbound 어댑터 leaf에 둔다. diff --git a/src/adapter/outbound/persistence-jpa/CLAUDE.md b/src/adapter/outbound/persistence-jpa/CLAUDE.md index a0ff79f3..cb4f403f 100644 --- a/src/adapter/outbound/persistence-jpa/CLAUDE.md +++ b/src/adapter/outbound/persistence-jpa/CLAUDE.md @@ -298,7 +298,7 @@ PostgreSQL `57P01`, `57P02`), SQLState 없는 전송 끊김을 가진 실패는 감사 metadata(`created_at` / `updated_at` / `created_by` / `updated_by`)는 기반 관심사이고 `domain-core`에 닿으면 안 된다. `audit/AuditableEntity` `@MappedSuperclass`에만 있다. 도메인 aggregate의 영속 엔티티가 그것을 상속해서 고른다(생성 명령이 만드는 서비스 persistence leaf의 엔티티가 그렇게 한다). 도메인 aggregate 자체는 감사 필드를 하나도 갖지 않는다. -ArchUnit `domain_is_pure`(`jakarta.persistence..` 없음)와 `domain_entities_do_not_carry_audit_fields`(`..domain..` 아래에 +ArchUnit `DOMAIN_IS_PURE`(`jakarta.persistence..` 없음)와 `DOMAIN_ENTITIES_DO_NOT_CARRY_AUDIT_FIELDS`(`..domain..` 아래에 `createdAt`/`updatedAt`/`createdBy`/`updatedBy` 필드 없음)가 강제한다. - **잡기 = 손으로 명시해 넣기(지금 기본).** repository 어댑터가 생성자로 `Clock`과 `AuditContextPort`를 받고 `save`에서 diff --git a/src/application-core/CLAUDE.md b/src/application-core/CLAUDE.md index fb6ecce2..0a8a6bf0 100644 --- a/src/application-core/CLAUDE.md +++ b/src/application-core/CLAUDE.md @@ -39,7 +39,7 @@ - HTTP 상태, 전송 타입(`org.springframework.web..`). - `org.springframework.transaction.annotation.Transactional`(대신 `TransactionPort`를 쓴다). - `org.springframework.context.ApplicationContext` — 직접 의존 금지 - (`getBean(Class)` 같은 리플렉션식 우회는 ArchUnit 규칙 `application_does_not_depend_on_application_context`가 막는다). 문자열 키로 + (`getBean(Class)` 같은 리플렉션식 우회는 ArchUnit 규칙 `APPLICATION_DOES_NOT_DEPEND_ON_APPLICATION_CONTEXT`가 막는다). 문자열 키로 bean을 찾기, `Class.forName(String)`, `BeanFactory#getBeansOfType`은 ArchUnit 정적 분석이 보지 못하는 곳이다. 코드 리뷰 체크리스트로 막는다. - Lombok(`lombok..`) — `domain-core`에서도 금지다. `application-core`에서는 지금 Lombok이 @@ -302,7 +302,7 @@ hikari.maximumPoolSize >= (concurrent_threads × (1 + max_inNew_depth)) + 1 - **순수성 가드레일(core, 기계로 강제):** 단순 이름이 `QueryPort`로 끝나는 읽기 포트는 반드시 애플리케이션 계층 projection DTO만 돌려준다 — 도메인 aggregate, JPA 엔티티, web 타입은 **제네릭 타입 인자를 거쳐서도**(`List`) 안 된다. ArchUnit - `query_ports_do_not_leak_domain_jpa_or_web_types`가 강제한다. projection 사용 자체는 강요된 기본이 + `QUERY_PORTS_DO_NOT_LEAK_DOMAIN_JPA_OR_WEB_TYPES`가 강제한다. projection 사용 자체는 강요된 기본이 아니라 **선택**이다. - **엄격한 절차:** 모든 읽기는 `QueryUseCase` bean을 거친다. web → 읽기 포트로 바로 가는 얇은 경로는 없다. 그런 경로는 필수인 `@UseCaseCapability` 적합성 검사를 건너뛴다. @@ -316,13 +316,13 @@ hikari.maximumPoolSize >= (concurrent_threads × (1 + max_inNew_depth)) + 1 ## ArchUnit 가드레일(강제됨) -- `application_does_not_depend_on_adapters_or_transport` -- `application_does_not_use_spring_transactional_annotation` -- `application_does_not_depend_on_application_context` +- `APPLICATION_DOES_NOT_DEPEND_ON_ADAPTERS_OR_TRANSPORT` +- `APPLICATION_DOES_NOT_USE_SPRING_TRANSACTIONAL_ANNOTATION` +- `APPLICATION_DOES_NOT_DEPEND_ON_APPLICATION_CONTEXT` - `APPLICATION_HAS_NO_DIAGNOSTIC_FRAMEWORK` -- `inbound_port_implementations_end_with_use_case` -- `inbound_port_implementations_declare_capability` -- `query_ports_do_not_leak_domain_jpa_or_web_types`(`*QueryPort` 반환 순수성) +- `INBOUND_PORT_IMPLEMENTATIONS_END_WITH_USE_CASE` +- `INBOUND_PORT_IMPLEMENTATIONS_DECLARE_CAPABILITY` +- `QUERY_PORTS_DO_NOT_LEAK_DOMAIN_JPA_OR_WEB_TYPES`(`*QueryPort` 반환 순수성) ## 테스트 diff --git a/src/application-core/README.md b/src/application-core/README.md index cce525f4..026f6593 100644 --- a/src/application-core/README.md +++ b/src/application-core/README.md @@ -117,10 +117,10 @@ JSON Schema diff로 호환성을 검사하는 fixture: payload schema가 닫혀 - 외부 `*Port`(outbound adapter 에 바인딩된 포트)를 호출하려면 `externalOutboundAllowed = true` 가 필요하다. 없으면 outbound 어댑터 호출 금지. - `repositoryAccess` 가 `WRITE_REPOSITORY` 가 아닌 유스케이스는 리포지토리 포트의 쓰기 - 메서드(save/delete/update/insert)를 호출할 수 없다 — `read_only_use_cases_do_not_call_repository_write_methods` + 메서드(save/delete/update/insert)를 호출할 수 없다 — `READ_ONLY_USE_CASES_DO_NOT_CALL_REPOSITORY_WRITE_METHODS` 규칙이 막는다. 단 정적 분석은 **직접 호출만** 잡으므로, helper/mapper 를 거친 쓰기는 리뷰가 본다. - `bulkWrite = true` 는 `WRITE_REPOSITORY` 를 함께 요구한다(대량 쓰기도 결국 쓰기). - `bulk_write_capability_requires_write_repository_access` 가 강제. + `BULK_WRITE_CAPABILITY_REQUIRES_WRITE_REPOSITORY_ACCESS` 가 강제. - 이 애너테이션은 `docs/registries/capabilities.yaml` 의 7개 capability 를 코드로 구현한 것이며, **코드가 SSOT** 다. 추가 플래그의 의미: - `sensitiveRead` — PII/자격증명/비밀을 읽는 유스케이스 선언. 필드 단위 마커(엔티티 FQN + diff --git a/src/composition/service-runtime/README.md b/src/composition/service-runtime/README.md index 0fcd9479..271b74ba 100644 --- a/src/composition/service-runtime/README.md +++ b/src/composition/service-runtime/README.md @@ -287,6 +287,6 @@ runtimeOnly project(':composition:service-runtime') - **SHAPE-OWNERSHIP(하드 규칙): 이 클래스는 `HealthEndpoint` / `HealthIndicator` / `HealthComponent`를 import·구현·의존해선 안 된다** — health 엔드포인트의 형태(shape)는 runtime-health 브랜치 소유다. 보안 매칭은 오직 엔드포인트 id 문자열로만 하고 health 내부 구조에는 절대 손대지 않는다. ArchUnit - 규칙 `management_security_does_not_depend_on_health_internals`(`CleanArchitectureTest`)가 이를 정적 + 규칙 `MANAGEMENT_SECURITY_DOES_NOT_DEPEND_ON_HEALTH_INTERNALS`(`CleanArchitectureTest`)가 이를 정적 으로 강제한다. diff --git a/src/domain-core/README.md b/src/domain-core/README.md index 29f3ab82..d89d7f84 100644 --- a/src/domain-core/README.md +++ b/src/domain-core/README.md @@ -57,7 +57,7 @@ 네이밍 규칙 대신, `@ValueObject` 처럼 **명시적이고 의도가 드러나는 선언**을 기준으로 모델링 가드레일을 걸 수 있게 한다. - **왜 프레임워크 중립으로 두나.** 일부러 어떤 프레임워크에도 의존하지 않게 만들어서 - `domain-core`가 순수 라이브러리로 남게 한다(`domain_is_pure` 가드레일). + `domain-core`가 순수 라이브러리로 남게 한다(`DOMAIN_IS_PURE` 가드레일). ### `@ValueObject` — 값 객체 @@ -67,7 +67,7 @@ 단 하나의 생성 경로에서 자기 불변식을 검증한다. - **강제 규칙 — public 무인자 생성자 금지.** `@ValueObject` 타입과 `..domain.vo..` 아래 모든 타입은 public 무인자 생성자를 노출하면 안 된다. 빈 생성자는 검증을 건너뛰고 객체를 만들 수 - 있는 "불변식 우회 뒷문"이기 때문이다(`value_objects_have_no_public_no_arg_constructor`). + 있는 "불변식 우회 뒷문"이기 때문이다(`VALUE_OBJECTS_HAVE_NO_PUBLIC_NO_ARG_CONSTRUCTOR`). - **왜 `RUNTIME` 리텐션인가.** ArchUnit(바이트코드 검사)과 리플렉션 기반 테스트가 둘 다 이 애너테이션을 읽을 수 있어야 해서 런타임까지 유지한다. @@ -79,7 +79,7 @@ - **상태 변경은 의도가 드러나는 메서드로만.** 상태 변경은 불변식을 강제하는, 의도가 분명한 애그리거트 메서드를 통해서만 일어나야 한다. 날것의 `setXxx` 세터를 public 으로 열어두면 안 된다. - **강제 규칙 — public 세터 금지.** `@AggregateRoot` 타입의 모든 `set*` 메서드는 - package-private 또는 protected 여야 한다(`aggregate_root_setters_are_not_public`). 이 + package-private 또는 protected 여야 한다(`AGGREGATE_ROOT_SETTERS_ARE_NOT_PUBLIC`). 이 가시성은 Vernon Option A(ORM 외부에서 매핑하는 방식)로 객체를 재구성할 때 의존하는 지점이다. - **이 규칙의 한계.** ArchUnit 은 정적으로 `set*` 라는 이름 패턴까지만 잡을 수 있다. `applyXxx` 처럼 이름이 다른 상태 변경 메서드는 자동 검사가 닿지 않으므로 코드 리뷰가 잡아야 @@ -94,6 +94,6 @@ 포맷·HTTP 같은 전송 계층 타입을 절대 참조하지 않는다는 뜻이다. 도메인 이벤트를 통합 이벤트나 와이어 이벤트로 번역하는 일은 애플리케이션/인프라 경계의 책임이지 도메인의 책임이 아니다. - **강제 규칙 두 가지.** 모든 `@DomainEvent` 타입은 (1) `record` 여야 하고 - (`domain_events_are_records`, 불변성 보장), (2) 어떤 전송 패키지(`org.apache.kafka..`, + (`DOMAIN_EVENTS_ARE_RECORDS`, 불변성 보장), (2) 어떤 전송 패키지(`org.apache.kafka..`, `org.springframework.http..`, `jakarta.ws.rs..`)도 의존하면 안 된다 - (`domain_events_are_transport_free`). + (`DOMAIN_EVENTS_ARE_TRANSPORT_FREE`). diff --git a/src/shared-contract/README.md b/src/shared-contract/README.md index a1d66198..b22731a4 100644 --- a/src/shared-contract/README.md +++ b/src/shared-contract/README.md @@ -508,7 +508,7 @@ Spring 배선(`DomainContextConfig`)은 `composition:service-runtime` 에 있고 흐르는 값도 없다. 도메인은 필요해질 때 자기 키를 선언한다(그 전까지 seam 은 관측 가능한 동작이 없다 — route 가 없는 `RateLimitKeyResolver` 와 같다). - **`ScopedValue`/`StructuredTaskScope` strategy:** Java 21 preview API 이고 빌드에 `--enable-preview` - 가 없어(빌드 사실 C1) 운영에서 컴파일되지 않는다. `domain_context_propagation_primitives_stay_unshipped` + 가 없어(빌드 사실 C1) 운영에서 컴파일되지 않는다. `DOMAIN_CONTEXT_PROPAGATION_PRIMITIVES_STAY_UNSHIPPED` ArchUnit 규칙(app-bootstrap `ForbiddenApiArchitectureTest`)이, 해당 구현이 추가되기 전까지 이를 운영 코드에서 배제한다. @@ -534,7 +534,7 @@ Spring 배선(`DomainContextConfig`)은 `composition:service-runtime` 에 있고 살고 inbound 필터가 virtual thread 에서 전파한다(B6 + D11). 이 propagator 는 **도메인 채널** — 별개의 관심사다. - **명시적 핸드오프(S3):** 구현은 스레드 간 암묵적 상속에 의존해선 안 된다(`InheritableThreadLocal` 은 - `no_inheritable_thread_local` ArchUnit 규칙으로 금지). 스레드/`fork()` 경계를 넘는 코드는 + `NO_INHERITABLE_THREAD_LOCAL` ArchUnit 규칙으로 금지). 스레드/`fork()` 경계를 넘는 코드는 `wrap()` 또는 `capture()`+`restore()` 로 컨텍스트를 명시적으로 재확립한다. ### 전략이 하나뿐인 이유 @@ -545,13 +545,13 @@ Spring 배선(`DomainContextConfig`)은 `composition:service-runtime` 에 있고 - `io.micrometer:context-propagation` 의 `ContextSnapshot`/`ContextRegistry`. 다중 키나 Reactor bridge 가 필요할 때 고른다(C7: 활성화 전에 virtual-thread 동작을 확인할 것). - Java 21 `ScopedValue`. PREVIEW 라 `--enable-preview` 가 필요한데 현재 빌드는 켜지 않는다(C1) → - `domain_context_propagation_primitives_stay_unshipped` ArchUnit 규칙으로 guard 된다. + `DOMAIN_CONTEXT_PROPAGATION_PRIMITIVES_STAY_UNSHIPPED` ArchUnit 규칙으로 guard 된다. ### ThreadLocalDomainContextPropagator (기본 구현) - plain `ThreadLocal` 이 현재 스레드의 도메인 컨텍스트 맵을 들고, 스레드 경계는 명시적 capture/restore 로 넘긴다(D4/D6). - **왜 plain `ThreadLocal` 인가:** `InheritableThreadLocal` 이 아니라서 pooled carrier 스레드 너머로 - 조용히 새지 않고 `no_inheritable_thread_local` ArchUnit 규칙(B6)을 지킨다. virtual thread 는 각자 + 조용히 새지 않고 `NO_INHERITABLE_THREAD_LOCAL` ArchUnit 규칙(B6)을 지킨다. virtual thread 는 각자 자기 copy 를 갖는다(Oracle Java 21 docs, TL-VT-C1) → 같은 스레드 read 는 동작하지만 fork 시 상속은 없다 — 그래서 핸드오프가 `wrap()`/`capture()` 로 **명시적**이어야 하는 것이다. - multi-key 고빈도 변경이나 Reactor bridging 용이 아니다 — 그건 context-propagation 기반 구현의 일이다. 이 From 74be416f93a736668c941b3e60cf4d079b51cfff Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 7 Nov 2026 17:33:54 +0900 Subject: [PATCH 5/6] =?UTF-8?q?docs(adr):=20=EC=95=84=ED=82=A4=ED=85=8D?= =?UTF-8?q?=EC=B2=98=20=EA=B2=B0=EC=A0=95=20=EA=B8=B0=EB=A1=9D=20=EB=B3=B8?= =?UTF-8?q?=EB=AC=B8=EC=9D=84=20=ED=95=9C=EA=B5=AD=EC=96=B4=EB=A1=9C=20?= =?UTF-8?q?=EC=98=AE=EA=B8=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: `docs/adr/`의 결정 기록 26개는 머리 블록만 한국어이고 본문이 영어다. 소유자는 2026-11-07에 결정 기록도 본문까지 한국어로 쓰기로 정했다(design-docs `repo-structure/README.md` 3.2절). 방법: 결정의 뜻을 바꾸지 않고 옮긴다. 머리 블록(상태·작성일·요약· 현재 정본·대체됨)은 한 글자도 바꾸지 않는다. 본문의 상태·날짜·범위 줄, 나중에 붙인 보완·대체 메모, 따져 본 대안도 함께 옮긴다. 코드· 명령·경로·식별자·설정 키·SQL·표 구조는 원문으로 둔다. 본문이 인용한 영어 원문(루트 CLAUDE.md의 한 문장, 플러그인 주석)은 원문을 두고 뜻을 괄호로 붙인다. 결정 기록은 본문을 고치지 않는 문서라서, 번역하며 본 지금 코드와 다른 점(예: ADR-MONGO-ADV-001은 지웠다고 적은 `scripts/verify-mongodb-advanced.sh`가 지금 있다)은 고치지 않고 보고에 남긴다. 위험: 머리 블록 둘째 줄 「본문은 결정한 때의 원문이다」는 번역한 뒤 문자 그대로는 맞지 않는다. 문구를 고칠지는 통합 단계에서 정한다. 검증: python3 scripts/check-docs.py rc=0(language 줄 26개 지움, head 실패 0), 머리 블록이 HEAD와 같은지 26개 모두 diff로 대조, check-work-docs.py --links(gates.md 범위) 깨진 링크 0. --- ...001-one-convention-for-shared-test-code.md | 172 ++++++++-------- ...1-graphql-context-and-storage-ownership.md | 92 ++++----- ...-001-platform-family-and-registry-shape.md | 75 ++++--- ...PC-002-schema-governance-without-protoc.md | 101 +++++----- ...-GRPC-003-three-axis-execution-evidence.md | 67 +++---- ...retry-ownership-and-durable-idempotency.md | 187 ++++++++---------- ...rver-streaming-single-writer-and-resume.md | 67 +++---- ...stable-discovery-and-kubernetes-routing.md | 94 ++++----- ...-capability-promotion-is-per-capability.md | 77 ++++---- ...R-JPA-001-domain-owns-persistence-model.md | 44 ++--- .../adr/ADR-JPA-002-full-transaction-retry.md | 54 +++-- docs/adr/ADR-JPA-003-completion-unknown.md | 72 +++---- ...R-JPA-004-flyway-schema-source-of-truth.md | 48 +++-- .../ADR-JPA-005-postgresql-real-contract.md | 47 ++--- .../ADR-JPA-006-canonical-technical-audit.md | 84 ++++---- docs/adr/ADR-MONGO-001-platform-boundary.md | 85 ++++---- docs/adr/ADR-MONGO-002-bson-representation.md | 80 ++++---- docs/adr/ADR-MONGO-003-transaction-retry.md | 78 ++++---- .../ADR-MONGO-004-index-schema-admin-plane.md | 88 ++++----- .../ADR-MONGO-ADV-001-capability-promotion.md | 118 +++++------ ...-WEB-ADV-001-streaming-is-live-delivery.md | 95 ++++----- ...virtual-threads-do-not-remove-admission.md | 95 ++++----- ...ADV-003-openapi-32-remains-experimental.md | 77 ++++---- ...platform-as-packages-and-its-boundaries.md | 77 ++++---- docs/adr/ADR-WS-002-resume-and-cluster.md | 86 ++++---- docs/adr/ADR-WS-003-stomp-and-broker-relay.md | 102 +++++----- scripts/check-docs-exceptions.txt | 26 --- 27 files changed, 1012 insertions(+), 1276 deletions(-) diff --git a/docs/adr/ADR-BUILD-001-one-convention-for-shared-test-code.md b/docs/adr/ADR-BUILD-001-one-convention-for-shared-test-code.md index 2e109b0a..e2292be7 100644 --- a/docs/adr/ADR-BUILD-001-one-convention-for-shared-test-code.md +++ b/docs/adr/ADR-BUILD-001-one-convention-for-shared-test-code.md @@ -7,122 +7,110 @@ - 현재 정본: `src/build-logic/README.md` -# ADR-BUILD-001: `java-test-fixtures` is the standard for shared test code +# ADR-BUILD-001: 공유 시험 코드의 표준은 `java-test-fixtures`다 -- Status: Accepted -- Date: 2026-09-07 -- Scope: every leaf that publishes or consumes shared test code -- Source: `docs/reviews/2026-09-07-app-bootstrap-module-code-review.md` BOOT-015 +- 상태: 채택 +- 날짜: 2026-09-07 +- 범위: 공유 시험 코드를 내놓거나 쓰는 모든 leaf +- 출처: `docs/reviews/2026-09-07-app-bootstrap-module-code-review.md` BOOT-015 -## Context +## 배경 -Two conventions do the same job in this repository. +이 저장소에서 같은 일을 하는 규약이 둘 있다. -`ca.testkit-publisher` — a convention plugin — gives a leaf a `testkit` source set, wires its output -onto the lanes that leaf names, and optionally publishes it as a consumable configuration. Five -leaves use it: `persistence-jpa` (published as `jpaTestkit`), `web` (`webTestkit`), `websocket` -(`websocketTestkit`), `persistence-mongo` and `httpclient` (both unpublished). +`ca.testkit-publisher` — 규약 플러그인 — 는 leaf에 `testkit` source set을 주고, 그 출력을 leaf가 이름을 댄 lane에 +배선하고, 원하면 쓸 수 있는 configuration으로 내놓는다. 다섯 leaf가 쓴다: `persistence-jpa`(`jpaTestkit`으로 내놓음), +`web`(`webTestkit`), `websocket`(`websocketTestkit`), `persistence-mongo`와 `httpclient`(둘 다 내놓지 않음). -`java-test-fixtures` — Gradle's own plugin — gives a leaf a `testFixtures` source set, puts it on -`test`'s classpath automatically, and always publishes it as a variant consumers reach with -`testFixtures(project(':x'))`. One leaf uses it: `graphql`, which additionally fails its build when a -fixture is written outside `src/testFixtures/java`. +`java-test-fixtures` — Gradle 자신의 플러그인 — 는 leaf에 `testFixtures` source set을 주고, 그것을 `test`의 +classpath에 자동으로 올리고, 쓰는 쪽이 `testFixtures(project(':x'))`로 닿는 variant로 언제나 내놓는다. 한 leaf가 +쓴다: `graphql`. 이 leaf는 fixture를 `src/testFixtures/java` 밖에 쓰면 빌드를 실패시키기도 한다. -Two conventions for one purpose is the defect. A contributor adding shared test code has to know -which leaf they are in before they know where the file goes, and the two answers are not -interchangeable: a consumer of the first writes `project(path: ':x', configuration: 'jpaTestkit')` -and has to know the configuration's name, while a consumer of the second writes -`testFixtures(project(':x'))` and does not. +한 목적에 규약 둘이 있는 것이 결함이다. 공유 시험 코드를 더하는 사람은 파일을 어디 둘지 알기 전에 자기가 어느 +leaf에 있는지 알아야 하고, 두 답은 서로 바꿔 쓸 수 없다: 첫째를 쓰는 쪽은 +`project(path: ':x', configuration: 'jpaTestkit')`를 쓰고 configuration 이름을 알아야 하지만, 둘째를 쓰는 쪽은 +`testFixtures(project(':x'))`를 쓰고 그럴 필요가 없다. -## Decision +## 결정 -**`java-test-fixtures` is the standard.** New shared test code goes in `src/testFixtures/java`, and a -consumer depends on it with `testFixtures(project(':x'))`. +**`java-test-fixtures`가 표준이다.** 새 공유 시험 코드는 `src/testFixtures/java`에 두고, 쓰는 쪽은 +`testFixtures(project(':x'))`로 의존한다. -Three reasons, in order of weight: +이유 셋, 무게 순으로: -1. **The consumer side describes itself.** `testFixtures(project(':adapter:inbound:web'))` says what - it is. `project(path: ':adapter:inbound:web', configuration: 'webTestkit')` says where to look, - and only after the reader has learned that `webTestkit` is a testkit rather than a lane. -2. **The enforcement already exists and is copyable.** `graphql`'s build fails when a fixture is - declared in the wrong place. The same guard applies unchanged to any leaf that adopts the plugin. -3. **It is one fewer local concept.** A convention plugin that reimplements a Gradle plugin has to be - maintained against it. +1. **쓰는 쪽이 스스로를 설명한다.** `testFixtures(project(':adapter:inbound:web'))`는 그것이 무엇인지 말한다. + `project(path: ':adapter:inbound:web', configuration: 'webTestkit')`는 어디를 볼지 말하고, 읽는 사람이 + `webTestkit`이 lane이 아니라 testkit임을 배운 뒤에야 뜻이 통한다. +2. **강제 장치가 이미 있고 복사할 수 있다.** `graphql`의 빌드는 fixture를 엉뚱한 곳에 선언하면 실패한다. 같은 + guard를 플러그인을 쓰는 어느 leaf에든 바꾸지 않고 적용한다. +3. **지역 개념이 하나 준다.** Gradle 플러그인을 다시 구현한 규약 플러그인은 그 플러그인에 맞춰 계속 관리해야 한다. -## What the local plugin does better, and how it is replaced +## 지역 플러그인이 더 잘하는 것과 그것을 대신하는 방법 -This is worth writing down, because the review that prompted this ADR recommended the migration -before reading `ca.testkit-publisher`, and the plugin turns out to encode two deliberate decisions -rather than being an oversight. +이것은 적어 둘 만하다. 이 ADR을 낳은 리뷰는 `ca.testkit-publisher`를 읽기 전에 옮기기를 권했고, 읽어 보니 그 +플러그인은 빠뜨린 것이 아니라 일부러 정한 결정 둘을 담고 있었다. -**Publishing is opt-in.** `persistence-mongo` and `httpclient` have a testkit and publish nothing; -`persistence-jpa` publishes. The plugin's own comment names this as "a real difference in what each -leaf offers rather than an oversight to normalise away". `java-test-fixtures` always creates the -variant, so the distinction is lost — a leaf that never meant to offer its fixtures will offer them. +**내놓기는 고를 때만 한다.** `persistence-mongo`와 `httpclient`는 testkit이 있지만 아무것도 내놓지 않는다. +`persistence-jpa`는 내놓는다. 플러그인 자신의 주석이 이것을 "a real difference in what each leaf offers rather than +an oversight to normalise away"(각 leaf가 주는 것의 실제 차이이지, 맞춰 없앨 빠뜨림이 아니다)라고 부른다. +`java-test-fixtures`는 언제나 variant를 만드니 이 구별이 사라진다 — fixture를 줄 생각이 없던 leaf도 주게 된다. -> Replacement: none at the build level. The distinction moves to review: the fixtures of a leaf that -> nobody consumes are simply unconsumed. This is a real, accepted loss. +> 대신하는 것: 빌드 수준에서는 없다. 구별은 리뷰로 옮긴다: 아무도 쓰지 않는 leaf의 fixture는 그냥 쓰이지 않는다. +> 실제 손실이고, 받아들인 손실이다. -**Lane consumption is declared.** `persistence-jpa` says `consumedBy 'test', 'postgresqlIntegrationTest'`. -`java-test-fixtures` puts fixtures on `test` only, so every other lane needs the output added -explicitly. +**lane이 쓰는 것을 선언한다.** `persistence-jpa`는 `consumedBy 'test', 'postgresqlIntegrationTest'`라고 말한다. +`java-test-fixtures`는 fixture를 `test`에만 올리니, 다른 모든 lane에는 출력을 명시해서 더해야 한다. -> Replacement: `strictTestLanes`' existing `compilesAgainst` expresses this unchanged — a lane -> declares `compilesAgainst 'main', 'testFixtures'`. The first draft of this ADR assumed the DSL -> would need a change, because `sourceSet(name)` creates what it is given and `testFixtures` already -> exists. The `persistence-mongo` migration showed otherwise: `compilesAgainst` only *looks a source -> set up*, so naming a plugin-created one works as-is. What the leaf drops is the -> `sourceSet('testkit')` declaration, not the lane's. +> 대신하는 것: `strictTestLanes`의 기존 `compilesAgainst`가 바꾸지 않고 이것을 나타낸다 — lane이 +> `compilesAgainst 'main', 'testFixtures'`를 선언한다. 이 ADR의 첫 초안은 DSL을 바꿔야 한다고 가정했다. +> `sourceSet(name)`은 받은 것을 만들고 `testFixtures`는 이미 있기 때문이다. `persistence-mongo`를 옮겨 보니 아니었다: +> `compilesAgainst`는 source set을 *찾기만* 하므로, 플러그인이 만든 것의 이름을 대도 그대로 된다. leaf가 버리는 것은 +> lane의 선언이 아니라 `sourceSet('testkit')` 선언이다. -## Migration: done, and what it cost +## 옮기기: 끝났고, 든 비용 -Five leaves, eleven lanes, two published testkits, all migrated leaf by leaf with the suite run -between each. `ca.testkit-publisher` is deleted. +leaf 다섯, lane 열하나, 내놓은 testkit 둘을 leaf 하나씩, 그 사이마다 suite를 돌리며 모두 옮겼다. +`ca.testkit-publisher`는 지웠다. -The order was chosen so a mistake would be cheap: unpublished leaves first, published ones last with -their consumer in the same step. +순서는 실수가 싸게 끝나도록 골랐다: 내놓지 않는 leaf를 먼저, 내놓는 leaf를 마지막에 그 쓰는 쪽과 같은 단계에서. -1. `persistence-mongo` — one leaf, two lanes, no cross-module consumer; the proof the path works. - What it took, per leaf: - - `apply plugin: 'java-test-fixtures'` at the top of the leaf build file; +1. `persistence-mongo` — leaf 하나, lane 둘, 다른 모듈의 쓰는 쪽 없음. 길이 되는지 보는 증명이다. + leaf마다 든 일: + - leaf 빌드 파일 맨 위에 `apply plugin: 'java-test-fixtures'`; - `git mv src/testkit src/testFixtures`; - - drop `sourceSet('testkit')` and the whole `testkitPublisher` block; keep every other lane's - `compilesAgainst`, renaming `'testkit'` to `'testFixtures'`; - - rename `testkitImplementation` to `testFixturesImplementation`, **and add what the old source - set was inheriting silently**. This is the one non-mechanical step: `testkit*` extended - `testImplementation`, so the fixtures saw every test library the leaf declared. Mongo's needed - four more lines (AssertJ, BSON, Spring Data commons, Toxiproxy) — none of which the leaf had - ever stated the fixtures depended on; - - regenerate the leaf's lock state. -2. `httpclient`, then `websocket` — unpublished as well, more lanes. -3. `web` and `persistence-jpa` with `app-bootstrap`'s two consumer declarations, which became - `testImplementation(testFixtures(project(':…')))`. -4. `ca.testkit-publisher` deleted, along with its `plugins {}` entry and its application in the root - build. + - `sourceSet('testkit')`와 `testkitPublisher` 블록 전체를 버린다. 다른 모든 lane의 `compilesAgainst`는 두고 + `'testkit'`을 `'testFixtures'`로 이름을 바꾼다; + - `testkitImplementation`을 `testFixturesImplementation`으로 이름을 바꾸고, **옛 source set이 소리 없이 + 물려받던 것을 더한다**. 기계적이지 않은 단계는 이것 하나다: `testkit*`는 `testImplementation`을 상속해서, + fixture가 leaf가 선언한 모든 시험 라이브러리를 봤다. Mongo는 네 줄(AssertJ, BSON, Spring Data commons, + Toxiproxy)이 더 필요했다 — leaf가 fixture의 의존으로 적은 적이 한 번도 없는 것들이다; + - leaf의 잠금 상태를 다시 만든다. +2. `httpclient`, 그다음 `websocket` — 역시 내놓지 않고, lane이 더 많다. +3. `web`과 `persistence-jpa`, 그리고 `app-bootstrap`의 쓰는 쪽 선언 둘. 그 선언은 + `testImplementation(testFixtures(project(':…')))`가 됐다. +4. `ca.testkit-publisher`를 지웠다. 그 `plugins {}` 항목과 루트 빌드의 적용도 함께. -### Two things the migration broke, and what they taught +### 옮기기가 깨뜨린 것 둘과 그것이 가르친 것 -Both were caught by tests that exist to catch exactly this, which is the argument for having them. +둘 다 바로 이것을 잡으려고 있는 시험이 잡았다. 그런 시험을 둘 이유가 그것이다. -**ArchUnit corpora went wrong in opposite directions.** `httpclient`'s boundary rules *excluded* -`build/classes/java/testkit`; after the move the fixtures arrived as a `…-test-fixtures.jar` on the -same classpath, so the exclusion missed them and 258 fixture-to-fixture calls were reported as -production depending on the testkit. `persistence-jpa`'s rules *included* only -`build/classes/java/main`; applying `java-test-fixtures` makes the module's own test classpath carry -the module as a **jar** rather than as a class directory, so its corpus became empty. The second is -the dangerous one — an empty corpus makes every `noClasses()` rule pass — and it surfaced only -because that suite asserts its corpus is non-empty before asserting anything about it. +**ArchUnit 대상 묶음이 반대 방향으로 틀어졌다.** `httpclient`의 경계 규칙은 `build/classes/java/testkit`을 +*뺐다*. 옮긴 뒤 fixture는 같은 classpath에 `…-test-fixtures.jar`로 들어왔고, 그래서 빼기가 그것을 놓쳤으며 +fixture 사이 호출 258개가 운영 코드가 testkit에 의존한다고 보고됐다. `persistence-jpa`의 규칙은 +`build/classes/java/main`만 *넣었다*. `java-test-fixtures`를 적용하면 모듈 자신의 시험 classpath가 모듈을 class +디렉터리가 아니라 **jar**로 싣는다. 그래서 대상 묶음이 비었다. 위험한 쪽은 둘째다 — 빈 묶음이면 모든 +`noClasses()` 규칙이 통과한다 — 그리고 그 suite가 무엇이든 단언하기 전에 묶음이 비어 있지 않음을 단언했기 +때문에만 드러났다. -**Fixtures had invisible dependencies.** `testkit*` configurations extended `testImplementation`, so -the fixtures compiled against every test library their leaf declared without ever naming one. Making -them explicit took roughly thirty `testFixturesImplementation` lines across the five leaves — -Micrometer, Spring Web, Netty, logback, Jackson, JUnit, AssertJ, Spring Data. None of them were -wrong; none of them were stated. +**fixture에 보이지 않는 의존이 있었다.** `testkit*` configuration은 `testImplementation`을 상속해서, fixture는 이름 +한 번 대지 않고 leaf가 선언한 모든 시험 라이브러리에 대고 컴파일됐다. 그것을 명시하는 데 다섯 leaf에 걸쳐 +`testFixturesImplementation` 줄이 대략 서른 개 들었다 — Micrometer, Spring Web, Netty, logback, Jackson, JUnit, AssertJ, +Spring Data. 틀린 것은 없었다. 적힌 것도 없었다. -## Consequences +## 결과 -- `docs/testing/TESTING_STRATEGY.md` §5 records the standard; this ADR records why and at what cost. -- Until step 5, two conventions remain visible. The strategy document says so explicitly, so a - contributor reading it is not left to infer which one is current. -- The opt-in-publishing distinction is given up. If it later proves load-bearing — a leaf whose - fixtures genuinely must not be reachable — the answer is a separate module, not a third convention. +- `docs/testing/TESTING_STRATEGY.md` §5가 표준을 적는다. 이 ADR은 왜, 어떤 비용으로인지를 적는다. +- 5단계까지는 규약 둘이 보이는 채로 남는다. 전략 문서가 그것을 분명히 말하므로, 읽는 사람이 어느 것이 지금 + 것인지 짐작하게 두지 않는다. +- 고를 때만 내놓는 구별은 포기한다. 나중에 그것이 꼭 필요한 것으로 드러나면 — fixture에 정말 닿으면 안 되는 + leaf — 답은 세 번째 규약이 아니라 따로 둔 모듈이다. diff --git a/docs/adr/ADR-GQL-001-graphql-context-and-storage-ownership.md b/docs/adr/ADR-GQL-001-graphql-context-and-storage-ownership.md index 57af5bc7..d228397c 100644 --- a/docs/adr/ADR-GQL-001-graphql-context-and-storage-ownership.md +++ b/docs/adr/ADR-GQL-001-graphql-context-and-storage-ownership.md @@ -7,73 +7,63 @@ - 현재 정본: `src/adapter/inbound/graphql/README.md` -# ADR-GQL-001 — GraphQL context stays inbound; object authorization moves to application-core; the persisted-operation store stays an inbound SPI +# ADR-GQL-001 — GraphQL 문맥은 inbound에 머물고, 객체 인가는 application-core로 옮기며, persisted operation 저장소는 inbound SPI로 남는다 -- Status: Accepted -- Date: 2026-08-24 -- Review: `docs/reviews/2026-08-14-graphql-module-code-review.md` GQL-026 +- 상태: 채택 +- 날짜: 2026-08-24 +- 리뷰: `docs/reviews/2026-08-14-graphql-module-code-review.md` GQL-026 -## Context +## 배경 -The GraphQL leaf's own documentation described three things crossing its boundary: a -`GraphQlRequestContext` with a deadline propagated into application, JPA, Mongo and the HTTP client; -object authorization decided inside the transport; and a persisted-operation registry implemented by -an external durable store. +GraphQL leaf 자신의 문서는 경계를 넘는 것 셋을 적었다: application, JPA, Mongo, HTTP client로 deadline을 전파하는 +`GraphQlRequestContext`, 전송 계층 안에서 정하는 객체 인가, 외부 durable 저장소가 구현하는 persisted operation +registry. -Two of those invert the dependency direction. If `application-core` or an outbound adapter -implements a type that lives in `adapter:inbound:graphql`, the registry edge that says inbound -depends on application is satisfied while the real compile-time dependency runs the other way. +그중 둘은 의존 방향을 뒤집는다. `application-core`나 outbound 어댑터가 `adapter:inbound:graphql`에 있는 타입을 +구현하면, inbound가 application에 의존한다는 registry edge는 만족되지만 실제 컴파일 의존은 반대로 간다. -The third is a business rule in the wrong layer: whether an actor may see an object is a decision -about the domain, and GraphQL is one of four transports this skeleton ships. +셋째는 엉뚱한 계층의 업무 규칙이다: actor가 객체를 볼 수 있는지는 도메인에 대한 판단이고, GraphQL은 이 골격이 +싣는 전송 계층 넷 중 하나다. -## Decision +## 결정 -Three different answers, because the three problems are not the same problem. +세 문제가 같은 문제가 아니므로 답도 셋이다. -**GraphQL context stays inbound-local.** It is mapped explicitly onto application command fields — -actor, tenant, deadline — rather than travelling as a type. Nothing outside the leaf references -`GraphQlRequestContext`, and the boundary test is that grep returns nothing outside it. +**GraphQL 문맥은 inbound 안에 머문다.** 타입으로 실려 다니지 않고 application command 필드 — actor, tenant, +deadline — 로 명시해 대응시킨다. leaf 밖의 어떤 것도 `GraphQlRequestContext`를 참조하지 않고, 경계 시험은 leaf +밖에서 grep이 아무것도 돌려주지 않는 것이다. -**Object authorization moves to `application-core`.** `ObjectAccessPolicy`, `ObjectAccessRequest` -and `ObjectAccessDecision` are transport-neutral and live with the other application policies; -`ApplicationObjectAuthorization` in the GraphQL leaf is the bridge that calls them. This is the one -of the three that was a real layering defect, and it is fixed rather than documented. +**객체 인가는 `application-core`로 옮긴다.** `ObjectAccessPolicy`, `ObjectAccessRequest`, `ObjectAccessDecision`은 +전송 중립이고 다른 애플리케이션 정책과 함께 있다. GraphQL leaf의 `ApplicationObjectAuthorization`이 그것을 부르는 +다리다. 셋 중 이것이 실제 계층 결함이었고, 적어 두지 않고 고친다. -**The persisted-operation store stays an inbound-owned SPI.** `GraphQlPersistedOperationRegistry` -remains in `advanced/persisted`, and no leaf outside GraphQL implements it. +**persisted operation 저장소는 inbound가 가진 SPI로 남는다.** `GraphQlPersistedOperationRegistry`는 +`advanced/persisted`에 남고, GraphQL 밖의 어떤 leaf도 그것을 구현하지 않는다. -## Consequences +## 결과 -The third decision is the one that needs defending, because it leaves the reported risk in place -rather than removing it. +변호가 필요한 것은 셋째 결정이다. 보고된 위험을 없애지 않고 그 자리에 두기 때문이다. -The risk is conditional: the direction inverts only when something outside the leaf implements the -interface. Nothing does. The template ships an in-memory registry and no durable one, because it -ships no persisted-operation store at all. +위험은 조건부다: leaf 밖의 무엇이 그 인터페이스를 구현할 때만 방향이 뒤집힌다. 그런 것은 없다. 템플릿은 메모리 +registry를 싣고 durable registry는 싣지 않는다. persisted operation 저장소를 아예 싣지 않기 때문이다. -The alternative was to introduce a generic operational key-value store port owned by a neutral -contract holder, with the GraphQL adapter owning only the key and value mapping. That port would -have exactly one interface, zero implementations and one speculative consumer — a new abstraction -whose shape is guessed from a requirement nobody has stated. This repository has spent a full -remediation pass deleting controls that existed and were reached by nothing, and inventing a port -for a store that does not exist is how the next one of those gets written. +대안은 중립 계약 보유자가 가진 범용 운영 key-value 저장소 포트를 들이고, GraphQL 어댑터는 키와 값 대응만 가지는 +것이었다. 그 포트는 인터페이스 정확히 하나, 구현 0개, 짐작으로 정한 쓰는 쪽 하나를 가졌을 것이다 — 아무도 말하지 +않은 요구에서 모양을 짐작한 새 추상이다. 이 저장소는 있었지만 아무것도 닿지 않던 통제를 지우는 데 수정 한 바퀴를 +통째로 썼다. 없는 저장소를 위해 포트를 지어내는 것이 그런 것을 다음에 또 쓰는 길이다. -So the decision is to leave the SPI where it is and to move it when a durable store is actually -built. Moving it then is a rename across one leaf and one new adapter, which is cheaper than -carrying a wrong abstraction until then. What must not happen in the meantime is an outbound leaf -implementing the inbound interface, because that is the moment the direction actually inverts, and -it would happen in a commit whose diff looks like an implementation rather than a layering change. +그래서 결정은 SPI를 있는 곳에 두고, durable 저장소를 실제로 만들 때 옮기는 것이다. 그때 옮기는 일은 leaf 하나와 +새 어댑터 하나에 걸친 이름 바꾸기이고, 그때까지 틀린 추상을 끌고 다니는 것보다 싸다. 그동안 일어나면 안 되는 것은 +outbound leaf가 inbound 인터페이스를 구현하는 것이다. 그때가 방향이 실제로 뒤집히는 순간이고, 그것은 계층 변경이 +아니라 구현처럼 보이는 diff의 커밋에서 일어날 것이다. -The composition root wires these and owns no business or storage policy of its own. +조립 루트가 이것들을 배선하고, 자기 업무·저장 정책은 가지지 않는다. -## Enforcement +## 강제 -`verifyCleanArchitectureDependencies` and `modules.json` hold the leaf's edges to -`domain-core`, `application-core` and `shared-contract`. `ObjectAccessPolicyTest` covers the -application-side policy and `ApplicationObjectAuthorizationTest` the bridge. +`verifyCleanArchitectureDependencies`와 `modules.json`이 leaf의 `domain-core`, `application-core`, `shared-contract` +edge를 지킨다. `ObjectAccessPolicyTest`가 application 쪽 정책을, `ApplicationObjectAuthorizationTest`가 다리를 덮는다. -The condition this ADR turns on — that nothing outside the GraphQL leaf implements the -persisted-operation SPI — is a claim about the whole repository, so it is checked at the -composition root rather than inside the leaf, next to the other GraphQL boundary rules in -`app-bootstrap`'s architecture suite. +이 ADR이 기대는 조건 — GraphQL leaf 밖의 어떤 것도 persisted operation SPI를 구현하지 않는다 — 은 저장소 전체에 +대한 주장이다. 그래서 leaf 안이 아니라 조립 루트에서, `app-bootstrap` architecture suite의 다른 GraphQL 경계 규칙 +옆에서 검사한다. diff --git a/docs/adr/ADR-GRPC-001-platform-family-and-registry-shape.md b/docs/adr/ADR-GRPC-001-platform-family-and-registry-shape.md index c45ff9c8..617992bf 100644 --- a/docs/adr/ADR-GRPC-001-platform-family-and-registry-shape.md +++ b/docs/adr/ADR-GRPC-001-platform-family-and-registry-shape.md @@ -7,58 +7,51 @@ - 현재 정본: `docs/compatibility/grpc-support-matrix.md` -# ADR-GRPC-001: The gRPC platform ships as a registered family, not as one adapter leaf +# ADR-GRPC-001: gRPC 플랫폼은 adapter leaf 하나가 아니라 등록된 family로 싣는다 -- Status: accepted -- Date: 2026-08-30 -- Scope: `:grpc:*`, `:grpc-advanced:*`, `src/config/architecture/modules.json` +- 상태: 채택 +- 날짜: 2026-08-30 +- 범위: `:grpc:*`, `:grpc-advanced:*`, `src/config/architecture/modules.json` -## Context +## 배경 -The two source plans describe a type-safe gRPC execution platform with its own API, SPI, adapters and -composition root: fifteen Stable modules under `modules/grpc` and sixteen Advanced ones under -`modules/grpc-advanced`, on Gradle Kotlin DSL, in package `io.backend.skeleton.grpc`, against -Spring Boot 4.1. +두 원본 계획은 자기 API, SPI, 어댑터, 조립 루트를 가진 타입 안전 gRPC 실행 플랫폼을 설명한다: `modules/grpc` 아래 +Stable 모듈 열다섯과 `modules/grpc-advanced` 아래 Advanced 모듈 열여섯, Gradle Kotlin DSL, 패키지 +`io.backend.skeleton.grpc`, Spring Boot 4.1 기준. -None of that layout exists here. This repository uses Groovy DSL, a fail-closed module registry that -owns the leaf list, package root `dev.caskeleton`, and Spring Boot 4.0.8. The plans anticipate this: -their last Global Constraint says that when the repository structure differs, file paths are remapped -and the public contracts, invariants and test meanings are not changed. +그 배치는 여기 하나도 없다. 이 저장소는 Groovy DSL, leaf 목록을 가진 실패하면 닫히는 모듈 registry, 패키지 루트 +`dev.caskeleton`, Spring Boot 4.0.8을 쓴다. 계획은 이것을 예상한다: 마지막 Global Constraint가, 저장소 구조가 다르면 +파일 경로를 다시 대응시키고 공개 계약·불변식·시험의 뜻은 바꾸지 않는다고 말한다. -Two shapes were available. Fold the platform into the existing `:adapter:inbound:grpc` leaf as -packages — which is what the JPA, GraphQL, WebSocket and HTTP platforms did here — or register it as -a family the way `messaging:*` is registered. +고를 수 있는 모양은 둘이었다. 플랫폼을 기존 `:adapter:inbound:grpc` leaf에 패키지로 접어 넣기 — JPA, GraphQL, +WebSocket, HTTP 플랫폼이 여기서 그렇게 했다 — 또는 `messaging:*`를 등록한 방식대로 family로 등록하기. -## Decision +## 결정 -Register it as a family: twelve Stable leaves under `src/grpc/` and six Advanced ones under -`src/grpc-advanced/`. +family로 등록한다: `src/grpc/` 아래 Stable leaf 열둘과 `src/grpc-advanced/` 아래 Advanced leaf 여섯. -The deciding property is that this is not a layer of this application. Root `CLAUDE.md` already -describes `messaging:*` as "a vendored messaging platform: a product with its own API, SPI, adapters -and composition boundary, not a layer of this application", and the gRPC platform is the same shape -for the same reason — the application is meant to reach it the way it reaches a library, through an -application-owned port. The four platforms that became packages are all layers of this application; -this one is not. +결정을 가른 성질은 이것이 이 애플리케이션의 계층이 아니라는 점이다. 루트 `CLAUDE.md`는 이미 `messaging:*`를 "a +vendored messaging platform: a product with its own API, SPI, adapters and composition boundary, not a layer of this +application"(들여온 메시징 플랫폼: 자기 API, SPI, 어댑터, 조립 경계를 가진 제품이고 이 애플리케이션의 계층이 +아니다)이라고 설명하고, gRPC 플랫폼은 같은 이유로 같은 모양이다 — 애플리케이션은 라이브러리에 닿듯, 애플리케이션이 +가진 포트를 거쳐 그것에 닿아야 한다. 패키지가 된 네 플랫폼은 모두 이 애플리케이션의 계층이다. 이것은 아니다. -The split between `src/grpc/` and `src/grpc-advanced/` is not organisational. The Stable plan -requires that the Stable starter's build fail if it reaches an Advanced module, and separate Gradle -path prefixes make that a `verifyCleanArchitectureDependencies` failure rather than a review note: -`grpc-spring-boot-starter`'s registry entry names no advanced id, and it cannot acquire one silently. +`src/grpc/`와 `src/grpc-advanced/`의 분리는 정리용이 아니다. Stable 계획은 Stable starter의 빌드가 Advanced 모듈에 +닿으면 실패해야 한다고 요구하고, Gradle 경로 접두어를 따로 두면 그것이 리뷰 메모가 아니라 +`verifyCleanArchitectureDependencies` 실패가 된다: `grpc-spring-boot-starter`의 registry 항목은 advanced id를 하나도 +대지 않고, 소리 없이 얻을 수도 없다. -## Consequences +## 결과 -**The registry grew from 44 leaves to 62.** That is a large registry change, made deliberately and in -one place. Every new leaf is `runtime_memberships: []`, so nothing ships until a second, explicit -decision moves it. +**registry가 leaf 44개에서 62개로 늘었다.** 큰 registry 변경이고, 일부러 한곳에서 했다. 새 leaf는 모두 +`runtime_memberships: []`라서, 두 번째로 명시한 결정이 옮기기 전까지 아무것도 실리지 않는다. -**The advanced boundary is checked twice.** Once by the registry at build time, and once by -`GrpcStableBuildInvariant` at runtime, because a fat jar or a shaded artifact is assembled by -something the registry never sees. +**advanced 경계는 두 번 검사한다.** 빌드 때 registry가 한 번, 런타임에 `GrpcStableBuildInvariant`가 한 번. fat jar나 +shaded artifact는 registry가 보지 못하는 무언가가 조립하기 때문이다. -**Four testkit modules became four test lanes.** The plan's split exists so in-process results cannot -be mistaken for network results; this repository expresses that with `ca.strict-test-lane`, whose -lanes fail when they discover nothing and never serve an up-to-date result. `GrpcEvidenceGrade` keeps -the same rule inside the code, so a report cannot cite a contract run as transport evidence. +**testkit 모듈 넷은 시험 lane 넷이 됐다.** 계획이 나눈 이유는 프로세스 안 결과를 네트워크 결과로 착각하지 못하게 +하려는 것이다. 이 저장소는 그것을 `ca.strict-test-lane`으로 나타낸다. 그 lane은 아무것도 찾지 못하면 실패하고, +up-to-date 결과를 내주지 않는다. `GrpcEvidenceGrade`가 코드 안에서 같은 규칙을 지키므로, 보고서가 계약 실행을 전송 +증거로 인용할 수 없다. -**Codegen is not wired.** See ADR-GRPC-002. +**codegen은 배선하지 않았다.** ADR-GRPC-002를 본다. diff --git a/docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md b/docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md index 82641867..67320b8e 100644 --- a/docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md +++ b/docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md @@ -8,74 +8,65 @@ - 대체됨: `docs/capability-status.md` -# ADR-GRPC-002: Schema governance runs without protoc and without the Buf CLI +# ADR-GRPC-002: schema 관리는 protoc 없이, Buf CLI 없이 돈다 -- Status: **superseded (2026-09-28)** by owner decision 18 of the 2026-09-25 review follow-up -- Date: 2026-08-30 -- Scope: `:grpc:grpc-proto-contract`, `:grpc:grpc-codegen` (both removed) +- 상태: **대체됨(2026-09-28)** — 2026-09-25 리뷰 후속의 소유자 결정 18 +- 날짜: 2026-08-30 +- 범위: `:grpc:grpc-proto-contract`, `:grpc:grpc-codegen`(둘 다 지움) -> **Superseded.** The regex `.proto` validator and the Java re-implementation of Buf's rules were -> deleted. The schema now lives in `:grpc:grpc-contract` (`src/grpc/grpc-contract/src/main/proto`), -> compiled by the Gradle protobuf plugin (`com.google.protobuf`, version pinned in -> `src/gradle/libs.versions.toml`; protoc and the protobuf-java runtime are both `protobufGrpc`). -> Generated sources are excluded from Spotless, Checkstyle and Error Prone in that leaf only. -> `buf lint` and `buf breaking` (`src/grpc/grpc-contract/buf.yaml`, STANDARD lint, FILE breaking) -> run in CI, job `grpc-proto-buf` in `.github/workflows/ci-quality-gates.yml`. The proto organization -> is `caskeleton` (was `hyeonworks`). The text below is kept as the record of the original decision. +> **대체됨.** 정규식 `.proto` 검증기와 Buf 규칙의 Java 재구현은 지웠다. schema는 이제 `:grpc:grpc-contract` +> (`src/grpc/grpc-contract/src/main/proto`)에 있고 Gradle protobuf 플러그인(`com.google.protobuf`, 버전은 +> `src/gradle/libs.versions.toml`에 고정. protoc와 protobuf-java runtime은 둘 다 `protobufGrpc`)이 컴파일한다. 생성된 +> 소스는 그 leaf에서만 Spotless, Checkstyle, Error Prone에서 뺀다. `buf lint`와 `buf breaking` +> (`src/grpc/grpc-contract/buf.yaml`, STANDARD lint, FILE breaking)은 CI의 `.github/workflows/ci-quality-gates.yml` +> job `grpc-proto-buf`에서 돈다. proto organization은 `caskeleton`이다(예전에는 `hyeonworks`). 아래 글은 원래 결정의 +> 기록으로 남긴다. -## Context +## 배경 -Stable Tasks 8 through 11 require proto style rules, Buf format/lint/breaking governance, a single -Java codegen owner, and a descriptor artifact whose consumer-compile result gates a release. +Stable Task 8부터 11은 proto 문체 규칙, Buf format·lint·breaking 관리, Java codegen 소유자 하나, 그리고 쓰는 쪽 +컴파일 결과가 릴리스를 막는 descriptor artifact를 요구한다. -Two of the tools those tasks name are absent from this toolchain. The Buf CLI is not installed. And -`protoc` is available through the Gradle protobuf plugin, but every leaf in this repository passes -spotless with google-java-format, checkstyle, SpotBugs at HIGH confidence, Error Prone and `-Werror` -— and generated protobuf sources pass none of them. Turning codegen on means excluding a source set -from five quality gates. +그 Task가 이름을 대는 도구 중 둘이 이 toolchain에 없다. Buf CLI는 설치돼 있지 않다. 그리고 `protoc`는 Gradle +protobuf 플러그인으로 쓸 수 있지만, 이 저장소의 모든 leaf는 google-java-format을 쓴 spotless, checkstyle, HIGH +confidence의 SpotBugs, Error Prone, `-Werror`를 통과하는데 — 생성된 protobuf 소스는 그중 어느 것도 통과하지 못한다. +codegen을 켜면 source set 하나를 품질 게이트 다섯에서 빼야 한다. -There is precedent for such an exclusion: the `jmh` source set has `spotbugsJmh` and `checkstyleJmh` -disabled and Error Prone off. So the carve-out is available. It is also a decision about the quality -baseline of a leaf, taken for one task, and outside what this work was asked to change. +그런 예외에는 선례가 있다: `jmh` source set은 `spotbugsJmh`와 `checkstyleJmh`를 끄고 Error Prone도 끈다. 그러니 빼는 +길은 있다. 하지만 그것은 Task 하나를 위해 leaf의 품질 기준선에 대해 내리는 결정이고, 이 일이 바꾸라고 받은 범위 +밖이다. -`adapter:inbound:grpc` also carries a recorded decision in the opposite direction: its `CLAUDE.md` -forbids the protobuf plugin and `.proto` in that leaf, on the grounds that a consuming feature module -should own its schema. +`adapter:inbound:grpc`에도 반대 방향으로 기록된 결정이 있다: 그 `CLAUDE.md`는 쓰는 기능 모듈이 자기 schema를 가져야 +한다는 이유로 그 leaf에서 protobuf 플러그인과 `.proto`를 금지한다. -## Decision +## 결정 -Commit the `.proto` sources and implement every rule the tasks require as executable Java, with no -protoc run and no Buf CLI invocation. +`.proto` 소스를 커밋하고, Task가 요구하는 모든 규칙을 protoc 실행도 Buf CLI 호출도 없이 실행되는 Java로 구현한다. -`GrpcProtoContractValidator` reads `.proto` text and enforces proto3 syntax, the -`{organization}.{domain}.v{major}` package rule, `java_multiple_files`, a generated Java package -disjoint from the hand-written one, `_UNSPECIFIED` enum zero values, `reserved` declarations checked -against a supplied removal history, a well-known-type allowlist and a map-field allowlist. It runs -against the committed schema in its own test, so the shipped `.proto` files are live rather than -decorative. +`GrpcProtoContractValidator`는 `.proto` 글을 읽고 다음을 강제한다: proto3 문법, `{organization}.{domain}.v{major}` +패키지 규칙, `java_multiple_files`, 손으로 쓴 것과 겹치지 않는 생성 Java 패키지, `_UNSPECIFIED` enum 0값, 받은 삭제 +이력과 대조한 `reserved` 선언, well-known type 허용 목록, map 필드 허용 목록. 자기 시험에서 커밋한 schema에 대고 +돌므로, 출하하는 `.proto` 파일은 장식이 아니라 살아 있다. -`GrpcBufPolicy` fixes the breaking gate at Buf's `FILE` category and names the four lifecycle stages -a compliant pipeline registers. `GrpcCodegenManifest` fixes one codegen owner and refuses a literal -generator version. `GrpcDescriptorArtifact`, `GrpcConsumerFixture` and `GrpcSchemaArtifactPublisher` -carry the schema hash, the descriptor digest and the per-consumer source-break report, and refuse a -publish that breaks a consumer or republishes a released version with different bytes. +`GrpcBufPolicy`는 breaking gate를 Buf의 `FILE` category로 고정하고, 규칙을 따르는 pipeline이 등록하는 lifecycle 단계 +넷을 이름으로 댄다. `GrpcCodegenManifest`는 codegen 소유자를 하나로 고정하고 리터럴 생성기 버전을 거절한다. +`GrpcDescriptorArtifact`, `GrpcConsumerFixture`, `GrpcSchemaArtifactPublisher`는 schema hash, descriptor digest, 쓰는 +쪽별 소스 깨짐 보고를 싣고, 쓰는 쪽을 깨뜨리는 게시나 이미 릴리스한 버전을 다른 바이트로 다시 게시하는 것을 +거절한다. -The committed `buf.yaml` states the same rules, so running the CLI in an environment that has it -reaches the same verdict. +커밋한 `buf.yaml`도 같은 규칙을 적으므로, CLI가 있는 환경에서 돌리면 같은 판정에 닿는다. -## Consequences +## 결과 -**The invariants are enforced; the process is not run.** Everything Tasks 8 to 11 are about — which -schema changes are refused, which consumer breaks block a release, who owns generation — is a -build-checkable rule here. What is missing is the protoc invocation and the Buf binary. +**불변식은 강제하고, 과정은 돌리지 않는다.** Task 8부터 11이 다루는 모든 것 — 어떤 schema 변경을 거절하는지, 어떤 +쓰는 쪽 깨짐이 릴리스를 막는지, 생성을 누가 가지는지 — 이 여기서는 빌드로 검사하는 규칙이다. 빠진 것은 protoc +호출과 Buf 바이너리다. -**Turning codegen on is a bounded change.** `GrpcCodegenManifest.caSkeleton()` already names the -owner, the managed version source, the build-directory output paths and the disjoint package policy -that a real plugin configuration has to satisfy. The work is a source-set carve-out and a plugin -block, not a redesign. +**codegen을 켜는 것은 한계 있는 변경이다.** `GrpcCodegenManifest.caSkeleton()`이 이미 실제 플러그인 설정이 만족해야 +할 소유자, 관리되는 버전 출처, 빌드 디렉터리 출력 경로, 겹치지 않는 패키지 정책을 이름으로 댄다. 할 일은 source set +예외와 플러그인 블록이지 재설계가 아니다. -**The fixtures use a text codec.** `GrpcTextCodec` gives the testkit a UTF-8 marshaller so the -in-process and Netty lanes can exercise interceptors, status mapping, metadata limits and stream -sequencing without generated stubs. Those contracts are properties of the platform and the transport, -not of any message shape, so the substitution costs nothing — and the lanes run today rather than -after codegen lands. +**fixture는 텍스트 codec을 쓴다.** `GrpcTextCodec`이 testkit에 UTF-8 marshaller를 줘서, 프로세스 안 lane과 Netty +lane이 생성된 stub 없이 interceptor, status 대응, metadata 한계, stream 순서를 시험할 수 있다. 그 계약은 메시지 +모양이 아니라 플랫폼과 전송의 성질이므로 바꿔 넣어도 잃는 것이 없다 — 그리고 lane이 codegen이 들어온 뒤가 아니라 +오늘 돈다. diff --git a/docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md b/docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md index 9a944e96..c40c9fd9 100644 --- a/docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md +++ b/docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md @@ -7,53 +7,48 @@ - 현재 정본: `docs/compatibility/grpc-support-matrix.md` -# ADR-GRPC-003: Transport, business and stream evidence are three axes, and none implies another +# ADR-GRPC-003: 전송·업무·stream 증거는 세 축이고, 어느 것도 다른 것을 뜻하지 않는다 -- Status: accepted -- Date: 2026-08-30 -- Scope: `:grpc:grpc-core-api`, `:grpc:grpc-runtime` (was `grpc-policy`), `:grpc:grpc-testkit` +- 상태: 채택 +- 날짜: 2026-08-30 +- 범위: `:grpc:grpc-core-api`, `:grpc:grpc-runtime`(예전 `grpc-policy`), `:grpc:grpc-testkit` -## Context +## 배경 -A failed RPC produces a status code, and a status code is not an answer to the question the caller -actually has. `DEADLINE_EXCEEDED` on a mutation does not say whether the mutation happened; -`UNAVAILABLE` after the request was sent does not say the server never saw it; response headers -arriving does not say a transaction committed. +실패한 RPC는 status code를 낸다. 그리고 status code는 호출자가 실제로 가진 질문의 답이 아니다. 변경 요청의 +`DEADLINE_EXCEEDED`는 변경이 일어났는지 말하지 않는다. 요청을 보낸 뒤의 `UNAVAILABLE`은 서버가 그것을 한 번도 보지 +않았다고 말하지 않는다. 응답 header가 도착했다고 트랜잭션이 커밋된 것은 아니다. -Every one of those is a place where a plausible inference produces a duplicate write or a lost one, -and none of them is visible in a test that only exercises the happy path. +그 하나하나가 그럴듯한 추론이 중복 쓰기나 잃은 쓰기를 낳는 자리이고, 성공 경로만 시험하는 시험에서는 하나도 보이지 +않는다. -## Decision +## 결정 -Model what happened as three independent axes, and refuse the inferences between them. +일어난 일을 서로 독립인 세 축으로 모델링하고, 축 사이의 추론을 거절한다. -`GrpcTransportEvidence` records what the client observed on the wire, and distinguishes `NOT_SENT` — -the client watched its own send fail — from `UNOBSERVED`, which is every other case where nothing is -known. `GrpcBusinessEvidence` records what the application confirmed, with `COMMIT_UNKNOWN` as a real -state rather than a placeholder. `GrpcStreamEvidence` is a sealed hierarchy whose non-empty cases all -carry a position, because "partial" without a last sequence can be neither resumed nor reconciled. +`GrpcTransportEvidence`는 client가 wire에서 본 것을 기록하고, `NOT_SENT` — client가 자기 보내기가 실패하는 것을 봤다 +— 와, 아무것도 모르는 다른 모든 경우인 `UNOBSERVED`를 구별한다. `GrpcBusinessEvidence`는 애플리케이션이 확인한 것을 +기록하고, `COMMIT_UNKNOWN`은 자리표시가 아니라 실제 상태다. `GrpcStreamEvidence`는 sealed 계층이고, 비어 있지 않은 +경우는 모두 위치를 싣는다. 마지막 순번 없는 「부분」은 이어 가지도 맞춰 보지도 못하기 때문이다. -`GrpcExecutionEvidence` holds all three and rejects combinations nobody could have observed: a unary -call with stream evidence, or a request the client watched fail to send that nonetheless carries -business evidence. Promoting response headers to a confirmed commit is possible only by editing -`withResponseHeadersSeen`, which is one method rather than a plausible line in an interceptor. +`GrpcExecutionEvidence`는 셋을 모두 가지고, 아무도 볼 수 없었을 조합을 거절한다: stream 증거가 있는 unary 호출, 또는 +client가 보내기 실패를 봤는데도 업무 증거를 실은 요청. 응답 header를 확인된 커밋으로 올리는 것은 +`withResponseHeadersSeen`을 고쳐야만 할 수 있다. 그것은 interceptor 안의 그럴듯한 한 줄이 아니라 메서드 하나다. -`GrpcCompletionOutcome.forMutation` derives what a caller may conclude, and defaults -`DEADLINE_EXCEEDED` and post-send `UNAVAILABLE` on a mutation to `COMPLETION_UNKNOWN`. +`GrpcCompletionOutcome.forMutation`이 호출자가 결론 내릴 수 있는 것을 끌어내고, 변경 요청의 `DEADLINE_EXCEEDED`와 +보낸 뒤의 `UNAVAILABLE`을 기본으로 `COMPLETION_UNKNOWN`으로 둔다. -The same types are used by the failure model and by the observation convention, so an incident has -one account of a call rather than two. +실패 모델과 관측 규약이 같은 타입을 쓰므로, 사고 때 호출 하나에 대한 설명이 둘이 아니라 하나다. -## Consequences +## 결과 -**A whole class of retry bug becomes unrepresentable.** `GrpcRetryEligibility` reads all three axes -plus the idempotency profile; a caller cannot reach "retry" from a status alone because the status -alone is not an input. +**재시도 결함의 한 종류를 아예 나타낼 수 없게 된다.** `GrpcRetryEligibility`는 세 축 모두와 멱등성 profile을 읽는다. +status만으로는 입력이 아니므로, 호출자는 status만 보고 「재시도」에 닿을 수 없다. -**The fault lane has something to check.** `GrpcTransportEvidenceClassifier` turns a client's -observations into evidence and refuses to infer `NOT_SENT` from an unobserved state — and the lane -exercises it against a real connection dropped mid-call, not against a mock. +**장애 lane에 검사할 것이 생긴다.** `GrpcTransportEvidenceClassifier`가 client의 관찰을 증거로 바꾸고, 관찰하지 않은 +상태에서 `NOT_SENT`를 추론하기를 거절한다 — 그리고 lane은 mock이 아니라 호출 중간에 끊은 실제 연결에 대고 그것을 +시험한다. -**Callers must handle a third outcome.** `COMPLETION_UNKNOWN` is not a failure and not a success, and -a caller that treats it as either is wrong. `GrpcOperationStatusQuery` and `GrpcCompletionReconciler` -exist so that resolving it is a supported path rather than an exercise for the caller. +**호출자는 세 번째 결과를 다뤄야 한다.** `COMPLETION_UNKNOWN`은 실패도 성공도 아니고, 둘 중 하나로 다루는 호출자는 +틀렸다. `GrpcOperationStatusQuery`와 `GrpcCompletionReconciler`는 그것을 푸는 일이 호출자에게 맡긴 숙제가 아니라 +지원하는 경로가 되게 하려고 있다. diff --git a/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md b/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md index 00a03ed1..f86b2b31 100644 --- a/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md +++ b/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md @@ -7,129 +7,106 @@ - 현재 정본: `docs/compatibility/grpc-support-matrix.md` -# ADR-GRPC-004: One retry owner, and keyed mutations need a durable ledger +# ADR-GRPC-004: 재시도 소유자는 하나이고, 키가 있는 변경에는 durable 원장이 필요하다 -- Status: accepted -- Date: 2026-08-30 -- Scope: `:grpc:grpc-runtime` (was `grpc-policy`), `:grpc:grpc-operation-ledger-jpa`, `:grpc:grpc-core-api` +- 상태: 채택 +- 날짜: 2026-08-30 +- 범위: `:grpc:grpc-runtime`(예전 `grpc-policy`), `:grpc:grpc-operation-ledger-jpa`, `:grpc:grpc-core-api` -## Context +## 배경 -Three layers can retry a gRPC call: the application, the channel's service config, and a service -mesh. Their effects multiply. Three attempts at each layer is twenty-seven requests for one call, and -the load arrives exactly when the dependency is already failing. +gRPC 호출을 재시도할 수 있는 계층이 셋 있다: 애플리케이션, channel의 service config, service mesh. 그 효과는 곱해진다. +계층마다 세 번 시도하면 호출 하나에 요청 스물일곱 개이고, 그 부하는 의존 대상이 이미 실패하고 있을 바로 그때 온다. -Separately, a mutation that is safe to repeat needs somewhere to record that it ran. Without one, a -retry after a lost response either duplicates the effect or drops it, and nothing distinguishes the -two afterwards. +따로, 되풀이해도 안전한 변경에는 그것이 돌았다는 기록을 둘 곳이 필요하다. 없으면 응답을 잃은 뒤의 재시도는 효과를 +겹치게 하거나 버리게 되고, 나중에 둘을 구별할 것이 없다. -## Decision +## 결정 -**Exactly one retry owner per channel.** `GrpcRetryOwner` has four values including `NONE`, which is a -decision rather than an omission. `GrpcServiceConfigPolicy` refuses an in-process retry entry when the -owner is the mesh or nobody, and `GrpcRetryOwnershipValidator` compares the service config's method -names against the policy catalog — a renamed method leaves its retry entry matching nothing, silently, -and the method then runs with channel defaults. +**channel마다 재시도 소유자는 정확히 하나다.** `GrpcRetryOwner`에는 `NONE`을 포함해 값이 넷 있고, `NONE`은 빠뜨림이 +아니라 결정이다. `GrpcServiceConfigPolicy`는 소유자가 mesh이거나 아무도 아닐 때 프로세스 안 재시도 항목을 거절하고, +`GrpcRetryOwnershipValidator`는 service config의 메서드 이름을 정책 catalog와 대조한다 — 이름이 바뀐 메서드는 그 재시도 +항목이 소리 없이 아무것과도 맞지 않게 되고, 그 메서드는 channel 기본값으로 돈다. -**Retry eligibility reads the method, the evidence and the status together.** -`GrpcRetryEligibility` refuses a non-idempotent method outright, refuses any call whose stream -delivered a prefix, and turns a `DEADLINE_EXCEEDED` or post-send `UNAVAILABLE` mutation into -"resolve the completion first" rather than a retry. +**재시도 자격은 메서드, 증거, status를 함께 읽는다.** `GrpcRetryEligibility`는 멱등이 아닌 메서드를 바로 거절하고, +stream이 앞부분을 전달한 호출을 모두 거절하며, 변경 요청의 `DEADLINE_EXCEEDED`나 보낸 뒤의 `UNAVAILABLE`을 재시도가 +아니라 「먼저 완료를 풀어라」로 바꾼다. -**A keyed mutation is retryable only with both a caller key and a durable ledger.** -`GrpcOperationLedger` is a port in `grpc-core-api`, so the policy layer can require durable -idempotency without depending on a database. Its `claim` contract is a single atomic insert-or-read -against a unique constraint: `JpaGrpcOperationLedger` inserts first and reads on constraint violation, -because a read-then-insert implementation has a window exactly as wide as the race it closes and -passes every test that does not run two attempts concurrently. +**키가 있는 변경은 호출자 키와 durable 원장이 둘 다 있을 때만 재시도할 수 있다.** `GrpcOperationLedger`는 +`grpc-core-api`의 포트라서, 정책 계층이 데이터베이스에 의존하지 않고 durable 멱등성을 요구할 수 있다. 그 `claim` 계약은 +unique 제약에 대한 원자적 insert-or-read 하나다: `JpaGrpcOperationLedger`는 먼저 insert하고 제약 위반이면 읽는다. +read-then-insert 구현에는 그것이 닫으려는 경쟁만큼 넓은 창이 있고, 두 시도를 동시에 돌리지 않는 모든 시험을 +통과하기 때문이다. -The identity is caller fingerprint plus full method plus hashed key. All three are load-bearing: -without the caller, one tenant's key suppresses another's write; without the method, a key reused -across operations makes the second a replay of the first. +identity는 호출자 fingerprint + 전체 메서드 + hash한 키다. 셋 모두 꼭 필요하다: 호출자가 없으면 한 테넌트의 키가 다른 +테넌트의 쓰기를 막는다. 메서드가 없으면 operation 사이에서 다시 쓴 키 때문에 둘째가 첫째의 재생이 된다. -## Consequences +## 결과 -**A budget bounds retries as a fraction of traffic.** `GrpcRetryBudget` degrades to roughly no -retries when everything is failing, which is the behaviour that lets a dependency recover. +**예산이 재시도를 traffic의 비율로 묶는다.** `GrpcRetryBudget`은 모든 것이 실패할 때 재시도가 거의 없는 쪽으로 +떨어진다. 그것이 의존 대상이 회복하게 하는 동작이다. -**The ledger and the mutation should commit together.** `JpaGrpcOperationLedger` carries no -transaction annotations, deliberately: a `REQUIRES_NEW` would put the claim in its own transaction and -reintroduce the window where the write is durable and the claim is not. +**원장과 변경은 함께 커밋해야 한다.** `JpaGrpcOperationLedger`는 일부러 트랜잭션 애너테이션을 달지 않는다: +`REQUIRES_NEW`는 claim을 자기 트랜잭션에 넣어서, 쓰기는 durable한데 claim은 아닌 창을 다시 들인다. -**A claim expires instead of blocking its key forever** (review 2026-11-01, 03-10). A claim still -`IN_PROGRESS` after the claim TTL is presumed abandoned by a dead owner, and the next retry of the same -request takes it over with `GrpcOperationLedger.reclaimStale` — one conditional -`UPDATE … WHERE state = 'IN_PROGRESS' AND claimed_at < :cutoff`, so of two concurrent takeovers exactly -one wins, the same shape as `reclaimFailed`. The TTL is the `claimTtl` argument of -`GrpcIdempotencyInterceptor`, refused at construction when it is not longer than every keyed method's -deadline. Since the 03-11 follow-up the starter assembles the interceptor when -`app.grpc.platform.operation-ledger-enabled=true` and takes the TTL from -`app.grpc.platform.operation-ledger-claim-ttl` (default 5m); a TTL the constructor refuses fails startup -naming that key, and an enabled flag without a `GrpcOperationLedger` bean fails startup too. +**claim은 키를 영원히 막지 않고 만료된다**(review 2026-11-01, 03-10). claim TTL이 지난 뒤에도 `IN_PROGRESS`인 claim은 +죽은 주인이 버린 것으로 보고, 같은 요청의 다음 재시도가 `GrpcOperationLedger.reclaimStale`로 넘겨받는다 — 조건부 +`UPDATE … WHERE state = 'IN_PROGRESS' AND claimed_at < :cutoff` 하나라서, 동시에 넘겨받기 둘이 오면 정확히 하나가 이긴다. +`reclaimFailed`와 같은 모양이다. TTL은 `GrpcIdempotencyInterceptor`의 `claimTtl` 인자이고, 키가 있는 모든 메서드의 +deadline보다 길지 않으면 만들 때 거절한다. 03-11 후속부터 starter는 `app.grpc.platform.operation-ledger-enabled=true`이면 +interceptor를 조립하고 TTL을 `app.grpc.platform.operation-ledger-claim-ttl`(기본 5m)에서 가져온다. 생성자가 거절하는 +TTL은 그 키 이름을 대며 기동을 실패시키고, `GrpcOperationLedger` bean 없이 flag를 켜도 기동이 실패한다. -The takeover is safe only because the commit is recorded in the mutation's own transaction: then a -claim still `IN_PROGRESS` means the mutation never committed. An adopter that commits them separately -turns an abandoned claim into an unknown outcome, and a takeover can run the mutation twice. A takeover -of an owner that is merely slow does the same, which is why the TTL must exceed the slowest keyed -method and not just its deadline. +넘겨받기가 안전한 것은 커밋을 변경 자신의 트랜잭션 안에서 기록하기 때문뿐이다: 그러면 아직 `IN_PROGRESS`인 claim은 +변경이 한 번도 커밋되지 않았다는 뜻이다. 둘을 따로 커밋하는 채택자는 버려진 claim을 모르는 결과로 만들고, 넘겨받기가 +변경을 두 번 돌릴 수 있다. 그저 느린 주인을 넘겨받아도 같은 일이 생긴다. 그래서 TTL은 deadline만이 아니라 키가 있는 +가장 느린 메서드보다 길어야 한다. -Rejected: an owner token with a heartbeat lease (the outbox lease model) — needed only when a keyed -method can run longer than any fixed TTL; revisit when one exists. A sweeper job that deletes stale -rows — it needs a scheduler this family does not have, and deleting a claim makes the next retry a -fresh claim with no record that an attempt was abandoned. +버린 것: heartbeat lease를 단 owner token(outbox lease 모델) — 키가 있는 메서드가 어떤 고정 TTL보다 오래 돌 수 있을 때만 +필요하다. 그런 메서드가 생기면 다시 본다. 낡은 행을 지우는 sweeper job — 이 family에 없는 scheduler가 필요하고, +claim을 지우면 다음 재시도가 시도를 버렸다는 기록 없는 새 claim이 된다. -**A taken-over owner is fenced by a claim token** (re-review 2026-11-03, RR-02-04). The owner a -takeover presumes dead may only be slow. Without knowing which attempt held the claim, its late -`markFailed` turned the new attempt's claim `FAILED_TERMINAL`, the next retry re-claimed it, and two -attempts ran the mutation at once; its late `markCommitted` committed beside the new attempt. Every -claim now carries a `GrpcClaimToken` (`claim_attempt`, migration V003): 1 for the first claim, one more -for each `reclaimFailed` or `reclaimStale`. `decide` returns it on `PROCEED`, and `recordCommit` / -`recordFailure` hand it back. A commit or a failure is one conditional -`UPDATE … WHERE state = 'IN_PROGRESS' AND claim_attempt = :attempt`: a commit by an attempt that lost -the claim is refused with an exception, so its business transaction rolls back; a failure by one is -ignored (`markFailed` returns false). The same conditional update closes the JPA commit race — -load-check-save let two commits that both read `IN_PROGRESS` both write; now exactly one matches. -A claim whose conflicting row is purged between insert and read retries the insert once instead of -failing the call. +**넘겨받긴 주인은 claim token으로 막는다**(re-review 2026-11-03, RR-02-04). 넘겨받기가 죽었다고 보는 주인은 그저 느릴 +수 있다. 어느 시도가 claim을 쥐었는지 모르면, 그 주인의 늦은 `markFailed`가 새 시도의 claim을 `FAILED_TERMINAL`로 +만들었고, 다음 재시도가 그것을 다시 claim해서 두 시도가 동시에 변경을 돌렸다. 늦은 `markCommitted`는 새 시도 옆에서 +커밋했다. 이제 모든 claim은 `GrpcClaimToken`(`claim_attempt`, migration V003)을 싣는다: 첫 claim은 1이고, +`reclaimFailed`나 `reclaimStale`마다 하나씩 늘어난다. `decide`는 `PROCEED`에서 그것을 돌려주고, `recordCommit` / +`recordFailure`가 그것을 되돌려 준다. 커밋이나 실패는 조건부 +`UPDATE … WHERE state = 'IN_PROGRESS' AND claim_attempt = :attempt` 하나다: claim을 잃은 시도의 커밋은 예외로 거절해서 +그 업무 트랜잭션이 롤백되고, 그런 시도의 실패는 무시한다(`markFailed`가 false를 돌려준다). 같은 조건부 update가 JPA +커밋 경쟁도 닫는다 — load-check-save에서는 둘 다 `IN_PROGRESS`를 읽은 커밋 둘이 둘 다 썼다. 이제 정확히 하나만 맞는다. +insert와 read 사이에 충돌 행이 지워진 claim은 호출을 실패시키지 않고 insert를 한 번 다시 시도한다. -`release(identity, claimToken)` is fenced the same way (re-review 2026-11-03 round 2, RR-01-15): it is a -conditional `DELETE … WHERE state = 'IN_PROGRESS' AND claim_attempt = :attempt` and returns whether it -deleted. It used to delete by key alone, so any caller could erase the claim of the attempt that held -it, or a finished record a retry replays. The counter lives in the row, so a deleted row's key starts -again at attempt 1: the token separates the attempts of one row, not attempts across a delete. Both -deletions are limited accordingly — release only for a claim whose owner is known to be gone, purge -only for rows finished longer ago than any retry. Rejected: dropping `release` from the port -(`markFailed` then `reclaimFailed` keeps the counter, but a deployment that must free a key for a -different request has no other path), and a tombstone row that keeps the counter (a second state to -purge, for a window the two limits already close). +`release(identity, claimToken)`도 같은 방식으로 막는다(re-review 2026-11-03 round 2, RR-01-15): 조건부 +`DELETE … WHERE state = 'IN_PROGRESS' AND claim_attempt = :attempt`이고 지웠는지를 돌려준다. 예전에는 키만으로 지웠기 +때문에, 아무 호출자나 그것을 쥔 시도의 claim이나 재시도가 재생하는 끝난 레코드를 지울 수 있었다. counter는 행 안에 +있으므로 지운 행의 키는 다시 attempt 1에서 시작한다: token은 행 하나의 시도들을 가르지, 삭제를 넘는 시도들을 가르지 +않는다. 그래서 두 삭제를 모두 제한한다 — release는 주인이 사라졌다고 아는 claim에만, purge는 어떤 재시도보다 오래 전에 +끝난 행에만. 버린 것: 포트에서 `release`를 빼기(`markFailed` 뒤 `reclaimFailed`는 counter를 지키지만, 다른 요청을 위해 +키를 풀어야 하는 배포에는 다른 길이 없다), counter를 지키는 tombstone 행(지울 두 번째 상태가 생기는데, 그 창은 두 제한이 +이미 닫는다). -Chosen over the claim moment as the token (`WHERE claimed_at = :claimedAt`), which needs no column: -PostgreSQL stores microseconds while `Instant` carries nanoseconds, so the token a caller holds and -the one stored can differ by rounding, and two processes' clocks can give two attempts the same -moment. The counter has neither problem. The heartbeat lease above stays rejected for the same reason -as before; the token fences without one. +token으로 claim 시각(`WHERE claimed_at = :claimedAt`)을 쓰는 안보다 이것을 골랐다. 시각은 열이 따로 필요 없지만, +PostgreSQL은 마이크로초를 저장하고 `Instant`는 나노초를 싣는다. 그래서 호출자가 쥔 token과 저장된 것이 반올림만큼 +다를 수 있고, 두 프로세스의 시계가 두 시도에 같은 시각을 줄 수 있다. counter에는 두 문제가 다 없다. 위 heartbeat lease는 +앞과 같은 이유로 계속 버린다. token은 그것 없이 막는다. -**What `operation-ledger-enabled=true` promises (03-11 (b), recorded 2026-11-03, RR-02-07).** The -2026-11-01 review offered (a) delete the flag and judge by whether a ledger bean exists, or (b) keep the -flag and have the starter assemble the decision function from it. (b) is kept: the assembly and the -TTL validation live in one place instead of in every adopter. (a) was rejected because it removes the -false promise only by removing the assembly with it. The limit stays and is stated where an operator -meets it: the starter builds no server, so the flag assembles the decision function only, and keys are -honoured once the adopter's `IDEMPOTENCY` stage interceptor or service adapter calls `decide` and -`recordCommit`. `GrpcPlatformStartupValidator`'s refusal for a keyed method says exactly that; a running -process cannot see whether the stage exists, so the validator does not claim to check it. +**`operation-ledger-enabled=true`가 약속하는 것(03-11 (b), 2026-11-03 기록, RR-02-07).** 2026-11-01 리뷰는 (a) flag를 +지우고 원장 bean이 있는지로 판단하기와 (b) flag를 두고 starter가 그것으로 판정 함수를 조립하기를 내놓았다. (b)를 +지킨다: 조립과 TTL 검증이 채택자마다가 아니라 한곳에 있다. (a)는 거짓 약속을 없애되 조립까지 함께 없애기 때문에 +버렸다. 한계는 남고, 운영자가 그것을 만나는 곳에 적는다: starter는 서버를 만들지 않으므로 flag는 판정 함수만 +조립하고, 채택자의 `IDEMPOTENCY` 단계 interceptor나 service adapter가 `decide`와 `recordCommit`을 부를 때 비로소 키가 +지켜진다. 키가 있는 메서드에 대한 `GrpcPlatformStartupValidator`의 거절이 바로 그것을 말한다. 돌고 있는 프로세스는 그 +단계가 있는지 볼 수 없으니, validator는 그것을 검사한다고 주장하지 않는다. -**Finished rows are purged after a retention; in-progress rows never are** (03-10 follow-up). -`GrpcOperationLedger.purgeCompletedBefore(cutoff, limit)` deletes at most `limit` `COMMITTED` or -`FAILED_TERMINAL` rows that completed before the cutoff, oldest first — on PostgreSQL one bounded -`DELETE … WHERE storage_key IN (SELECT … LIMIT … FOR UPDATE SKIP LOCKED)` served by the partial index -of migration V002. `GrpcOperationLedgerRetention.purgeExpired(now)` applies -`app.grpc.platform.operation-ledger-retention` (default 24h, the HTTP idempotency replay TTL) in -batches. A retry after its record was purged is a fresh claim and runs again, so the retention must -exceed the callers' retry window. The adopter schedules the purge; the starter assembles the policy -only, because a scheduled bean would force a scheduler onto every deployment and the starter cannot -know which replica should run it. +**끝난 행은 보존 기간 뒤에 지우고, 진행 중인 행은 절대 지우지 않는다**(03-10 후속). +`GrpcOperationLedger.purgeCompletedBefore(cutoff, limit)`는 cutoff 전에 끝난 `COMMITTED`나 `FAILED_TERMINAL` 행을 오래된 +것부터 많아야 `limit`개 지운다 — PostgreSQL에서는 migration V002의 부분 index가 받쳐 주는 한계 있는 +`DELETE … WHERE storage_key IN (SELECT … LIMIT … FOR UPDATE SKIP LOCKED)` 하나다. +`GrpcOperationLedgerRetention.purgeExpired(now)`가 `app.grpc.platform.operation-ledger-retention`(기본 24h, HTTP 멱등성 +재생 TTL)을 batch로 적용한다. 레코드가 지워진 뒤의 재시도는 새 claim이고 다시 돈다. 그래서 보존 시간은 호출자의 재시도 +창보다 길어야 한다. 지우기 일정은 채택자가 잡는다. starter는 정책만 조립한다. 예약된 bean은 모든 배포에 scheduler를 +강요하고, starter는 어느 replica가 돌려야 하는지 알 수 없기 때문이다. -**A key reused for a different request is a caller error, not a duplicate.** The stored request -fingerprint turns that into `FAILED_PRECONDITION` rather than silently returning the first request's -answer. +**다른 요청에 다시 쓴 키는 중복이 아니라 호출자 오류다.** 저장된 요청 fingerprint가 그것을 소리 없이 첫 요청의 답을 +돌려주는 대신 `FAILED_PRECONDITION`으로 바꾼다. diff --git a/docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md b/docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md index 712eddf8..a210de5d 100644 --- a/docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md +++ b/docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md @@ -7,53 +7,46 @@ - 현재 정본: `docs/compatibility/grpc-support-matrix.md` -# ADR-GRPC-005: One writer per stream, a bounded queue, and resume that refuses to guess +# ADR-GRPC-005: stream마다 쓰는 쪽 하나, 한계 있는 queue, 짐작하기를 거절하는 resume -- Status: accepted -- Date: 2026-08-30 -- Scope: `:grpc:grpc-runtime` (was `grpc-policy`) +- 상태: 채택 +- 날짜: 2026-08-30 +- 범위: `:grpc:grpc-runtime`(예전 `grpc-policy`) -## Context +## 배경 -`StreamObserver` is not thread-safe, and the failure when two producers call `onNext` concurrently is -not an exception — it is interleaved bytes, which a client decodes as a corrupt message or, worse, as -a valid one it should never have received. +`StreamObserver`는 thread-safe가 아니다. 두 producer가 동시에 `onNext`를 부를 때의 실패는 예외가 아니다 — 섞인 바이트이고, +client는 그것을 깨진 메시지로, 더 나쁘게는 받지 말았어야 할 유효한 메시지로 decode한다. -Two further properties of server streams are easy to get wrong in ways that look healthy. A consumer -that falls behind either terminates the stream or silently loses messages, and the second leaves a -client with a stream that appears fine and is missing changes. And a reconnect either continues from -a position the server can still replay, or skips whatever is no longer there. +server stream에는 건강해 보이는 방식으로 틀리기 쉬운 성질이 둘 더 있다. 뒤처진 소비자는 stream을 끝내거나 메시지를 소리 +없이 잃는데, 둘째는 client에게 멀쩡해 보이지만 변경이 빠진 stream을 남긴다. 그리고 재연결은 서버가 아직 재생할 수 있는 +위치에서 이어 가거나, 더는 없는 것을 건너뛴다. -## Decision +## 결정 -**A bounded queue drained by one writer.** `GrpcSerializedStreamWriter` accepts messages from any -thread and hands them to the transport only from `flush`, which is synchronized. `write` returning -`ACCEPTED` means queued, and the name is deliberately not `sent`: the transport call returns as soon -as bytes are handed over, so no method here can honestly report delivery. +**쓰는 쪽 하나가 비우는 한계 있는 queue.** `GrpcSerializedStreamWriter`는 어느 스레드에서든 메시지를 받고, synchronized인 +`flush`에서만 전송에 넘긴다. `write`가 `ACCEPTED`를 돌려주는 것은 줄 세웠다는 뜻이고, 이름을 일부러 `sent`로 하지 +않았다: 전송 호출은 바이트를 넘기자마자 돌아오므로, 여기 어떤 메서드도 전달을 정직하게 알릴 수 없다. -**Both a message bound and a byte bound.** Either alone is unbounded in the other dimension. -`GrpcFlowControlPolicy` also takes the transport's own readiness signal, because a writer that relies -only on its queue bound produces as fast as it can allocate. +**메시지 한계와 바이트 한계를 둘 다.** 하나만 두면 다른 차원으로는 한계가 없다. `GrpcFlowControlPolicy`는 전송 자신의 +readiness 신호도 받는다. queue 한계에만 기대는 쓰는 쪽은 메모리를 할당할 수 있는 만큼 빨리 만들어 내기 때문이다. -**Termination is the default for a slow consumer.** `GrpcSlowConsumerPolicy.DROP_OLDEST` exists for -feeds whose business meaning tolerates loss, and is not the default, because a client cannot detect -dropped messages: the sequence numbers it sees are the ones it was sent. +**느린 소비자에게는 끝내기가 기본이다.** `GrpcSlowConsumerPolicy.DROP_OLDEST`는 업무 뜻이 손실을 견디는 feed를 위해 +있고 기본값이 아니다. client는 버려진 메시지를 알아챌 수 없기 때문이다: client가 보는 순번은 보내진 것의 순번이다. -**Resume is refused rather than faked.** `GrpcStreamGapDetector` requires a signed, unexpired token -whose caller and filter fingerprints match the current request, refuses one whose snapshot version -moved, and returns `FULL_RESYNC_REQUIRED` when the cursor predates retained history. `GrpcResumeToken` -carries a key id so the signing key can rotate without invalidating every outstanding token. +**resume은 꾸며 내지 않고 거절한다.** `GrpcStreamGapDetector`는 서명됐고 만료되지 않았으며 호출자·필터 fingerprint가 +지금 요청과 맞는 token을 요구하고, snapshot version이 움직인 token을 거절하며, cursor가 보존한 이력보다 앞서면 +`FULL_RESYNC_REQUIRED`를 돌려준다. `GrpcResumeToken`은 key id를 싣는다. 그래서 서명 키를 바꿔도 아직 쓰이는 모든 token이 +무효가 되지 않는다. -## Consequences +## 결과 -**A stream carries an envelope, not a bare payload.** `GrpcStreamEnvelope` holds the stream id, -generation, sequence, snapshot version and resume token, because resume, gap detection and drain all -need a position and a generation. +**stream은 맨 payload가 아니라 envelope을 싣는다.** `GrpcStreamEnvelope`은 stream id, generation, 순번, snapshot version, +resume token을 가진다. resume, 빈틈 찾기, 비우기가 모두 위치와 generation을 필요로 하기 때문이다. -**Four clocks, not one.** `GrpcStreamLifetimePolicy` separates setup deadline, idle timeout, max -duration and heartbeat interval, and refuses combinations where one can never fire. Merging any pair -produces a familiar bug: an idle timeout used as a max duration kills healthy busy streams. +**시계는 하나가 아니라 넷이다.** `GrpcStreamLifetimePolicy`는 준비 deadline, idle timeout, 최대 지속 시간, heartbeat +간격을 나누고, 하나가 절대 울릴 수 없는 조합을 거절한다. 어느 둘을 합치든 익숙한 결함이 나온다: 최대 지속 시간으로 쓴 +idle timeout은 건강하게 바쁜 stream을 죽인다. -**A heartbeat is a liveness signal and nothing else.** It is not an application acknowledgement and -not an ordering guarantee; `GrpcStreamHeartbeat` says so in the place somebody would otherwise reuse -it. +**heartbeat는 살아 있다는 신호이고 그 밖의 무엇도 아니다.** 애플리케이션 확인 응답도 순서 보장도 아니다. +`GrpcStreamHeartbeat`가 누가 그것을 다르게 다시 쓸 법한 자리에서 그렇게 말한다. diff --git a/docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md b/docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md index 17e677a6..c58764b0 100644 --- a/docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md +++ b/docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md @@ -7,71 +7,61 @@ - 현재 정본: `docs/compatibility/grpc-support-matrix.md` -# ADR-GRPC-006: Stable discovery is DNS and static, and a Kubernetes profile names who balances +# ADR-GRPC-006: Stable discovery는 DNS와 static이고, Kubernetes profile은 누가 분산하는지 이름으로 댄다 -- Status: accepted -- Date: 2026-08-31 -- Scope: `:grpc:grpc-runtime` (was `grpc-discovery`, `grpc-client`) +- 상태: 채택 +- 날짜: 2026-08-31 +- 범위: `:grpc:grpc-runtime`(예전 `grpc-discovery`, `grpc-client`) -## Context +## 배경 -A gRPC channel's discovery configuration has a failure mode with no runtime symptom: it works, and -it does not do what the dashboard says it does. +gRPC channel의 discovery 설정에는 런타임 증상이 없는 실패 방식이 있다: 동작은 하는데, 대시보드가 말하는 일을 하지 않는다. -The specific case is `round_robin` over a Kubernetes Service ClusterIP. The Service is one virtual -address, so the resolver returns one endpoint and the client-side balancer has nothing to rotate -across; kube-proxy picks a pod at connect time, and an HTTP/2 connection is long-lived, so every -request from that client goes to the same pod for the life of the connection. Nothing fails. The -configuration says `round_robin`, the metrics show requests spread across clients rather than pods, -and the conclusion "we have client-side load balancing" is wrong in a way nobody is prompted to -check. +구체적인 경우는 Kubernetes Service ClusterIP 위의 `round_robin`이다. Service는 가상 주소 하나라서 resolver가 endpoint 하나를 +돌려주고 client 쪽 분산기는 돌려 가며 보낼 대상이 없다. kube-proxy는 연결할 때 pod를 고르고, HTTP/2 연결은 오래 살기 +때문에, 그 client의 모든 요청이 연결이 사는 동안 같은 pod로 간다. 실패하는 것은 없다. 설정은 `round_robin`이라고 말하고, +metric은 요청이 pod가 아니라 client 사이에 퍼진 것을 보여 주며, 「client 쪽 부하 분산을 한다」는 결론은 아무도 확인할 +계기가 없는 방식으로 틀렸다. -The mirror-image mistake is `pick_first` over a headless record, which pins a client to one pod out -of many. +거울상 실수는 headless record 위의 `pick_first`다. 많은 pod 중 하나에 client를 묶는다. -Separately, a service mesh changes who owns retries, and a deployment that adds mesh routing without -removing its own retry policy has two retriers whose effects multiply. +따로, service mesh는 재시도를 누가 가지는지 바꾸고, mesh 라우팅을 더하면서 자기 재시도 정책을 빼지 않은 배포는 효과가 +곱해지는 재시도자 둘을 가진다. -## Decision +## 결정 -**Stable resolvers are Static, DNS and Unix domain socket; Stable load balancing is `pick_first` and -`round_robin`.** `GrpcDiscoveryPolicyValidator.requireStableScheme` refuses `xds`, `consul`, `etcd` -and `eureka` by name, with a message saying they are Advanced capabilities with their own control -plane and promotion gate rather than unknown schemes. +**Stable resolver는 Static, DNS, Unix domain socket이고, Stable 부하 분산은 `pick_first`와 `round_robin`이다.** +`GrpcDiscoveryPolicyValidator.requireStableScheme`은 `xds`, `consul`, `etcd`, `eureka`를 이름으로 거절하고, 그것이 모르는 +scheme이 아니라 자기 control plane과 승격 gate를 가진 Advanced capability라고 메시지로 말한다. -**The pairing is checked against the resolved address count, not against intent.** -`GrpcResolverProfile` carries `expectedAddressCount`, and `GrpcStableLoadBalancer.effective` answers -whether the policy distributes anything over that many endpoints. A `round_robin` profile over one -address is a reported violation whose message says it describes spreading that is not happening. +**짝 맞춤은 의도가 아니라 해석된 주소 수와 대조한다.** `GrpcResolverProfile`은 `expectedAddressCount`를 싣고, +`GrpcStableLoadBalancer.effective`가 그 수의 endpoint 위에서 정책이 무언가를 분산하는지 답한다. 주소 하나 위의 +`round_robin` profile은 보고되는 위반이고, 그 메시지는 그것이 일어나지 않는 퍼뜨리기를 설명한다고 말한다. -**A Kubernetes deployment names its routing mode**, and the mode implies both the balancer and the -retry owner. `GrpcKubernetesRoutingMode` has three values — `K8S_VIP`, `K8S_HEADLESS`, `MESH` — and -`GrpcKubernetesProfile` refuses a mesh profile whose retry owner retries in-process. +**Kubernetes 배포는 자기 라우팅 모드를 이름으로 대고**, 그 모드가 분산기와 재시도 소유자를 둘 다 정한다. +`GrpcKubernetesRoutingMode`에는 값이 셋 있다 — `K8S_VIP`, `K8S_HEADLESS`, `MESH` — 그리고 `GrpcKubernetesProfile`은 재시도 +소유자가 프로세스 안에서 재시도하는 mesh profile을 거절한다. -**A profile that carries long-lived streams must state a reconnect budget and a readiness drain -grace.** A stream pins a client to one pod for its whole life, so every rollout, eviction and -scale-down ends it. `GrpcKubernetesProfileValidator` additionally reports a VIP profile carrying -long streams, and a drain grace shorter than the reconnect budget — the second means the pod stops -serving before its clients have finished reconnecting elsewhere. +**오래 사는 stream을 싣는 profile은 재연결 예산과 readiness 비우기 유예를 밝혀야 한다.** stream은 사는 내내 client를 pod +하나에 묶으므로, 모든 rollout, eviction, scale-down이 그것을 끝낸다. `GrpcKubernetesProfileValidator`는 긴 stream을 싣는 +VIP profile과, 재연결 예산보다 짧은 비우기 유예도 알린다 — 후자는 client가 다른 곳으로 재연결을 마치기 전에 pod가 응답을 +멈춘다는 뜻이다. -**A DNS profile must refresh.** `GrpcResolverProfile` refuses a zero refresh interval on DNS, -because a channel that resolved once at startup keeps sending to addresses that stopped existing an -hour ago, and the resulting `UNAVAILABLE` looks like an unhealthy deployment long after the rollout -finished. +**DNS profile은 새로 고쳐야 한다.** `GrpcResolverProfile`은 DNS에서 새로 고침 간격 0을 거절한다. 기동 때 한 번 해석한 +channel은 한 시간 전에 없어진 주소로 계속 보내고, 그 결과인 `UNAVAILABLE`은 rollout이 끝난 지 한참 뒤에도 건강하지 않은 +배포처럼 보인다. -## Consequences +## 결과 -**Two validators, not one.** `GrpcDiscoveryPolicyValidator` asks whether a balancer does anything -over the addresses it will see; `GrpcKubernetesProfileValidator` asks whether the deployment shape, -the retry owner and the stream obligations agree. A deployment can have a coherent resolver profile -and still have put retries in two places, so merging them would let one answer hide the other. +**validator는 하나가 아니라 둘이다.** `GrpcDiscoveryPolicyValidator`는 분산기가 자기가 볼 주소 위에서 무언가를 하는지 +묻는다. `GrpcKubernetesProfileValidator`는 배포 모양, 재시도 소유자, stream 의무가 맞는지 묻는다. 배포는 resolver profile이 +앞뒤가 맞으면서도 재시도를 두 곳에 둘 수 있다. 그래서 둘을 합치면 한 답이 다른 답을 가린다. -**`expectedAddressCount` has to come from somewhere.** It is a declared number, and a declaration can -be wrong. It is still better than the alternative, which is not comparing anything: a wrong -declaration is a wrong statement somebody wrote down, and a missing one is a question nobody asked. -`GrpcChannelProfileValidator` takes resolved counts where they are known at startup and skips the -check where they are not, rather than guessing and failing on a name that cannot be resolved yet. +**`expectedAddressCount`는 어딘가에서 와야 한다.** 선언한 숫자이고, 선언은 틀릴 수 있다. 그래도 아무것도 비교하지 않는 +대안보다 낫다: 틀린 선언은 누가 적어 둔 틀린 말이고, 빠진 선언은 아무도 묻지 않은 질문이다. +`GrpcChannelProfileValidator`는 기동 때 알 수 있는 곳에서는 해석된 수를 받고, 알 수 없는 곳에서는 짐작해서 아직 해석할 수 +없는 이름에서 실패하는 대신 검사를 건너뛴다. -**xDS is reachable, and not by this route.** It lives in `grpc-advanced` (package `resilience`/`xds`) behind its -capability flag and its production approval, and `GrpcXdsStartupGuard.advertisableAsStableSupport()` -returns false so the Stable support statement cannot widen quietly. See ADR-GRPC-ADV-001. +**xDS에는 닿을 수 있지만, 이 길로는 아니다.** xDS는 `grpc-advanced`(패키지 `resilience`/`xds`)에서 자기 capability flag와 +운영 승인 뒤에 있고, `GrpcXdsStartupGuard.advertisableAsStableSupport()`가 false를 돌려주므로 Stable 지원 설명이 조용히 +넓어질 수 없다. ADR-GRPC-ADV-001을 본다. diff --git a/docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md b/docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md index 63e6bfde..07decf9c 100644 --- a/docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md +++ b/docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md @@ -7,60 +7,51 @@ - 현재 정본: `docs/compatibility/grpc-advanced-support-matrix.md` -# ADR-GRPC-ADV-001: Each advanced capability has its own flag, its own grade and its own promotion +# ADR-GRPC-ADV-001: advanced capability마다 자기 flag, 자기 등급, 자기 승격이 있다 -- Status: accepted -- Date: 2026-08-30 -- Scope: `:grpc-advanced:*` +- 상태: 채택 +- 날짜: 2026-08-30 +- 범위: `:grpc-advanced:*` -## Context +## 배경 -The advanced plan covers sixteen capabilities that differ by orders of magnitude in what they bring -with them. gRPC-Web adds a proxy. Reactor adds a dependency. xDS adds a control plane, its outage -modes, its own security boundary and its own version skew. Hedging duplicates production traffic. +advanced 계획은 capability 열여섯을 다룬다. 그것들이 함께 가져오는 것은 몇 자릿수씩 다르다. gRPC-Web은 proxy를 더한다. +Reactor는 의존 하나를 더한다. xDS는 control plane, 그 장애 방식, 자기 보안 경계, 자기 버전 어긋남을 더한다. hedging은 운영 +traffic을 겹친다. -Bundling them under one flag makes enabling the cheapest of those the same decision as enabling the -most consequential. +그것들을 flag 하나로 묶으면 가장 싼 것을 켜는 일이 가장 무거운 것을 켜는 일과 같은 결정이 된다. -## Decision +## 결정 -**One flag per capability**, under `ca-skeleton.grpc.advanced..enabled`, all off by -default. +**capability마다 flag 하나.** `ca-skeleton.grpc.advanced..enabled` 아래에 있고, 기본은 모두 꺼짐이다. -**Four grades.** `ADVANCED_STABLE` starts on its flag; `EXPERIMENTAL` additionally needs a separate -production approval, because the flag says somebody wanted the feature and the approval says somebody -accepted that its failure modes are not fully characterised; `WATCH` cannot start at all; `DISABLED` -is withdrawn. +**등급 넷.** `ADVANCED_STABLE`은 flag로 시작한다. `EXPERIMENTAL`은 따로 운영 승인도 필요하다. flag는 누가 그 기능을 원했다는 +뜻이고, 승인은 누가 그 장애 방식이 다 밝혀지지 않았음을 받아들였다는 뜻이기 때문이다. `WATCH`는 아예 시작할 수 없다. +`DISABLED`는 거둬들인 것이다. -`GrpcAdvancedModuleGuard` distinguishes the three refusals — flag unset, grade unstartable, -production unapproved — because the remedy differs in each case. +`GrpcAdvancedModuleGuard`는 세 거절 — flag 없음, 시작할 수 없는 등급, 운영 승인 없음 — 을 구별한다. 경우마다 고치는 법이 +다르기 때문이다. -**Promotion evidence is per capability.** `GrpcAdvancedPromotionEvidence` is one record per -capability, so no promotion can drag another along; -`GrpcAdvancedPromotionGate.capabilitiesDraggedAlong` returns an empty list, and that is a tested -property rather than a claim. (2026-09-28: the gate classes were removed because nothing outside -their own tests called them — review 2026-09-24 S5-lead-4. The per-capability rule stands as a -review rule in `docs/runbooks/grpc-advanced-capabilities.md`.) Two thresholds: seven days of soak plus complete evidence for -`ADVANCED_STABLE`, thirty for a Stable default, because the second means every deployment gets the -capability's dependencies and its failure modes. +**승격 증거는 capability마다다.** `GrpcAdvancedPromotionEvidence`는 capability마다 record 하나라서, 어떤 승격도 다른 것을 +끌고 가지 못한다. `GrpcAdvancedPromotionGate.capabilitiesDraggedAlong`은 빈 목록을 돌려주고, 그것은 주장이 아니라 시험한 +성질이다. (2026-09-28: gate 클래스는 자기 시험 밖에서 부르는 것이 없어서 지웠다 — review 2026-09-24 S5-lead-4. +capability별 규칙은 `docs/runbooks/grpc-advanced-capabilities.md`의 리뷰 규칙으로 남는다.) 문턱은 둘이다: +`ADVANCED_STABLE`에는 7일 soak와 완전한 증거, Stable 기본값에는 30일. 후자는 모든 배포가 그 capability의 의존과 장애 방식을 +받는다는 뜻이기 때문이다. -**Infrastructure is named per capability.** `GrpcAdvancedInfrastructureTestkit` records that -gRPC-Web needs a proxy, Servlet needs a container, xDS needs a stoppable control plane and Kotlin -needs a toolchain. A suite that runs without its infrastructure passes and establishes nothing, which -is worse than not having one. +**기반 시설은 capability마다 이름으로 댄다.** `GrpcAdvancedInfrastructureTestkit`은 gRPC-Web에는 proxy가, Servlet에는 +container가, xDS에는 멈출 수 있는 control plane이, Kotlin에는 toolchain이 필요하다고 적는다. 기반 시설 없이 도는 suite는 +통과하고 아무것도 세우지 않는다. 없는 것보다 나쁘다. -## Consequences +## 결과 -**The Kotlin adapter fails closed here, and says why.** This repository has no Kotlin toolchain, so -`GrpcKotlinCompatibilityGate.supportableHere()` returns false. The four contract requirements — one -schema source, coroutine cancellation propagation, Flow backpressure inside the Stable bounds, -platform evidence types preserved — are checkable and are checked; only the compile lane is missing. +**Kotlin 어댑터는 여기서 실패하면 닫히고, 이유를 말한다.** 이 저장소에는 Kotlin toolchain이 없어서 +`GrpcKotlinCompatibilityGate.supportableHere()`가 false를 돌려준다. 계약 요구 넷 — schema 출처 하나, coroutine 취소 전파, +Stable 한계 안의 Flow backpressure, 플랫폼 증거 타입 보존 — 은 검사할 수 있고 검사한다. 빠진 것은 compile lane뿐이다. -**Edition 2026 cannot be used however its watch report reads.** `GrpcEdition2026Guard` is not -conditional on the report, because letting a status record also authorise use means a schema moves -onto an edition the moment somebody marks four fields SUPPORTED, with no promotion decision, no -consumer migration and no ADR. +**Edition 2026은 그 watch 보고가 무어라 하든 쓸 수 없다.** `GrpcEdition2026Guard`는 보고에 따라 달라지지 않는다. 상태 기록이 +사용까지 허락하게 두면, 누가 필드 넷을 SUPPORTED로 표시하는 순간 schema가 승격 결정도, 쓰는 쪽 옮기기도, ADR도 없이 그 +edition으로 옮겨 가기 때문이다. -**xDS is not part of the Stable support statement.** It works, behind its flag and its approval; -`GrpcXdsStartupGuard.advertisableAsStableSupport()` returns false so a support matrix cannot widen -quietly. +**xDS는 Stable 지원 설명의 일부가 아니다.** flag와 승인 뒤에서 동작한다. `GrpcXdsStartupGuard.advertisableAsStableSupport()`가 +false를 돌려주므로 support matrix가 조용히 넓어질 수 없다. diff --git a/docs/adr/ADR-JPA-001-domain-owns-persistence-model.md b/docs/adr/ADR-JPA-001-domain-owns-persistence-model.md index 24a06a89..65d7427e 100644 --- a/docs/adr/ADR-JPA-001-domain-owns-persistence-model.md +++ b/docs/adr/ADR-JPA-001-domain-owns-persistence-model.md @@ -7,38 +7,34 @@ - 현재 정본: `docs/jpa/repository-adaptation.md` -# ADR-JPA-001 — The domain owns the persistence model +# ADR-JPA-001 — 영속 모델은 도메인이 가진다 -- Status: Accepted -- Date: 2026-08-11 -- Design: §10.1, §23.3 +- 상태: 채택 +- 날짜: 2026-08-11 +- 설계: §10.1, §23.3 -## Context +## 배경 -A persistence platform can either own the repository abstraction — a `GenericRepository` -every aggregate inherits — or provide only the pieces domains assemble themselves. +영속 플랫폼은 repository 추상 — 모든 aggregate가 상속하는 `GenericRepository` — 을 가질 수도 있고, 도메인이 스스로 +조립할 조각만 줄 수도 있다. -## Decision +## 결정 -The domain owns entities, embeddables, repositories, queries, index requirements, and lock, -soft-delete, and audit policy. The platform provides no generic CRUD repository and no base -repository. `JpaRepositoryFragmentSupport` exists, has no `save`, `findById`, `findAll`, or -`delete`, and is enforced not to acquire them. +엔티티, embeddable, repository, query, index 요구, lock·soft-delete·감사 정책은 도메인이 가진다. 플랫폼은 범용 CRUD +repository도 기반 repository도 주지 않는다. `JpaRepositoryFragmentSupport`는 있지만 `save`, `findById`, `findAll`, `delete`가 +없고, 그것을 얻지 못하게 강제한다. -## Consequences +## 결과 -A generic base repository has one property that looks like a benefit and is not: every aggregate -gets the same operations. That means each aggregate is offered operations that may be wrong for it — -a `delete` on an append-only ledger, a `findAll` on a table that will never be small — and, worse, -one aggregate's later requirement changes the shared base and therefore changes behaviour for -aggregates nobody reviewed. +범용 기반 repository에는 이득처럼 보이지만 이득이 아닌 성질이 하나 있다: 모든 aggregate가 같은 operation을 받는다. 그러면 +aggregate마다 자기에게 틀릴 수 있는 operation을 받게 된다 — append-only 원장의 `delete`, 결코 작지 않을 테이블의 `findAll` — +그리고 더 나쁘게, 한 aggregate의 나중 요구가 공용 기반을 바꾸고 그래서 아무도 리뷰하지 않은 aggregate의 동작을 바꾼다. -Spring Data already implements CRUD. Re-implementing it adds a layer whose only function is to be -harder to opt out of. +Spring Data는 이미 CRUD를 구현한다. 그것을 다시 구현하면 빠져나가기 더 어렵게 만드는 것만이 하는 일인 계층이 더해진다. -The cost is a small amount of repetition: each domain declares the repository interface it needs. -That repetition is the thing that makes each aggregate's persistence surface reviewable. +비용은 약간의 되풀이다: 도메인마다 필요한 repository 인터페이스를 선언한다. 그 되풀이가 aggregate마다 영속 surface를 리뷰할 +수 있게 만든다. -## Enforcement +## 강제 -`JpaArchitectureRules.noGenericRepository()`; `JpaRepositoryFragmentSupportTest`. +`JpaArchitectureRules.noGenericRepository()`, `JpaRepositoryFragmentSupportTest`. diff --git a/docs/adr/ADR-JPA-002-full-transaction-retry.md b/docs/adr/ADR-JPA-002-full-transaction-retry.md index a2491bce..fb5f1e36 100644 --- a/docs/adr/ADR-JPA-002-full-transaction-retry.md +++ b/docs/adr/ADR-JPA-002-full-transaction-retry.md @@ -8,43 +8,39 @@ - 대체됨: `docs/capability-status.md` -# ADR-JPA-002 — Retry re-runs the whole use case +# ADR-JPA-002 — 재시도는 유스케이스 전체를 다시 돌린다 -- Status: Superseded (2026-09-25) — the retry engine this ADR describes - (`FullTransactionRetryCoordinator`, `JpaTransactionExecutor`) was removed. `SpringTransactionPort` - retries nothing; a caller that retries still re-runs the whole use case, which is the part of this - decision that stands. The last commit is in `docs/capability-status.md`. -- Date: 2026-08-11 -- Design: §19.2 +- 상태: 대체됨(2026-09-25) — 이 ADR이 설명하는 재시도 엔진(`FullTransactionRetryCoordinator`, `JpaTransactionExecutor`)은 + 지웠다. `SpringTransactionPort`는 아무것도 재시도하지 않는다. 재시도하는 호출자는 여전히 유스케이스 전체를 다시 돌리고, + 이 결정 중 그 부분이 남는다. 마지막 커밋은 `docs/capability-status.md`에 있다. +- 날짜: 2026-08-11 +- 설계: §19.2 -## Context +## 배경 -Optimistic conflicts, deadlocks, and serialization failures are recoverable. The question is what -unit gets retried: the failed statement, the transaction, or the use case. +낙관적 충돌, 교착, serialization 실패는 회복할 수 있다. 질문은 무엇을 단위로 재시도하느냐다: 실패한 문장, 트랜잭션, 또는 +유스케이스. -## Decision +## 결정 -The whole use case, in a new transaction with a new Persistence Context. -`FullTransactionRetryCoordinator` re-enters `JpaTransactionExecutor` for every attempt, and the -retry advice is ordered outside Spring's transaction advice so each attempt begins a new -transaction. +유스케이스 전체를, 새 Persistence Context를 가진 새 트랜잭션에서. `FullTransactionRetryCoordinator`는 시도마다 +`JpaTransactionExecutor`에 다시 들어가고, 재시도 advice는 Spring 트랜잭션 advice 바깥으로 순서를 잡아 시도마다 새 +트랜잭션을 시작한다. -## Consequences +## 결과 -Statement-level retry is wrong for exactly the failures being retried. An optimistic conflict means -the state the attempt computed against is no longer the committed state; re-issuing the same -statement computes the same wrong answer against a version that has moved on. The domain rules have -to run again over reloaded data, which means the whole use case. +문장 단위 재시도는 바로 재시도하려는 실패에 틀린 답이다. 낙관적 충돌은 시도가 계산의 바탕으로 삼은 상태가 더는 커밋된 +상태가 아니라는 뜻이다. 같은 문장을 다시 내면 이미 움직인 version에 대고 같은 틀린 답을 계산한다. 도메인 규칙은 다시 읽은 +데이터 위에서 다시 돌아야 하고, 그것은 유스케이스 전체라는 뜻이다. -Reusing the Persistence Context would be equally wrong: the second attempt would read the first -attempt's stale entities out of the first-level cache. And with the advice ordering inverted, the -retry loop would run inside one transaction that has already been marked rollback-only, so the -second attempt fails immediately without executing anything. +Persistence Context를 다시 쓰는 것도 똑같이 틀렸다: 두 번째 시도가 1차 cache에서 첫 시도의 낡은 엔티티를 읽게 된다. 그리고 +advice 순서가 뒤집히면 재시도 반복문이 이미 rollback-only로 표시된 트랜잭션 하나 안에서 돌아서, 두 번째 시도가 아무것도 +실행하지 않고 바로 실패한다. -The cost is that a retryable use case must be safe to run from scratch — no irreversible external -effect before the commit. `IrreversibleSideEffectContext` lets a use case declare when that does not -hold, and the policy then refuses to retry it whatever budget remains. +비용은 재시도할 수 있는 유스케이스가 처음부터 돌려도 안전해야 한다는 것이다 — 커밋 전에 되돌릴 수 없는 외부 효과가 없어야 +한다. `IrreversibleSideEffectContext`로 유스케이스가 그렇지 않을 때를 선언할 수 있고, 그러면 정책은 남은 예산이 얼마든 그 +재시도를 거절한다. -## Enforcement +## 강제 -`FullTransactionRetryCoordinatorTest`; `RetryableJpaTransactionInterceptor.DEFAULT_ORDER`. +`FullTransactionRetryCoordinatorTest`, `RetryableJpaTransactionInterceptor.DEFAULT_ORDER`. diff --git a/docs/adr/ADR-JPA-003-completion-unknown.md b/docs/adr/ADR-JPA-003-completion-unknown.md index c283d6db..eef2a271 100644 --- a/docs/adr/ADR-JPA-003-completion-unknown.md +++ b/docs/adr/ADR-JPA-003-completion-unknown.md @@ -7,57 +7,49 @@ - 현재 정본: `docs/jpa/transaction-guide.md` -# ADR-JPA-003 — Completion unknown is never retried +# ADR-JPA-003 — 완료를 모름은 절대 재시도하지 않는다 -- Status: Accepted; amended 2026-09-25 — `TransactionCompletionResolver`, `CommitFailureClassifier` - and the retry engine were removed. The invariant holds because `SpringTransactionPort`, the only - transaction engine, retries nothing; enforcement below is updated accordingly. -- Date: 2026-08-11 -- Design: §17 +- 상태: 채택. 2026-09-25 보완 — `TransactionCompletionResolver`, `CommitFailureClassifier`, 재시도 엔진을 지웠다. 유일한 + 트랜잭션 엔진인 `SpringTransactionPort`가 아무것도 재시도하지 않으므로 불변식이 지켜진다. 아래 강제 절도 그에 맞게 + 고쳤다. +- 날짜: 2026-08-11 +- 설계: §17 -## Context +## 배경 -A connection can break while a commit is in flight. The server may have committed; the -acknowledgement may simply have been lost. The driver cannot tell the two apart. +커밋이 진행 중일 때 연결이 끊길 수 있다. 서버가 커밋했을 수도 있고, 확인 응답만 잃었을 수도 있다. driver는 둘을 구별하지 +못한다. -## Decision +## 결정 -`TransactionCompletionUnknownException` is never retried, automatically or otherwise. It is -produced only by a failure observed while the transaction phase is `COMMITTING`, and only for -SQLSTATE `40003`, a connection-class (`08*`) state, or a transport break. Recovery is -domain-specific reconciliation. +`TransactionCompletionUnknownException`은 자동이든 아니든 절대 재시도하지 않는다. 트랜잭션 단계가 `COMMITTING`인 동안 본 +실패에서만, 그리고 SQLSTATE `40003`, 연결 class(`08*`) 상태, 전송 끊김에 대해서만 만든다. 회복은 도메인별 맞춰 보기다. -## Consequences +## 결과 -Retrying a possibly-committed write is the most damaging thing this platform could do: a duplicate -payment, a duplicate order, a double decrement. There is no budget or backoff that makes it safe, -because the failure is epistemic rather than transient. +커밋됐을지 모르는 쓰기를 재시도하는 것이 이 플랫폼이 할 수 있는 가장 해로운 일이다: 중복 결제, 중복 주문, 두 번 깎기. +실패가 일시적인 것이 아니라 알 수 없는 것이라서, 그것을 안전하게 만드는 예산이나 backoff는 없다. -The invariant is enforced at the type level rather than by policy alone. `JpaFailureContext` refuses -to construct a retryable completion-unknown context, and the exception rebuilds its context through -the safe factory whatever it is handed. A future policy bug therefore cannot produce an unsafe -retry — the value it would need does not exist. +불변식은 정책만이 아니라 타입 수준에서 강제한다. `JpaFailureContext`는 재시도할 수 있는 completion-unknown 문맥을 만들기를 +거절하고, 예외는 무엇을 받든 안전한 factory로 자기 문맥을 다시 만든다. 그래서 나중의 정책 결함이 안전하지 않은 재시도를 낳을 +수 없다 — 그것에 필요한 값이 존재하지 않는다. -The rule is deliberately narrow in the other direction too. Classifying every connection failure as -completion-unknown would push ordinary pool exhaustion and server restarts into the reconciliation -queue, which trains operators to clear that queue without reading it — and then the one entry that -mattered gets cleared with the rest. +규칙은 반대 방향으로도 일부러 좁다. 모든 연결 실패를 completion-unknown으로 분류하면 보통의 pool 고갈과 서버 재시작이 맞춰 +보기 queue로 밀려 들어가고, 그것은 운영자에게 그 queue를 읽지 않고 비우도록 길들인다 — 그러면 중요했던 항목 하나가 나머지와 +함께 지워진다. -The cost is that the domain must supply the resolver. The platform cannot: only the domain knows -which idempotency record, business row, or outbox entry proves the write happened. +비용은 도메인이 resolver를 줘야 한다는 것이다. 플랫폼은 할 수 없다: 어떤 멱등성 레코드, 업무 행, outbox 항목이 쓰기가 +일어났음을 증명하는지는 도메인만 안다. -## Enforcement +## 강제 -Production path: `SpringTransaction` records when the action has returned in a write transaction it -began; a failure after that point goes through -`PersistenceExceptionTranslator#translateCommitFailure`, which builds this exception for `08*`, -`40003`, a vendor termination state (`SqlStateErrorMapping#commitOutcomeUnknownStates`, PostgreSQL -`57P01`/`57P02`) or a transport break. Hibernate's flush inside the commit is not separated from the -COMMIT itself, so a connection lost during that flush is also reported as unknown — the safe side. -Until review 04-01 (2026-11-01) nothing constructed the exception and a commit-phase `08*` reached -callers as the retryable `DB_UNAVAILABLE`. +운영 경로: `SpringTransaction`은 자기가 시작한 쓰기 트랜잭션에서 action이 돌아온 때를 기록한다. 그 뒤의 실패는 +`PersistenceExceptionTranslator#translateCommitFailure`를 거치고, 그것이 `08*`, `40003`, vendor 종료 상태 +(`SqlStateErrorMapping#commitOutcomeUnknownStates`, PostgreSQL `57P01`/`57P02`), 전송 끊김에 대해 이 예외를 만든다. 커밋 안의 +Hibernate flush는 COMMIT 자체와 나뉘지 않으므로, 그 flush 중에 잃은 연결도 모름으로 알린다 — 안전한 쪽이다. review +04-01(2026-11-01) 전까지는 아무것도 이 예외를 만들지 않았고, 커밋 단계의 `08*`가 재시도할 수 있는 `DB_UNAVAILABLE`로 호출자에게 +닿았다. -`JpaFailureContextTest`; `SpringTransactionTest`; `PersistenceExceptionTranslatorTest`; +`JpaFailureContextTest`, `SpringTransactionTest`, `PersistenceExceptionTranslatorTest`, `PostgreSqlTransactionIntegrationTest#connectionLossDuringCommitSurfacesAsCompletionUnknownAndIsNeverRetried` -(asserts `DB_COMPLETION_UNKNOWN`; also the `jpa-failure` lane, i.e. release gate -`completion-unknown-no-retry`). +(`DB_COMPLETION_UNKNOWN`을 단언한다. `jpa-failure` lane, 곧 릴리스 gate `completion-unknown-no-retry`이기도 하다). diff --git a/docs/adr/ADR-JPA-004-flyway-schema-source-of-truth.md b/docs/adr/ADR-JPA-004-flyway-schema-source-of-truth.md index 63be96de..fbd69256 100644 --- a/docs/adr/ADR-JPA-004-flyway-schema-source-of-truth.md +++ b/docs/adr/ADR-JPA-004-flyway-schema-source-of-truth.md @@ -7,41 +7,37 @@ - 현재 정본: `docs/jpa/migration-guide.md` -# ADR-JPA-004 — Flyway is the schema source of truth +# ADR-JPA-004 — schema의 정본은 Flyway다 -- Status: Accepted -- Date: 2026-08-11 -- Design: §31 +- 상태: 채택 +- 날짜: 2026-08-11 +- 설계: §31 -## Context +## 배경 -Hibernate can create and alter schema from the entity mapping. Flyway can apply versioned scripts. -Both cannot own the schema. +Hibernate는 엔티티 대응에서 schema를 만들고 바꿀 수 있다. Flyway는 버전 있는 script를 적용할 수 있다. 둘이 함께 schema를 가질 +수는 없다. -## Decision +## 결정 -Flyway owns every schema change. Hibernate validates and never mutates: `ddl-auto` is `validate` or -`none`, enforced at startup. The runtime database credential holds no DDL privilege, so the rule is -enforced by the server as well as by configuration. +모든 schema 변경은 Flyway가 가진다. Hibernate는 검증만 하고 절대 바꾸지 않는다: `ddl-auto`는 `validate`나 `none`이고, 기동 때 +강제한다. 런타임 데이터베이스 credential에는 DDL 권한이 없으므로, 규칙을 설정만이 아니라 서버도 강제한다. -## Consequences +## 결과 -`ddl-auto=update` fails in a specific and expensive way: it adds but never drops or narrows, so the -result is a schema that is neither the previous one nor the one the mappings describe — produced -silently, by whichever instance started first, with no record of what it did. +`ddl-auto=update`는 구체적이고 비싸게 실패한다: 더하기만 하고 지우거나 좁히지 않아서, 결과는 이전 것도 대응이 설명하는 것도 +아닌 schema다 — 먼저 시작한 인스턴스가 무엇을 했는지 기록도 없이 소리 없이 만든다. -Two credentials rather than one is what makes this more than a convention. A configuration rule can -be overridden by a property; a role without `CREATE` cannot be overridden by anything the -application does. +credential을 하나가 아니라 둘 두는 것이 이것을 관례 이상으로 만든다. 설정 규칙은 속성 하나로 덮을 수 있다. `CREATE`가 없는 +role은 애플리케이션이 무엇을 하든 덮을 수 없다. -Validation fails closed and never repairs. `repair` rewrites the schema history to match the scripts -on disk, which resolves a checksum mismatch by deleting the evidence of which change is missing. +검증은 실패하면 닫히고 절대 고치지 않는다. `repair`는 schema 이력을 디스크의 script에 맞게 다시 쓰는데, 그것은 어떤 변경이 +빠졌는지의 증거를 지워서 checksum 불일치를 푸는 것이다. -The cost is that a schema change requires a migration script and a deployment step. That is the -intended cost: it makes schema change reviewable and reversible. +비용은 schema 변경에 migration script와 배포 단계가 필요하다는 것이다. 그것이 의도한 비용이다: schema 변경을 리뷰할 수 있고 +되돌릴 수 있게 만든다. -## Enforcement +## 강제 -`JpaDangerousConfigurationGuard`; `FlywaySchemaPolicy`; `FlywayValidationGate` (testkit, used by the -migration contract tests); `PostgreSqlRuntimeRoleVerifier`; release gates `flyway-validate` and -`runtime-role-no-ddl`. +`JpaDangerousConfigurationGuard`, `FlywaySchemaPolicy`, `FlywayValidationGate`(testkit, migration 계약 시험이 쓴다), +`PostgreSqlRuntimeRoleVerifier`, 릴리스 gate `flyway-validate`와 `runtime-role-no-ddl`. diff --git a/docs/adr/ADR-JPA-005-postgresql-real-contract.md b/docs/adr/ADR-JPA-005-postgresql-real-contract.md index 116d2487..26223db6 100644 --- a/docs/adr/ADR-JPA-005-postgresql-real-contract.md +++ b/docs/adr/ADR-JPA-005-postgresql-real-contract.md @@ -7,41 +7,36 @@ - 현재 정본: `docs/jpa/support-matrix.md` -# ADR-JPA-005 — Contracts run against real PostgreSQL +# ADR-JPA-005 — 계약은 실제 PostgreSQL에 대고 돈다 -- Status: Accepted -- Date: 2026-08-11 -- Design: §40 +- 상태: 채택 +- 날짜: 2026-08-11 +- 설계: §40 -## Context +## 배경 -An in-memory database makes tests fast and hermetic. A container makes them slow and requires -Docker. +메모리 데이터베이스는 시험을 빠르고 밀폐되게 만든다. container는 느리게 만들고 Docker를 요구한다. -## Decision +## 결정 -Every persistence contract runs against real PostgreSQL 16, 17, and 18 in containers. H2 remains a -local-development convenience and never satisfies a contract. The lanes fail closed when Docker is -absent rather than skipping. +모든 영속 계약은 container 안의 실제 PostgreSQL 16, 17, 18에 대고 돈다. H2는 로컬 개발 편의로 남고 어떤 계약도 만족시키지 +않는다. Docker가 없으면 lane은 건너뛰지 않고 실패하면 닫힌다. -## Consequences +## 결과 -The behaviours these contracts verify either do not exist in H2 or differ there: SQLSTATE values for -the same violation, `FOR UPDATE SKIP LOCKED` semantics, JSONB operators, range types, concurrent -index builds, `search_path` privileges, and the generated SQL for a paged collection fetch. A green -H2 run is evidence that the code compiles and runs — not that any of the above holds. +이 계약이 검증하는 동작은 H2에 없거나 다르다: 같은 위반의 SQLSTATE 값, `FOR UPDATE SKIP LOCKED`의 뜻, JSONB 연산자, 범위 타입, +concurrent index 만들기, `search_path` 권한, page를 나눈 컬렉션 fetch의 생성 SQL. H2 실행이 초록이면 코드가 컴파일되고 돈다는 +증거이지 — 위 어느 것이 지켜진다는 증거가 아니다. -Three versions rather than one because the platform claims three. A contract suite that ran only on -16 would make "Stable on 17 and 18" an assumption. +버전을 하나가 아니라 셋 두는 것은 플랫폼이 셋을 주장하기 때문이다. 16에서만 도는 계약 suite는 「17과 18에서 Stable」을 가정으로 +만든다. -Skipping on missing Docker is the failure mode this decision most wants to avoid: a skipped contract -reports success, and CI eventually inherits that silence. `PostgreSqlContainerFactory.assertDockerAvailable()` -throws instead. +Docker가 없을 때 건너뛰는 것이 이 결정이 가장 피하려는 실패 방식이다: 건너뛴 계약은 성공을 알리고, CI는 결국 그 침묵을 +물려받는다. `PostgreSqlContainerFactory.assertDockerAvailable()`은 대신 던진다. -The cost is that the contract lanes need Docker and take minutes. The unit lane stays hermetic and -fast, and is where most tests live; the container lanes verify the things only a real server can -answer. +비용은 계약 lane에 Docker가 필요하고 몇 분이 걸린다는 것이다. 단위 lane은 밀폐되고 빠른 채로 남고 대부분의 시험이 거기 있다. +container lane은 실제 서버만 답할 수 있는 것을 검증한다. -## Enforcement +## 강제 -`PostgreSqlVersion.stable()`; `PostgreSqlContainerFactory`; release gate `postgresql-contract`. +`PostgreSqlVersion.stable()`, `PostgreSqlContainerFactory`, 릴리스 gate `postgresql-contract`. diff --git a/docs/adr/ADR-JPA-006-canonical-technical-audit.md b/docs/adr/ADR-JPA-006-canonical-technical-audit.md index 80aadd31..476d9ce3 100644 --- a/docs/adr/ADR-JPA-006-canonical-technical-audit.md +++ b/docs/adr/ADR-JPA-006-canonical-technical-audit.md @@ -7,68 +7,58 @@ - 현재 정본: `docs/jpa/repository-adaptation.md` -# ADR-JPA-006 — `audit` is the sole technical audit model +# ADR-JPA-006 — 기술 감사 모델은 `audit` 하나뿐이다 -- Status: Accepted -- Date: 2026-08-24 -- Review: `docs/reviews/2026-08-14-jpa-module-code-review.md` JPA-022 +- 상태: 채택 +- 날짜: 2026-08-24 +- 리뷰: `docs/reviews/2026-08-14-jpa-module-code-review.md` JPA-022 -## Context +## 배경 -Two complete technical-audit mechanisms live in this leaf and they disagree about the schema. +이 leaf에 완전한 기술 감사 장치가 둘 있고, 둘은 schema에 대해 의견이 다르다. -`audit/AuditableEntity` stamps `created_at`/`created_by`/`updated_at`/`updated_by` with an actor -column of length 256, captured through explicit `initializeAudit`/`applyModification` calls and an -`AuditContextPort`. `auditing/AuditMetadata` is a Spring Data embeddable that stamps -`created_*`/`modified_*` with an actor column of length 64, captured by `@CreatedDate` and friends -through an `AuditorAware`. +`audit/AuditableEntity`는 길이 256의 actor 열과 함께 `created_at`/`created_by`/`updated_at`/`updated_by`를 넣고, 명시적인 +`initializeAudit`/`applyModification` 호출과 `AuditContextPort`로 값을 잡는다. `auditing/AuditMetadata`는 길이 64의 actor 열과 +함께 `created_*`/`modified_*`를 넣는 Spring Data embeddable이고, `AuditorAware`를 거쳐 `@CreatedDate` 같은 것으로 값을 잡는다. -Only the first is real: it is what the sample entities extend and what the migrations were written -for. `JpaAuditingConfiguration` is not a Spring `@Configuration`, and nothing in production -constructs any of the three `auditing` types. +실제로 쓰이는 것은 첫째뿐이다: 샘플 엔티티가 상속하는 것이고 migration도 그것을 위해 썼다. `JpaAuditingConfiguration`은 Spring +`@Configuration`이 아니고, 운영 코드의 어떤 것도 `auditing` 타입 셋 중 하나를 만들지 않는다. -The review asked for one canonical model with a migration or activation decision. The failure mode -it was protecting against is specific: an author of a new entity picks whichever package they find -first, and column names, actor lengths and capture lifecycles then diverge per table. +리뷰는 migration이나 켜기 결정이 붙은 정해진 모델 하나를 요구했다. 막으려던 실패 방식은 구체적이다: 새 엔티티를 쓰는 사람이 +먼저 찾은 패키지를 고르고, 그러면 열 이름, actor 길이, 값 잡는 lifecycle이 테이블마다 갈라진다. -## Decision +## 결정 -`audit/AuditableEntity` is canonical and the unused `auditing/*` implementation is removed. +`audit/AuditableEntity`가 정본이고, 쓰지 않는 `auditing/*` 구현은 지운다. -Keeping a complete, incompatible implementation as a dormant candidate created exactly the -ambiguity the review warned about: a new entity could choose a package by autocomplete and silently -change column names, actor bounds and capture lifecycle. A future move to Spring Data auditing is a -migration of the canonical model, not activation of a second model that has drifted beside it. +완전하고 호환되지 않는 구현을 잠든 후보로 두는 것이 바로 리뷰가 경고한 모호함을 만들었다: 새 엔티티가 자동 완성으로 패키지를 +고르고 열 이름, actor 한계, 값 잡는 lifecycle을 소리 없이 바꿀 수 있었다. 나중에 Spring Data auditing으로 옮기는 것은 정본 +모델의 migration이지, 옆에서 어긋나 온 두 번째 모델을 켜는 것이 아니다. -That future migration must preserve `created_*`/`updated_*`, the 256-character actor contract, -`AuditContextPort`, and the shared `Clock`; listener wiring and entity conversion land atomically. +그 나중의 migration은 `created_*`/`updated_*`, 256자 actor 계약, `AuditContextPort`, 공용 `Clock`을 지켜야 한다. listener 배선과 +엔티티 변환은 한 번에 들어온다. -## Consequences +## 결과 -Two audit mechanisms remain readable in one leaf, and a reader has to be told which one is live. -That cost is paid in this document, in the package javadoc and in a test whose name says so. +감사 장치 둘이 한 leaf 안에 읽을 수 있게 남고, 읽는 사람에게 어느 것이 살아 있는지 알려야 한다. 그 비용은 이 문서, 패키지 +javadoc, 그리고 이름이 그것을 말하는 시험이 낸다. -Two failure modes stay silent unless they are asserted, so both are: +단언하지 않으면 소리 없이 남는 실패 방식이 둘 있으므로, 둘 다 단언한다: -- The candidate acquires a stereotype and starts stamping in every deployment that has this module - on the classpath, including the ones whose tables have no `modified_*` columns — where the result - is a failed startup rather than a feature. -- Somebody "harmonises" the two by editing one side's column names, at which point the schema a - deployed table was migrated for and the schema its entity expects diverge with no migration - between them. +- 후보가 stereotype을 얻어 이 모듈이 classpath에 있는 모든 배포에서 값을 넣기 시작한다. 테이블에 `modified_*` 열이 없는 배포도 + 포함된다 — 거기서 결과는 기능이 아니라 기동 실패다. +- 누가 한쪽 열 이름을 고쳐 둘을 「맞춘다」. 그러면 배포된 테이블이 migration된 schema와 그 엔티티가 기대하는 schema가 둘 사이 + migration 없이 갈라진다. -If the candidate is ever promoted, it is promoted atomically: forward migration, sample conversion, -`AuditContextPort → AuditorAware` and `Clock → DateTimeProvider` bridges land together, and this -ADR is superseded rather than amended. +후보를 언젠가 승격하면 한 번에 승격한다: 앞으로 가는 migration, 샘플 변환, `AuditContextPort → AuditorAware`와 +`Clock → DateTimeProvider` 다리가 함께 들어오고, 이 ADR은 보완이 아니라 대체된다. -Bulk and native updates stamp nothing under either mechanism. That is a property of JPA, not of the -choice made here, so it is enforced separately rather than assumed away. +bulk·native update는 어느 장치에서든 아무것도 넣지 않는다. 그것은 여기서 고른 것의 성질이 아니라 JPA의 성질이므로, 없다고 +치지 않고 따로 강제한다. -## Enforcement +## 강제 -`JpaAuditMechanismRule.entitiesUseExactlyOneAuditMechanism` and -`bulkUpdatesOfAuditedEntitiesStampAudit`, run against the real production graph by -`JpaProductionArchitectureTest` at the composition root — not against fixtures, which is how the -earlier version of this rule pack passed while applying to nothing. `AuditingCandidateStatusTest` -asserts the candidate carries no composing stereotype and that the two column sets stay distinct. -`JpaAuditMechanismRuleTest` exercises the rules' own negative cases. +`JpaAuditMechanismRule.entitiesUseExactlyOneAuditMechanism`과 `bulkUpdatesOfAuditedEntitiesStampAudit`를 조립 루트의 +`JpaProductionArchitectureTest`가 실제 운영 그래프에 대고 돌린다 — fixture가 아니다. 이 규칙 묶음의 앞 버전은 fixture에 대고 +돌아서 아무것에도 적용되지 않은 채 통과했다. `AuditingCandidateStatusTest`가 후보에 조립하는 stereotype이 없고 두 열 집합이 +따로 남는다고 단언한다. `JpaAuditMechanismRuleTest`가 규칙 자신의 부정 경우를 시험한다. diff --git a/docs/adr/ADR-MONGO-001-platform-boundary.md b/docs/adr/ADR-MONGO-001-platform-boundary.md index 62358927..7da70fc2 100644 --- a/docs/adr/ADR-MONGO-001-platform-boundary.md +++ b/docs/adr/ADR-MONGO-001-platform-boundary.md @@ -7,66 +7,59 @@ - 현재 정본: `docs/mongodb/repository-adaptation.md` -# ADR-MONGO-001 — MongoDB platform boundary +# ADR-MONGO-001 — MongoDB 플랫폼 경계 -- **Status:** Accepted -- **Date:** 2026-08-13 -- **Design source:** `docs/superpowers/specs/2026-08-11-mongodb-document-persistence-platform-design.md` §1, §2 (D-01, D-04, D-05), §5, §6 +- **상태:** 채택 +- **날짜:** 2026-08-13 +- **설계 출처:** `docs/superpowers/specs/2026-08-11-mongodb-document-persistence-platform-design.md` §1, §2 (D-01, D-04, D-05), §5, §6 -## Context +## 배경 -Two failure modes are common when a team wraps MongoDB. +팀이 MongoDB를 감쌀 때 흔한 실패 방식이 둘 있다. -The first is flattening: a shared `CommonMongoRepository` and a generic CRUD facade, which -forces every collection to share an id strategy, a consistency profile and a query surface. MongoDB's -single-document atomicity, aggregation model and change streams stop being reachable, and the first -collection that needs something different gets a cast or a leaky generic. +첫째는 납작하게 만들기다: 공용 `CommonMongoRepository`와 범용 CRUD 창구. 모든 collection이 id 전략, 일관성 profile, +query surface를 같이 쓰게 강요한다. MongoDB의 단일 문서 원자성, aggregation 모델, change stream에 더는 닿을 수 없고, 다른 것이 +필요한 첫 collection은 cast나 새는 제네릭을 받는다. -The second is unrestricted exposure: the driver and `runCommand` available everywhere. Then any -service can drop a collection, run an unbounded pipeline, or issue an admin command from a request -thread, and no review catches it because there is nothing structural to catch. +둘째는 제한 없는 노출이다: driver와 `runCommand`를 어디서나 쓸 수 있다. 그러면 어느 서비스든 요청 스레드에서 collection을 +지우거나, 한계 없는 pipeline을 돌리거나, admin 명령을 낼 수 있고, 구조로 잡을 것이 없으니 어떤 리뷰도 잡지 못한다. -## Decision +## 결정 -The domain owns its documents; the platform owns the cross-cutting decisions. Four exposure planes: +도메인이 자기 문서를 가지고, 플랫폼이 가로지르는 결정을 가진다. 노출 plane 넷: -| Plane | Contents | Client | +| plane | 내용 | client | |---|---|---| -| D1 Standard document persistence | Spring Data repositories, typed queries, mapping manifest, atomic update primitives, optimistic revision | Stable API V1, `apiStrict=true` | -| D2 Advanced document operations | `MongoTemplate`, transactions/sessions, bulk, aggregation, keyset cursors, change streams | Stable API V1, `apiStrict=true` | -| D3 Explicit Mongo capability | Native BSON, time series, search/vector, CSFLE/QE, shard-aware operations | Separate capability client | -| D4 Admin plane | Collection, validator, index, migration, shard, repair | Separate admin client and credential | +| D1 표준 문서 영속 | Spring Data repository, 타입 있는 query, 대응 manifest, 원자 update 기본 장치, 낙관적 revision | Stable API V1, `apiStrict=true` | +| D2 고급 문서 연산 | `MongoTemplate`, 트랜잭션·세션, bulk, aggregation, keyset cursor, change stream | Stable API V1, `apiStrict=true` | +| D3 명시적 Mongo capability | native BSON, time series, search·vector, CSFLE·QE, shard를 아는 연산 | 따로 둔 capability client | +| D4 admin plane | collection, validator, index, migration, shard, repair | 따로 둔 admin client와 credential | -Specifically: +구체적으로: -1. **No `CommonMongoRepository`.** Each aggregate declares its own repository. -2. **D1/D2 run on Stable API V1 with `apiStrict=true`,** so a command outside the versioned API fails - at development time instead of on the next server upgrade. -3. **D3 is not a raw-client escape.** Every call passes a fixed admission order: capability registered - → database profile → collection allowlist → operation name → timeout → consistency profile → - result limit → trace → redaction → command category → admin-command refusal → execute. -4. **D4 is a separate client with a separate credential.** No application-plane path reaches it; - `PolicyAwareMongoNativeGateway` refuses admin-category commands regardless of capability. -5. **Advanced and Experimental capabilities are opt-in modules**, never transitive dependencies of the - Stable surface. +1. **`CommonMongoRepository`가 없다.** aggregate마다 자기 repository를 선언한다. +2. **D1·D2는 `apiStrict=true`인 Stable API V1에서 돈다.** 그래서 버전 있는 API 밖의 명령은 다음 서버 업그레이드 때가 아니라 + 개발 때 실패한다. +3. **D3는 raw client로 빠져나가는 길이 아니다.** 모든 호출이 정해진 허가 순서를 지난다: capability 등록 → 데이터베이스 + profile → collection 허용 목록 → operation 이름 → timeout → 일관성 profile → 결과 한계 → trace → 가리기 → 명령 category → + admin 명령 거절 → 실행. +4. **D4는 따로 둔 credential을 가진 따로 둔 client다.** 애플리케이션 plane 경로는 그것에 닿지 않는다. + `PolicyAwareMongoNativeGateway`는 capability와 관계없이 admin category 명령을 거절한다. +5. **Advanced와 Experimental capability는 골라 쓰는 모듈이고**, Stable surface의 전이 의존이 되지 않는다. -## Consequences +## 결과 -**Positive.** MongoDB's semantics stay reachable. Misuse is refused structurally rather than reviewed -for. A server upgrade cannot silently change D1/D2 behaviour. Admin operations have their own audit -trail and credential. +**좋은 점.** MongoDB의 뜻에 계속 닿을 수 있다. 잘못된 사용은 리뷰로 찾지 않고 구조로 거절한다. 서버 업그레이드가 D1·D2 +동작을 소리 없이 바꿀 수 없다. admin 연산은 자기 감사 흔적과 credential을 가진다. -**Negative.** Every operation needs a registered name and profile, so a new query is a small amount of -configuration rather than zero. A genuinely new capability requires a registration before it can be -used. Both are deliberate: the cost is paid once per operation, at review time. +**나쁜 점.** 모든 operation에 등록된 이름과 profile이 필요해서, 새 query에는 0이 아니라 약간의 설정이 든다. 정말 새 capability는 +쓰기 전에 등록이 필요하다. 둘 다 일부러다: 비용은 operation마다 한 번, 리뷰 때 낸다. -**Rejected alternative — "expose the driver, rely on code review."** Review does not scale to every -query in every service, and the operations that matter (unbounded pipeline, `dropCollection`, -unanchored regex on user input) look unremarkable in a diff. +**버린 대안 — 「driver를 내놓고 코드 리뷰에 기댄다」.** 리뷰는 모든 서비스의 모든 query로 늘어나지 못하고, 중요한 연산 +(한계 없는 pipeline, `dropCollection`, 사용자 입력에 대한 anchor 없는 정규식)은 diff에서 눈에 띄지 않는다. -## Repository adaptation +## 저장소에 맞추기 -The design assumes 19 Gradle modules under `modules/mongodb/`. This repository's fail-closed registry -declares exactly 19 leaf identities, so the modules became package boundaries inside -`:adapter:outbound:persistence-mongo`, enforced by ArchUnit. See -[docs/mongodb/repository-adaptation.md](../mongodb/repository-adaptation.md). +설계는 `modules/mongodb/` 아래 Gradle 모듈 19개를 가정한다. 이 저장소의 실패하면 닫히는 registry는 정확히 19개의 leaf identity를 +선언하므로, 그 모듈들은 `:adapter:outbound:persistence-mongo` 안의 패키지 경계가 됐고 ArchUnit이 강제한다. +[docs/mongodb/repository-adaptation.md](../mongodb/repository-adaptation.md)를 본다. diff --git a/docs/adr/ADR-MONGO-002-bson-representation.md b/docs/adr/ADR-MONGO-002-bson-representation.md index 73e478a7..a53a5915 100644 --- a/docs/adr/ADR-MONGO-002-bson-representation.md +++ b/docs/adr/ADR-MONGO-002-bson-representation.md @@ -7,61 +7,53 @@ - 현재 정본: `docs/mongodb/bson-mapping-guide.md` -# ADR-MONGO-002 — BSON representation is a pinned manifest +# ADR-MONGO-002 — BSON 표현은 고정한 manifest다 -- **Status:** Accepted -- **Date:** 2026-08-13 -- **Design source:** design §10, decision D-06 +- **상태:** 채택 +- **날짜:** 2026-08-13 +- **설계 출처:** 설계 §10, 결정 D-06 -## Context +## 배경 -How a Java value is represented in BSON is a data contract, but nothing in the default toolchain -treats it as one. Spring Data and the MongoDB driver both have defaults, and those defaults have -changed across versions. A `BigDecimal` can land as a `Double`, a `String` or a `Decimal128`; a `UUID` -can land as `Binary` subtype 3 or subtype 4; an `Instant` can land as a `Date` or a `String`. +Java 값을 BSON으로 어떻게 나타내는지는 데이터 계약인데, 기본 toolchain의 어떤 것도 그것을 계약으로 다루지 않는다. Spring Data와 +MongoDB driver에는 둘 다 기본값이 있고, 그 기본값은 버전마다 바뀌어 왔다. `BigDecimal`은 `Double`, `String`, `Decimal128` 중 +무엇으로든 들어갈 수 있다. `UUID`는 `Binary` subtype 3이나 subtype 4로 들어갈 수 있다. `Instant`는 `Date`나 `String`으로 들어갈 +수 있다. -The consequences are asymmetric. A representation change is invisible in a value-equality test — -`12.30` looks like `12.30` whether it is a double or a `Decimal128` — but once a collection holds -production data, changing it is a full migration. And the UUID case is worse than a migration: legacy -Java representation byte-swaps two halves of the UUID, so a document written under one representation -and read under the other yields a *different, valid-looking* UUID. Nothing errors. You get the wrong -record. +결과는 비대칭이다. 표현이 바뀌어도 값 동등 시험에는 보이지 않는다 — `12.30`은 double이든 `Decimal128`이든 `12.30`처럼 보인다 — +하지만 collection에 운영 데이터가 들면 그것을 바꾸는 것은 전체 migration이다. 그리고 UUID 경우는 migration보다 나쁘다: 옛 Java +표현은 UUID의 두 절반을 byte-swap하므로, 한 표현으로 쓰고 다른 표현으로 읽은 문서는 *다르지만 유효해 보이는* UUID를 낸다. +오류는 없다. 엉뚱한 레코드를 받는다. -## Decision +## 결정 -`MongoTypeRepresentationManifest` pins the representation for every type the platform maps, and -`MongoMappingConfiguration` builds the Spring Data converters from it. Nothing relies on a library -default. +`MongoTypeRepresentationManifest`가 플랫폼이 대응시키는 모든 타입의 표현을 고정하고, `MongoMappingConfiguration`이 그것으로 +Spring Data converter를 만든다. 라이브러리 기본값에 기대는 것은 없다. -| Java | BSON | Rationale | +| Java | BSON | 근거 | |---|---|---| -| `UUID` | `Binary` subtype 4 (`STANDARD`) | Subtype 3 byte-swaps; cross-representation reads are silently wrong. | -| `BigDecimal` | `Decimal128` | A double cannot represent `12.30`; money compared as a double is eventually wrong by a cent. | -| `BigInteger` | `Decimal128`, or declared `String` when out of range | 34 significant digits; out of range fails on write instead of rounding. | -| `Instant` / `OffsetDateTime` / `ZonedDateTime` | UTC `Date` | One instant, one representation. | -| `LocalDate` | declared per field | A calendar day is not an instant. | -| `LocalDateTime` | **refused** | No offset: the stored value depends on the writing JVM's default zone. | -| `enum` | `String` name | Ordinals renumber when someone inserts a constant. | +| `UUID` | `Binary` subtype 4(`STANDARD`) | subtype 3은 byte-swap한다. 표현을 넘나드는 읽기는 소리 없이 틀린다. | +| `BigDecimal` | `Decimal128` | double은 `12.30`을 나타내지 못한다. double로 비교한 돈은 결국 1원씩 틀린다. | +| `BigInteger` | `Decimal128`, 범위를 넘으면 선언한 `String` | 유효 숫자 34자리. 범위를 넘으면 반올림하지 않고 쓰기에서 실패한다. | +| `Instant` / `OffsetDateTime` / `ZonedDateTime` | UTC `Date` | 시각 하나, 표현 하나. | +| `LocalDate` | 필드마다 선언 | 달력의 날은 시각이 아니다. | +| `LocalDateTime` | **거절** | offset이 없다: 저장 값이 쓰는 JVM의 기본 시간대에 따라 달라진다. | +| `enum` | `String` 이름 | 누가 상수를 끼워 넣으면 ordinal이 다시 매겨진다. | -Type metadata follows `MongoTypeMetadataPolicy` — `NONE`, `ALIAS` or `CLASS_NAME`. A -`@LongLivedMongoDocument` type may not use `CLASS_NAME`: writing a FQCN into a million documents makes -a package rename a data migration. +타입 metadata는 `MongoTypeMetadataPolicy` — `NONE`, `ALIAS`, `CLASS_NAME` — 를 따른다. `@LongLivedMongoDocument` 타입은 +`CLASS_NAME`을 쓰면 안 된다: 문서 백만 개에 FQCN을 쓰면 패키지 이름 바꾸기가 데이터 migration이 된다. -The manifest is enforced by a golden gate. `MongoBsonSnapshot` canonicalises a stored document, -preserving BSON types and keeping missing distinct from null, and -`MongoBsonSnapshotAssert.hasTypeSignature(...)` fails on any representation change. The registry -pins `UuidCodec(STANDARD)` explicitly rather than inheriting a default, since inheriting the default -is the exact drift the gate exists to catch. +manifest는 golden gate가 강제한다. `MongoBsonSnapshot`이 저장된 문서를 정규화하면서 BSON 타입을 지키고 없음과 null을 구별해 +두며, `MongoBsonSnapshotAssert.hasTypeSignature(...)`가 표현이 바뀌면 실패한다. registry는 기본값을 물려받지 않고 +`UuidCodec(STANDARD)`를 명시해 고정한다. 기본값을 물려받는 것이 바로 gate가 잡으려는 어긋남이기 때문이다. -## Consequences +## 결과 -**Positive.** A library upgrade cannot move a representation without failing a test. Money is exact. -UUIDs read back as themselves. Class moves stay refactors. +**좋은 점.** 라이브러리 업그레이드가 시험을 실패시키지 않고 표현을 옮길 수 없다. 돈이 정확하다. UUID가 자기 자신으로 다시 +읽힌다. 클래스 옮기기는 리팩터링으로 남는다. -**Negative.** Every representation-affecting change requires updating a snapshot *and* writing a -migration. A new mapped type needs a manifest entry before it can be used. This is the intended -friction: the alternative is discovering the change in production. +**나쁜 점.** 표현에 영향을 주는 모든 변경에 snapshot 갱신 *그리고* migration 작성이 필요하다. 새로 대응시키는 타입은 쓰기 전에 +manifest 항목이 필요하다. 의도한 마찰이다: 대안은 운영에서 변경을 발견하는 것이다. -**Rejected alternative — "snapshot the JSON."** JSON destroys exactly the distinctions the gate -protects: `Decimal128` and `String` both render as text, `Binary` UUID and `ObjectId` both render as -hex, and missing and null both disappear. +**버린 대안 — 「JSON을 snapshot한다」.** JSON은 gate가 지키는 바로 그 구별을 없앤다: `Decimal128`과 `String`은 둘 다 글로 +나오고, `Binary` UUID와 `ObjectId`는 둘 다 hex로 나오며, 없음과 null은 둘 다 사라진다. diff --git a/docs/adr/ADR-MONGO-003-transaction-retry.md b/docs/adr/ADR-MONGO-003-transaction-retry.md index 7d675461..ec655164 100644 --- a/docs/adr/ADR-MONGO-003-transaction-retry.md +++ b/docs/adr/ADR-MONGO-003-transaction-retry.md @@ -7,33 +7,29 @@ - 현재 정본: `docs/mongodb/consistency-transaction-guide.md` -# ADR-MONGO-003 — Transaction body retry and commit retry are separate loops +# ADR-MONGO-003 — 트랜잭션 본문 재시도와 커밋 재시도는 따로 도는 반복문이다 -- **Status:** Accepted -- **Date:** 2026-08-13 -- **Design source:** design §14–§16, decisions D-07 through D-10 +- **상태:** 채택 +- **날짜:** 2026-08-13 +- **설계 출처:** 설계 §14–§16, 결정 D-07부터 D-10 -## Context +## 배경 -MongoDB reports two transaction failures that look similar and must be handled in opposite ways. +MongoDB는 비슷해 보이지만 정반대로 다뤄야 하는 트랜잭션 실패 둘을 알린다. -`TransientTransactionError` means the transaction definitively did not commit. The correct response is -to run the whole thing again. +`TransientTransactionError`는 트랜잭션이 분명히 커밋되지 않았다는 뜻이다. 맞는 대응은 전체를 다시 돌리는 것이다. -`UnknownTransactionCommitResult` means the commit **may already have applied** — typically because the -primary changed while the commit was in flight. The correct response is to retry *the commit*, which -is a no-op if it already succeeded. +`UnknownTransactionCommitResult`는 커밋이 **이미 적용됐을 수 있다**는 뜻이다 — 보통 커밋이 진행 중일 때 primary가 바뀌었기 +때문이다. 맞는 대응은 *커밋*을 재시도하는 것이고, 이미 성공했다면 그것은 아무 일도 하지 않는다. -The common implementation wraps everything in one retry loop. That loop replays the body after an -unknown commit, and if the commit did apply, the body applies twice. In a payment or notification path -that is a duplicate charge or a duplicate message, produced by the error handler. +흔한 구현은 모든 것을 재시도 반복문 하나로 감싼다. 그 반복문은 모르는 커밋 뒤에 본문을 다시 돌리고, 커밋이 적용됐었다면 본문이 +두 번 적용된다. 결제나 알림 경로에서 그것은 오류 handler가 만든 중복 청구나 중복 메시지다. -The related trap is session reuse: retrying on the same session after an abort carries the aborted -transaction's state into the retry. +관련된 함정은 세션 다시 쓰기다: abort 뒤에 같은 세션으로 재시도하면 abort된 트랜잭션의 상태가 재시도로 넘어간다. -## Decision +## 결정 -`MongoTransactionRetryCoordinator` implements two loops with different scopes. +`MongoTransactionRetryCoordinator`가 범위가 다른 반복문 둘을 구현한다. ``` for each body attempt within the budget: @@ -44,34 +40,30 @@ for each body attempt within the budget: UnknownTransactionCommitResult -> retry the COMMIT ONLY, same session ``` -Rules that follow, all of them load-bearing: +따라 나오는 규칙. 모두 꼭 필요하다: -1. **A new session per body attempt.** No aborted state leaks into a retry. -2. **The body is never replayed after a commit ambiguity.** `MongoRetryScope.COMMIT_ONLY` is a - distinct value from `BODY` precisely so this cannot be collapsed by accident. -3. **One budget bounds both loops.** `MongoRetryBudget` limits attempts *and* elapsed time, with - jittered backoff, so a struggling primary is not retried into the ground by every instance at once. -4. **An exhausted commit retry surfaces `TRANSACTION_COMMIT_UNKNOWN`,** never a generic failure. An - ambiguous outcome reported as a failure invites the caller to retry — the one thing that must not - happen. See [docs/mongodb/runbooks/unknown-commit.md](../mongodb/runbooks/unknown-commit.md). -5. **Transaction bodies write a deterministic marker** so `MongoCommitReconciler` can establish what - actually happened. A transaction that cannot be reconciled has no recovery path. -6. **Classification reads labels before codes.** Server error labels are the authoritative statement - about retryability; error codes vary by version. +1. **본문 시도마다 새 세션.** abort된 상태가 재시도로 새지 않는다. +2. **커밋이 모호해진 뒤에는 본문을 절대 다시 돌리지 않는다.** `MongoRetryScope.COMMIT_ONLY`가 `BODY`와 다른 값인 것은 바로 + 이것이 실수로 뭉개지지 않게 하려는 것이다. +3. **예산 하나가 두 반복문을 묶는다.** `MongoRetryBudget`이 시도 수 *그리고* 흐른 시간을 jitter 있는 backoff와 함께 제한한다. + 그래서 힘든 primary를 모든 인스턴스가 한꺼번에 재시도로 짓밟지 않는다. +4. **바닥난 커밋 재시도는 일반 실패가 아니라 `TRANSACTION_COMMIT_UNKNOWN`으로 드러난다.** 실패로 알린 모호한 결과는 호출자에게 + 재시도를 부른다 — 일어나면 안 되는 바로 그 일이다. + [docs/mongodb/runbooks/unknown-commit.md](../mongodb/runbooks/unknown-commit.md)를 본다. +5. **트랜잭션 본문은 결정적인 표지를 쓴다.** 그래서 `MongoCommitReconciler`가 실제로 무엇이 일어났는지 세울 수 있다. 맞춰 볼 수 + 없는 트랜잭션에는 회복 길이 없다. +6. **분류는 코드보다 label을 먼저 읽는다.** 서버 오류 label이 재시도 가능성에 대한 정본 진술이고, 오류 코드는 버전마다 다르다. -Surrounding decisions that reduce how often this path is reached at all: single-document atomic -operations are preferred over transactions (D-09), partial changes use update operators rather than -`save()` (D-07), and whole-document replacement requires an optimistic revision (D-08). +이 경로에 닿는 횟수 자체를 줄이는 주변 결정: 트랜잭션보다 단일 문서 원자 연산을 고른다(D-09), 부분 변경은 `save()`가 아니라 +update 연산자를 쓴다(D-07), 문서 전체 바꾸기에는 낙관적 revision이 필요하다(D-08). -## Consequences +## 결과 -**Positive.** A commit ambiguity cannot become a duplicate effect. The ambiguity reaches the caller as -an ambiguity. The retry budget is bounded in both attempts and time. +**좋은 점.** 커밋 모호함이 중복 효과가 될 수 없다. 모호함이 모호함으로 호출자에게 닿는다. 재시도 예산이 시도 수와 시간 둘 다에서 +한계를 가진다. -**Negative.** Callers must handle a third outcome beyond success and failure. Transaction bodies must -write a marker they would not otherwise need. Both costs are small compared with reconciling -duplicated financial effects after the fact. +**나쁜 점.** 호출자는 성공과 실패 밖의 세 번째 결과를 다뤄야 한다. 트랜잭션 본문은 그렇지 않으면 필요 없을 표지를 써야 한다. 두 +비용 모두 중복된 금전 효과를 나중에 맞춰 보는 것에 비하면 작다. -**Rejected alternative — "one retry loop, at-least-once everywhere."** It requires every transaction -body to be fully idempotent, which is a much stronger and much less checkable property than writing -one marker, and it is silently violated the first time someone adds a non-idempotent step. +**버린 대안 — 「재시도 반복문 하나, 어디서나 at-least-once」.** 모든 트랜잭션 본문이 완전히 멱등이어야 한다. 표지 하나를 쓰는 +것보다 훨씬 강하고 훨씬 검사하기 어려운 성질이고, 누가 멱등이 아닌 단계를 처음 더하는 순간 소리 없이 깨진다. diff --git a/docs/adr/ADR-MONGO-004-index-schema-admin-plane.md b/docs/adr/ADR-MONGO-004-index-schema-admin-plane.md index eeb2896c..f26ca08d 100644 --- a/docs/adr/ADR-MONGO-004-index-schema-admin-plane.md +++ b/docs/adr/ADR-MONGO-004-index-schema-admin-plane.md @@ -7,65 +7,55 @@ - 현재 정본: `docs/mongodb/schema-index-migration-guide.md` -# ADR-MONGO-004 — Index and schema changes belong to the admin plane +# ADR-MONGO-004 — index와 schema 변경은 admin plane의 것이다 -- **Status:** Accepted -- **Date:** 2026-08-13 -- **Design source:** design §21–§25, decisions D-11, D-13 +- **상태:** 채택 +- **날짜:** 2026-08-13 +- **설계 출처:** 설계 §21–§25, 결정 D-11, D-13 -## Context +## 배경 -Spring Data can create indexes automatically from annotations. On a laptop this is convenient. On a -collection with a hundred million documents, an index build is a capacity event: it consumes CPU, IO -and memory on the primary for minutes to hours, and it starts because a pod restarted. +Spring Data는 애너테이션에서 index를 자동으로 만들 수 있다. 노트북에서는 편하다. 문서 1억 개가 든 collection에서 index 만들기는 +용량 사건이다: primary의 CPU, IO, 메모리를 몇 분에서 몇 시간 동안 쓰고, pod 하나가 재시작했다는 이유로 시작된다. -Worse, it starts N times when N pods restart, and there is no approval step, no ordering relative to -the code that needs the index, and no record afterwards of what was created. +더 나쁘게, pod N개가 재시작하면 N번 시작하고, 승인 단계도, 그 index가 필요한 코드와의 순서도, 나중에 무엇을 만들었는지의 기록도 +없다. -Schema validators have the same shape with a sharper edge: tightening a validator on a collection with -existing data rejects writes to documents that were legal when they were written. +schema validator도 같은 모양인데 날이 더 서 있다: 데이터가 있는 collection에서 validator를 조이면, 쓸 때는 적법했던 문서에 대한 +쓰기를 거절한다. -TTL has a third shape. It looks like a scheduler and is not one: the TTL monitor runs about once a -minute and deletes in batches, so an expired document routinely remains readable for minutes or hours. +TTL은 세 번째 모양이다. scheduler처럼 보이지만 아니다: TTL monitor는 대략 1분에 한 번 돌고 batch로 지우므로, 만료된 문서가 몇 +분에서 몇 시간 동안 읽히는 것이 예사다. -## Decision +## 결정 -**Indexes and validators are declared in a manifest and applied by the admin plane (D4).** Automatic -index creation in production is disabled. +**index와 validator는 manifest에 선언하고 admin plane(D4)이 적용한다.** 운영에서 자동 index 만들기는 끈다. -1. `MongoManifestRegistry` holds the declared indexes (`MongoIndexManifest`) and validator - (`MongoSchemaManifest`) per collection. The manifest is the source of truth, reviewed in a pull - request. -2. `MongoIndexDiffEngine` compares manifest against observed state and reports missing, extra and - *changed* indexes. Changed ones are reported rather than re-issued: MongoDB will not silently - rebuild an index whose definition moved. -3. `MongoIndexApplyPolicy` sets what an environment may do — `APPLY` (local), `APPLY_WITH_DIFF` - (staging), `DIFF_WITH_APPROVED_APPLY` (production), `REPORT_ONLY` (audit). -4. **Ownership gates every drop.** `MongoMetadataOwnership` distinguishes `APPLICATION_MANAGED` from - `SEARCH_MANAGED`, `ENCRYPTION_MANAGED` and `EXTERNAL`. Only application-managed objects are - droppable on drift. A diff engine without ownership eventually proposes dropping - `enxcol_.customers.esc`, and "the drift tool cleaned it up" is a very bad incident summary. -5. **Retirement is staged.** `MongoIndexRetirementState` moves an index declared → hidden → - observed-unused → droppable, one deployment per transition. Hiding is instantly reversible; - dropping is a rebuild. -6. **Stable validation actions are `error` and `warn` only.** `errorAndLog` is not part of the Stable - contract on 7.0 or 8.0 and is refused. Tightening goes `warn`+`MODERATE` → confirm zero warnings → - `error`+`STRICT`, in two deployments. -7. **TTL is physical cleanup only** (D-13). `MongoExpirationAccessPolicy` states the rule: a - document's presence is not authorization and its absence is not a deadline. Access control checks - the expiry field; scheduling uses a scheduler. -8. **Migrations are checksummed, locked, precondition-checked and resumable.** - `MongoMigrationRunner` fails hard when an applied id's checksum changed — two environments running - different code under one id is worse than a failed deploy. +1. `MongoManifestRegistry`가 collection마다 선언한 index(`MongoIndexManifest`)와 validator(`MongoSchemaManifest`)를 가진다. + manifest가 정본이고 pull request에서 리뷰한다. +2. `MongoIndexDiffEngine`이 manifest를 관찰한 상태와 비교해 빠진 index, 남는 index, *바뀐* index를 알린다. 바뀐 것은 다시 내지 + 않고 알린다: MongoDB는 정의가 움직인 index를 소리 없이 다시 만들지 않는다. +3. `MongoIndexApplyPolicy`가 환경이 할 수 있는 것을 정한다 — `APPLY`(로컬), `APPLY_WITH_DIFF`(staging), + `DIFF_WITH_APPROVED_APPLY`(운영), `REPORT_ONLY`(감사). +4. **모든 drop은 소유권이 막는다.** `MongoMetadataOwnership`이 `APPLICATION_MANAGED`를 `SEARCH_MANAGED`, `ENCRYPTION_MANAGED`, + `EXTERNAL`과 구별한다. 어긋났을 때 지울 수 있는 것은 애플리케이션이 관리하는 객체뿐이다. 소유권 없는 diff 엔진은 결국 + `enxcol_.customers.esc`를 지우자고 제안하고, 「drift 도구가 치웠다」는 아주 나쁜 사고 요약이다. +5. **은퇴는 단계를 밟는다.** `MongoIndexRetirementState`가 index를 선언됨 → 숨김 → 안 쓰는 것 확인 → 지울 수 있음으로 옮기고, + 전이마다 배포 한 번이다. 숨기기는 바로 되돌릴 수 있다. 지우기는 다시 만들기다. +6. **Stable validation action은 `error`와 `warn`뿐이다.** `errorAndLog`는 7.0이나 8.0에서 Stable 계약에 속하지 않아 거절한다. + 조이기는 `warn`+`MODERATE` → 경고 0 확인 → `error`+`STRICT`로, 배포 두 번에 걸쳐 간다. +7. **TTL은 물리적 치우기일 뿐이다**(D-13). `MongoExpirationAccessPolicy`가 규칙을 말한다: 문서가 있다고 인가가 아니고, 없다고 + 기한이 아니다. 접근 통제는 만료 필드를 검사하고, 일정은 scheduler를 쓴다. +8. **migration은 checksum을 두고, 잠그고, 전제 조건을 검사하고, 이어서 할 수 있다.** `MongoMigrationRunner`는 적용한 id의 + checksum이 바뀌면 단단히 실패한다 — 두 환경이 id 하나 아래 다른 코드를 돌리는 것은 실패한 배포보다 나쁘다. -## Consequences +## 결과 -**Positive.** Index builds are scheduled by people who know the capacity. Rollback is possible at -every step. Drift is visible without being dangerous. Nothing drops what it does not own. +**좋은 점.** index 만들기 일정은 용량을 아는 사람이 잡는다. 모든 단계에서 되돌릴 수 있다. drift는 위험하지 않게 보인다. 아무것도 +자기가 가지지 않은 것을 지우지 않는다. -**Negative.** Adding an index is a manifest change plus an apply, not an annotation. Local development -uses `APPLY` so the friction is confined to environments where it is warranted. +**나쁜 점.** index 더하기는 애너테이션이 아니라 manifest 변경 + 적용이다. 로컬 개발은 `APPLY`를 쓰므로 마찰은 그것이 정당한 +환경에만 머문다. -**Rejected alternative — "auto-create with a feature flag."** The flag is either on in production, -which is the problem, or off, in which case the manifest is the real mechanism and the annotation is a -second, divergent source of truth. +**버린 대안 — 「feature flag와 함께 자동으로 만들기」.** flag가 운영에서 켜져 있으면 그것이 문제이고, 꺼져 있으면 manifest가 +실제 장치이고 애너테이션은 두 번째의 갈라진 정본이다. diff --git a/docs/adr/ADR-MONGO-ADV-001-capability-promotion.md b/docs/adr/ADR-MONGO-ADV-001-capability-promotion.md index 9b3bc6b3..1ac930b9 100644 --- a/docs/adr/ADR-MONGO-ADV-001-capability-promotion.md +++ b/docs/adr/ADR-MONGO-ADV-001-capability-promotion.md @@ -7,90 +7,78 @@ - 현재 정본: `docs/mongodb/support-matrix.md` -# ADR-MONGO-ADV-001 — Advanced capability promotion +# ADR-MONGO-ADV-001 — Advanced capability 승격 -- **Status:** Accepted -- **Date:** 2026-08-13 -- **Design source:** design §2 (D-15), §3.2–§3.3; Advanced expansion plan Task 15 -- **Amended 2026-09-25:** the `ca-skeleton.persistence-mongo.advanced.*.enabled` binding - (`MongoAdvancedConfiguration`/`MongoAdvancedSettings`) was imported by nothing, so no deployment - property ever reached the flags; it was removed together with `propertyFor`. The flags are now - built in code by the adapter that constructs an entry point. `MongoAdvancedPromotionGate`, - `MongoAdvancedPromotionEvidence`, `MongoVectorSearchBenchmarkGate` and the search, vector, time - series and GridFS packages (interfaces with no implementation) were removed. The evidence - categories below remain a review obligation; no class checks them. +- **상태:** 채택 +- **날짜:** 2026-08-13 +- **설계 출처:** 설계 §2 (D-15), §3.2–§3.3. Advanced 확장 계획 Task 15 +- **2026-09-25 보완:** `ca-skeleton.persistence-mongo.advanced.*.enabled` 바인딩(`MongoAdvancedConfiguration`/ + `MongoAdvancedSettings`)은 아무것도 import하지 않아서 어떤 배포 속성도 flag에 닿지 않았다. `propertyFor`와 함께 지웠다. flag는 + 이제 entry point를 만드는 어댑터가 코드로 만든다. `MongoAdvancedPromotionGate`, `MongoAdvancedPromotionEvidence`, + `MongoVectorSearchBenchmarkGate`, 그리고 search, vector, time series, GridFS 패키지(구현 없는 인터페이스)를 지웠다. 아래 증거 + category는 리뷰 의무로 남는다. 그것을 검사하는 클래스는 없다. -## Context +## 배경 -Sharding, time series, CSFLE, Queryable Encryption, search, vector search and multi-tenancy each work -in a demo within an afternoon. What they do not do is behave the same way in production, and the -differences are not discovered by functional tests: +sharding, time series, CSFLE, Queryable Encryption, search, vector search, multi-tenancy는 하나같이 오후 한나절이면 demo에서 +동작한다. 하지 않는 것은 운영에서 같은 방식으로 동작하는 것이고, 그 차이는 기능 시험으로 찾지 못한다: -- Sharding changes which queries are efficient. A query that misses the shard key becomes - scatter-gather, which passes every test on a one-shard cluster. -- Encryption's failure modes are KMS failure modes — wrong key, revoked permission, mid-rotation — - none of which occur against a local key provider. -- Search and vector search can be functionally correct and useless: the index returns results, and - the results are not relevant. Recall is not visible in a pass/fail assertion. -- Database-per-tenant works until the tenant count crosses what the connection and file-handle - budget supports, which is an operational property, not a code property. +- sharding은 어떤 query가 효율적인지 바꾼다. shard key를 놓친 query는 scatter-gather가 되는데, shard 하나짜리 cluster에서는 + 모든 시험을 통과한다. +- 암호화의 실패 방식은 KMS의 실패 방식이다 — 틀린 키, 거둬들인 권한, 교체 중 — 로컬 키 provider에 대고는 하나도 일어나지 않는다. +- search와 vector search는 기능상 맞으면서 쓸모없을 수 있다: index는 결과를 돌려주는데 결과가 관련이 없다. recall은 통과·실패 + 단언에 보이지 않는다. +- 테넌트마다 데이터베이스는 테넌트 수가 연결·파일 handle 예산이 받쳐 주는 수를 넘을 때까지 동작한다. 그것은 코드가 아니라 운영의 + 성질이다. -The failure mode this ADR prevents is a capability marked "done" on the strength of a green test that -never touched the environment where it will run. +이 ADR이 막는 실패 방식은 그것이 돌 환경을 한 번도 건드리지 않은 초록 시험을 근거로 capability를 「끝남」으로 표시하는 것이다. -## Decision +## 결정 -Every Advanced and Experimental capability is an **opt-in module behind its own flag**, and promotion -requires evidence, not confidence. +모든 Advanced·Experimental capability는 **자기 flag 뒤의 골라 쓰는 모듈**이고, 승격에는 자신감이 아니라 증거가 필요하다. -### Enablement +### 켜기 -`MongoAdvancedCapabilityFlags` gates construction of every Advanced entry point. A disabled capability -does not produce a runtime warning — the type refuses to be constructed, naming the property that -enables it (`MongoAdvancedCapabilityFlags.propertyFor(capability)`). Being on the classpath is not -being enabled, and `stableNeverDependsOnAdvanced` (ArchUnit) keeps the Stable surface free of them. +`MongoAdvancedCapabilityFlags`가 모든 Advanced entry point의 생성을 막는다. 꺼진 capability는 런타임 경고를 내지 않는다 — 타입이 +그것을 켜는 속성 이름을 대며 만들어지기를 거절한다(`MongoAdvancedCapabilityFlags.propertyFor(capability)`). classpath에 있다고 +켜진 것이 아니고, `stableNeverDependsOnAdvanced`(ArchUnit)가 Stable surface에서 그것을 떼어 둔다. -### Promotion evidence +### 승격 증거 -`MongoAdvancedPromotionGate.verify(evidence)` requires every category: +`MongoAdvancedPromotionGate.verify(evidence)`는 모든 category를 요구한다: -| Category | Means | +| category | 뜻 | |---|---| -| `stable-platform` | The Stable release gate passed on the same revision. | -| `actual-topology` | The capability ran on the real topology — a real sharded cluster, the real KMS, the actual target deployment. Atlas Local is a pull-request convenience and explicitly not release evidence (`MongoAtlasCapabilityContractSuite.Environment.ATLAS_LOCAL`). | -| `security` | Privileges reviewed; the capability's admin role is separate from the application role. | -| `migration` | A documented path in and, where the capability is irreversible, an explicit statement that there is no path back. | -| `failure` | Negative cases fail closed: wrong key, missing permission, rotation, non-ready index, unrouted query. | -| `runbook` | A runbook exists for the capability's characteristic incident. | +| `stable-platform` | 같은 revision에서 Stable 릴리스 gate가 통과했다. | +| `actual-topology` | capability가 실제 topology에서 돌았다 — 실제 sharded cluster, 실제 KMS, 실제 대상 배포. Atlas Local은 pull request용 편의이고 릴리스 증거가 아님을 명시한다(`MongoAtlasCapabilityContractSuite.Environment.ATLAS_LOCAL`). | +| `security` | 권한을 리뷰했다. capability의 admin role은 애플리케이션 role과 따로다. | +| `migration` | 들어가는 길을 적었고, capability가 되돌릴 수 없으면 돌아오는 길이 없다고 명시했다. | +| `failure` | 부정 경우가 실패하면 닫힌다: 틀린 키, 빠진 권한, 교체, 준비되지 않은 index, 라우팅되지 않은 query. | +| `runbook` | capability의 대표 사고를 위한 runbook이 있다. | -### Additional per-capability requirements +### capability별 추가 요구 -- **Search / vector search:** relevance and performance evidence, not functional success alone. - `MongoVectorSearchBenchmarkGate` requires recall alongside latency and index size; a gate that - measures only latency certifies a fast wrong answer. -- **Database-per-tenant and reshard orchestration remain Experimental** until operational scale - evidence exists. Both are correct in the small and unbounded in the large. -- **Reshard requires an explicit `ReshardApproval`** — a named approver and a stated window. It - rewrites the collection. +- **search / vector search:** 기능 성공만이 아니라 관련성과 성능 증거. `MongoVectorSearchBenchmarkGate`는 지연 시간·index 크기와 + 함께 recall을 요구한다. 지연 시간만 재는 gate는 빠른 틀린 답을 인증한다. +- **테넌트마다 데이터베이스와 reshard 조율은 운영 규모 증거가 생길 때까지 Experimental로 남는다.** 둘 다 작게는 맞고 크게는 + 한계가 없다. +- **reshard에는 명시한 `ReshardApproval`이 필요하다** — 이름 있는 승인자와 밝힌 시간 창. reshard는 collection을 다시 쓴다. -### Promotion does not change the dependency boundary +### 승격은 의존 경계를 바꾸지 않는다 -A capability promoted to Stable **remains an opt-in module** unless a later starter ADR changes the -dependency boundary. Promotion is a statement about evidence, not an invitation to add a transitive -dependency to every service. +Stable로 승격한 capability도 나중의 starter ADR이 의존 경계를 바꾸지 않는 한 **골라 쓰는 모듈로 남는다**. 승격은 증거에 대한 +진술이지, 모든 서비스에 전이 의존을 더하라는 초대가 아니다. -## Consequences +## 결과 -**Positive.** No capability reaches production on the strength of a container-only test. The evidence -list is the same for every capability, so promotion is reviewable rather than negotiated. +**좋은 점.** container 전용 시험을 근거로 운영에 닿는 capability는 없다. 증거 목록이 모든 capability에 같으므로, 승격은 흥정이 +아니라 리뷰할 수 있는 것이 된다. -**Negative.** Promotion requires access to real infrastructure — a sharded cluster, a real KMS, the -target deployment. That is the cost of the guarantee: the alternative is finding out in production, -where encryption and sharding are both expensive to reverse. +**나쁜 점.** 승격에는 실제 기반 시설 — sharded cluster, 실제 KMS, 대상 배포 — 에 대한 접근이 필요하다. 그것이 보장의 비용이다: +대안은 운영에서 알게 되는 것이고, 거기서는 암호화와 sharding 둘 다 되돌리기 비싸다. -## Verification +## 검증 -`scripts/verify-mongodb-advanced.sh` enforced this ADR until it was removed on 2026-08-15. The -promotion evidence categories this ADR requires are therefore no longer checked by any automated -gate; they are a review obligation until one is rebuilt. See `docs/mongodb/repository-adaptation.md` -§5 for the Gradle lanes the script wrapped. +`scripts/verify-mongodb-advanced.sh`가 2026-08-15에 지워질 때까지 이 ADR을 강제했다. 그래서 이 ADR이 요구하는 승격 증거 +category는 이제 어떤 자동 gate도 검사하지 않는다. 다시 만들 때까지 리뷰 의무다. 그 script가 감싸던 Gradle lane은 +`docs/mongodb/repository-adaptation.md` §5를 본다. diff --git a/docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md b/docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md index 8883fe61..d83135de 100644 --- a/docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md +++ b/docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md @@ -7,73 +7,62 @@ - 현재 정본: `docs/web/streaming-contract.md` -# ADR-WEB-ADV-001: Streaming is live delivery, and the web module stores no history +# ADR-WEB-ADV-001: streaming은 실시간 전달이고, web 모듈은 이력을 저장하지 않는다 -- Status: Accepted -- Date: 2026-08-25 -- Scope: `adapter:inbound:web` — `advanced.stream.**` +- 상태: 채택 +- 날짜: 2026-08-25 +- 범위: `adapter:inbound:web` — `advanced.stream.**` -## Context +## 배경 -Advanced Tasks 6–13 add SSE, NDJSON and JSON text sequences, with a `Last-Event-ID` resume path. +Advanced Task 6–13은 `Last-Event-ID` resume 경로와 함께 SSE, NDJSON, JSON text sequence를 더한다. -One fact drives every decision here: **after the first byte, the HTTP status is 200 and cannot -change.** A stream that ends because a dependency failed and one that ends because it finished are -identical at the transport layer — both are a closed connection after a 200. So is a stream that was -cut off mid-flight. +여기의 모든 결정을 이끄는 사실은 하나다: **첫 바이트 뒤에 HTTP status는 200이고 바꿀 수 없다.** 의존 대상이 실패해서 끝난 +stream과 다 마쳐서 끝난 stream은 전송 계층에서 똑같다 — 둘 다 200 뒤에 닫힌 연결이다. 도중에 잘린 stream도 그렇다. -The second fact is that a resume path invites the web module to remember things. It must not: the -messaging platform already owns durable event history, and a second copy would have its own -retention, its own eviction and its own opinion about ordering. +둘째 사실은 resume 경로가 web 모듈에게 무언가를 기억하라고 꾄다는 것이다. 그러면 안 된다: durable 이벤트 이력은 이미 메시징 +플랫폼이 가지고, 두 번째 사본은 자기 보존 기간, 자기 eviction, 순서에 대한 자기 의견을 가질 것이다. -## Decision +## 결정 -**Three outcomes, expressed in the stream rather than in the status.** The wire record (for NDJSON, -`NdjsonRecord`) is an item, a failure or a completion. A client that sees neither terminal record -has been cut off, and that third case is recorded as `ABRUPT_CLOSE` rather than counted as a -completion — which is where a rising rate of mid-stream failures would otherwise hide. +**결과는 셋이고, status가 아니라 stream 안에서 나타낸다.** wire record(NDJSON이면 `NdjsonRecord`)는 항목, 실패, 완료 중 하나다. +끝 record를 하나도 보지 못한 client는 잘린 것이고, 그 셋째 경우는 완료로 세지 않고 `ABRUPT_CLOSE`로 기록한다 — 그렇지 않으면 +도중 실패 비율이 오르는 것이 거기 숨는다. -**Nothing writes an error body onto a committed response.** Before commit, a failure is an ordinary -HTTP error (the `Envelope`) with a real status; after, a terminal record. Attempting both produces a -body that is half stream and half JSON, which no client parses and every proxy caches as a success. -(The mapper that encoded this, `WebStreamTerminationMapper`, was removed on 2026-09-25 with the -problem-document vocabulary it returned; the rule stands.) +**커밋된 응답 위에 오류 body를 쓰는 것은 없다.** 커밋 전의 실패는 실제 status를 가진 보통 HTTP 오류(`Envelope`)이고, 커밋 뒤에는 +끝 record다. 둘 다 하려 하면 반은 stream이고 반은 JSON인 body가 나오는데, 어떤 client도 그것을 파싱하지 못하고 모든 proxy가 +성공으로 cache한다. (이것을 인코딩하던 mapper `WebStreamTerminationMapper`는 그것이 돌려주던 problem document 어휘와 함께 +2026-09-25에 지웠다. 규칙은 남는다.) -**Positions are monotonic, and it is enforced.** `WebStreamEvidence.recordDelivered` refuses a -repeated or regressing position. A client deduplicating on position would silently drop the second -item. +**위치는 단조 증가하고, 그것을 강제한다.** `WebStreamEvidence.recordDelivered`는 되풀이되거나 뒤로 가는 위치를 거절한다. 위치로 +중복을 거르는 client는 두 번째 항목을 소리 없이 버리게 된다. -**A slow consumer is disconnected, not buffered.** `WebStreamPolicy.maxBufferedItems` is a hard -bound. Backpressure protects the reactive pipeline; it does not protect the server's heap from a -consumer that reads slowly for an hour. +**느린 소비자는 buffer에 담지 않고 연결을 끊는다.** `WebStreamPolicy.maxBufferedItems`는 단단한 한계다. backpressure는 reactive +pipeline을 지키지만, 한 시간 동안 천천히 읽는 소비자로부터 서버 heap을 지키지는 않는다. -**Every stream is in a registry, and shutdown drains it.** A node with a hundred open streams and no -other traffic looks idle by request rate. `WebStreamDrainCoordinator` stops accepting first, asks -clients to reconnect, and only then forces the remainder — because a client whose socket is cut -retries immediately, and if every socket is cut at once, every client retries at once. +**모든 stream은 registry에 있고, 종료가 그것을 비운다.** 열린 stream 백 개 말고 다른 traffic이 없는 노드는 요청 비율로 보면 놀고 +있는 것처럼 보인다. `WebStreamDrainCoordinator`는 먼저 받기를 멈추고, client에게 다시 연결하라고 요청하고, 그다음에야 나머지를 +강제로 끊는다 — socket이 끊긴 client는 바로 다시 시도하고, 모든 socket을 한꺼번에 끊으면 모든 client가 한꺼번에 다시 시도하기 +때문이다. -**The web module stores no durable history.** `WebStreamReplaySource` is an interface this module -implements nowhere. An expired cursor raises `ReplayCursorExpiredException` rather than resuming from -the oldest retained position, because that delivers a stream with a hole the client cannot see. +**web 모듈은 durable 이력을 저장하지 않는다.** `WebStreamReplaySource`는 이 모듈이 어디에서도 구현하지 않는 인터페이스다. 만료된 +cursor는 보존한 가장 오래된 위치에서 이어 가지 않고 `ReplayCursorExpiredException`을 올린다. 그렇게 하면 client가 볼 수 없는 +구멍이 있는 stream을 전달하기 때문이다. -**The replay-to-live seam is watched.** `GapAndDuplicateGuard` detects both directions. Neither is -visible in either half on its own. +**재생에서 실시간으로 넘어가는 이음매를 지켜본다.** `GapAndDuplicateGuard`가 두 방향을 모두 찾는다. 어느 쪽도 한 절반만 보면 +보이지 않는다. -## Consequences +## 결과 -- Clients must handle three outcomes. A client that treats a closed connection as completion will be - wrong, and no server change can fix that for it. -- An expired `Last-Event-ID` costs the client a full re-read. That is the honest answer. -- JSON-seq is preferred over NDJSON where truncation matters: its separator comes first, so a parser - resynchronises at the next record. NDJSON's delimiter is the thing that gets truncated away. +- client는 결과 셋을 다뤄야 한다. 닫힌 연결을 완료로 다루는 client는 틀리고, 서버가 무엇을 바꿔도 그것을 대신 고칠 수 없다. +- 만료된 `Last-Event-ID`는 client에게 전체 다시 읽기를 치르게 한다. 그것이 정직한 답이다. +- 잘림이 중요한 곳에서는 NDJSON보다 JSON-seq를 고른다: 구분자가 앞에 오므로 parser가 다음 record에서 다시 맞춘다. NDJSON의 + 구분자는 잘려 나가는 바로 그것이다. -## Alternatives considered +## 따져 본 대안 -- **Emit a problem document when a stream fails after commit.** Rejected: the body becomes - unparseable and the 200 is cached. -- **Resume from the oldest retained position when the cursor expires.** Rejected: positions are - contiguous from where the replay started, so nothing in the data says events are missing. -- **Store replay history in the web module.** Rejected: a second source of truth that drifts - invisibly. -- **Unbounded buffering for slow consumers.** Rejected: it moves the client's slowness into the - server's heap. +- **커밋 뒤에 stream이 실패하면 problem document를 낸다.** 버렸다: body가 파싱할 수 없게 되고 200이 cache된다. +- **cursor가 만료되면 보존한 가장 오래된 위치에서 이어 간다.** 버렸다: 위치는 재생이 시작된 곳부터 이어지므로, 데이터 안의 어떤 + 것도 이벤트가 빠졌다고 말하지 않는다. +- **재생 이력을 web 모듈에 저장한다.** 버렸다: 보이지 않게 어긋나는 두 번째 정본이다. +- **느린 소비자를 위한 한계 없는 buffer.** 버렸다: client의 느림을 서버 heap으로 옮긴다. diff --git a/docs/adr/ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md b/docs/adr/ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md index fafaeeae..4f3a9397 100644 --- a/docs/adr/ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md +++ b/docs/adr/ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md @@ -7,73 +7,60 @@ - 현재 정본: `docs/web/virtual-thread-profile.md` -# ADR-WEB-ADV-002: Virtual threads change scheduling, not the concurrency budget +# ADR-WEB-ADV-002: virtual thread는 스케줄링을 바꾸지 동시성 예산을 바꾸지 않는다 -- Status: Accepted -- Date: 2026-08-25 -- Scope: `adapter:inbound:web` — `advanced.virtualthread`, `advanced.blockingbridge` +- 상태: 채택 +- 날짜: 2026-08-25 +- 범위: `adapter:inbound:web` — `advanced.virtualthread`, `advanced.blockingbridge` -## Context +## 배경 -Advanced Task 2 offers a virtual-thread executor for MVC; Task 3 offered a bounded blocking bridge -for WebFlux. (The WebFlux adapter for it was removed on 2026-09-25 — the template is servlet only; -`advanced.blockingbridge` remains as library code.) +Advanced Task 2는 MVC용 virtual thread executor를 준다. Task 3은 WebFlux용 한계 있는 blocking bridge를 줬다. (그 WebFlux 어댑터는 +2026-09-25에 지웠다 — 템플릿은 servlet만이다. `advanced.blockingbridge`는 라이브러리 코드로 남는다.) -A platform-thread MVC deployment has an implicit concurrency limit — the thread pool — and that -limit is usually what has been protecting the database pool, the outbound HTTP bulkhead and every -downstream service from the full arrival rate. Nobody wrote it down as an admission policy; it was a -side effect of the pool size. +platform thread MVC 배포에는 숨은 동시성 한계 — thread pool — 가 있고, 보통 그 한계가 데이터베이스 pool, outbound HTTP +bulkhead, 모든 하류 서비스를 전체 도착 비율로부터 지켜 왔다. 아무도 그것을 admission 정책으로 적지 않았다. pool 크기의 +부작용이었다. -Switching to virtual threads deletes that limit without deleting anything that depended on it. +virtual thread로 바꾸면 그 한계가 지워지는데, 그것에 기대던 것은 하나도 지워지지 않는다. -## Decision +## 결정 -**An explicit admission limit is required when virtual threads are enabled.** -`VirtualThreadProfile` refuses construction without one. Without it the deployment accepts every -arrival, queues all of them on the downstream budgets, and times out work that would have succeeded -had it been refused. The load that used to be shed at the front door is shed at the back, after the -cost of accepting it. +**virtual thread를 켜면 명시적 admission 한계가 필요하다.** `VirtualThreadProfile`은 그것 없이는 만들어지기를 거절한다. 없으면 +배포는 모든 도착을 받고, 그것을 모두 하류 예산 위에 줄 세우며, 거절됐으면 성공했을 일을 timeout으로 끝낸다. 예전에 정문에서 +덜어 내던 부하를, 받아들이는 비용을 치른 뒤 뒷문에서 덜어 낸다. -**The limit bounds concurrent use cases, not threads.** `VirtualThreadAdmissionGuard` is a fair -semaphore, not a pool. Bounding threads would put the waiting back and throw away what virtual -threads bought. Ten thousand virtual threads may exist while a hundred hold permits. +**한계는 스레드가 아니라 동시 유스케이스를 묶는다.** `VirtualThreadAdmissionGuard`는 pool이 아니라 공정한 semaphore다. 스레드를 +묶으면 기다림을 되돌려 놓고 virtual thread가 산 것을 버린다. virtual thread 만 개가 있어도 허가를 쥔 것은 백 개일 수 있다. -**The downstream budgets are carried in the profile and stated as unchanged.** The whole point is -that they did not grow. `admissionFitsDownstreamBudgets()` reports when the admission limit exceeds -them, without refusing — a deployment can legitimately admit more than its pool when the work is not -all database-bound, and that should be a choice rather than an accident. +**하류 예산은 profile에 싣고 바뀌지 않았다고 밝힌다.** 요점은 그것이 늘지 않았다는 것이다. `admissionFitsDownstreamBudgets()`는 +admission 한계가 그것을 넘으면 거절하지 않고 알린다 — 일이 모두 데이터베이스에 묶인 것이 아니면 배포가 pool보다 많이 받는 +것이 정당할 수 있고, 그것은 사고가 아니라 선택이어야 한다. -**Blocking offloads are registered, bounded and timed out.** `boundedElastic()` is available from -anywhere and unbounded in practice, so a controller that calls it has silently opted the whole -application into an unbounded pool. `BlockingBridgeProfile` names the operations permitted to -offload; `BlockingBridgeBudget` bounds the concurrency and refuses a caller that cannot get a slot -in time, because otherwise a slow dependency's callers accumulate until the heap does and the fast -dependencies starve behind them. +**blocking offload는 등록하고, 한계를 두고, timeout을 둔다.** `boundedElastic()`은 어디서나 쓸 수 있고 실제로는 한계가 없어서, +그것을 부르는 controller는 애플리케이션 전체를 소리 없이 한계 없는 pool에 들여놓는다. `BlockingBridgeProfile`이 offload해도 되는 +operation을 이름으로 대고, `BlockingBridgeBudget`이 동시성을 묶으며 제때 자리를 얻지 못한 호출자를 거절한다. 그렇지 않으면 느린 +의존 대상의 호출자가 heap이 찰 때까지 쌓이고 빠른 의존 대상이 그 뒤에서 굶는다. -> 2026-09-25: `advanced.blockingbridge` was removed. Its WebFlux adapter went with the WebFlux twin -> (D4), and a budget for a bridge that no longer exists bounded nothing. +> 2026-09-25: `advanced.blockingbridge`를 지웠다. 그 WebFlux 어댑터는 WebFlux 쌍둥이와 함께 갔고(D4), 더는 없는 bridge의 예산은 +> 아무것도 묶지 않았다. -**Pinning is observed, not assumed away.** `VirtualThreadProfile.requiredObservations()` lists what -has to be watched — `jdk.VirtualThreadPinned` above all. A synchronized block held across a blocking -call pins the carrier thread, the carrier pool is bounded by CPU count, and enough pinned carriers is -a deadlock a thread dump does not obviously show. +**pinning은 없다고 치지 않고 관찰한다.** `VirtualThreadProfile.requiredObservations()`가 지켜봐야 할 것 — 무엇보다 +`jdk.VirtualThreadPinned` — 을 적는다. blocking 호출을 가로질러 쥔 synchronized 블록은 carrier thread를 고정하고, carrier pool은 +CPU 수로 묶여 있으며, 고정된 carrier가 충분히 많으면 thread dump로도 잘 드러나지 않는 교착이 된다. -## Consequences +## 결과 -- Enabling virtual threads is a two-part change: the executor and the admission limit. The profile - will not let it be one. -- Refusals rise under load, and that is correct. A request refused in a millisecond is better for - the client than the same request accepted and timed out thirty seconds later behind a full pool. - An operator seeing 503s climb should read them as the limit working. -- `VirtualThreadAdmissionGuard.peakActive()` exists so a load test can assert the limit was applied. - It is invisible from throughput, which is why a load test that only measures throughput would pass - with the guard removed. +- virtual thread 켜기는 두 부분짜리 변경이다: executor와 admission 한계. profile은 그것이 한 부분이 되게 두지 않는다. +- 부하 아래에서 거절이 오르고, 그것이 맞다. 1밀리초 안에 거절된 요청이, 꽉 찬 pool 뒤에서 받아들여졌다가 30초 뒤 timeout된 같은 + 요청보다 client에게 낫다. 503이 오르는 것을 본 운영자는 그것을 한계가 동작하는 것으로 읽어야 한다. +- `VirtualThreadAdmissionGuard.peakActive()`는 부하 시험이 한계가 적용됐음을 단언할 수 있게 하려고 있다. 처리량에서는 보이지 + 않는다. 그래서 처리량만 재는 부하 시험은 guard를 빼도 통과한다. -## Alternatives considered +## 따져 본 대안 -- **Enable virtual threads and raise the downstream budgets to match.** Rejected: the budgets are - sized to what the dependencies can serve, not to what the web tier can accept. -- **Bound the virtual threads themselves with a fixed-size executor.** Rejected: that is a platform - thread pool with extra steps. -- **Let controllers call `boundedElastic()` directly.** Rejected: every such call site is invisible - until the pool is the thing consuming the heap. +- **virtual thread를 켜고 하류 예산을 거기 맞춰 올린다.** 버렸다: 예산은 web 계층이 받을 수 있는 양이 아니라 의존 대상이 감당할 + 수 있는 양에 맞춘 것이다. +- **고정 크기 executor로 virtual thread 자체를 묶는다.** 버렸다: 단계만 더 많은 platform thread pool이다. +- **controller가 `boundedElastic()`을 직접 부르게 둔다.** 버렸다: 그런 호출 자리는 pool이 heap을 먹는 범인이 될 때까지 하나도 + 보이지 않는다. diff --git a/docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md b/docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md index d850da30..32782c1e 100644 --- a/docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md +++ b/docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md @@ -7,62 +7,51 @@ - 현재 정본: `docs/web/openapi-32-compatibility.md` -# ADR-WEB-ADV-003: OpenAPI 3.2 is generated in parallel and stays experimental +# ADR-WEB-ADV-003: OpenAPI 3.2는 나란히 생성하고 실험용으로 남는다 -- Status: Accepted -- Date: 2026-08-25 -- Scope: `adapter:inbound:web` — `advanced.openapi` +- 상태: 채택 +- 날짜: 2026-08-25 +- 범위: `adapter:inbound:web` — `advanced.openapi` -## Context +## 배경 -Advanced Task 17 adds an OpenAPI 3.2 generation lane beside the Stable 3.1.2 snapshot. +Advanced Task 17은 Stable 3.1.2 snapshot 옆에 OpenAPI 3.2 생성 lane을 더한다. -Generating 3.2 is cheap. Adopting it is not, and the two get conflated because the generated -document looks fine. The value of an API description is entirely in what consumes it, and a document -in a version a client generator does not fully understand produces a client that compiles and is -wrong — which is worse than no document at all. +3.2 생성은 싸다. 채택은 싸지 않고, 생성된 문서가 멀쩡해 보여서 둘이 뒤섞인다. API 설명의 가치는 전부 그것을 쓰는 쪽에 있고, +client 생성기가 다 이해하지 못하는 버전의 문서는 컴파일되지만 틀린 client를 낳는다 — 문서가 아예 없는 것보다 나쁘다. -## Decision +## 결정 -**3.1.2 remains the release artifact.** `OpenApiVersionLane.STABLE_3_1.releaseArtifact()` is true and -`EXPERIMENTAL_3_2`'s is false. This is a property of the type, not a configuration setting. +**3.1.2가 릴리스 artifact로 남는다.** `OpenApiVersionLane.STABLE_3_1.releaseArtifact()`는 true이고 `EXPERIMENTAL_3_2`의 것은 +false다. 이것은 설정이 아니라 타입의 성질이다. -**Generating 3.2 must not change the 3.1 snapshot.** Both are produced from the same model, so a -contributor that mutates it on the way to 3.2 changes the artifact that is actually shipped — -silently, and only when the experimental lane runs. `OpenApi32CompatibilityReport` compares the -snapshot hash before and after and makes a difference a promotion blocker. +**3.2를 생성해도 3.1 snapshot이 바뀌면 안 된다.** 둘은 같은 모델에서 만들어지므로, 3.2로 가는 길에 모델을 바꾸는 기여자는 실제로 +출하하는 artifact를 바꾼다 — 소리 없이, 실험 lane이 돌 때만. `OpenApi32CompatibilityReport`가 전후의 snapshot hash를 비교하고, +차이를 승격을 막는 것으로 만든다. -> 2026-09-25: `OpenApi32CompatibilityReport` and `OpenApiToolchainMatrix` were removed — promotion -> checks kept in production code, called only by their own tests. `WebOpenApi32Generator` remains -> as library code in `adapter:inbound:web-advanced`; the decision below is unchanged. +> 2026-09-25: `OpenApi32CompatibilityReport`와 `OpenApiToolchainMatrix`를 지웠다 — 운영 코드에 둔 승격 검사인데 자기 시험만 +> 불렀다. `WebOpenApi32Generator`는 `adapter:inbound:web-advanced`에 라이브러리 코드로 남는다. 아래 결정은 바뀌지 않았다. -**Four kinds of tool are checked separately.** A parser reports structural errors; a linter applies -style rules and accepts documents a parser rejects; a generator produces client code, and this is -where an unsupported construct surfaces — not as an error but as a method with the wrong signature; -a compile of that generated code is the only step that catches it. "OpenAPI 3.2 works" is not a -statement anybody can make. "This document is read correctly by these four tools at these versions" -is. +**도구 네 종류를 따로 검사한다.** parser는 구조 오류를 알린다. linter는 문체 규칙을 적용하고 parser가 거절하는 문서도 받는다. +생성기는 client 코드를 만들고, 지원되지 않는 구문이 드러나는 곳이 여기다 — 오류가 아니라 시그니처가 틀린 메서드로. 그 생성 코드를 +컴파일하는 것이 그것을 잡는 유일한 단계다. 「OpenAPI 3.2가 된다」는 누구도 할 수 있는 말이 아니다. 「이 문서를 이 버전의 이 네 +도구가 맞게 읽는다」는 할 수 있다. -**Promotion requires an accepted ADR regardless of how green the matrix is.** -`promotionBlockers(false)` always contains that blocker. A machine-checkable matrix cannot decide -whether the consumer population is ready. +**표가 얼마나 초록이든 승격에는 채택된 ADR이 필요하다.** `promotionBlockers(false)`는 언제나 그 막음을 담는다. 기계로 검사하는 +표는 쓰는 쪽 집단이 준비됐는지 정할 수 없다. -**Streaming description differences are reported separately.** They are the substantive difference -between the two versions for this application, and folding them into a pass/fail hides what -changed. +**streaming 설명의 차이는 따로 알린다.** 이 애플리케이션에서 두 버전의 실질적 차이가 그것이고, 통과·실패 하나로 접으면 무엇이 +바뀌었는지 가려진다. -## Consequences +## 결과 -- The 3.2 document is published as an artifact of the experimental workflow, never of the release - workflow. -- A client generator that only understands 3.1 is unaffected, which is the point. -- Adopting 3.2 later is a documented decision with a named consumer matrix behind it. +- 3.2 문서는 릴리스 workflow가 아니라 실험 workflow의 artifact로만 게시한다. +- 3.1만 이해하는 client 생성기는 영향을 받지 않는다. 그것이 요점이다. +- 나중에 3.2를 채택하는 것은 이름 있는 쓰는 쪽 표를 뒤에 둔, 문서로 남긴 결정이다. -## Alternatives considered +## 따져 본 대안 -- **Switch to 3.2 and keep a 3.1 downgrade.** Rejected: the downgrade is lossy in exactly the - constructs 3.2 was wanted for, so it would ship a description that is wrong for both audiences. -- **Generate only 3.2 and let consumers cope.** Rejected: the failure mode is a generated client - that compiles and misbehaves. -- **Skip the client-compile step in the matrix.** Rejected: it is the only one that catches the - failure the others miss. +- **3.2로 바꾸고 3.1로 낮춘 것을 둔다.** 버렸다: 낮추기는 바로 3.2를 원한 이유인 구문에서 손실이 있어서, 두 독자 모두에게 틀린 + 설명을 출하하게 된다. +- **3.2만 생성하고 쓰는 쪽이 알아서 하게 둔다.** 버렸다: 실패 방식은 컴파일되고 잘못 동작하는 생성 client다. +- **표에서 client 컴파일 단계를 건너뛴다.** 버렸다: 다른 단계가 놓치는 실패를 잡는 유일한 단계다. diff --git a/docs/adr/ADR-WS-001-platform-as-packages-and-its-boundaries.md b/docs/adr/ADR-WS-001-platform-as-packages-and-its-boundaries.md index 69cc7efb..81465281 100644 --- a/docs/adr/ADR-WS-001-platform-as-packages-and-its-boundaries.md +++ b/docs/adr/ADR-WS-001-platform-as-packages-and-its-boundaries.md @@ -8,62 +8,51 @@ - 대체됨: `docs/capability-status.md` -# ADR-WS-001: The WebSocket platform ships as packages in one leaf, with machine-checked boundaries +# ADR-WS-001: WebSocket 플랫폼은 leaf 하나 안의 패키지로 싣고, 경계는 기계로 검사한다 -- Status: Superseded 2026-09-25 — the eighteen-package platform was cut to the parts a Spring - configuration or a real-container lane reaches: the `stomp` channel and the servlet handler - library (`servlet`, `outbound`, `budget`). The Advanced packages, the reactive runtime and the - `WebSocketArchitectureRules` pack went with the rest (see `docs/capability-status.md`). -- Date: 2026-08-25 -- Scope: `:adapter:inbound:websocket` +- 상태: 대체됨 2026-09-25 — 패키지 열여덟 개짜리 플랫폼을 Spring 설정이나 실제 container lane이 닿는 부분으로 잘랐다: `stomp` + 채널과 servlet handler 라이브러리(`servlet`, `outbound`, `budget`). Advanced 패키지, reactive runtime, `WebSocketArchitectureRules` + 묶음은 나머지와 함께 갔다(`docs/capability-status.md`를 본다). +- 날짜: 2026-08-25 +- 범위: `:adapter:inbound:websocket` -## Context +## 배경 -The realtime connection platform design models itself as eighteen Gradle modules under -`modules/websocket`, each with a declared purity grade and a declared set of allowed dependencies. -This repository's `src/config/architecture/modules.json` is a fail-closed registry that owns the -leaf list; adding eighteen leaves is a registry change of a size that needs its own decision, and -HARD-STOP #5 forbids doing it implicitly. +실시간 연결 플랫폼 설계는 스스로를 `modules/websocket` 아래 Gradle 모듈 열여덟 개로 모델링하고, 모듈마다 순수성 등급과 허용 의존 +집합을 선언한다. 이 저장소의 `src/config/architecture/modules.json`은 leaf 목록을 가진 실패하면 닫히는 registry다. leaf 열여덟 개를 +더하는 것은 자기 결정이 필요한 크기의 registry 변경이고, HARD-STOP #5가 그것을 은근슬쩍 하는 것을 금지한다. -Three earlier platforms in this repository — JPA, GraphQL, and the HTTP platform — met the same -situation and resolved it the same way. +이 저장소의 앞선 플랫폼 셋 — JPA, GraphQL, HTTP 플랫폼 — 이 같은 상황을 만났고 같은 방식으로 풀었다. -## Decision +## 결정 -The eighteen design modules ship as packages inside the single registered leaf. `WebSocketStableModule` -declares each one's package, purity grade and exact allowed edges, and `WebSocketModuleBoundaryTest` -scans the production tree and fails when the declaration and the tree disagree in either direction. +설계 모듈 열여덟 개를 등록된 leaf 하나 안의 패키지로 싣는다. `WebSocketStableModule`이 모듈마다 패키지, 순수성 등급, 정확한 허용 +edge를 선언하고, `WebSocketModuleBoundaryTest`가 운영 트리를 scan해 선언과 트리가 어느 방향으로든 다르면 실패한다. -Three deviations from the design's module map were forced by the check and are recorded in -`docs/websocket/repository-adaptation.md`: `WebSocketSubprotocolName` moved to `core` and the codec -moved to its own FRAMEWORK_BOUND module, both to avoid cycles the design's placement created here; -and the `budget -> core` edge was inverted because `budget` imports nothing from `core`. +검사가 강요한, 설계 모듈 지도와 다른 점 셋은 `docs/websocket/repository-adaptation.md`에 적었다: `WebSocketSubprotocolName`을 +`core`로 옮겼고 codec을 자기 FRAMEWORK_BOUND 모듈로 옮겼다. 둘 다 설계의 배치가 여기서 만든 순환을 피하려는 것이다. 그리고 +`budget`이 `core`에서 아무것도 import하지 않으므로 `budget -> core` edge를 뒤집었다. -## Consequences +## 결과 -**The boundary is enforced, not documented.** Six violations were caught during implementation that -a document would not have: two would-be cycles, a duplicate module declaration where two ids claimed -one package, and three undeclared edges. The duplicate is the instructive one — with two ids on one -package, ownership depends on iteration order and one module's rules silently apply to nothing. A -guard against it is now part of the boundary test. +**경계를 문서로 두지 않고 강제한다.** 구현 중에 문서라면 잡지 못했을 위반 여섯 개를 잡았다: 순환이 될 뻔한 것 둘, id 둘이 패키지 +하나를 주장한 중복 모듈 선언, 선언하지 않은 edge 셋. 배울 것이 있는 쪽은 중복이다 — 패키지 하나에 id가 둘이면 소유가 반복 순서에 +달리고 한 모듈의 규칙이 소리 없이 아무것에도 적용되지 않는다. 그것을 막는 guard가 이제 경계 시험의 일부다. -**The detector had a hole.** Its framework-import list named `com.fasterxml` (Jackson 2) and not -`tools.jackson` (Jackson 3), which is what Spring 7 actually uses — so a CORE module could have -imported a mapper unnoticed. Fixed here and in the HTTP platform, which shared the list. +**찾는 장치에 구멍이 있었다.** 그 프레임워크 import 목록은 `com.fasterxml`(Jackson 2)를 대고 Spring 7이 실제로 쓰는 +`tools.jackson`(Jackson 3)을 대지 않았다 — 그래서 CORE 모듈이 mapper를 import해도 들키지 않을 수 있었다. 여기와, 그 목록을 같이 쓰던 +HTTP 플랫폼에서 고쳤다. -**Promotion stays cheap.** Each enum constant is already shaped like a leaf specification, so -splitting one out later is a registry edit rather than an archaeology exercise. +**승격은 싸게 남는다.** enum 상수 하나하나가 이미 leaf 명세 모양이라서, 나중에 하나를 떼어 내는 것은 고고학이 아니라 registry +수정이다. -**The design's own rules were kept where they cost something.** `core` names no framework, so the -same decisions serve both runtimes and are testable without a server; no Java class name reaches the -wire; the payload is an encoded string rather than a map; and handlers are given no way to write, -which is what makes ordering and backpressure guarantees rather than conventions. +**비용이 드는 곳에서도 설계 자신의 규칙을 지켰다.** `core`는 어떤 프레임워크도 이름으로 대지 않으므로 같은 결정이 두 runtime에 +쓰이고 서버 없이 시험할 수 있다. Java 클래스 이름이 wire에 닿지 않는다. payload는 map이 아니라 인코딩한 문자열이다. 그리고 +handler에게는 쓸 길을 주지 않는다. 그것이 순서와 backpressure를 관례가 아니라 보장으로 만든다. -## Alternatives considered +## 따져 본 대안 -**Register eighteen leaves.** Faithful to the design and a large change to a fail-closed registry -for a platform that ships as one artifact either way. Rejected as disproportionate; the boundary -test provides the property the modules were for. +**leaf 열여덟 개를 등록한다.** 설계에 충실하지만, 어느 쪽이든 artifact 하나로 싣는 플랫폼을 위해 실패하면 닫히는 registry를 크게 +바꾼다. 지나치다고 보고 버렸다. 경계 시험이 모듈이 주려던 성질을 준다. -**Ship the modules as packages with no enforcement.** Cheapest, and it makes the boundary a claim. -The six violations found during implementation are the argument against it. +**모듈을 강제 없는 패키지로 싣는다.** 가장 싸지만 경계를 주장으로 만든다. 구현 중에 찾은 위반 여섯 개가 그것에 반대하는 근거다. diff --git a/docs/adr/ADR-WS-002-resume-and-cluster.md b/docs/adr/ADR-WS-002-resume-and-cluster.md index 6f089e9d..30ad5578 100644 --- a/docs/adr/ADR-WS-002-resume-and-cluster.md +++ b/docs/adr/ADR-WS-002-resume-and-cluster.md @@ -8,64 +8,56 @@ - 대체됨: `docs/capability-status.md` -# ADR-WS-002: Resume and cluster state are caches, and are treated as caches +# ADR-WS-002: resume와 cluster 상태는 cache이고, cache로 다룬다 -- Status: Superseded 2026-09-25 — `advanced.resume`, `advanced.cluster` and `advanced.presence` - were removed: nothing assembled them (see `docs/capability-status.md`). -- Date: 2026-08-25 -- Scope: `adapter:inbound:websocket` — `advanced.resume`, `advanced.cluster`, `advanced.presence` +- 상태: 대체됨 2026-09-25 — `advanced.resume`, `advanced.cluster`, `advanced.presence`를 지웠다: 아무것도 그것을 조립하지 + 않았다(`docs/capability-status.md`를 본다). +- 날짜: 2026-08-25 +- 범위: `adapter:inbound:websocket` — `advanced.resume`, `advanced.cluster`, `advanced.presence` -## Context +## 배경 -Advanced Tasks 2–8 add three things that all look like state and are not: a resume token that says -where a client got to, a cluster index that says which node holds a session, and a presence summary -derived from that index. +Advanced Task 2–8은 모두 상태처럼 보이지만 상태가 아닌 것 셋을 더한다: client가 어디까지 왔는지 말하는 resume token, 어느 노드가 +세션을 가졌는지 말하는 cluster index, 그 index에서 끌어낸 presence 요약. -Each is a statement about the past. The resume token was minted before the disconnect; the index -entry was written by a node that may since have died; presence is a read of the index and inherits -everything wrong with it. The failure this ADR exists to prevent is treating any of them as current -fact, because each reads as one at the call site. +하나하나가 과거에 대한 진술이다. resume token은 연결이 끊기기 전에 만들어졌다. index 항목은 그 뒤에 죽었을 수 있는 노드가 썼다. +presence는 index를 읽은 것이고 그것의 틀린 점을 모두 물려받는다. 이 ADR이 막으려는 실패는 그중 어느 것이든 지금의 사실로 다루는 +것이다. 부르는 자리에서는 하나같이 사실처럼 읽히기 때문이다. -## Decision +## 결정 -**Resume is bounded by what the replay store actually holds, not by what the token claims.** -`ResumeCoordinator` consults `ReplayAvailability` before honouring a position. A token that names a -position the store has evicted produces a resynchronise, not a gap-filled stream. The alternative — -trusting the token — silently delivers a stream with a hole in it, which is worse than an explicit -resynchronise because the client believes it is complete. +**resume은 token이 주장하는 것이 아니라 replay 저장소가 실제로 가진 것으로 묶는다.** `ResumeCoordinator`는 위치를 받아 주기 전에 +`ReplayAvailability`를 묻는다. 저장소가 이미 버린 위치를 대는 token은 빈틈을 메운 stream이 아니라 다시 맞추기를 낸다. 대안 — token을 +믿기 — 은 구멍 난 stream을 소리 없이 전달하고, client가 그것이 완전하다고 믿으므로 명시적 다시 맞추기보다 나쁘다. -**Cluster index entries carry an observation time and are checked against it on every read.** -`ExternalSessionSummary.staleAt` exists so that "the index says edge-2" cannot be used without also -answering "as of when". An entry whose node stopped reporting is not evidence that the node holds -the session. +**cluster index 항목은 관찰 시각을 싣고, 읽을 때마다 그것과 대조한다.** `ExternalSessionSummary.staleAt`은 「index가 edge-2라고 +한다」를 「언제 기준으로」에 답하지 않고는 쓸 수 없게 하려고 있다. 보고를 멈춘 노드의 항목은 그 노드가 세션을 가졌다는 증거가 +아니다. -**Durable fan-out is deduplicated by stream position, not by message id.** At-least-once is the -contract, so redelivery is normal operation: a redeploy, a slow consumer or a broker rebalance all -produce it. `FanoutDeduplicator` keys on `(stream, position)` and advances a high-water mark under -`compute`, so two consumer threads cannot both deliver the same position. +**durable fan-out의 중복은 message id가 아니라 stream 위치로 거른다.** 계약이 at-least-once이므로 재전달은 보통 동작이다: 재배포, +느린 소비자, broker rebalance가 모두 그것을 낳는다. `FanoutDeduplicator`는 `(stream, position)`을 키로 쓰고 `compute` 아래에서 +high-water mark를 올리므로, 소비자 스레드 둘이 같은 위치를 둘 다 전달할 수 없다. -**Presence has four states, not two.** `OFFLINE` is a reported fact; `STALE` is the absence of one. -Collapsing them reports every user as disconnected during a Redis partition, when what happened is -that the index went dark and the connections are fine. +**presence에는 상태가 둘이 아니라 넷이다.** `OFFLINE`은 보고된 사실이고, `STALE`은 사실이 없는 것이다. 둘을 합치면 Redis partition +동안 모든 사용자를 연결 끊김으로 알리는데, 실제로 일어난 일은 index가 어두워졌고 연결은 멀쩡한 것이다. -**Nothing security-relevant may depend on presence.** An attacker who can make a node stop reporting -can move the platform's belief about who is present. Presence answers "show a green dot". +**보안에 관련된 어떤 것도 presence에 기대면 안 된다.** 노드가 보고를 멈추게 할 수 있는 공격자는 누가 있는지에 대한 플랫폼의 믿음을 +움직일 수 있다. presence는 「초록 점을 보여 줄까」에 답한다. -## Consequences +## 결과 -- A resume that cannot be honoured is visible to the client as a resynchronise. Clients must - implement one; there is no mode in which the platform silently pretends. -- Every read of the cluster index needs a clock. This is deliberate friction. -- `PresenceSummary.classify` refuses an idle window at or past the stale window, because otherwise - `IDLE` is unreachable and the caller believes it has a four-state model when it has three. -- Fan-out envelopes carry a bounded reference and the catalog-encoded document, never a business - object. A rolling deploy has two versions of the code reading the same envelope. +- 받아 줄 수 없는 resume은 client에게 다시 맞추기로 보인다. client는 그것을 구현해야 한다. 플랫폼이 소리 없이 시늉하는 모드는 없다. +- cluster index를 읽을 때마다 시계가 필요하다. 일부러 둔 마찰이다. +- `PresenceSummary.classify`는 stale 창 이상인 idle 창을 거절한다. 그렇지 않으면 `IDLE`에 닿을 수 없고, 호출자는 상태 셋짜리를 + 가지고 넷짜리 모델이라고 믿는다. +- fan-out envelope은 한계 있는 참조와 catalog로 인코딩한 문서를 싣고, 업무 객체는 싣지 않는다. rolling deploy에서는 코드 두 버전이 + 같은 envelope을 읽는다. -## Alternatives considered +## 따져 본 대안 -- **Trust the resume token.** Rejected: it makes a gap indistinguishable from a complete stream. -- **Deduplicate by message id.** Rejected: a broker that redelivers may re-mint ids, and a producer - that retries certainly does. Position is the property the ordering actually has. -- **A single `online` boolean.** Rejected for the partition case above. -- **Write presence separately from the session index.** Rejected: two sources of truth for "who is - connected" drift, and the drift is invisible — both look plausible and nothing reconciles them. +- **resume token을 믿는다.** 버렸다: 빈틈을 완전한 stream과 구별할 수 없게 만든다. +- **message id로 중복을 거른다.** 버렸다: 재전달하는 broker는 id를 다시 만들 수 있고, 재시도하는 producer는 반드시 그렇게 한다. + 위치가 순서가 실제로 가진 성질이다. +- **`online` boolean 하나.** 위 partition 경우 때문에 버렸다. +- **presence를 세션 index와 따로 쓴다.** 버렸다: 「누가 연결돼 있나」의 정본이 둘이면 어긋나고, 그 어긋남은 보이지 않는다 — 둘 다 + 그럴듯해 보이고 아무것도 둘을 맞추지 않는다. diff --git a/docs/adr/ADR-WS-003-stomp-and-broker-relay.md b/docs/adr/ADR-WS-003-stomp-and-broker-relay.md index fab91a73..b87857ec 100644 --- a/docs/adr/ADR-WS-003-stomp-and-broker-relay.md +++ b/docs/adr/ADR-WS-003-stomp-and-broker-relay.md @@ -8,78 +8,66 @@ - 대체됨: `docs/capability-status.md` -# ADR-WS-003: STOMP is an Advanced adapter with a declared destination catalog +# ADR-WS-003: STOMP는 destination catalog를 선언한 Advanced 어댑터다 -- Status: Superseded 2026-09-25 — `advanced.stomp` and `advanced.stomp.rabbit` were removed; the - `stomp` package is the only STOMP channel (see `docs/capability-status.md`). -- Date: 2026-08-25 -- Scope: `adapter:inbound:websocket` — `advanced.stomp`, `advanced.stomp.rabbit` +- 상태: 대체됨 2026-09-25 — `advanced.stomp`와 `advanced.stomp.rabbit`을 지웠다. `stomp` 패키지가 유일한 STOMP 채널이다 + (`docs/capability-status.md`를 본다). +- 날짜: 2026-08-25 +- 범위: `adapter:inbound:websocket` — `advanced.stomp`, `advanced.stomp.rabbit` -## Context +## 배경 -Advanced Tasks 9–13 add STOMP 1.2 alongside the platform's own protocol, plus a RabbitMQ broker -relay and cross-node user destinations. +Advanced Task 9–13은 플랫폼 자신의 프로토콜 옆에 STOMP 1.2를 더하고, RabbitMQ broker relay와 노드를 가로지르는 user destination도 +더한다. -This leaf already ships an older STOMP-over-SockJS channel (`stomp`, gated on -`app.websocket.enabled`). Two `@EnableWebSocketMessageBroker` configurations in one context -do not conflict loudly — both contribute a configurer, both call `configureMessageBroker`, and the -broker that results is whichever ran last. Nothing errors and nothing logs. +이 leaf는 이미 더 오래된 STOMP-over-SockJS 채널(`stomp`, `app.websocket.enabled`로 막는다)을 싣는다. 한 context 안의 +`@EnableWebSocketMessageBroker` 설정 둘은 시끄럽게 충돌하지 않는다 — 둘 다 configurer를 기여하고, 둘 다 +`configureMessageBroker`를 부르며, 결과 broker는 마지막에 돈 쪽의 것이다. 오류도 로그도 없다. -STOMP also brings a destination model that is a free string from the client. Without a catalog, the -set of reachable destinations is whatever the broker accepts, which for the simple broker is every -string. +STOMP는 client에게서 오는 자유 문자열인 destination 모델도 가져온다. catalog가 없으면 닿을 수 있는 destination 집합은 broker가 받는 +모든 것이고, simple broker에게 그것은 모든 문자열이다. -## Decision +## 결정 -**The Advanced adapter is its own module (`advanced-stomp`), separate from `advanced`.** It is the -one Advanced capability that cannot be pure — STOMP here *is* the Spring Messaging types — and -folding it into `advanced` would relax that module's purity for every capability in it. +**Advanced 어댑터는 `advanced`와 따로 둔 자기 모듈(`advanced-stomp`)이다.** 순수할 수 없는 유일한 Advanced capability다 — 여기서 +STOMP는 곧 Spring Messaging 타입이다 — 그리고 `advanced`에 접어 넣으면 그 모듈의 모든 capability에 대해 순수성을 느슨하게 만든다. -**The relay is a further module (`advanced-stomp-rabbit`).** The adapter parses a protocol; the -relay opens a TCP connection to somebody else's broker and makes every delivery depend on it. -Different blast radius, different decision, different module. +**relay는 그다음 모듈(`advanced-stomp-rabbit`)이다.** 어댑터는 프로토콜을 파싱한다. relay는 남의 broker에 TCP 연결을 열고 모든 +전달을 그것에 기대게 만든다. 피해 범위가 다르고, 결정이 다르고, 모듈이 다르다. -**Destinations are declared, per operation.** `StompDestinationCatalog` maps `(operation, -destination)` to a required permission. Undeclared is refused. `SUBSCRIBE` and `SEND` are separate -declarations, because reading a feed and publishing into it are different rights. +**destination은 operation마다 선언한다.** `StompDestinationCatalog`는 `(operation, destination)`을 필요한 권한에 대응시킨다. 선언하지 +않은 것은 거절한다. `SUBSCRIBE`와 `SEND`는 따로 선언한다. feed를 읽는 것과 거기에 게시하는 것은 다른 권리이기 때문이다. -**The authorization decision is a value, not an interceptor method.** `StompAuthorizationPolicy` -returns a `StompAuthorizationDecision`; `StompSecurityInterceptor` only extracts and enforces. A rule -reachable only through a `MessageChannel` gets tested for the cases somebody built a channel for. +**인가 판정은 interceptor 메서드가 아니라 값이다.** `StompAuthorizationPolicy`가 `StompAuthorizationDecision`을 돌려주고, +`StompSecurityInterceptor`는 꺼내서 강제하기만 한다. `MessageChannel`을 거쳐서만 닿는 규칙은 누가 channel을 만들어 둔 경우만 +시험된다. -**Only one STOMP runtime may run.** `StompBrokerExclusivity` fails the context when both channels -are enabled, when both brokers are, or when the adapter is enabled with no broker behind it. +**STOMP runtime은 하나만 돌 수 있다.** `StompBrokerExclusivity`는 두 채널이 모두 켜졌을 때, 두 broker가 모두 켜졌을 때, 또는 뒤에 +broker 없이 어댑터가 켜졌을 때 context를 실패시킨다. -**A `RECEIPT` is never promoted to a commit.** `StompEvidence` has six stages and -`StompAckPolicy.evidenceForReceipt()` is fixed at `PROTOCOL_RECEIPT`. The receipt is written by the -protocol layer, which knows nothing about whether the work succeeded. +**`RECEIPT`는 절대 커밋으로 올리지 않는다.** `StompEvidence`에는 단계가 여섯 있고 `StompAckPolicy.evidenceForReceipt()`는 +`PROTOCOL_RECEIPT`로 고정이다. receipt는 프로토콜 계층이 쓰고, 그 계층은 일이 성공했는지 아무것도 모른다. -**The simple broker declares what it cannot do.** `SimpleBrokerProfile` cannot be constructed -claiming cluster support or durable acks, and refuses activation outside local/test — in a -multi-node deployment it does not error, it delivers to whichever fraction of users is on the -publishing node. +**simple broker는 할 수 없는 것을 선언한다.** `SimpleBrokerProfile`은 cluster 지원이나 durable ack를 주장하며 만들 수 없고, +local·test 밖에서 켜기를 거절한다 — 여러 노드 배포에서 그것은 오류를 내지 않고, 게시한 노드에 있는 사용자 일부에게만 전달한다. -**Unresolved user destinations are broadcast once and then dead-lettered.** -`MultiNodeUserDestination` distinguishes a message that arrived *via* the broadcast from one that did -not. Without that, every node rebroadcasts every unresolvable message on receipt. +**풀리지 않은 user destination은 한 번 broadcast한 뒤 dead-letter로 보낸다.** `MultiNodeUserDestination`은 broadcast를 *거쳐* 온 +메시지와 그렇지 않은 메시지를 구별한다. 그렇지 않으면 모든 노드가 풀 수 없는 메시지를 받을 때마다 다시 broadcast한다. -## Consequences +## 결과 -- Enabling Advanced STOMP requires disabling the legacy channel. There is no migration path that - runs both; the exclusivity check makes that explicit at startup rather than at 3am. -- A deployment must write its own catalog. There is deliberately no default: an empty one refuses - every frame and reads as a broken adapter, and a non-empty one publishes destinations nobody chose. -- The relay's cost is one broker connection per authenticated session plus one system connection. - `brokerConnectionsFor` exists so this is computed before the first outage. -- User-destination metrics are tagged with `UserDestinationAction`, never the destination — a user - destination contains a user identifier by construction. +- Advanced STOMP를 켜려면 옛 채널을 꺼야 한다. 둘을 함께 돌리는 옮기기 길은 없다. 배타성 검사가 그것을 새벽 3시가 아니라 기동 + 때 분명히 한다. +- 배포는 자기 catalog를 써야 한다. 일부러 기본값이 없다: 빈 catalog는 모든 frame을 거절해서 고장 난 어댑터처럼 읽히고, 비어 있지 + 않은 기본 catalog는 아무도 고르지 않은 destination을 게시한다. +- relay의 비용은 인증된 세션마다 broker 연결 하나 + 시스템 연결 하나다. `brokerConnectionsFor`는 첫 장애 전에 그것을 계산하려고 + 있다. +- user destination metric은 destination이 아니라 `UserDestinationAction`으로 tag를 단다 — user destination은 구조상 사용자 식별자를 + 담는다. -## Alternatives considered +## 따져 본 대안 -- **Extend the existing `stomp` package.** Rejected: it is Stable, and WS-ARCH-6 forbids a Stable - module naming an Advanced one. Making the legacy channel profile-driven would have required that - edge. -- **One `advanced-stomp` module including the relay.** Rejected: the relay is a separate operational - decision and deserves to be refusable on its own. -- **Allow undeclared destinations with a wildcard permission.** Rejected: the wildcard becomes the - default and the catalog becomes documentation. +- **기존 `stomp` 패키지를 넓힌다.** 버렸다: 그것은 Stable이고, WS-ARCH-6은 Stable 모듈이 Advanced 모듈 이름을 대는 것을 금지한다. + 옛 채널을 profile로 움직이게 하려면 그 edge가 필요했다. +- **relay를 포함한 `advanced-stomp` 모듈 하나.** 버렸다: relay는 따로 정할 운영 결정이고, 그것만 따로 거절할 수 있어야 한다. +- **wildcard 권한으로 선언하지 않은 destination을 허용한다.** 버렸다: wildcard가 기본이 되고 catalog는 문서가 된다. diff --git a/scripts/check-docs-exceptions.txt b/scripts/check-docs-exceptions.txt index 173f1fd2..acde70c0 100644 --- a/scripts/check-docs-exceptions.txt +++ b/scripts/check-docs-exceptions.txt @@ -9,32 +9,6 @@ language .github/dependency-vulnerability-policy.md language .github/pull_request_template.md language compose/keycloak/README.md language compose/redis/acl/README.md -language docs/adr/ADR-BUILD-001-one-convention-for-shared-test-code.md -language docs/adr/ADR-GQL-001-graphql-context-and-storage-ownership.md -language docs/adr/ADR-GRPC-001-platform-family-and-registry-shape.md -language docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md -language docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md -language docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md -language docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md -language docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md -language docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md -language docs/adr/ADR-JPA-001-domain-owns-persistence-model.md -language docs/adr/ADR-JPA-002-full-transaction-retry.md -language docs/adr/ADR-JPA-003-completion-unknown.md -language docs/adr/ADR-JPA-004-flyway-schema-source-of-truth.md -language docs/adr/ADR-JPA-005-postgresql-real-contract.md -language docs/adr/ADR-JPA-006-canonical-technical-audit.md -language docs/adr/ADR-MONGO-001-platform-boundary.md -language docs/adr/ADR-MONGO-002-bson-representation.md -language docs/adr/ADR-MONGO-003-transaction-retry.md -language docs/adr/ADR-MONGO-004-index-schema-admin-plane.md -language docs/adr/ADR-MONGO-ADV-001-capability-promotion.md -language docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md -language docs/adr/ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md -language docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md -language docs/adr/ADR-WS-001-platform-as-packages-and-its-boundaries.md -language docs/adr/ADR-WS-002-resume-and-cluster.md -language docs/adr/ADR-WS-003-stomp-and-broker-relay.md language docs/compatibility/grpc-advanced-support-matrix.md language docs/compatibility/grpc-support-matrix.md language docs/fileserver/configuration.md From 94ac85adf6827b466be8c7854186fb748b48f478 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 7 Nov 2026 17:34:51 +0900 Subject: [PATCH 6/6] =?UTF-8?q?docs(notification-adr):=20=EC=95=8C?= =?UTF-8?q?=EB=A6=BC=20=EA=B2=B0=EC=A0=95=20=EA=B8=B0=EB=A1=9D=20=EB=B3=B8?= =?UTF-8?q?=EB=AC=B8=EC=9D=84=20=ED=95=9C=EA=B5=AD=EC=96=B4=EB=A1=9C=20?= =?UTF-8?q?=EC=98=AE=EA=B8=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: `docs/notification/adr/`의 NOTIF-ADR-001~004는 머리 블록만 한국어이고 본문이 영어다. NOTIF-ADR-005는 한국어지만 상태 값과 절 제목 하나, 인용문이 영어로 남아 있다. 방법: 결정의 뜻을 바꾸지 않고 제자리에서 옮긴다(폴더 옮기기는 통합 단계의 몫이다). 머리 블록은 바꾸지 않는다. 식별자·타입 이름·상태 값 같은 코드 표기는 원문으로 두고, NOTIF-ADR-005가 인용한 영어 원문에는 뜻을 괄호로 붙인다. 파일 이름이 그대로라 NotificationReleaseGateTest가 보는 존재 단언은 영향이 없다. 위험: 없음. 본문 뜻은 바꾸지 않았다. 검증: python3 scripts/check-docs.py rc=0(language 줄 4개 지움, head 실패 0), 머리 블록이 HEAD와 같은지 5개 모두 diff로 대조. --- .../adr/NOTIF-ADR-001-durable-acceptance.md | 34 +++++++------- .../NOTIF-ADR-002-event-ledger-projection.md | 31 ++++++------- .../adr/NOTIF-ADR-003-ambiguous-submission.md | 46 +++++++++---------- .../adr/NOTIF-ADR-004-fcm-fid-primary.md | 33 ++++++------- .../adr/NOTIF-ADR-005-canonical-namespace.md | 7 +-- scripts/check-docs-exceptions.txt | 4 -- 6 files changed, 70 insertions(+), 85 deletions(-) diff --git a/docs/notification/adr/NOTIF-ADR-001-durable-acceptance.md b/docs/notification/adr/NOTIF-ADR-001-durable-acceptance.md index fb7d5f2f..de2293f7 100644 --- a/docs/notification/adr/NOTIF-ADR-001-durable-acceptance.md +++ b/docs/notification/adr/NOTIF-ADR-001-durable-acceptance.md @@ -7,30 +7,28 @@ - 현재 정본: `docs/notification/support-matrix.md` -# NOTIF-ADR-001 — `submit()` means durable acceptance +# NOTIF-ADR-001 — `submit()`은 durable 접수를 뜻한다 -## 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: +알림 플랫폼의 뻔한 API는 성공이나 실패를 돌려주는 `send()`다. 이 플랫폼이 지원하는 모든 채널이 그 반환값을 거짓말로 만든다: -- 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. +- SES는 요청을 받고 `MessageId`를 돌려준 뒤에도 보내기를 거절할 수 있다. +- Twilio는 `accepted`, `sent`, `delivered`를 따로따로, 나중에 오는 이벤트로 나눈다. +- APNs는 알림을 받은 뒤 전달하거나, 저장하거나, 버릴 수 있다. +- Web Push는 프로토콜 수준에서 push service의 접수와 user agent의 확인 응답을 나눈다. -## 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. +`submit()`과 `schedule()`은 논리 요청과 그 수신자 job이 데이터베이스에 커밋되면 돌아온다. 접수증은 `notificationId`, +`RequestStatus`, `acceptedAt`을 싣고, `delivered`·`sent`·`read` 요소가 없다. 트랜잭션이 열려 있는 동안에는 어떤 provider에도 +연락하지 않는다. -## 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. +타입이 그렇게 읽을 길을 주지 않으므로, 호출자는 접수를 전달로 착각할 수 없다. 전달 상태는 provider 이벤트 원장에서 만든 +projection에 대한 따로 둔 query다. 비용은 「도착했나?」가 두 번째 질문이라는 것이다 — 그것이 정직한 질문 수다. diff --git a/docs/notification/adr/NOTIF-ADR-002-event-ledger-projection.md b/docs/notification/adr/NOTIF-ADR-002-event-ledger-projection.md index 67afe419..bcbf6ada 100644 --- a/docs/notification/adr/NOTIF-ADR-002-event-ledger-projection.md +++ b/docs/notification/adr/NOTIF-ADR-002-event-ledger-projection.md @@ -7,28 +7,25 @@ - 현재 정본: `docs/notification/support-matrix.md` -# NOTIF-ADR-002 — append-only event ledger with channel projectors +# NOTIF-ADR-002 — 채널 projector를 둔 append-only 이벤트 원장 -## 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. +선형 전달 상태 하나는 제자리에서 고쳐야 하고, 그러면 새 이벤트가 저장된 것보다 앞서는지 정할 규칙이 필요하다. 자연스러운 규칙 — +ordinal 비교 — 은 실제 provider traffic에서 틀린다. Twilio는 callback 순서를 보장하지 않아서 `sent`가 `delivered` 뒤에 온다. email은 +전달 뒤에 불만 신고를 낸다. 두 경우 모두 ordinal 규칙 아래에서 정보를 잃는다. -## 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. +provider 이벤트는 어떤 projection이 돌기 전에 바뀌지 않는 원장에 덧붙인다. 채널별 projector가 명시한 전이 표로 이벤트를 +`SubmissionOutcome`, `DeliveryOutcome`, `EvidenceLevel`, `EngagementFacts`, `SuppressionFacts`로 합친다. projection은 멱등이고 원장에서 +다시 돌릴 수 있다. -## 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. +중복, 순서가 뒤바뀐, 늦은 이벤트는 결함이 아니라 보통 입력이다. 잘못 project한 이벤트가 아직 저장돼 있으므로 projector 결함은 +회복할 수 있다. projector 버전은 다시 돌려서 옮길 수 있다. 비용은 이벤트마다 두 번째 쓰기와, 원장보다 늦을 수 있는 projection이다. diff --git a/docs/notification/adr/NOTIF-ADR-003-ambiguous-submission.md b/docs/notification/adr/NOTIF-ADR-003-ambiguous-submission.md index c38e6184..08bf8113 100644 --- a/docs/notification/adr/NOTIF-ADR-003-ambiguous-submission.md +++ b/docs/notification/adr/NOTIF-ADR-003-ambiguous-submission.md @@ -7,40 +7,36 @@ - 현재 정본: `docs/notification/support-matrix.md` -# NOTIF-ADR-003 — ambiguous submission is a first-class state +# NOTIF-ADR-003 — 모호한 제출은 정식 상태다 -## 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. +가장 흔한 심각한 실패는 거절이 아니다. body는 provider에 닿았는데 응답이 돌아오지 않은 요청이다. 플랫폼에는 provider 요청 id가 없고, +사용자는 알림을 받았을 수도 안 받았을 수도 있다. -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. +그것을 실패로 다루면 중복이 생긴다: 재시도가 두 번째 메시지를 보내고, 채널을 넘는 대체가 이미 도착한 push 옆에 SMS를 보낸다. 성공으로 +다루면 실제 실패를 잃는다. -## 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`. +`AMBIGUOUS`는 저장되는 `SubmissionOutcome`이자 `AttemptConfirmation`이다. 시도는 `requestStarted`, `requestBodyCommitted`, +`providerResponseReceived`를 기록하고, 각각 `PROVEN`, `INFERRED`, `UNKNOWN` 중 하나의 `EvidenceCertainty`를 가진다. 그래서 모르는 +어댑터가 `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 +- provider가 요청별 멱등성을 증명하지 않으면 자동 재시도를 막는다 +- 채널을 넘는 자동 대체는 조건 없이 막는다 +- provider가 상태 query를 지원하면 맞춰 보기를 돌린다 +- 그렇지 않으면 전달을 멈추고 운영자를 기다린다 -Operator redrive of an ambiguous attempt requires explicit duplicate-risk approval. +모호한 시도를 운영자가 다시 보내려면 중복 위험을 명시해 승인해야 한다. -## Consequences +## 결과 -Some notifications stop in a state that needs a human or a reconciliation pass. That is the intended -trade: an unresolved unknown is cheaper than a guaranteed duplicate, and the state is visible rather -than silently resolved in either direction. +어떤 알림은 사람이나 맞춰 보기 한 바퀴가 필요한 상태에서 멈춘다. 그것이 의도한 거래다: 풀리지 않은 모름이 보장된 중복보다 싸고, +상태는 어느 쪽으로든 소리 없이 풀리지 않고 보인다. diff --git a/docs/notification/adr/NOTIF-ADR-004-fcm-fid-primary.md b/docs/notification/adr/NOTIF-ADR-004-fcm-fid-primary.md index e7b84c67..4a885de3 100644 --- a/docs/notification/adr/NOTIF-ADR-004-fcm-fid-primary.md +++ b/docs/notification/adr/NOTIF-ADR-004-fcm-fid-primary.md @@ -7,30 +7,27 @@ - 현재 정본: `docs/notification/provider-runbooks.md` -# NOTIF-ADR-004 — FCM installation id is the primary target +# NOTIF-ADR-004 — FCM installation id가 주 대상이다 -## 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. +Firebase는 이제 installation id(FID)를 권하고 registration token multicast 경로를 옛것으로 다룬다. `token` 문자열 하나 위에 세운 +contact point 모델은 옛 모델을 유일한 것으로 담게 되고, 나중의 옮기기는 런타임 해석 문제가 된다: 같은 문자열 필드가 행마다 다른 +뜻이 된다. -## 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. +`MobilePushTarget`은 `FcmInstallationId`, `LegacyFcmRegistrationToken`, `ApnsDeviceToken`으로 된 sealed 계층이다. 종류는 문자열 필드 +하나의 구분자가 아니라 따로 둔 타입이고, 각각 자기 `ContactPointType`을 싣는다. 그래서 유일성 범위와 암호화 associated data가 다르다. -APNs tokens additionally carry their environment, because sandbox and production are separate -namespaces rather than a flag. +APNs token은 환경도 싣는다. sandbox와 production은 flag가 아니라 따로 둔 namespace이기 때문이다. -## 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. +대상 종류를 옮기는 것은 런타임 짐작이 아니라 빠짐없는 `switch`를 쓴 컴파일 시점 변경이다. 어댑터가 종류마다 자기 wire 표현으로 +대응시키므로, provider가 한 경로를 바꿔도 다른 경로가 소리 없이 바뀌지 않는다. 비용은 문자열 필드보다 타입이 하나 더 필요하다는 +것이다. diff --git a/docs/notification/adr/NOTIF-ADR-005-canonical-namespace.md b/docs/notification/adr/NOTIF-ADR-005-canonical-namespace.md index 299363ac..a6b6e491 100644 --- a/docs/notification/adr/NOTIF-ADR-005-canonical-namespace.md +++ b/docs/notification/adr/NOTIF-ADR-005-canonical-namespace.md @@ -11,7 +11,7 @@ ## 상태 -Accepted (2026-08-15). NTF-018 대응. +채택(2026-08-15). NTF-018 대응. **갱신 (2026-09-25):** R1 type은 삭제됐다. production consumer가 끝까지 0건이었고 fake로만 증명된 계약이라, 새 consumer를 막는 ArchUnit 규칙을 유지할 이유가 없어졌다. 남은 것은 adapter core의 @@ -47,9 +47,10 @@ bridge도 import도 없다. reconciliation을 실제 PostgreSQL 레인으로 증명한다(NOTIF-ADR-001~003). R1은 fake로 증명된 R1 계약이며 스스로 그렇게 선언한다 — `application-core/CLAUDE.md`가 "R1 application contract proven with fakes. It does not claim PostgreSQL schema/locking, provider protocol, cryptographic verifier, or runtime -wiring qualification"이라고 적어 둔 그대로다. +wiring qualification"(fake로 증명한 R1 애플리케이션 계약이다. PostgreSQL schema·locking, provider 프로토콜, 암호 +검증기, 런타임 배선 검증은 주장하지 않는다)이라고 적어 둔 그대로다. -## Disposition +## 처분 R1 public type 100개의 처분은 네 가지 중 하나다. diff --git a/scripts/check-docs-exceptions.txt b/scripts/check-docs-exceptions.txt index acde70c0..354c3b9b 100644 --- a/scripts/check-docs-exceptions.txt +++ b/scripts/check-docs-exceptions.txt @@ -54,10 +54,6 @@ language docs/mongodb/runbooks/unknown-commit.md language docs/mongodb/schema-index-migration-guide.md language docs/mongodb/security-observability.md language docs/mongodb/support-matrix.md -language docs/notification/adr/NOTIF-ADR-001-durable-acceptance.md -language docs/notification/adr/NOTIF-ADR-002-event-ledger-projection.md -language docs/notification/adr/NOTIF-ADR-003-ambiguous-submission.md -language docs/notification/adr/NOTIF-ADR-004-fcm-fid-primary.md language docs/notification/at-rest-threat-model.md language docs/notification/callback-reconciliation.md language docs/notification/configuration-reference.md