Merge branch 'claude/d2b-src-adr-d46d23' — 모듈 문서와 ADR 번역
충돌: scripts/check-docs-exceptions.txt. 두 쪽 모두 줄을 지우기만 했다(D2a 11줄, D2b 81줄, 겹침 0). 기준의 줄 중 두 쪽이 모두 남긴 줄만 남겼다(220 → 128줄).
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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 목록과 수는 레지스트리가 정한다). 즉 레지스트리는 닫혀 있지 않았고,
|
||||
"확장하면 게이트가 깨진다"는 전제는 과했다. 두 플랫폼이 서로 다른 패턴을 쓰고 있으므로
|
||||
**어느 쪽으로 통일할지는 미결 아키텍처 결정**이다.
|
||||
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
# adapter:inbound:grpc — inbound gRPC adapter (skeleton machinery)
|
||||
# adapter:inbound:grpc — inbound gRPC 어댑터(골격 장치)
|
||||
|
||||
## Registered identity
|
||||
## 등록 정보
|
||||
|
||||
- Module ID: `adapter-inbound-grpc`
|
||||
- Gradle path: `:adapter:inbound:grpc`
|
||||
- Focused test (derived from Gradle path): `./gradlew :adapter:inbound:grpc:test --console=plain`
|
||||
- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0.
|
||||
- Registry SSOT: `src/config/architecture/modules.json`.
|
||||
- 모듈 ID: `adapter-inbound-grpc`
|
||||
- Gradle 경로: `:adapter:inbound:grpc`
|
||||
- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:inbound:grpc:test --console=plain`
|
||||
- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다.
|
||||
- registry 정본: `src/config/architecture/modules.json`.
|
||||
|
||||
Package root: `dev.caskeleton.adapter.inbound.grpc`.
|
||||
|
||||
코드 주석에서 덜어낸 **설계 결정의 근거**는 [README.md](README.md) 가 모아둔다 (이 문서는 모듈
|
||||
규칙 SSOT).
|
||||
|
||||
## Responsibility
|
||||
## 책임
|
||||
|
||||
- gRPC 전송 인프라만: 서버 수명주기(`GrpcServerRunner`), 타입드 설정(`GrpcServerSettings`),
|
||||
feature 인증 정책 경계, 프로토콜 에러 매핑(`GrpcStatusMapper` +
|
||||
@@ -22,13 +22,13 @@ Package root: `dev.caskeleton.adapter.inbound.grpc`.
|
||||
- feature-agnostic: 모든 `io.grpc.BindableService` 빈을 generic 하게 등록하며 구체 기능을
|
||||
이름으로 알지 않는다.
|
||||
|
||||
## Allowed
|
||||
## 허용
|
||||
|
||||
- `:application-core`, `:domain-core`, `:shared-contract`.
|
||||
- `io.grpc:*` (grpc-netty-shaded / grpc-protobuf / grpc-stub / grpc-services),
|
||||
`spring-boot-starter`, `spring-boot-starter-validation`.
|
||||
|
||||
## Forbidden
|
||||
## 금지
|
||||
|
||||
- outbound 어댑터(`:adapter:outbound:*`)에 대한 직접 의존 — 인바운드는 application 아웃바운드
|
||||
포트를 통해서만 persistence/messaging/cache/http 에 닿는다 (ArchUnit
|
||||
@@ -38,7 +38,7 @@ Package root: `dev.caskeleton.adapter.inbound.grpc`.
|
||||
- 프로덕션 feature RPC 를 스켈레톤에 두는 것 — health/reflection 표면만 (web 의
|
||||
`HealthcheckController` 와 동일 원칙).
|
||||
|
||||
## Config knobs (`app.grpc.server.*`)
|
||||
## 설정 손잡이 (`app.grpc.server.*`)
|
||||
|
||||
타입드 `@ConfigurationProperties` 만 두고, 값은 composition-root `application.yml` 에 산다
|
||||
(모듈별 `yml` 없음). prefix가 `app.grpc`가 아니라 `.server`까지인 이유: 바인딩이
|
||||
@@ -69,24 +69,22 @@ Package root: `dev.caskeleton.adapter.inbound.grpc`.
|
||||
`enabled=true`는 `allowInsecureLocal=true`와 실제 loopback `bindAddress`가 함께 없으면
|
||||
configuration binding/startup 단계에서 실패한다.
|
||||
|
||||
## Adopting this capability
|
||||
## 이 capability 채택하기
|
||||
|
||||
gRPC is also a **build-composition opt-in**. The default bootJar does not contain this leaf.
|
||||
gRPC도 **빌드 조립에서 고르는 것**이다. 기본 bootJar에는 이 leaf가 없다.
|
||||
|
||||
1. Add `:adapter:inbound:grpc` to the consuming composition and add the corresponding allowed
|
||||
dependency edge in `config/architecture/modules.json`.
|
||||
2. Register settings through the capability root; do not add
|
||||
`dev.caskeleton.adapter.inbound.grpc` to the shipped `@ConfigurationPropertiesScan`.
|
||||
3. Provide any feature `BindableService` plus exactly one `GrpcAuthenticationPolicy`.
|
||||
4. Run `./gradlew :adapter:inbound:grpc:test :conditionalTransportQualification` before promotion.
|
||||
5. Production adoption is incomplete until composition-owned configuration/env registry entries
|
||||
exist for the selected runtime contract.
|
||||
1. 쓰는 조립에 `:adapter:inbound:grpc`를 더하고 `config/architecture/modules.json`에 맞는 허용 의존
|
||||
edge를 더한다.
|
||||
2. 설정은 capability 루트로 등록한다. 출하하는 `@ConfigurationPropertiesScan`에
|
||||
`dev.caskeleton.adapter.inbound.grpc`를 더하지 않는다.
|
||||
3. 기능의 `BindableService`와 정확히 하나의 `GrpcAuthenticationPolicy`를 준다.
|
||||
4. 승격 전에 `./gradlew :adapter:inbound:grpc:test :conditionalTransportQualification`을 돌린다.
|
||||
5. 고른 런타임 계약에 대한 조립 소유의 설정·env registry 항목이 생기기 전에는 운영 채택이 끝난 것이 아니다.
|
||||
|
||||
**Current transport limit:** the P1 server is plaintext and deliberately permits only loopback
|
||||
binding. It is therefore suitable for local-process or same-Pod sidecar communication only. It
|
||||
cannot bind `0.0.0.0` for a normal Kubernetes Service, cannot accept cross-Pod traffic, and must
|
||||
not be presented as a cluster-facing gRPC endpoint. Cluster exposure requires the deferred TLS/mTLS
|
||||
credential path and a separately qualified non-loopback bind.
|
||||
**지금 전송의 한계:** P1 서버는 평문이고 일부러 loopback bind만 허용한다. 그래서 같은 프로세스나 같은
|
||||
Pod sidecar 통신에만 맞다. 보통 Kubernetes Service를 위해 `0.0.0.0`에 bind할 수 없고, 다른 Pod의 트래픽을
|
||||
받을 수 없으며, 클러스터를 향한 gRPC endpoint로 내세우면 안 된다. 클러스터에 노출하려면 미뤄 둔 TLS/mTLS
|
||||
credential 경로와 따로 검증한 loopback 아닌 bind가 필요하다.
|
||||
|
||||
## Feature 기여 방법
|
||||
|
||||
@@ -109,7 +107,7 @@ listener 시작이 실패한다. 정책은 `Optional<Principal> authenticate(Met
|
||||
이 증거는 local insecure unary qualification일 뿐 production-ready 근거가 아니다. TLS/mTLS,
|
||||
external bind, 메서드별 deadline, streaming/backpressure, generated protobuf 호환성은 P2로 남아 있다.
|
||||
|
||||
## Test
|
||||
## 테스트
|
||||
|
||||
```bash
|
||||
cd src
|
||||
|
||||
@@ -1,25 +1,23 @@
|
||||
# adapter:inbound:messaging
|
||||
|
||||
- Module ID `adapter-inbound-messaging`, Gradle path `:adapter:inbound:messaging`. Registry SSOT:
|
||||
- 모듈 ID `adapter-inbound-messaging`, Gradle 경로 `:adapter:inbound:messaging`. registry 정본:
|
||||
`src/config/architecture/modules.json`.
|
||||
- Responsibility: the application's consume side of the vendored messaging platform — the inbox
|
||||
parts the platform needs from the application (`JdbcInboxRepository` over the application
|
||||
DataSource, a `TransactionRunner` over its `PlatformTransactionManager`, the inbox migration as
|
||||
its own Flyway stream `MessagingInboxSchemaStream`) and the application's `MessageHandler`
|
||||
implementations, each turning a delivery into one use case call. A handler registers nothing
|
||||
else: the platform decodes what its `destination()` and `schemaVersions()` declare.
|
||||
- Boundaries: no business rule in a handler (HARD-STOP 4); no persistence entity or repository; no
|
||||
broker SDK type. Allowed edges come only from the registry entry.
|
||||
- A handler that calls a write use case is `@SystemCaller(reason = ...)` and constructs the
|
||||
`@SystemInvoked` use case itself; the use case is never a bean, and no user transport calls the
|
||||
handler (manual 09 「소비」 step 4, manual 07 「시스템이 부르는 쓰기」,
|
||||
- 책임: 들여온 메시징 플랫폼의 애플리케이션 소비 쪽이다 — 플랫폼이 애플리케이션에서 받아야 하는
|
||||
inbox 부품(애플리케이션 DataSource 위의 `JdbcInboxRepository`, 그 `PlatformTransactionManager` 위의
|
||||
`TransactionRunner`, 자기 Flyway stream `MessagingInboxSchemaStream`인 inbox migration)과 애플리케이션의
|
||||
`MessageHandler` 구현들이다. 핸들러 하나는 전달 하나를 유스케이스 호출 하나로 바꾼다. 핸들러는 그 밖에
|
||||
아무것도 등록하지 않는다: 플랫폼이 그 `destination()`과 `schemaVersions()`가 선언한 것을 decode한다.
|
||||
- 경계: 핸들러에 업무 규칙을 두지 않는다(HARD-STOP 4). 영속 엔티티나 repository가 없다. broker SDK 타입이
|
||||
없다. 허용 edge는 registry 항목에서만 온다.
|
||||
- 쓰기 유스케이스를 부르는 핸들러는 `@SystemCaller(reason = ...)`이고 `@SystemInvoked` 유스케이스를 직접
|
||||
만든다. 유스케이스는 bean이 아니고, 사용자 전송 계층은 핸들러를 부르지 않는다
|
||||
(`docs/manual/09-outbox-events.md` 「소비 — 이벤트를 받는 쪽」 순서 4단계,
|
||||
`docs/manual/07-authorization.md` 「시스템이 부르는 쓰기」,
|
||||
`ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`,
|
||||
`USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`). The handler implements only project types
|
||||
(`MessageHandler<T>`), never `Runnable` or another type outside the project
|
||||
(`SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`).
|
||||
- Tests: focused auto-configuration and inbox behavior tests; `./gradlew :adapter:inbound:messaging:check`.
|
||||
The real Kafka + PostgreSQL redelivery lane is `messagingInboxRedeliveryIntegrationTest`
|
||||
(`:integrationCheck`).
|
||||
- Coordinates: group `dev.caskeleton.adapter.inbound`, jar `adapter-inbound-messaging`. Do not drop them —
|
||||
with the default group this project and `:adapter:outbound:messaging` are one module to Gradle.
|
||||
- Design and rejected alternatives: `README.md`.
|
||||
`USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`). 핸들러는 프로젝트 타입(`MessageHandler<T>`)만 구현하고,
|
||||
`Runnable`이나 프로젝트 밖의 다른 타입은 구현하지 않는다(`SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`).
|
||||
- 시험: 자동 구성과 inbox 동작을 보는 시험. `./gradlew :adapter:inbound:messaging:check`.
|
||||
실제 Kafka + PostgreSQL 재전달 lane은 `messagingInboxRedeliveryIntegrationTest`다(`:integrationCheck`).
|
||||
- 좌표: group `dev.caskeleton.adapter.inbound`, jar `adapter-inbound-messaging`. 지우지 않는다 — 기본
|
||||
group이면 Gradle에게 이 프로젝트와 `:adapter:outbound:messaging`은 같은 모듈이 된다.
|
||||
- 설계와 버린 대안: `README.md`.
|
||||
|
||||
@@ -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
|
||||
|
||||
+136
-179
@@ -1,213 +1,170 @@
|
||||
# adapter:inbound:web — inbound HTTP adapter
|
||||
# adapter:inbound:web — inbound HTTP 어댑터
|
||||
|
||||
## Registered identity
|
||||
## 등록 정보
|
||||
|
||||
- Module ID: `adapter-inbound-web`
|
||||
- Gradle path: `:adapter:inbound:web`
|
||||
- Focused test (derived from Gradle path): `./gradlew :adapter:inbound:web:test --console=plain`
|
||||
- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0.
|
||||
- Registry SSOT: `src/config/architecture/modules.json`.
|
||||
- 모듈 ID: `adapter-inbound-web`
|
||||
- Gradle 경로: `:adapter:inbound:web`
|
||||
- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:inbound:web:test --console=plain`
|
||||
- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다.
|
||||
- registry 정본: `src/config/architecture/modules.json`.
|
||||
|
||||
Package root: `dev.caskeleton.adapter.inbound.web`.
|
||||
패키지 루트: `dev.caskeleton.adapter.inbound.web`.
|
||||
|
||||
코드 주석에서 덜어낸 **설계 결정의 근거**는 [README.md](README.md) 가 모아둔다 (이 문서는 모듈 규칙 SSOT).
|
||||
|
||||
## Responsibility
|
||||
## 책임
|
||||
|
||||
- HTTP controllers.
|
||||
- Request/response DTOs.
|
||||
- Request DTO to application command mapping.
|
||||
- Authentication, validation, error mapping, filters, and web/security settings.
|
||||
- Sanitized request correlation context exposed through application-owned `CorrelationIdPort`.
|
||||
- Transport-owned OpenAPI customization that keeps `ApiError.details` as `type: object` without
|
||||
leaking Swagger dependencies into `shared-contract`.
|
||||
- HTTP controller.
|
||||
- 요청·응답 DTO.
|
||||
- 요청 DTO를 application command로 바꾸기.
|
||||
- 인증, 검증, 오류 대응, filter, web·보안 설정.
|
||||
- 애플리케이션이 가진 `CorrelationIdPort`로 내놓는, 걸러 낸 요청 correlation 문맥.
|
||||
- `shared-contract`로 Swagger 의존을 새게 하지 않으면서 `ApiError.details`를 `type: object`로 두는,
|
||||
전송 계층이 가진 OpenAPI 손질.
|
||||
|
||||
Every service ships this leaf, so it holds only what the servlet production path reaches: its
|
||||
`AutoConfiguration.imports` roots (`WebAdapterAutoConfiguration` imports the envelope, filters,
|
||||
health and rate-limit beans; `WebSecurityAutoConfiguration` imports the JWT chain, so an application
|
||||
with its own posture excludes only that root; `WebMethodSecurityAutoConfiguration` imports method
|
||||
security and the permission port and stays when the chain is replaced; nobody scans
|
||||
this leaf), and the types
|
||||
`app-bootstrap`, `web-fileserver` and `composition:fileserver-platform` name —
|
||||
plus their transitive references. Library code that no production path reaches (streaming, virtual
|
||||
threads, patch, codecs, OpenAPI 3.2, URI/method policy, versioning, operation, budget, contract,
|
||||
security-context bridge, `JsonIdempotentResponseCodec`, route inventory) lives in the opt-in leaf
|
||||
`adapter:inbound:web-advanced`. A new type that nothing on the
|
||||
production path uses belongs there, not here. This leaf never depends on it (Gradle registry +
|
||||
ArchUnit `WEB-ARCH-ADV`).
|
||||
모든 서비스가 이 leaf를 싣는다. 그래서 servlet 운영 경로가 닿는 것만 담는다: 그 `AutoConfiguration.imports`
|
||||
루트(`WebAdapterAutoConfiguration`은 envelope, filter, health, rate-limit bean을 import한다.
|
||||
`WebSecurityAutoConfiguration`은 JWT chain을 import하므로, 자기 보안 방식을 가진 애플리케이션은 그 루트만
|
||||
뺀다. `WebMethodSecurityAutoConfiguration`은 method security와 권한 포트를 import하고 chain을 바꿔도 남는다.
|
||||
이 leaf를 scan하는 쪽은 없다), 그리고 `app-bootstrap`, `web-fileserver`, `composition:fileserver-platform`이
|
||||
이름을 대는 타입과 그것이 전이로 참조하는 것. 운영 경로가 닿지 않는 라이브러리 코드(streaming, virtual
|
||||
thread, patch, codec, OpenAPI 3.2, URI·method 정책, versioning, operation, budget, contract, security context
|
||||
bridge, `JsonIdempotentResponseCodec`, route 목록)는 골라 쓰는 leaf `adapter:inbound:web-advanced`에 있다.
|
||||
운영 경로에서 아무도 쓰지 않는 새 타입은 여기가 아니라 거기에 둔다. 이 leaf는 그 leaf에 의존하지 않는다
|
||||
(Gradle registry + ArchUnit `WEB-ARCH-ADV`).
|
||||
|
||||
## Allowed
|
||||
## 허용
|
||||
|
||||
- `:application-core`
|
||||
- `:domain-core`
|
||||
- `:shared-contract`
|
||||
- `:adapter:outbound:support` — `StrictSettingsBinder` only. `app.security` (`SecuritySettings`, the
|
||||
authentication mode included) is bound by the one strict binder every module uses (since
|
||||
2026-11-01); the ArchUnit inbound/outbound rules allow that class and nothing else from the
|
||||
leaf.
|
||||
- Spring Web/Security/Validation dependencies.
|
||||
- `:adapter:outbound:support` — `StrictSettingsBinder`만. `app.security`(`SecuritySettings`, 인증 모드 포함)는
|
||||
모든 모듈이 쓰는 엄격한 binder 하나로 바인딩한다(2026-11-01부터). ArchUnit inbound·outbound 규칙은 그
|
||||
leaf에서 이 클래스만 허용한다.
|
||||
- Spring Web·Security·Validation 의존성.
|
||||
|
||||
## Forbidden
|
||||
## 금지
|
||||
|
||||
- Direct dependency on `adapter-persistence` or any other `adapter-outbound` type.
|
||||
- Direct repository or JPA entity access from controllers.
|
||||
- Core business rules in controller, filter, config, mapper, or settings code.
|
||||
- DTO leakage into application or domain.
|
||||
- `adapter:outbound:persistence-jpa`나 다른 `adapter:outbound:*` 타입에 직접 의존하기.
|
||||
- controller에서 repository나 JPA 엔티티에 직접 접근하기.
|
||||
- controller, filter, config, mapper, settings 코드 안의 핵심 업무 규칙.
|
||||
- DTO가 application이나 domain으로 새는 것.
|
||||
|
||||
## Boundary validation & mapper contract
|
||||
## 경계 검증과 mapper 계약
|
||||
|
||||
`feature-boundary-validation-mapping-contract` (design record) fixes the
|
||||
behaviour at this layer's boundaries. The repo-level guardrails (ArchUnit +
|
||||
Jackson config + handler) only catch the static violations — the contract below
|
||||
also drives the runtime patterns reference implementations must follow.
|
||||
`feature-boundary-validation-mapping-contract`(설계 기록)가 이 계층 경계의 동작을 정한다. 저장소 단위
|
||||
가드레일(ArchUnit + Jackson 설정 + handler)은 정적 위반만 잡는다. 아래 계약은 참조 구현이 따라야 할 런타임
|
||||
패턴도 정한다.
|
||||
|
||||
- **B1 — Jackson policy at the request boundary.** `spring.jackson.deserialization`
|
||||
pins `fail-on-unknown-properties`, `fail-on-null-for-primitives`,
|
||||
`fail-on-ignored-properties` to `true` and `read-unknown-enum-values-as-null`
|
||||
to `false`. Do NOT undo this per-DTO with class-level
|
||||
`@JsonIgnoreProperties(ignoreUnknown = true)` — ArchUnit rule
|
||||
`request_dtos_do_not_silence_unknown_fields` blocks it. Use wrapper types
|
||||
(`Integer`, `Long`, `Boolean`, `Optional<T>`) in request records so JSON
|
||||
`null` cannot become primitive `0`.
|
||||
- **B2 — PATCH semantics.** Do not adopt RFC 7396 `application/merge-patch+json`
|
||||
(`null = deletion`). PATCH endpoints must distinguish *absent* (no change),
|
||||
*explicit null* (clear field), and *value* (replace). Use
|
||||
`org.openapitools:jackson-databind-nullable` (`JsonNullable<T>`) or
|
||||
`Optional<T>` wrappers on request records.
|
||||
- **B3 — Mapper-internal failures.** Map record canonical-constructor
|
||||
`IllegalArgumentException`, MapStruct generated NPE, ACL normalization
|
||||
failures, etc. by throwing `MappingException`; the global handler routes it to `MAPPING_FAILED` (HTTP 400),
|
||||
never to `BAD_PARAMETER` or `INTERNAL_ERROR`. Plain `IllegalArgumentException`
|
||||
remains `BAD_PARAMETER` for non-mapper callers.
|
||||
- **B4 — Validation layering.** Class-level Bean Validation constraints belong
|
||||
to the *syntax* layer (request DTO). Domain invariants belong to
|
||||
`application-core` / `domain-core`. Use `@GroupSequence(...)` to short-circuit
|
||||
invariant evaluation when syntax fails. Keep `@Valid` cascade depth ≤ 3.
|
||||
- **B5 — Polymorphic deserialization.** Calling
|
||||
`ObjectMapper.enableDefaultTyping()` / `activateDefaultTyping()` or
|
||||
referencing `LaissezFaireSubTypeValidator` is the CVE-2019-14379 RCE entry
|
||||
point and is blocked by ArchUnit (`no_jackson_laissez_faire_subtype_validator`,
|
||||
`no_jackson_enable_default_typing_call`). Sealed `Command` types must use
|
||||
`@JsonTypeInfo(use = NAME)` + `@JsonSubTypes`, or a
|
||||
`BasicPolymorphicTypeValidator` allowlist.
|
||||
- **B6 — Virtual thread context propagation.** With
|
||||
`spring.threads.virtual.enabled=true`, do not use `InheritableThreadLocal`
|
||||
(ArchUnit rule `no_inheritable_thread_local`). Filters and interceptors must
|
||||
propagate `requestId` / `traceId` via SLF4J 2.0+ MDC or
|
||||
`RequestContextHolder`.
|
||||
- **B7 — Outbound ACL mapper scope.** Outbound HTTP / messaging adapter
|
||||
responses must pass through an ACL mapper (normalization, masking, public
|
||||
field selection) before reaching `application-core` or `domain-core` — the
|
||||
same boundary contract as inbound. Raw external response types must not leak
|
||||
into `domain-core`.
|
||||
- **B8 — Bulk endpoint partial success.** Envelope `success = true` only when
|
||||
every item succeeded. Partial failure responds with `success = false` +
|
||||
`error.code = BATCH_PARTIAL_FAILURE` + `error.details[]` (per-item array) —
|
||||
a different shape from the single-item endpoint. Document the shape divergence
|
||||
in the OpenAPI spec.
|
||||
- **B1 — 요청 경계의 Jackson 정책.** `spring.jackson.deserialization`이 `fail-on-unknown-properties`,
|
||||
`fail-on-null-for-primitives`, `fail-on-ignored-properties`를 `true`로, `read-unknown-enum-values-as-null`을
|
||||
`false`로 고정한다. 클래스 수준 `@JsonIgnoreProperties(ignoreUnknown = true)`로 DTO마다 이것을 되돌리지
|
||||
**않는다** — ArchUnit 규칙 `REQUEST_DTOS_DO_NOT_SILENCE_UNKNOWN_FIELDS`가 막는다. 요청 record에는
|
||||
wrapper 타입(`Integer`, `Long`, `Boolean`, `Optional<T>`)을 써서 JSON `null`이 primitive `0`이 되지 못하게
|
||||
한다.
|
||||
- **B2 — PATCH 뜻.** RFC 7396 `application/merge-patch+json`(`null = 삭제`)을 쓰지 않는다. PATCH endpoint는
|
||||
*없음*(바꾸지 않음), *명시한 null*(필드 비움), *값*(바꿈)을 구별해야 한다. 요청 record에
|
||||
`org.openapitools:jackson-databind-nullable`(`JsonNullable<T>`)이나 `Optional<T>` wrapper를 쓴다.
|
||||
- **B3 — mapper 안의 실패.** record 정규 생성자의 `IllegalArgumentException`, MapStruct가 생성한 NPE, ACL
|
||||
정규화 실패 등은 `MappingException`을 던져 대응시킨다. 전역 handler가 그것을 `MAPPING_FAILED`(HTTP 400)로
|
||||
보내고, `BAD_PARAMETER`나 `INTERNAL_ERROR`로 보내지 않는다. mapper가 아닌 호출자의 평범한
|
||||
`IllegalArgumentException`은 계속 `BAD_PARAMETER`다.
|
||||
- **B4 — 검증 층.** 클래스 수준 Bean Validation 제약은 *문법* 층(요청 DTO)에 속한다. 도메인 불변식은
|
||||
`application-core` / `domain-core`에 속한다. 문법이 실패하면 `@GroupSequence(...)`로 불변식 평가를 건너뛴다.
|
||||
`@Valid` cascade 깊이는 3 이하로 둔다.
|
||||
- **B5 — 다형 역직렬화.** `ObjectMapper.enableDefaultTyping()` / `activateDefaultTyping()`을 부르거나
|
||||
`LaissezFaireSubTypeValidator`를 참조하는 것은 CVE-2019-14379 RCE의 입구이고 ArchUnit이 막는다
|
||||
(`NO_JACKSON_LAISSEZ_FAIRE_SUBTYPE_VALIDATOR`, `NO_JACKSON_ENABLE_DEFAULT_TYPING_CALL`). sealed `Command`
|
||||
타입은 `@JsonTypeInfo(use = NAME)` + `@JsonSubTypes`나 `BasicPolymorphicTypeValidator` 허용 목록을 쓴다.
|
||||
- **B6 — virtual thread 문맥 전파.** `spring.threads.virtual.enabled=true`이면 `InheritableThreadLocal`을 쓰지
|
||||
않는다(ArchUnit 규칙 `NO_INHERITABLE_THREAD_LOCAL`). filter와 interceptor는 SLF4J 2.0+ MDC나
|
||||
`RequestContextHolder`로 `requestId` / `traceId`를 전파한다.
|
||||
- **B7 — outbound ACL mapper 범위.** outbound HTTP·메시징 어댑터의 응답은 `application-core`나 `domain-core`에
|
||||
닿기 전에 ACL mapper(정규화, 가리기, 공개 필드 고르기)를 거친다 — inbound와 같은 경계 계약이다. 외부 응답
|
||||
원본 타입은 `domain-core`로 새면 안 된다.
|
||||
- **B8 — bulk endpoint의 부분 성공.** envelope `success = true`는 모든 항목이 성공했을 때뿐이다. 일부가
|
||||
실패하면 `success = false` + `error.code = BATCH_PARTIAL_FAILURE` + `error.details[]`(항목별 배열)로
|
||||
답한다 — 단일 항목 endpoint와 모양이 다르다. 모양이 다르다는 것을 OpenAPI spec에 적는다.
|
||||
|
||||
Domain `@RestControllerAdvice` in a consuming module must be annotated
|
||||
`@Order(Ordered.HIGHEST_PRECEDENCE)` (or otherwise ordered ahead of this
|
||||
module's base `GlobalExceptionHandler`), because the base handler's catch-all
|
||||
`@ExceptionHandler(Exception.class)` would otherwise resolve domain exceptions
|
||||
to `INTERNAL_ERROR`.
|
||||
이 모듈을 쓰는 모듈의 도메인 `@RestControllerAdvice`에는 `@Order(Ordered.HIGHEST_PRECEDENCE)`를 단다(또는
|
||||
다른 방법으로 이 모듈의 기본 `GlobalExceptionHandler`보다 앞에 둔다). 그렇지 않으면 기본 handler의
|
||||
catch-all `@ExceptionHandler(Exception.class)`가 도메인 예외를 `INTERNAL_ERROR`로 만든다.
|
||||
|
||||
The base operational handler (`error/GlobalExceptionHandler`), the error-code
|
||||
contract (`dev.caskeleton.shared.error.ApiErrorCode` + `OperationalError`), the
|
||||
`error/ErrorResponseFactory`, and the `envelope/EnvelopeBodyAdvice` now live in
|
||||
production modules (`adapter:inbound:web` / `shared-contract`), so the running application
|
||||
provides them. 기능 전용 예외 handler와 오류 코드는 그 기능을 가진 모듈에 둔다(`docs/manual/06-errors.md`).
|
||||
기본 운영 handler(`error/GlobalExceptionHandler`), 오류 코드 계약
|
||||
(`dev.caskeleton.shared.error.ApiErrorCode` + `OperationalError`), `error/ErrorResponseFactory`,
|
||||
`envelope/EnvelopeBodyAdvice`는 이제 운영 모듈(`adapter:inbound:web` / `shared-contract`)에 있어서, 돌아가는
|
||||
애플리케이션이 그것을 준다. 기능 전용 예외 handler와 오류 코드는 그 기능을 가진 모듈에 둔다(`docs/manual/06-errors.md`).
|
||||
|
||||
## Schema / serialization contract
|
||||
## schema·직렬화 계약
|
||||
|
||||
`feature-schema-serialization-contract` (design record) fixes the
|
||||
*response producer* side of the wire contract — the sibling of the B1 *request
|
||||
consumer* policy above. The deserialization switches (B1) and the
|
||||
null/empty/missing 3-state (`Patch<T>` + `JsonNullable`, B2) already cover the
|
||||
inbound side; the rules below cover the outbound side. The Jackson properties
|
||||
live in `app-bootstrap` (`application.yml` `spring.jackson.serialization.*` /
|
||||
`spring.jackson.generator.*`); ArchUnit + effective-config tests live in
|
||||
`app-bootstrap` (`JacksonSerializationPolicyTest`, `no_bigdecimal_double_constructor`).
|
||||
`feature-schema-serialization-contract`(설계 기록)가 wire 계약의 *응답을 만드는* 쪽을 정한다 — 위 B1
|
||||
*요청을 받는* 정책의 짝이다. 역직렬화 스위치(B1)와 null·빈 값·없음 세 상태(`Patch<T>` + `JsonNullable`,
|
||||
B2)가 이미 inbound 쪽을 덮고, 아래 규칙이 outbound 쪽을 덮는다. Jackson 속성은 `app-bootstrap`의
|
||||
`application.yml`(`spring.jackson.deserialization.*`, `spring.jackson.datatype.*`)에 있다. ArchUnit과 실제
|
||||
설정 시험도 `app-bootstrap`에 있다(`JacksonSerializationPolicyTest`, `NO_BIGDECIMAL_DOUBLE_CONSTRUCTOR`).
|
||||
|
||||
- **S1 — Date / time / timezone.** `WRITE_DATES_AS_TIMESTAMPS=false` is
|
||||
pinned, so `java.time` values serialize as ISO-8601 strings via `JavaTimeModule`
|
||||
(`OffsetDateTime` → `"...Z"`, `LocalDate` → `"YYYY-MM-DD"`), never a numeric
|
||||
epoch or `[y,m,d,...]` array. Server timezone is **UTC**: emit instants as
|
||||
`OffsetDateTime`/`Instant` with a `Z` offset. Use `LocalDate` only for
|
||||
date-only calendar fields. Do **not** put timezone-less `LocalDateTime` on a
|
||||
response DTO — it serializes without an offset and breaks the contract.
|
||||
- **S2 — Money / BigDecimal.** Default scale 2, rounding `HALF_UP` unless
|
||||
the domain documents otherwise (KRW/JPY = scale 0 with a schema note).
|
||||
`WRITE_BIGDECIMAL_AS_PLAIN=true` is pinned so values never serialize in
|
||||
scientific notation. Pick **one** JSON representation per API and state it in
|
||||
the OpenAPI schema: **string** (`@JsonSerialize(using = ToStringSerializer.class)`)
|
||||
for public / financial endpoints (client parses, no precision loss), or
|
||||
**number + plain** for internal service-to-service endpoints. Never rely on
|
||||
the default — decide at endpoint design time.
|
||||
- **S3 — `new BigDecimal(double)` is banned.** The `double`/`float` constructors
|
||||
capture binary floating-point error (`new BigDecimal(0.1)` ≠ `0.1`). Build from
|
||||
a `String` (`new BigDecimal("0.1")`) or `BigDecimal.valueOf(double)`. Enforced
|
||||
by the `no_bigdecimal_double_constructor` ArchUnit rule.
|
||||
- **S4 — Enum / null·empty·missing.** Request-side unknown enum →
|
||||
`VALIDATION_FAILED` (B1 `read-unknown-enum-values-as-null=false`); legacy values
|
||||
map through an explicit adapter, never a silent fallback. The
|
||||
absent / explicit-null / value distinction is owned by the inbound web mapper
|
||||
(Controller DTO → Command), expressed with `Patch<T>` (B2); `domain-core` and
|
||||
`application-core` receive the already-resolved 3-state, never a wire type.
|
||||
- **S5 — Out of this branch's scope.** OpenAPI drift enforcement is owned by
|
||||
the verification suite / api-contract-baseline; removed-field-reuse ban tooling
|
||||
(`x-removed-fields` vs markdown catalog) is `needs-confirmation`; Avro
|
||||
Schema Registry for outbox/event and response field rename/versioning
|
||||
(`feature-api-compatibility-deprecation-contract`) are separate branches.
|
||||
- **S1 — 날짜·시간·시간대.** `WRITE_DATES_AS_TIMESTAMPS=false`로 고정하므로 `java.time` 값은
|
||||
`JavaTimeModule`을 거쳐 ISO-8601 문자열로 직렬화한다(`OffsetDateTime` → `"...Z"`, `LocalDate` →
|
||||
`"YYYY-MM-DD"`). 숫자 epoch나 `[y,m,d,...]` 배열이 되지 않는다. 서버 시간대는 **UTC**다: 시각은 `Z`
|
||||
offset을 가진 `OffsetDateTime`/`Instant`로 낸다. 날짜만 있는 달력 필드에만 `LocalDate`를 쓴다. 시간대
|
||||
없는 `LocalDateTime`을 응답 DTO에 넣지 **않는다** — offset 없이 직렬화되어 계약을 깬다.
|
||||
- **S2 — 돈·BigDecimal.** 도메인이 따로 적지 않으면 기본 scale 2, 반올림 `HALF_UP`이다(KRW/JPY는 scale 0과
|
||||
schema 메모). 값은 지수 표기로 직렬화되지 않는다 — 설정 키로 고정하지 않고 `JacksonSerializationPolicyTest`가
|
||||
큰 값과 끝자리 0을 단언한다. API마다 JSON 표현을 **하나** 고르고 OpenAPI schema에 적는다: 공개·금융
|
||||
endpoint는 **string**(`@JsonSerialize(using = ToStringSerializer.class)`. 클라이언트가 파싱하고 정밀도를
|
||||
잃지 않는다), 내부 서비스 사이 endpoint는 **number + plain**. 기본값에 기대지 않는다 — endpoint를 설계할
|
||||
때 정한다.
|
||||
- **S3 — `new BigDecimal(double)`은 금지다.** `double`/`float` 생성자는 이진 부동소수점 오차를 담는다
|
||||
(`new BigDecimal(0.1)` ≠ `0.1`). `String`(`new BigDecimal("0.1")`)이나 `BigDecimal.valueOf(double)`로
|
||||
만든다. ArchUnit 규칙 `NO_BIGDECIMAL_DOUBLE_CONSTRUCTOR`가 강제한다.
|
||||
- **S4 — enum과 null·빈 값·없음.** 요청 쪽의 모르는 enum → `VALIDATION_FAILED`(B1
|
||||
`read-unknown-enum-values-as-null=false`). 옛 값은 명시한 어댑터로 대응시키고 소리 없는 대체값을 쓰지
|
||||
않는다. 없음·명시한 null·값의 구별은 inbound web mapper(Controller DTO → Command)가 가지고 `Patch<T>`(B2)로
|
||||
나타낸다. `domain-core`와 `application-core`는 이미 풀린 세 상태를 받고 wire 타입은 받지 않는다.
|
||||
- **S5 — 이 브랜치의 범위 밖.** OpenAPI drift 강제는 검증 suite / api-contract-baseline의 몫이다. 지운
|
||||
필드 재사용 금지 도구(`x-removed-fields` 대 markdown catalog)는 `needs-confirmation`이다. outbox·event용
|
||||
Avro Schema Registry와 응답 필드 이름 바꾸기·versioning(`feature-api-compatibility-deprecation-contract`)은
|
||||
다른 브랜치다.
|
||||
|
||||
## Business rule validation contract
|
||||
## 업무 규칙 검증 계약
|
||||
|
||||
`feature-business-rule-validation-contract` (design record) fixes **which
|
||||
rule is validated at which boundary**, so "validation" does not collapse into the
|
||||
controller DTO or a DB constraint. It sits on top of the boundary/mapping contract
|
||||
above and is enforced by ArchUnit + contract tests (not new runtime mechanism).
|
||||
`feature-business-rule-validation-contract`(설계 기록)는 **어떤 규칙을 어느 경계에서 검증하는지** 정해서,
|
||||
「검증」이 controller DTO나 DB 제약 하나로 뭉개지지 않게 한다. 위 경계·대응 계약 위에 놓이고, ArchUnit과
|
||||
계약 시험이 강제한다(새 런타임 장치가 아니다).
|
||||
|
||||
| Layer | Owner | Validates | `error.category` | Enforced by |
|
||||
| 층 | 소유 | 검증하는 것 | `error.category` | 강제하는 곳 |
|
||||
|---|---|---|---|---|
|
||||
| syntax / shape | `adapter:inbound:web` request DTO (`@Valid` / `jakarta.validation`) | request shape, types, required fields | `VALIDATION` | `validation_constraints_stay_at_web_boundary` ArchUnit rule |
|
||||
| use case policy | `application-core` | authorization, cross-aggregate policy, state preconditions | `AUTHZ` / `CONFLICT` | `BusinessRuleValidationContractTest` |
|
||||
| domain invariant | `domain-core` model / value object **constructor** | business invariants (e.g. end ≥ start) | `CONFLICT` / `VALIDATION` | domain unit tests (e.g. `PeriodTest`) — constructor is the sole, immutable construction path |
|
||||
| persistence integrity | `adapter-persistence` (translator owned by `feature-persistence-failure-baseline`) | unique / FK / check / serialization | `DATA_INTEGRITY` / `CONFLICT` | `BusinessRuleValidationContractTest` + leak test |
|
||||
| 문법·모양 | `adapter:inbound:web` 요청 DTO(`@Valid` / `jakarta.validation`) | 요청 모양, 타입, 필수 필드 | `VALIDATION` | ArchUnit 규칙 `VALIDATION_CONSTRAINTS_STAY_AT_WEB_BOUNDARY` |
|
||||
| 유스케이스 정책 | `application-core` | 인가, aggregate를 가로지르는 정책, 상태 전제 조건 | `AUTHZ` / `CONFLICT` | `BusinessRuleValidationContractTest` |
|
||||
| 도메인 불변식 | `domain-core` 모델·값 객체 **생성자** | 업무 불변식(예: end ≥ start) | `CONFLICT` / `VALIDATION` | 도메인 단위 시험(예: `PeriodTest`) — 생성자가 유일하고 바뀌지 않는 생성 경로다 |
|
||||
| 영속 무결성 | `adapter:outbound:persistence-jpa`(번역기는 `feature-persistence-failure-baseline`의 것) | unique / FK / check / serialization | `DATA_INTEGRITY` / `CONFLICT` | `BusinessRuleValidationContractTest` + 누출 시험 |
|
||||
|
||||
- **C1 — Validation annotations stay at the web boundary.** `jakarta.validation`
|
||||
(`@NotNull`, `@Valid`, …) must appear only in `adapter:inbound:web`. `domain-core` and
|
||||
`application-core` express invariants and policy as plain Java. The
|
||||
`validation_constraints_stay_at_web_boundary` ArchUnit rule fails the build if a
|
||||
Bean Validation annotation leaks into `..domain..` or `..application..`.
|
||||
- **C2 — Business invariants live in the domain, un-bypassable.** Enforce invariants
|
||||
in the value-object / entity **constructor** (the sole construction path) and keep
|
||||
the type immutable, so no application-service or persistence path can hand out an
|
||||
invariant-violating instance. A DB constraint is a backstop, never the only check
|
||||
(Forbidden: "DB constraint as only invariant").
|
||||
- **C3 / C7 — Persistence integrity maps to an operational error, leak-free.** A
|
||||
unique/FK/check/serialization failure maps to `DATA_INTEGRITY` / `CONFLICT` with a
|
||||
**client-safe message only**. The raw SQL, constraint/index name, SQLState code,
|
||||
exception class, and stack frame must never reach `error.message` or
|
||||
`error.details`. The base `GlobalExceptionHandler` catch-all already replaces the
|
||||
message with the opaque shared message (`ClientErrorMessages.OPAQUE`) and emits `null` details; the
|
||||
category-correct mapping (23505 → `CONFLICT/DB_UNIQUE_VIOLATION`, …) is owned by
|
||||
`feature-persistence-failure-baseline`'s persistence-adapter translator.
|
||||
- **C8 — Duplicate validation needs a canonical owner.** The same rule MAY be
|
||||
pre-checked at another layer for UX / performance (e.g. an application pre-check
|
||||
mirroring a DB unique constraint), but the **canonical owner** of the rule must be
|
||||
named in a code comment or the relevant `CLAUDE.md`. A duplicate validator with no
|
||||
documented owner is a review failure (silent contradiction risk). This is a process
|
||||
gate (PR review), not an automated rule — `needs-confirmation` until an owner-marker
|
||||
annotation is justified.
|
||||
- **C1 — 검증 애너테이션은 web 경계에 머문다.** `jakarta.validation`(`@NotNull`, `@Valid`, …)은
|
||||
`adapter:inbound:web`에만 나와야 한다. `domain-core`와 `application-core`는 불변식과 정책을 평범한 Java로
|
||||
나타낸다. Bean Validation 애너테이션이 `..domain..`이나 `..application..`으로 새면 ArchUnit 규칙
|
||||
`VALIDATION_CONSTRAINTS_STAY_AT_WEB_BOUNDARY`가 빌드를 실패시킨다.
|
||||
- **C2 — 업무 불변식은 도메인에 있고 우회할 수 없다.** 불변식은 값 객체·엔티티 **생성자**(유일한 생성
|
||||
경로)에서 강제하고 타입을 불변으로 둔다. 그래서 어떤 application service나 영속 경로도 불변식을 어긴
|
||||
인스턴스를 내줄 수 없다. DB 제약은 뒷받침일 뿐 유일한 검사가 아니다(금지: 「불변식을 DB 제약으로만
|
||||
지키기」).
|
||||
- **C3 / C7 — 영속 무결성은 새는 것 없이 운영 오류로 대응한다.** unique·FK·check·serialization 실패는
|
||||
**클라이언트에게 안전한 메시지만** 가진 `DATA_INTEGRITY` / `CONFLICT`로 대응한다. SQL 원문, 제약·index
|
||||
이름, SQLState 코드, 예외 클래스, stack frame은 `error.message`나 `error.details`에 닿으면 안 된다. 기본
|
||||
`GlobalExceptionHandler` catch-all이 이미 메시지를 불투명한 공용 메시지(`ClientErrorMessages.OPAQUE`)로
|
||||
바꾸고 details를 `null`로 낸다. category가 맞는 대응(23505 → `CONFLICT/DB_UNIQUE_VIOLATION`, …)은
|
||||
`feature-persistence-failure-baseline`의 영속 어댑터 번역기가 가진다.
|
||||
- **C8 — 중복 검증에는 정본 소유자가 있어야 한다.** UX나 성능을 위해 같은 규칙을 다른 층에서 미리 검사할 수
|
||||
있다(예: DB unique 제약을 따라 하는 application 사전 검사). 단 그 규칙의 **정본 소유자**를 코드 주석이나
|
||||
관련 `CLAUDE.md`에 적어야 한다. 소유자를 적지 않은 중복 검증기는 리뷰에서 실패다(소리 없이 서로 어긋날
|
||||
위험). 자동 규칙이 아니라 절차 게이트(PR 리뷰)다 — 소유자 표지 애너테이션이 정당해질 때까지
|
||||
`needs-confirmation`이다.
|
||||
|
||||
Out of this branch's scope (cross-referenced, not re-implemented here): the
|
||||
SQLState→code 9-row matrix and the `DataAccessException` translator
|
||||
(`feature-persistence-failure-baseline`); the Jackson B1/B2 request-boundary switches
|
||||
and mapper sentinel (`feature-boundary-validation-mapping-contract`); the envelope,
|
||||
`Category` enum, and `OperationalError` codes
|
||||
이 브랜치의 범위 밖(참조만 하고 여기서 다시 구현하지 않는다): SQLState → 코드 9행 표와
|
||||
`DataAccessException` 번역기(`feature-persistence-failure-baseline`), Jackson B1/B2 요청 경계 스위치와 mapper
|
||||
표지 예외(`feature-boundary-validation-mapping-contract`), envelope, `Category` enum, `OperationalError` 코드
|
||||
(`feature-operational-error-observability-foundation`).
|
||||
|
||||
## Test
|
||||
## 테스트
|
||||
|
||||
```bash
|
||||
cd src
|
||||
|
||||
@@ -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 두 계층이 서로 다른
|
||||
|
||||
@@ -1,127 +1,120 @@
|
||||
# adapter:inbound:websocket — conditional WebSocket/STOMP boundary
|
||||
# adapter:inbound:websocket — 고를 때만 켜는 WebSocket·STOMP 경계
|
||||
|
||||
## Registered identity
|
||||
## 등록 정보
|
||||
|
||||
- Module ID: `adapter-inbound-websocket`
|
||||
- Gradle path: `:adapter:inbound:websocket`
|
||||
- Focused test: `./gradlew :adapter:inbound:websocket:test --console=plain`
|
||||
- Runtime baseline: Java 21, Spring Boot 4.0.8
|
||||
- Registry SSOT: `src/config/architecture/modules.json`
|
||||
- 모듈 ID: `adapter-inbound-websocket`
|
||||
- Gradle 경로: `:adapter:inbound:websocket`
|
||||
- 이 모듈만 시험: `./gradlew :adapter:inbound:websocket:test --console=plain`
|
||||
- 실행 기준: Java 21. Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다.
|
||||
- registry 정본: `src/config/architecture/modules.json`
|
||||
|
||||
Package root: `dev.caskeleton.adapter.inbound.websocket`.
|
||||
패키지 루트: `dev.caskeleton.adapter.inbound.websocket`.
|
||||
|
||||
## Responsibility
|
||||
## 책임
|
||||
|
||||
This leaf contains **two different scopes** and they must not be read as one deployed feature:
|
||||
이 leaf에는 **서로 다른 범위 둘**이 있고, 배포되는 기능 하나로 읽으면 안 된다.
|
||||
|
||||
1. **Opt-in STOMP/SockJS channel** — `stomp/**` owns the Spring transport configuration, typed
|
||||
`app.websocket.*` settings, handshake principal/origin checks, destination policy,
|
||||
fixed client-safe STOMP `ERROR` mapping, and best-effort in-process event projection.
|
||||
2. **Servlet handler library** — `servlet/`, `outbound/`, `budget/` plus the two id records
|
||||
`core/WebSocketConnectionId` and `protocol/WebSocketMessageId`. No settings keys, no Spring
|
||||
configuration: a service's own adapter leaf constructs `PlatformWebSocketHandler` and registers
|
||||
it. README "라이브러리 API" lists the entry points and the wiring.
|
||||
1. **골라 쓰는 STOMP·SockJS 채널** — `stomp/**`가 Spring 전송 설정, 타입 있는 `app.websocket.*` 설정,
|
||||
handshake principal·origin 검사, destination 정책, 정해진 클라이언트 안전 STOMP `ERROR` 대응, 할 수 있는
|
||||
만큼만 하는(best-effort) 프로세스 안 이벤트 projection을 가진다.
|
||||
2. **servlet handler 라이브러리** — `servlet/`, `outbound/`, `budget/`과 id record 둘
|
||||
`core/WebSocketConnectionId`, `protocol/WebSocketMessageId`. 설정 키도 Spring 설정도 없다: 서비스 자신의
|
||||
어댑터 leaf가 `PlatformWebSocketHandler`를 만들고 등록한다. README 「라이브러리 API」가 진입점과 배선을
|
||||
적는다.
|
||||
|
||||
This leaf does not deduplicate commands and owns no storage SPI. The former `idempotency/`
|
||||
package (command ledger, `WebSocketActorReference`, `WebSocketEndpointName`) was removed on
|
||||
2026-09-25. A command that must run at most once goes through the application
|
||||
`IdempotencyExecutor` inside its use case, with a scope that survives a reconnect (endpoint + actor
|
||||
+ the client's own message id), never the connection id.
|
||||
이 leaf는 command 중복을 걸러 내지 않고 저장소 SPI를 가지지 않는다. 예전 `idempotency/` 패키지(command
|
||||
원장, `WebSocketActorReference`, `WebSocketEndpointName`)는 2026-09-25에 지웠다. 많아야 한 번 돌아야 하는
|
||||
command는 그 유스케이스 안에서 애플리케이션 `IdempotencyExecutor`를 거친다. 범위(scope)는 다시 연결해도
|
||||
살아남는 값(endpoint + actor + 클라이언트 자신의 message id)이고, connection id가 아니다.
|
||||
|
||||
The module itself is absent from both shipped runtime compositions. Being registered and tested
|
||||
does not activate either scope.
|
||||
이 모듈은 출하하는 런타임 조립 둘 어디에도 없다. 등록되고 시험된다고 두 범위 중 어느 것도 켜지지 않는다.
|
||||
|
||||
## Allowed
|
||||
## 허용
|
||||
|
||||
- Registered dependency on `:domain-core` for the `@DomainEvent` marker.
|
||||
- Spring Boot WebSocket and validation starters, managed by the repository BOM.
|
||||
- Test-only embedded Tomcat/Jetty/SockJS/STOMP clients and Testcontainers (Nginx lane).
|
||||
- `@DomainEvent` 표지를 위한 `:domain-core` 등록 의존.
|
||||
- 저장소 BOM이 관리하는 Spring Boot WebSocket·validation starter.
|
||||
- 시험에서만: 내장 Tomcat·Jetty·SockJS·STOMP 클라이언트와 Testcontainers(Nginx lane).
|
||||
|
||||
## Forbidden
|
||||
## 금지
|
||||
|
||||
- Direct dependency on any `adapter:outbound:*` module.
|
||||
- Repository, Spring Data, persistence entity, or business policy access.
|
||||
- Raw `@DomainEvent` payload transmission or reflection-based event serialization.
|
||||
- Wildcard/blank handshake origins when enabled.
|
||||
- Anonymous handshakes, arbitrary topic subscriptions, or client sends to broker destinations.
|
||||
- A production feature `@MessageMapping` in this skeleton leaf.
|
||||
- A module-local YAML file; composition roots own property values.
|
||||
- Settings keys, flags or catalogs for behaviour no code in this leaf performs. A bound that the
|
||||
handler does not enforce is not a field of `WebSocketConnectionBudget`.
|
||||
- Reactive (WebFlux) WebSocket code: the template is servlet-only.
|
||||
- 어떤 `adapter:outbound:*` 모듈에든 직접 의존하기.
|
||||
- repository, Spring Data, 영속 엔티티, 업무 정책 접근.
|
||||
- `@DomainEvent` payload를 그대로 보내기, 리플렉션 기반 이벤트 직렬화.
|
||||
- 켜져 있을 때 wildcard·빈 handshake origin.
|
||||
- 익명 handshake, 아무 topic 구독, 클라이언트가 broker destination으로 보내기.
|
||||
- 이 골격 leaf 안의 운영 기능 `@MessageMapping`.
|
||||
- 모듈 안의 YAML 파일. 속성 값은 조립 루트가 가진다.
|
||||
- 이 leaf의 어떤 코드도 하지 않는 동작을 위한 설정 키·flag·catalog. handler가 강제하지 않는 한계는
|
||||
`WebSocketConnectionBudget`의 필드가 아니다.
|
||||
- reactive(WebFlux) WebSocket 코드: 템플릿은 servlet만 쓴다.
|
||||
|
||||
## Typed settings (`app.websocket.*`)
|
||||
## 타입 있는 설정 (`app.websocket.*`)
|
||||
|
||||
There is one property tree and one operator env prefix: `app.websocket.*` ↔ `APP_WEBSOCKET_*`.
|
||||
They configure the STOMP channel only. The default bootJar does not contain this leaf, so these
|
||||
values matter only in a composition that adopts it.
|
||||
속성 트리 하나와 운영자 env 접두어 하나가 있다: `app.websocket.*` ↔ `APP_WEBSOCKET_*`. STOMP 채널만
|
||||
설정한다. 기본 bootJar에는 이 leaf가 없으니, 이 값은 이 leaf를 채택한 조립에서만 뜻이 있다.
|
||||
|
||||
| property | env | default / role |
|
||||
| 속성 | env | 기본값·역할 |
|
||||
| --- | --- | --- |
|
||||
| `app.websocket.enabled` | `APP_WEBSOCKET_ENABLED` | `true`; `false` turns the STOMP/SockJS channel off |
|
||||
| `app.websocket.enabled` | `APP_WEBSOCKET_ENABLED` | `true`. `false`이면 STOMP·SockJS 채널을 끈다 |
|
||||
| `app.websocket.endpoint` | `APP_WEBSOCKET_ENDPOINT` | `/ws` |
|
||||
| `app.websocket.allowed-origins` | `APP_WEBSOCKET_ALLOWED_ORIGINS` | `http://localhost:3000`; explicit origins only |
|
||||
| `app.websocket.allowed-origins` | `APP_WEBSOCKET_ALLOWED_ORIGINS` | `http://localhost:3000`. 명시한 origin만 |
|
||||
| `app.websocket.broadcast-destination` | `APP_WEBSOCKET_BROADCAST_DESTINATION` | `/topic/events` |
|
||||
| `app.websocket.channel-queue-capacity` | `APP_WEBSOCKET_CHANNEL_QUEUE_CAPACITY` | `10000`; messages each STOMP channel (client inbound, client outbound, broker) queues before rejecting |
|
||||
| `app.websocket.message-size-limit` | `APP_WEBSOCKET_MESSAGE_SIZE_LIMIT` | `64KB` (Spring default, now explicit) |
|
||||
| `app.websocket.send-buffer-size-limit` | `APP_WEBSOCKET_SEND_BUFFER_SIZE_LIMIT` | `512KB` (Spring default, now explicit) |
|
||||
| `app.websocket.send-time-limit` | `APP_WEBSOCKET_SEND_TIME_LIMIT` | `10s` (Spring default, now explicit) |
|
||||
| `app.websocket.time-to-first-message` | `APP_WEBSOCKET_TIME_TO_FIRST_MESSAGE` | `60s` (Spring default, now explicit) |
|
||||
| `app.websocket.max-connections` | `APP_WEBSOCKET_MAX_CONNECTIONS` | `1000`; STOMP sessions per node, the next is closed with 1013 |
|
||||
| `app.websocket.channel-queue-capacity` | `APP_WEBSOCKET_CHANNEL_QUEUE_CAPACITY` | `10000`. STOMP 채널마다(클라이언트 inbound, 클라이언트 outbound, broker) 거절하기 전에 쌓아 두는 메시지 수 |
|
||||
| `app.websocket.message-size-limit` | `APP_WEBSOCKET_MESSAGE_SIZE_LIMIT` | `64KB`(Spring 기본값을 이제 명시한다) |
|
||||
| `app.websocket.send-buffer-size-limit` | `APP_WEBSOCKET_SEND_BUFFER_SIZE_LIMIT` | `512KB`(Spring 기본값을 이제 명시한다) |
|
||||
| `app.websocket.send-time-limit` | `APP_WEBSOCKET_SEND_TIME_LIMIT` | `10s`(Spring 기본값을 이제 명시한다) |
|
||||
| `app.websocket.time-to-first-message` | `APP_WEBSOCKET_TIME_TO_FIRST_MESSAGE` | `60s`(Spring 기본값을 이제 명시한다) |
|
||||
| `app.websocket.max-connections` | `APP_WEBSOCKET_MAX_CONNECTIONS` | `1000`. 노드마다 STOMP 세션 수. 그다음 것은 1013으로 닫는다 |
|
||||
|
||||
`WebSocketSettings` is `@Validated`. Invalid enabled settings fail context startup.
|
||||
`WebSocketSettings`는 `@Validated`다. 켜진 상태의 잘못된 설정은 context 기동을 실패시킨다.
|
||||
|
||||
## Adopting this capability
|
||||
## 이 capability 채택하기
|
||||
|
||||
WebSocket is a **build-composition opt-in**, not a dormant feature inside the default bootJar.
|
||||
WebSocket은 기본 bootJar 안에 잠든 기능이 아니라 **빌드 조립에서 고르는 것**이다.
|
||||
|
||||
1. Add `:adapter:inbound:websocket` to the consuming composition's dependencies and add the
|
||||
matching allowed edge in `config/architecture/modules.json`.
|
||||
2. Keep settings registration with the capability root; do not add
|
||||
`dev.caskeleton.adapter.inbound.websocket` back to the shipped
|
||||
`@ConfigurationPropertiesScan`.
|
||||
3. The STOMP/SockJS channel is registered by this leaf's own `AutoConfiguration.imports` and is on
|
||||
whenever the leaf is on a servlet classpath; set a non-wildcard origin allowlist, and
|
||||
`app.websocket.enabled=false` to turn it off.
|
||||
4. For the handler library, follow README "라이브러리 API". The handler must be a bean so its
|
||||
`SmartLifecycle` stop (1001 to every open connection) runs before the web server stops.
|
||||
5. Run the leaf lanes and the repository conditional-transport aggregate before promoting the
|
||||
composition:
|
||||
1. 쓰는 조립의 의존성에 `:adapter:inbound:websocket`을 더하고 `config/architecture/modules.json`에 맞는 허용
|
||||
edge를 더한다.
|
||||
2. 설정 등록은 capability 루트에 둔다. 출하하는 `@ConfigurationPropertiesScan`에
|
||||
`dev.caskeleton.adapter.inbound.websocket`을 다시 더하지 않는다.
|
||||
3. STOMP·SockJS 채널은 이 leaf 자신의 `AutoConfiguration.imports`가 등록하고, leaf가 servlet classpath에
|
||||
있으면 언제나 켜진다. wildcard가 아닌 origin 허용 목록을 정하고, 끄려면 `app.websocket.enabled=false`로
|
||||
한다.
|
||||
4. handler 라이브러리는 README 「라이브러리 API」를 따른다. handler는 bean이어야 한다. 그래야 그
|
||||
`SmartLifecycle` 멈춤(열린 모든 연결에 1001)이 web 서버가 멈추기 전에 돈다.
|
||||
5. 조립을 승격하기 전에 leaf lane과 저장소 conditional-transport 묶음을 돌린다:
|
||||
`./gradlew :adapter:inbound:websocket:test :adapter:inbound:websocket:systemTest :conditionalTransportQualification`.
|
||||
|
||||
## Inbound policy (STOMP)
|
||||
## inbound 정책 (STOMP)
|
||||
|
||||
- The HTTP upgrade must already have a nonblank `Principal`; the adapter does not authenticate
|
||||
credentials itself.
|
||||
- STOMP `SUBSCRIBE` is allowed only for the configured broadcast destination.
|
||||
- Authenticated `SEND` is allowed only below `/app/**`.
|
||||
- Client `SEND` to `/topic/**` and other destinations is rejected.
|
||||
- Every client-visible processing failure becomes an ERROR frame with an empty payload and the
|
||||
fixed `message` `WEBSOCKET_REQUEST_REJECTED`. Its `error-code` header is the carried
|
||||
`ApiErrorCode` of the first `ApiErrorCarrier` in the cause chain (even behind an
|
||||
`IllegalArgumentException`), `BAD_PARAMETER` for an `IllegalArgumentException`, and
|
||||
`WEBSOCKET_REQUEST_REJECTED` otherwise.
|
||||
- HTTP upgrade에는 이미 비어 있지 않은 `Principal`이 있어야 한다. 어댑터는 credential을 직접 인증하지 않는다.
|
||||
- STOMP `SUBSCRIBE`는 설정한 broadcast destination에만 허용한다.
|
||||
- 인증된 `SEND`는 `/app/**` 아래에만 허용한다.
|
||||
- 클라이언트가 `/topic/**`나 다른 destination으로 보내는 `SEND`는 거절한다.
|
||||
- 클라이언트에게 보이는 처리 실패는 모두 빈 payload와 정해진 `message` `WEBSOCKET_REQUEST_REJECTED`를 가진
|
||||
ERROR frame이 된다. 그 `error-code` header는 cause chain에서 처음 나오는 `ApiErrorCarrier`가 실은
|
||||
`ApiErrorCode`(`IllegalArgumentException` 뒤에 있어도), `IllegalArgumentException`이면 `BAD_PARAMETER`, 그
|
||||
밖에는 `WEBSOCKET_REQUEST_REJECTED`다.
|
||||
|
||||
## Event projection contract
|
||||
## 이벤트 projection 계약
|
||||
|
||||
A future feature may contribute a `LiveEventProjector<T>` bean for one exact `@DomainEvent` class.
|
||||
The broadcaster sends only when exactly one projector matches. Zero or duplicate projectors,
|
||||
projection failures, invalid event types, null fields, and over-limit maps are dropped. The wire
|
||||
envelope contains only `type`, bounded string `fields`, and `occurredAt`. The broker channel has its
|
||||
own bounded executor, so the simple broker's fan-out to subscribers never runs on the thread that
|
||||
published the domain event; a full broker queue drops the event (best-effort, R1).
|
||||
나중의 기능이 정확히 하나의 `@DomainEvent` 클래스에 대해 `LiveEventProjector<T>` bean을 기여할 수 있다.
|
||||
broadcaster는 projector가 정확히 하나 맞을 때만 보낸다. projector가 없거나 둘 이상이거나, projection이
|
||||
실패하거나, 이벤트 타입이 잘못됐거나, 필드가 null이거나, map이 한계를 넘으면 버린다. wire envelope에는
|
||||
`type`, 한계 있는 문자열 `fields`, `occurredAt`만 있다. broker 채널은 자기 한계 있는 executor를 가지므로,
|
||||
simple broker가 구독자에게 퍼뜨리는 일은 도메인 이벤트를 발행한 스레드에서 돌지 않는다. broker queue가 차면
|
||||
이벤트를 버린다(best-effort, R1).
|
||||
|
||||
템플릿에는 WebSocket 이벤트를 발행하거나 projector를 기여하는 기능이 없다.
|
||||
|
||||
## Evidence and limits
|
||||
## 증거와 한계
|
||||
|
||||
| lane | what it proves |
|
||||
| lane | 증명하는 것 |
|
||||
| --- | --- |
|
||||
| `test` | STOMP settings/policy, queue/writer/budget, handler size and overflow closes |
|
||||
| `systemTest` | real Tomcat: STOMP boundary (`WebSocketBoundaryQualificationTest`), handler runtime and abuse contracts, context close sends 1001 |
|
||||
| `websocketJettyTest` | the handler runtime contract on Jetty |
|
||||
| `websocketNginxTest` | upgrade/forwarding behind a real Nginx (Docker required; fails without it) |
|
||||
| `websocketTransportQualificationTest` | no-skip execution of the STOMP boundary test |
|
||||
| `test` | STOMP 설정·정책, queue·writer·budget, handler 크기와 넘침 종료 |
|
||||
| `systemTest` | 실제 Tomcat: STOMP 경계(`WebSocketBoundaryQualificationTest`), handler 런타임과 남용 계약, context를 닫으면 1001을 보냄 |
|
||||
| `websocketJettyTest` | Jetty에서 handler 런타임 계약 |
|
||||
| `websocketNginxTest` | 실제 Nginx 뒤의 upgrade·forwarding(Docker 필요. 없으면 실패한다) |
|
||||
| `websocketTransportQualificationTest` | STOMP 경계 시험을 건너뛰지 않고 실행 |
|
||||
|
||||
The simple broker is local, single-process, best-effort R1 evidence only. Broker relay,
|
||||
multi-node/durable delivery, rollback-safe publication and replay/resume are not provided.
|
||||
simple broker는 로컬·단일 프로세스·best-effort R1 증거일 뿐이다. broker relay, 여러 노드·durable 전달,
|
||||
롤백에 안전한 발행, replay·resume은 주지 않는다.
|
||||
|
||||
@@ -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을 하나도 기여하지 않는다.
|
||||
|
||||
@@ -1,372 +1,321 @@
|
||||
# Redis semantic adapters
|
||||
# Redis semantic 어댑터
|
||||
|
||||
This module is the **semantic Redis capability adapter**, not a general Redis SDK.
|
||||
이 모듈은 범용 Redis SDK가 아니라 **semantic Redis capability 어댑터**다.
|
||||
|
||||
The Redis implementation is deliberately split into three Gradle leaves:
|
||||
Redis 구현은 일부러 Gradle leaf 셋으로 나눈다:
|
||||
|
||||
- `:adapter:outbound:redis-runtime` (`dev.caskeleton.adapter.outbound.cache.redis.runtime`) —
|
||||
shipped connection/topology/settings substrate: `RedisRuntimeSettings`, the lane owner, and the
|
||||
eight `SemanticRedisCommands` this module sends. It knows nothing of the typed SDK.
|
||||
- `:adapter:outbound:cache-redis` — shipped application-facing cache, rate-limit, lease and
|
||||
idempotency adapters.
|
||||
- `:adapter:outbound:redis-sdk` — optional typed/general-purpose SDK. It is not on the default
|
||||
application runtime graph.
|
||||
- `:adapter:outbound:redis-runtime`(`dev.caskeleton.adapter.outbound.cache.redis.runtime`) — 출하하는 연결·
|
||||
topology·설정 기반: `RedisRuntimeSettings`, lane owner, 이 모듈이 보내는 `SemanticRedisCommands` 여덟 개. typed
|
||||
SDK를 모른다.
|
||||
- `:adapter:outbound:cache-redis` — 출하하는, 애플리케이션을 향한 cache·rate-limit·lease·멱등성 어댑터.
|
||||
- `:adapter:outbound:redis-sdk` — 골라 쓰는 typed·범용 SDK. 기본 애플리케이션 runtime 그래프에 없다.
|
||||
|
||||
The default application therefore does not acquire the optional SDK's command policy merely by
|
||||
selecting a semantic Redis capability. Semantic adapters call the runtime's `SemanticRedisCommands`
|
||||
directly and own their own correctness rules.
|
||||
그래서 기본 애플리케이션은 semantic Redis capability를 골랐다는 이유만으로 골라 쓰는 SDK의 명령 정책을 얻지
|
||||
않는다. semantic 어댑터는 runtime의 `SemanticRedisCommands`를 직접 부르고 자기 정확성 규칙을 스스로 가진다.
|
||||
|
||||
## Using it as a capability module — what it provides, the one line, the env keys
|
||||
## capability 모듈로 쓰기 — 주는 것, 한 줄, env 키
|
||||
|
||||
The web-only default composition does not ship this module: `app-bootstrap/build.gradle` lists it
|
||||
as a commented `runtimeOnly` line. A service selects it by uncommenting that one line, and deleting
|
||||
the line removes everything below:
|
||||
web만 있는 기본 조립은 이 모듈을 싣지 않는다: `app-bootstrap/build.gradle`이 이것을 주석 처리한 `runtimeOnly` 줄로
|
||||
적는다. 서비스는 그 한 줄의 주석을 풀어 고르고, 그 줄을 지우면 아래 것이 모두 빠진다:
|
||||
|
||||
```groovy
|
||||
runtimeOnly project(':adapter:outbound:cache-redis') // brings :adapter:outbound:redis-runtime
|
||||
```
|
||||
|
||||
**Provides**, all registered by this module itself:
|
||||
**주는 것**. 모두 이 모듈이 스스로 등록한다:
|
||||
|
||||
- the port implementations the role selectors ask for — `CacheRegionPort` (cache),
|
||||
`EdgeRateLimitPort` (rate limit), `DistributedLeasePort` (lease), `IdempotencyStorePort`
|
||||
(idempotency; the application builds the executor over it);
|
||||
- `RedisCapabilityConfig` (`AutoConfiguration.imports`, after `RedisRuntimeAutoConfiguration`). With
|
||||
`APP_REDIS_ENABLED=false` neither it nor redis-runtime's `RedisRuntimeAutoConfiguration` contributes a
|
||||
bean — no settings, client, connection, thread or health contributor. The module pulls no Spring
|
||||
Data Redis, so there is no Boot Redis auto-configuration to exclude;
|
||||
- the readiness contribution `RedisReadinessGroupPostProcessor` (this module's `spring.factories`):
|
||||
`redisRequired` joins the readiness group only when a correctness role selects Redis. Which roles
|
||||
those are is this module's `RedisCorrectnessRoleSelectors`, registered in the same file as the
|
||||
runtime's `RedisCorrectnessRequirement` — the runtime asks, it does not list selectors;
|
||||
- the shipped settings `config/module-defaults/cache-redis.yml` — `app.redis.enabled`,
|
||||
`app.rate-limit.*`, and the Redis parts of `app.capabilities.*` (cache, lease, rate-limit,
|
||||
the Redis idempotency store's tuning). The support leaf's `ModuleDefaultsEnvironmentPostProcessor`
|
||||
loads it below every application setting.
|
||||
- role 선택자가 요구하는 포트 구현 — `CacheRegionPort`(cache), `EdgeRateLimitPort`(rate limit),
|
||||
`DistributedLeasePort`(lease), `IdempotencyStorePort`(멱등성. 애플리케이션이 그 위에 executor를 만든다);
|
||||
- `RedisCapabilityConfig`(`AutoConfiguration.imports`, `RedisRuntimeAutoConfiguration` 뒤). `APP_REDIS_ENABLED=false`이면
|
||||
그것도 redis-runtime의 `RedisRuntimeAutoConfiguration`도 bean을 기여하지 않는다 — 설정, client, 연결, 스레드,
|
||||
health contributor가 없다. 이 모듈은 Spring Data Redis를 끌어오지 않으니 뺄 Boot Redis 자동 구성도 없다;
|
||||
- readiness 기여 `RedisReadinessGroupPostProcessor`(이 모듈의 `spring.factories`): 정확성 role이 Redis를 고를 때만
|
||||
`redisRequired`가 readiness group에 들어간다. 어떤 role인지는 이 모듈의 `RedisCorrectnessRoleSelectors`가 정하고,
|
||||
같은 파일에 runtime의 `RedisCorrectnessRequirement`로 등록한다 — runtime은 묻기만 하고 선택자를 적지 않는다;
|
||||
- 출하하는 설정 `config/module-defaults/cache-redis.yml` — `app.redis.enabled`, `app.rate-limit.*`,
|
||||
`app.capabilities.*`의 Redis 부분(cache, lease, rate-limit, Redis 멱등성 store의 조정). support leaf의
|
||||
`ModuleDefaultsEnvironmentPostProcessor`가 모든 애플리케이션 설정보다 아래 우선순위로 읽는다.
|
||||
|
||||
The application provides `SecretSourcePort` and `Clock`.
|
||||
애플리케이션이 `SecretSourcePort`와 `Clock`을 준다.
|
||||
|
||||
**Env keys** (`src/.env.example`, registry `docs/registries/env-keys.yaml`):
|
||||
**env 키**(`src/.env.example`, registry `docs/registries/env-keys.yaml`):
|
||||
|
||||
| Purpose | Keys |
|
||||
| 용도 | 키 |
|
||||
|---|---|
|
||||
| Switch | `APP_REDIS_ENABLED` (default true; `false` turns the present module off) |
|
||||
| Connection | `APP_REDIS_MODE`, `APP_REDIS_NODES`, `APP_REDIS_DATABASE`, `APP_REDIS_SENTINEL_*`, `APP_REDIS_TLS_*`, `APP_REDIS_AUTHENTICATION_*` (credential references) |
|
||||
| Namespace | `APP_REDIS_NAMESPACE_ENVIRONMENT`, `APP_REDIS_NAMESPACE_SERVICE`, `APP_REDIS_NAMESPACE_DOMAIN` |
|
||||
| Roles | `APP_CACHE_CANONICAL_DEFAULT_PROVIDER`, `APP_RATE_LIMIT_PROVIDER`, `APP_LEASE_PROVIDER`, `APP_IDEMPOTENCY_PROVIDER=redis` |
|
||||
| Role tuning | `APP_CACHE_REDIS_*`, `APP_RATE_LIMIT_*`, `APP_LEASE_REDIS_*`, `APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT` |
|
||||
| Prod secrets (per selected role) | `APP_CACHE_REDIS_PASSWORD`, `APP_CACHE_REDIS_KEY_HMAC_SECRET`, `APP_RATE_LIMIT_REDIS_PASSWORD`, `APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET`, `APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET`, `APP_LEASE_REDIS_KEY_HMAC_SECRET` |
|
||||
| 스위치 | `APP_REDIS_ENABLED`(기본 true. `false`이면 있는 모듈을 끈다) |
|
||||
| 연결 | `APP_REDIS_MODE`, `APP_REDIS_NODES`, `APP_REDIS_DATABASE`, `APP_REDIS_SENTINEL_*`, `APP_REDIS_TLS_*`, `APP_REDIS_AUTHENTICATION_*`(credential 참조) |
|
||||
| namespace | `APP_REDIS_NAMESPACE_ENVIRONMENT`, `APP_REDIS_NAMESPACE_SERVICE`, `APP_REDIS_NAMESPACE_DOMAIN` |
|
||||
| role | `APP_CACHE_CANONICAL_DEFAULT_PROVIDER`, `APP_RATE_LIMIT_PROVIDER`, `APP_LEASE_PROVIDER`, `APP_IDEMPOTENCY_PROVIDER=redis` |
|
||||
| role 조정 | `APP_CACHE_REDIS_*`, `APP_RATE_LIMIT_*`, `APP_LEASE_REDIS_*`, `APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT` |
|
||||
| 운영 비밀 값(고른 role마다) | `APP_CACHE_REDIS_PASSWORD`, `APP_CACHE_REDIS_KEY_HMAC_SECRET`, `APP_RATE_LIMIT_REDIS_PASSWORD`, `APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET`, `APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET`, `APP_LEASE_REDIS_KEY_HMAC_SECRET` |
|
||||
|
||||
## Activation and composition
|
||||
## 켜기와 조립
|
||||
|
||||
Redis is on when this module is present. It has one off switch:
|
||||
이 모듈이 있으면 Redis가 켜진다. 끄는 스위치는 하나다:
|
||||
|
||||
`app.redis.enabled=false` / `APP_REDIS_ENABLED=false` (default `true`).
|
||||
`app.redis.enabled=false` / `APP_REDIS_ENABLED=false`(기본 `true`).
|
||||
|
||||
A semantic role does **not** activate Redis by itself: with the switch off this module
|
||||
contributes no bean at all, whatever a role selector says. Redis idempotency refuses
|
||||
`app.capabilities.idempotency.key-version` other than 1 at startup (no dual-read yet).
|
||||
semantic role 혼자서는 Redis를 켜지 **않는다**: 스위치가 꺼져 있으면 role 선택자가 무엇을 말하든 이 모듈은 bean을
|
||||
하나도 기여하지 않는다. Redis 멱등성은 기동 때 1이 아닌 `app.capabilities.idempotency.key-version`을 거절한다(아직
|
||||
이중 읽기가 없다).
|
||||
|
||||
Current role selectors are:
|
||||
지금의 role 선택자:
|
||||
|
||||
- cache: `app.capabilities.cache.bindings.default=redis`
|
||||
- rate limit: `app.capabilities.rate-limit.provider=redis`
|
||||
- lease: `app.capabilities.lease.provider=redis`
|
||||
- idempotency: `app.capabilities.idempotency.provider=redis`
|
||||
- 멱등성: `app.capabilities.idempotency.provider=redis`
|
||||
|
||||
Only selected capabilities contribute their application port bean.
|
||||
고른 capability만 자기 애플리케이션 포트 bean을 기여한다.
|
||||
|
||||
All capabilities render below the single namespace in `app.redis.namespace.*`. Per-capability
|
||||
namespace settings are deprecated because they made ACL fencing inconsistent.
|
||||
모든 capability는 `app.redis.namespace.*`의 namespace 하나 아래에 키를 만든다. capability별 namespace 설정은 ACL
|
||||
fencing을 들쭉날쭉하게 만들어서 폐기 예정이다.
|
||||
|
||||
## Runtime ownership
|
||||
## runtime 소유
|
||||
|
||||
`:adapter:outbound:redis-runtime` owns:
|
||||
`:adapter:outbound:redis-runtime`이 가진다:
|
||||
|
||||
- topology selection (standalone / sentinel / cluster),
|
||||
- role-aware credentials,
|
||||
- connection lifecycle and bounded lane leasing,
|
||||
- the low-level command gateway,
|
||||
- topology 고르기(standalone / sentinel / cluster),
|
||||
- role을 아는 credential,
|
||||
- 연결 lifecycle과 한계 있는 lane 대여,
|
||||
- 낮은 수준 명령 gateway,
|
||||
- health,
|
||||
- TLS and connection/client timeouts.
|
||||
- TLS와 연결·client timeout.
|
||||
|
||||
`RedisRuntimeOwner` stops admission before shutdown, drains outstanding leases within a bounded
|
||||
budget, closes connections, then closes the client.
|
||||
`RedisRuntimeOwner`는 종료 전에 admission을 멈추고, 한계 있는 예산 안에서 남은 lease를 비우고, 연결을 닫은 뒤
|
||||
client를 닫는다.
|
||||
|
||||
Connection lane limits and command queue limits are different contracts. In particular:
|
||||
연결 lane 한계와 명령 queue 한계는 다른 계약이다. 특히:
|
||||
|
||||
- `app.redis.capacity.maximum-in-flight-commands` bounds the per-connection command queue.
|
||||
- `app.redis.capacity.maximum-script-connections` bounds physical SCRIPT lane connections
|
||||
(default 8). Idempotency, rate limiting and leases share them.
|
||||
- `app.capabilities.cache.maximum-script-connections` (`APP_CACHE_REDIS_MAXIMUM_SCRIPT_CONNECTIONS`)
|
||||
bounds the cache's own script lane (`CacheScriptLane`, default 4), contributed only when the cache
|
||||
binding is `redis`. See "Why the cache has its own script lane" below.
|
||||
- `app.redis.lifecycle.acquire-timeout` (default 2s) is how long a borrow waits for a returned
|
||||
connection when its lane is full.
|
||||
- `app.redis.capacity.maximum-in-flight-commands`는 연결마다 명령 queue를 묶는다.
|
||||
- `app.redis.capacity.maximum-script-connections`는 SCRIPT lane의 물리 연결을 묶는다(기본 8). 멱등성, rate limit,
|
||||
lease가 그것을 같이 쓴다.
|
||||
- `app.capabilities.cache.maximum-script-connections`(`APP_CACHE_REDIS_MAXIMUM_SCRIPT_CONNECTIONS`)는 cache 자신의
|
||||
script lane(`CacheScriptLane`, 기본 4)을 묶고, cache 바인딩이 `redis`일 때만 기여한다. 아래 「cache가 자기 script
|
||||
lane을 가지는 이유」를 본다.
|
||||
- `app.redis.lifecycle.acquire-timeout`(기본 2s)은 lane이 찼을 때 대여가 돌아올 연결을 기다리는 시간이다.
|
||||
|
||||
The second limit exists so a burst of semantic Lua calls cannot turn a command-capacity number such
|
||||
as 64 into 64 physical Redis sockets. It bounds connections, not callers: a lease holds a connection
|
||||
for one script round trip, so the ninth concurrent caller waits for one to come back instead of
|
||||
being refused. Only a borrow still waiting when the acquire timeout runs out is refused, and that
|
||||
refusal is a `RedisCommandRejectedException` whose metadata is not ambiguous — no command was ever
|
||||
sent.
|
||||
두 번째 한계는 semantic Lua 호출이 몰려도 64 같은 명령 용량 숫자가 Redis 물리 socket 64개가 되지 않게 하려고
|
||||
있다. 호출자가 아니라 연결을 묶는다: lease는 script 왕복 한 번 동안 연결을 쥐니, 아홉 번째 동시 호출자는 거절되지
|
||||
않고 연결 하나가 돌아오기를 기다린다. acquire timeout이 다 됐을 때 아직 기다리는 대여만 거절하고, 그 거절은
|
||||
metadata가 모호하지 않은 `RedisCommandRejectedException`이다 — 명령을 한 번도 보내지 않았다.
|
||||
|
||||
## Script ACL startup probe
|
||||
## script ACL 기동 probe
|
||||
|
||||
Rate limiting, distributed leases and Redis idempotency execute Lua programs. If any of those roles
|
||||
select Redis, the composition root runs a startup probe on the SCRIPT lane:
|
||||
rate limit, 분산 lease, Redis 멱등성은 Lua program을 실행한다. 그 role 중 하나라도 Redis를 고르면 조립 루트가
|
||||
SCRIPT lane에서 기동 probe를 돌린다:
|
||||
|
||||
1. `SCRIPT LOAD` a program that calls the commands the semantic scripts depend on — `TIME`, then
|
||||
`HSET`/`PEXPIRE`/`HGET`/`DEL` on its own probe key, which it deletes;
|
||||
2. execute it through `EVALSHA`;
|
||||
3. require the expected reply (the value it wrote reads back).
|
||||
1. semantic script가 기대는 명령을 부르는 program을 `SCRIPT LOAD`한다 — `TIME`, 그다음 자기 probe 키에
|
||||
`HSET`/`PEXPIRE`/`HGET`/`DEL`을 하고 그 키를 지운다;
|
||||
2. `EVALSHA`로 실행한다;
|
||||
3. 기대한 응답(쓴 값이 다시 읽힌다)을 요구한다.
|
||||
|
||||
Redis checks a script's inner commands against the ACL only when they run, so a probe that ran
|
||||
nothing proved `EVALSHA` and nothing else: an account granted by category (`@read`/`@write`) lacks
|
||||
`TIME` and failed every rate-limit and idempotency request after a clean start. A deployment whose
|
||||
effective Redis account lacks script permissions fails during startup rather than at the first
|
||||
request.
|
||||
Redis는 script 안의 명령을 돌 때만 ACL과 대조한다. 그래서 아무것도 돌리지 않는 probe는 `EVALSHA`만 증명했다:
|
||||
category로(`@read`/`@write`) 권한을 준 계정에는 `TIME`이 없었고, 깨끗하게 시작한 뒤 모든 rate-limit·멱등성 요청이
|
||||
실패했다. 실제 Redis 계정에 script 권한이 없는 배포는 첫 요청이 아니라 기동 중에 실패한다.
|
||||
|
||||
A cache-only deployment (`app.capabilities.cache.bindings.default=redis`, no correctness role) runs
|
||||
a narrower probe: a program that calls only `SET`/`GET`, the commands the cache's conditional-write
|
||||
programs use. A server that answers and refuses it fails startup — every conditional record would
|
||||
otherwise come back degraded while plain reads looked healthy. A Redis that cannot be reached at
|
||||
startup is logged as a warning and the pod starts: a cache outage degrades, it never stops a pod.
|
||||
cache만 쓰는 배포(`app.capabilities.cache.bindings.default=redis`, 정확성 role 없음)는 더 좁은 probe를 돌린다: cache의
|
||||
조건부 쓰기 program이 쓰는 명령인 `SET`/`GET`만 부르는 program이다. 답은 하지만 그것을 거절하는 서버는 기동을
|
||||
실패시킨다 — 그렇지 않으면 보통 읽기는 건강해 보이는데 모든 조건부 기록이 degraded로 돌아온다. 기동 때 닿을 수
|
||||
없는 Redis는 경고로 남기고 pod를 시작한다: cache 장애는 성능을 떨어뜨릴 뿐 pod를 멈추지 않는다.
|
||||
|
||||
At runtime, `redisRequired` (redis-runtime) probes the SCRIPT lane too when a script role is
|
||||
selected, so a broken advanced-account credential makes the pod unready instead of leaving the
|
||||
regular-lane PING to report UP.
|
||||
런타임에는 script role을 골랐으면 `redisRequired`(redis-runtime)가 SCRIPT lane도 probe한다. 그래서 advanced 계정
|
||||
credential이 깨지면 regular lane PING이 UP을 알리게 두지 않고 pod를 unready로 만든다.
|
||||
|
||||
## Cache semantics
|
||||
## cache 뜻
|
||||
|
||||
`RedisCacheRegionAdapter` implements the application cache port.
|
||||
`RedisCacheRegionAdapter`가 애플리케이션 cache 포트를 구현한다.
|
||||
|
||||
Important contracts:
|
||||
중요한 계약:
|
||||
|
||||
- value entries have soft and hard expiry;
|
||||
- negative entries use the shorter negative TTL;
|
||||
- Redis physical TTL is the hard expiry;
|
||||
- cache outages degrade to the application's typed unavailable/degraded outcomes;
|
||||
- identifiers are rendered through a keyed digest before entering the keyspace.
|
||||
- 값 항목에는 soft·hard 만료가 있다;
|
||||
- 부정 항목은 더 짧은 부정 TTL을 쓴다;
|
||||
- Redis 물리 TTL은 hard 만료다;
|
||||
- cache 장애는 애플리케이션의 타입 있는 unavailable·degraded 결과로 떨어진다;
|
||||
- 식별자는 keyspace에 들어가기 전에 키 있는 digest를 거친다.
|
||||
|
||||
### Conditional replacement
|
||||
### 조건부 바꾸기
|
||||
|
||||
`ONLY_IF_OBSERVED` is an atomic server-side compare-and-replace.
|
||||
`ONLY_IF_OBSERVED`는 서버 쪽 원자 compare-and-replace다.
|
||||
|
||||
Every lookup returns a `CacheWriteCondition` naming the state it saw — `absent`, `vacant:<digest>`
|
||||
(an invalidation marker, an entry of an older region generation, an expired entry) or
|
||||
`present:<digest>`. A record that carries the condition applies only while the key is still in that
|
||||
state (registered program, cache script lane). This is what rejects a source load that began before an
|
||||
invalidation and finished after it.
|
||||
모든 조회는 본 상태를 이름으로 대는 `CacheWriteCondition`을 돌려준다 — `absent`, `vacant:<digest>`(무효화 표지, 옛
|
||||
region generation의 항목, 만료된 항목), `present:<digest>`. 그 조건을 실은 기록은 키가 아직 그 상태일 때만 적용한다
|
||||
(등록된 program, cache script lane). 무효화 전에 시작해 무효화 뒤에 끝난 source 읽기를 이것이 거절한다.
|
||||
|
||||
A hit also returns an opaque SHA-1 observation token over the stored bytes. SHA-1 here is **not a
|
||||
security primitive**; it is used only because Redis Lua exposes `redis.sha1hex`, allowing the
|
||||
script to perform:
|
||||
hit는 저장된 바이트 위의 불투명한 SHA-1 관찰 token도 돌려준다. 여기서 SHA-1은 **보안 기본 장치가 아니다**. Redis
|
||||
Lua가 `redis.sha1hex`를 내놓아서 script가 아래를 할 수 있기 때문에 쓴다:
|
||||
|
||||
`GET current -> compare observation -> SET replacement PX ttl`
|
||||
|
||||
inside one Redis execution. A stale source load therefore cannot overwrite a value written between
|
||||
observation and replacement.
|
||||
이것을 Redis 실행 한 번 안에서 한다. 그래서 낡은 source 읽기는 관찰과 바꾸기 사이에 쓰인 값을 덮어쓸 수 없다.
|
||||
|
||||
`ONLY_IF_SOURCE_REVISION_NEWER` is an atomic server-side revision comparison. The order is the
|
||||
port's `CacheSourceRevisionOrder` (application-core): a non-negative decimal integer without leading
|
||||
zeros (a row version, an offset, epoch millis), compared numerically at any length. Any other
|
||||
revision is refused by `CacheRecordMetadata` itself, for every provider, because text order would
|
||||
rank revision `10` below `9`. The Lua program reimplements the order (the comparison and the write
|
||||
must be one step); `CacheRegionContract`, run over the fixture and a real server, keeps it equal. The script reads the stored envelope's
|
||||
schema version, revision and generation and writes only when:
|
||||
`ONLY_IF_SOURCE_REVISION_NEWER`는 서버 쪽 원자 revision 비교다. 순서는 포트의 `CacheSourceRevisionOrder`
|
||||
(application-core)다: 앞자리 0이 없는 음이 아닌 10진 정수(row version, offset, epoch millis)이고, 길이와 관계없이
|
||||
숫자로 비교한다. 그 밖의 revision은 모든 provider에서 `CacheRecordMetadata`가 직접 거절한다. 글자 순서로는 revision
|
||||
`10`이 `9`보다 아래가 되기 때문이다. Lua program은 그 순서를 다시 구현한다(비교와 쓰기가 한 단계여야 한다).
|
||||
fixture와 실제 서버에 대고 도는 `CacheRegionContract`가 둘을 같게 지킨다. script는 저장된 envelope의 schema version,
|
||||
revision, generation을 읽고 다음일 때만 쓴다:
|
||||
|
||||
- nothing is stored, or the stored entry is from an older region generation (already invalidated);
|
||||
- otherwise, the stored revision is a decimal integer and the caller's is strictly greater.
|
||||
- 아무것도 저장돼 있지 않거나, 저장된 항목이 옛 region generation에서 왔다(이미 무효화됨);
|
||||
- 아니면, 저장된 revision이 10진 정수이고 호출자의 것이 엄격하게 크다.
|
||||
|
||||
Everything else — an equal or smaller revision, a stored revision with no numeric order (for
|
||||
example one written by `UPSERT` as `rev-1`), another schema version, a generation newer than the
|
||||
writer knows — is `NOT_RECORDED_CONDITION`.
|
||||
그 밖의 모든 것 — 같거나 작은 revision, 숫자 순서가 없는 저장 revision(예: `UPSERT`가 `rev-1`로 쓴 것), 다른
|
||||
schema version, 쓰는 쪽이 아는 것보다 새 generation — 은 `NOT_RECORDED_CONDITION`이다.
|
||||
|
||||
Both conditional intents, and any record carrying a write condition, run registered scripts, so
|
||||
they run on the scripting account (the advanced account when one is configured, the application
|
||||
account otherwise), on the cache's own script lane. The application account is not granted
|
||||
`EVALSHA`; on the REGULAR lane every conditional write came back `INDETERMINATE`. Unconditioned
|
||||
`UPSERT` and `ONLY_IF_ABSENT` stay on the REGULAR lane.
|
||||
두 조건부 의도와, 쓰기 조건을 실은 모든 기록은 등록된 script를 돌리므로 script 계정(advanced 계정을 설정했으면 그
|
||||
계정, 아니면 애플리케이션 계정)으로, cache 자신의 script lane에서 돈다. 애플리케이션 계정에는 `EVALSHA`를 주지
|
||||
않는다. REGULAR lane에서는 모든 조건부 쓰기가 `INDETERMINATE`로 돌아왔다. 조건 없는 `UPSERT`와 `ONLY_IF_ABSENT`는
|
||||
REGULAR lane에 남는다.
|
||||
|
||||
### Why the cache has its own script lane
|
||||
### cache가 자기 script lane을 가지는 이유
|
||||
|
||||
Recording with the condition a lookup returned is the normal way to use this port, so nearly every
|
||||
cache fill is a script. On the runtime's SCRIPT lane those fills shared eight connections per pod
|
||||
with idempotency claims, rate-limit evaluations and lease calls, and a timed-out lease is discarded
|
||||
rather than pooled, so each timeout also cost a reconnect. A slow Redis or a burst of misses after a
|
||||
region invalidation filled the lane with cache work; an idempotency claim then waited out its
|
||||
timeout and answered `UNAVAILABLE`, and a rate-limit call fell to its failure policy. The cache is a
|
||||
speed feature that may degrade; idempotency, rate limiting and leases are correctness features that
|
||||
must not (review 2026-11-03 README §4, RR-04-02).
|
||||
조회가 돌려준 조건으로 기록하는 것이 이 포트를 쓰는 보통 방법이라서 거의 모든 cache 채우기가 script다. runtime의
|
||||
SCRIPT lane에서 그 채우기는 pod마다 연결 여덟 개를 멱등성 claim, rate-limit 평가, lease 호출과 같이 썼다. timeout이
|
||||
난 lease는 pool로 돌아가지 않고 버려지니, timeout마다 재연결 비용도 들었다. Redis가 느리거나 region 무효화 뒤 miss가
|
||||
몰리면 lane이 cache 일로 찼다. 그러면 멱등성 claim은 timeout까지 기다렸다가 `UNAVAILABLE`로 답했고, rate-limit
|
||||
호출은 실패 정책으로 떨어졌다. cache는 성능이 떨어져도 되는 속도 기능이고, 멱등성·rate limit·lease는 떨어지면 안
|
||||
되는 정확성 기능이다(review 2026-11-03 README §4, RR-04-02).
|
||||
|
||||
So `CacheScriptLane.CACHE_SCRIPT` is a lane of its own — the same scripting account, its own
|
||||
connections, its own ceiling (`app.capabilities.cache.maximum-script-connections`, default 4). A cache
|
||||
that runs out of them degrades (`DEGRADED_UNAVAILABLE`, nothing sent) without touching the SCRIPT
|
||||
lane. Alternatives not taken: a per-capability permit cap inside the shared SCRIPT lane (still one
|
||||
pool of connections and one reconnect cost), and running the cache programs on the REGULAR lane
|
||||
(grants the application account `EVALSHA`, which the account split exists to withhold).
|
||||
그래서 `CacheScriptLane.CACHE_SCRIPT`는 자기 lane이다 — 같은 script 계정, 자기 연결, 자기 상한
|
||||
(`app.capabilities.cache.maximum-script-connections`, 기본 4). 연결이 바닥난 cache는 SCRIPT lane을 건드리지 않고
|
||||
성능을 떨어뜨린다(`DEGRADED_UNAVAILABLE`, 보낸 것 없음). 고르지 않은 대안: 공용 SCRIPT lane 안의 capability별 허가
|
||||
상한(여전히 연결 pool 하나와 재연결 비용 하나), cache program을 REGULAR lane에서 돌리기(애플리케이션 계정에
|
||||
`EVALSHA`를 준다. 계정을 나눈 것은 바로 그것을 주지 않으려는 것이다).
|
||||
|
||||
Whether the split holds under load is visible per lane. With a `MeterRegistry` in the context,
|
||||
`redis-runtime` registers these for every lane it pools — `REGULAR`, `SCRIPT`, `CACHE_SCRIPT` and the
|
||||
typed SDK's — tagged `lane=<name>` (`RedisLaneMetrics`; rows in `docs/registries/metrics.yaml`):
|
||||
부하 아래에서 이 분리가 지켜지는지는 lane마다 보인다. context에 `MeterRegistry`가 있으면 `redis-runtime`이 pool로 두는
|
||||
모든 lane — `REGULAR`, `SCRIPT`, `CACHE_SCRIPT`, typed SDK의 lane — 에 대해 아래를 `lane=<name>` tag로 등록한다
|
||||
(`RedisLaneMetrics`. 행은 `docs/registries/metrics.yaml`):
|
||||
|
||||
| Meter | Type | Read it as |
|
||||
| meter | 타입 | 읽는 법 |
|
||||
| --- | --- | --- |
|
||||
| `redis.lane.acquire.wait.seconds` (`outcome` = `admitted`/`refused`) | timer, histogram | how long a borrow queued for a connection; a growing admitted p99 comes before refusals |
|
||||
| `redis.lane.acquire.refused.total` (`reason` = `saturated`/`closing`/`interrupted`/`connect_failed`) | counter | a borrow that got no connection, nothing sent; `saturated` on `SCRIPT` is the starvation this lane exists to prevent |
|
||||
| `redis.lane.connections.opened.total` | counter | new connections; after warm-up a pooled lane opens one only to replace a discarded one. A routed lease (a Cluster `TRANSACTION` borrow) is opened for each borrow and closed after it without being counted as discarded, so on that lane a steady rate is normal use, not reconnects |
|
||||
| `redis.lane.connections.discarded.total` (`reason` = `invalidated`/`broken`) | counter | connections closed instead of pooled — `invalidated` is a timed-out or failed call (the lease is not reused), and is what the reconnects replace |
|
||||
| `redis.lane.connections.active`, `redis.lane.connections.pending` | gauge | connections lent out now; borrows waiting now |
|
||||
| `redis.lane.acquire.wait.seconds`(`outcome` = `admitted`/`refused`) | timer, histogram | 대여가 연결을 얼마나 기다렸나. 거절보다 먼저 admitted p99가 늘어난다 |
|
||||
| `redis.lane.acquire.refused.total`(`reason` = `saturated`/`closing`/`interrupted`/`connect_failed`) | counter | 연결을 얻지 못한 대여, 보낸 것 없음. `SCRIPT`의 `saturated`가 이 lane이 막으려는 굶주림이다 |
|
||||
| `redis.lane.connections.opened.total` | counter | 새 연결. 데운 뒤에는 pool로 두는 lane이 버린 연결을 대신할 때만 연다. route된 lease(Cluster `TRANSACTION` 대여)는 대여마다 열고 그 뒤에 닫지만 버린 것으로 세지 않는다. 그래서 그 lane에서 꾸준한 비율은 재연결이 아니라 보통 사용이다 |
|
||||
| `redis.lane.connections.discarded.total`(`reason` = `invalidated`/`broken`) | counter | pool로 두지 않고 닫은 연결 — `invalidated`는 timeout이 났거나 실패한 호출(그 lease는 다시 쓰지 않는다)이고, 재연결이 대신하는 것이 이것이다 |
|
||||
| `redis.lane.connections.active`, `redis.lane.connections.pending` | gauge | 지금 빌려준 연결, 지금 기다리는 대여 |
|
||||
|
||||
Every counter series exists from startup at zero, so an alert on "refusals above zero" sees the first
|
||||
one. A lane refusal is also logged, per call, by `RedisSemanticFailureLogger`.
|
||||
모든 counter series는 기동 때부터 0으로 있으니, 「거절이 0보다 많다」 경보가 첫 거절을 본다. lane 거절은
|
||||
`RedisSemanticFailureLogger`도 호출마다 남긴다.
|
||||
|
||||
### Key invalidation
|
||||
### 키 무효화
|
||||
|
||||
`invalidate(key)` writes a short-lived marker (`GET`, then `SET … PX softTtl` on the REGULAR lane)
|
||||
instead of deleting the key. While the marker lives, a record whose condition came from an earlier
|
||||
lookup, an unconditioned `ONLY_IF_ABSENT`, and an unconditioned `ONLY_IF_SOURCE_REVISION_NEWER` are
|
||||
`NOT_RECORDED_CONDITION`; a fresh lookup returns a `vacant:` condition that records normally;
|
||||
unconditioned `UPSERT` overwrites it. Limit: the marker lives for the soft TTL, so a source load
|
||||
slower than that, carrying an `absent` condition, can still land after it.
|
||||
`invalidate(key)`는 키를 지우지 않고 짧게 사는 표지를 쓴다(REGULAR lane에서 `GET`, 그다음 `SET … PX softTtl`). 표지가
|
||||
사는 동안 앞 조회에서 온 조건을 실은 기록, 조건 없는 `ONLY_IF_ABSENT`, 조건 없는 `ONLY_IF_SOURCE_REVISION_NEWER`는
|
||||
`NOT_RECORDED_CONDITION`이다. 새 조회는 보통으로 기록되는 `vacant:` 조건을 돌려준다. 조건 없는 `UPSERT`는 표지를
|
||||
덮어쓴다. 한계: 표지는 soft TTL 동안 산다. 그래서 그보다 느리고 `absent` 조건을 실은 source 읽기는 여전히 그 뒤에
|
||||
들어올 수 있다.
|
||||
|
||||
### Stampede
|
||||
### stampede
|
||||
|
||||
There is no stampede protection and no TTL jitter. Concurrent misses on one key each load from the
|
||||
source. Single-flight, where a source cannot take the burst, is the caller's.
|
||||
stampede 보호도 TTL jitter도 없다. 한 키에 동시에 난 miss는 각자 source에서 읽는다. source가 몰림을 감당하지 못하면
|
||||
single-flight는 호출자의 몫이다.
|
||||
|
||||
### Region invalidation
|
||||
### region 무효화
|
||||
|
||||
Region invalidation increments a generation key; it never scans/deletes the keyspace.
|
||||
region 무효화는 generation 키를 올린다. keyspace를 scan하거나 지우지 않는다.
|
||||
|
||||
Each adapter instance caches the observed generation only for the positive soft TTL. After that
|
||||
bounded interval it rechecks the server generation. This keeps ordinary cache hits from paying an
|
||||
extra Redis round trip while ensuring an invalidation issued by another process eventually becomes
|
||||
visible to every instance.
|
||||
어댑터 인스턴스마다 본 generation을 양의 soft TTL 동안만 cache한다. 그 한계 있는 시간이 지나면 서버 generation을 다시
|
||||
본다. 그래서 보통 cache hit는 Redis 왕복을 더 치르지 않으면서, 다른 프로세스가 낸 무효화도 결국 모든 인스턴스에
|
||||
보이게 된다.
|
||||
|
||||
## Rate-limit semantics
|
||||
## rate-limit 뜻
|
||||
|
||||
The rate-limit adapter supports the configured fixed-window, sliding-counter and token-bucket
|
||||
policies through registered Lua scripts.
|
||||
rate-limit 어댑터는 설정한 fixed-window, sliding-counter, token-bucket 정책을 등록된 Lua script로 지원한다.
|
||||
|
||||
Time is taken from Redis `TIME`, not the caller JVM clock. Multiple application nodes therefore
|
||||
make the same distributed decision even if their local clocks differ.
|
||||
시간은 호출자 JVM 시계가 아니라 Redis `TIME`에서 가져온다. 그래서 애플리케이션 노드 여럿의 로컬 시계가 달라도 같은
|
||||
분산 판단을 한다.
|
||||
|
||||
Script TTLs are computed as integer milliseconds in Java and passed as exact Lua arguments.
|
||||
`cleanup-grace` is part of the physical state TTL. There is no exposed
|
||||
`maximum-clock-regression` knob because Redis is the time authority for this state.
|
||||
script TTL은 Java에서 정수 밀리초로 계산해 정확한 Lua 인자로 넘긴다. `cleanup-grace`는 물리 상태 TTL의 일부다. 이
|
||||
상태의 시간 정본은 Redis이므로 `maximum-clock-regression` 손잡이는 내놓지 않는다.
|
||||
|
||||
Rate-limit failures remain fail-closed according to the application contract. A connection that
|
||||
could not be opened is `UNAVAILABLE_BEFORE_SEND` (nothing was sent). The caller's remaining
|
||||
deadline bounds the lane wait and the reply wait; opening a new connection is still bounded only by
|
||||
the driver's connect timeout.
|
||||
rate-limit 실패는 애플리케이션 계약대로 실패하면 닫힌다. 열지 못한 연결은 `UNAVAILABLE_BEFORE_SEND`다(보낸 것 없음).
|
||||
호출자의 남은 deadline이 lane 대기와 응답 대기를 묶는다. 새 연결 열기는 여전히 driver의 connect timeout만 묶는다.
|
||||
|
||||
Evaluation deduplication is **not implemented**: `RateLimitRequest.evaluationId` is ignored, so a
|
||||
retry after `NO_MUTATION_CONFIRMED` is charged again. Policies default to
|
||||
`RateLimitEvaluationDedupPolicy.disabled()`, and the adapter refuses a policy that enables it.
|
||||
평가 중복 제거는 **구현하지 않았다**: `RateLimitRequest.evaluationId`는 무시하므로 `NO_MUTATION_CONFIRMED` 뒤의
|
||||
재시도는 다시 센다. 정책 기본값은 `RateLimitEvaluationDedupPolicy.disabled()`이고, 어댑터는 그것을 켠 정책을
|
||||
거절한다.
|
||||
|
||||
## Idempotency semantics
|
||||
## 멱등성 뜻
|
||||
|
||||
The Redis idempotency adapter stores owner-safe claim state and executes claim/transition/release
|
||||
programs atomically. `RedisIdempotencyConfig` contributes only the `IdempotencyStorePort`; the
|
||||
`IdempotencyExecutor` and its lifecycle policy (lease, replay TTL, retention, codec id, policy
|
||||
revision) come from app-bootstrap `IdempotencySettings`. This leaf reads only `key-version` and
|
||||
`command-timeout` under `app.capabilities.idempotency`.
|
||||
Redis 멱등성 어댑터는 소유자를 안전하게 지키는 claim 상태를 저장하고 claim·전이·놓아주기 program을 원자적으로
|
||||
실행한다. `RedisIdempotencyConfig`는 `IdempotencyStorePort`만 기여한다. `IdempotencyExecutor`와 그 lifecycle 정책
|
||||
(lease, 재생 TTL, 보존, codec id, 정책 revision)은 `composition:idempotency`의 `IdempotencySettings`에서 온다. 이
|
||||
leaf는 `app.capabilities.idempotency` 아래의 `key-version`과 `command-timeout`만 읽는다.
|
||||
|
||||
`renew` has its own program rather than the generic transition. Renewal keeps the record in
|
||||
`EXECUTING`, and the transition answers "already in the target state" before it reads the revision
|
||||
(that answer exists for a retry whose first reply was lost), so a renewal sent through it was always
|
||||
`ALREADY_RENEWED_SAME_OPERATION` and never moved the lease. That answer is given only to the handle
|
||||
the transition was applied from — the record one revision past it, with `lastKind` (written by the
|
||||
claim, renew and transition programs) naming that transition. Another handle of the same
|
||||
attempt (one from before a takeover, or the current one a replayed claim returned) used to be told a
|
||||
start was applied and ran the action a second time (round6 RR6-02-01), and to be told a completion
|
||||
or failure that followed a takeover was its own (owner decision 2026-11-06); it is now `NOT_OWNER`
|
||||
or `NOT_CLAIMED`/`NOT_IN_PROGRESS`, as in the PostgreSQL store. Without the kind, a start through the
|
||||
handle a renewal was applied from was confirmed too — renewal leaves the record `EXECUTING` one
|
||||
revision past that handle (round8 RR8-04-02); it is `NOT_OWNER`. A failure from the handle that
|
||||
applied one, asking for the other disposition, is `OPERATION_CONFLICT` (it fell through to
|
||||
`NOT_OWNER`); the record keeps no retention, so another retention is confirmed (owner decision
|
||||
2026-11-07). The renew program checks owner,
|
||||
operation, revision and state, then extends `leaseUntil` from Redis `TIME` and bumps the revision.
|
||||
A lost renewal reply is recognised by what the renewal recorded — the revision it started from and
|
||||
the lease it asked for: the same lease is `ALREADY_RENEWED_SAME_OPERATION` with the current handle,
|
||||
a different lease is `OPERATION_CONFLICT`.
|
||||
`renew`는 범용 전이가 아니라 자기 program을 가진다. 갱신은 레코드를 `EXECUTING`에 두고, 전이는 revision을 읽기 전에
|
||||
「이미 목표 상태다」로 답한다(그 답은 첫 응답을 잃은 재시도를 위해 있다). 그래서 전이를 거쳐 보낸 갱신은 언제나
|
||||
`ALREADY_RENEWED_SAME_OPERATION`이었고 lease를 옮기지 못했다. 그 답은 전이를 적용한 handle에게만 준다 — 그 handle은
|
||||
한 revision 뒤의 레코드이고, `lastKind`(claim·renew·전이 program이 쓴다)가 그 전이를 이름으로 댄다. 같은 시도의
|
||||
다른 handle(넘겨받기 전의 것, 또는 재생된 claim이 돌려준 지금의 것)은 예전에 시작이 적용됐다는 답을 받아 action을
|
||||
두 번 돌렸고(round6 RR6-02-01), 넘겨받기 뒤에 온 완료나 실패를 자기 것이라고 들었다(소유자 결정 2026-11-06). 이제는
|
||||
PostgreSQL store처럼 `NOT_OWNER`나 `NOT_CLAIMED`/`NOT_IN_PROGRESS`다. kind가 없으면 갱신을 적용한 handle로 하는
|
||||
시작도 확인받았다 — 갱신은 레코드를 그 handle보다 한 revision 뒤의 `EXECUTING`에 둔다(round8 RR8-04-02). 이제는
|
||||
`NOT_OWNER`다. 실패를 적용한 handle이 다른 disposition을 요구하면 `OPERATION_CONFLICT`다(예전에는 `NOT_OWNER`로
|
||||
떨어졌다). 레코드는 retention을 두지 않으므로 다른 retention은 확인해 준다(소유자 결정 2026-11-07). renew program은
|
||||
owner, operation, revision, 상태를 검사한 뒤 Redis `TIME`으로 `leaseUntil`을 늘리고 revision을 올린다. 잃은 갱신
|
||||
응답은 그 갱신이 기록한 것 — 시작한 revision과 요청한 lease — 으로 알아본다: 같은 lease면 지금 handle과 함께
|
||||
`ALREADY_RENEWED_SAME_OPERATION`, 다른 lease면 `OPERATION_CONFLICT`다.
|
||||
|
||||
Every program compares the operation a call names with the one the record was claimed under, right
|
||||
after the owner token: another operation is `OPERATION_CONFLICT` and changes nothing. The PostgreSQL
|
||||
store and the in-memory fake used to apply it; they now answer the same (owner decision 2026-11-06,
|
||||
`IdempotencyStoreContract`). The release program also checks the handle's revision, as the
|
||||
transition does: owner token and operation alone let the handle from before the same attempt took
|
||||
its claim over release the claim it holds now. A release deletes the record, so a release that finds
|
||||
no record — its own retry, an expired record, one never claimed — is `ABSENT`; it used to be
|
||||
confirmed as `ALREADY_RELEASED_SAME_OPERATION`, which the store cannot know.
|
||||
모든 program은 owner token 바로 뒤에서 호출이 댄 operation과 레코드를 claim한 operation을 비교한다: 다른 operation이면
|
||||
`OPERATION_CONFLICT`이고 아무것도 바꾸지 않는다. PostgreSQL store와 메모리 fake는 예전에 그것을 적용했다. 이제 같은
|
||||
답을 한다(소유자 결정 2026-11-06, `IdempotencyStoreContract`). 놓아주기 program도 전이처럼 handle의 revision을
|
||||
검사한다: owner token과 operation만으로는 같은 시도가 claim을 넘겨받기 전의 handle이 지금 쥔 claim을 놓아줄 수
|
||||
있었다. 놓아주기는 레코드를 지우므로, 레코드를 찾지 못한 놓아주기 — 자기 재시도, 만료된 레코드, claim한 적 없는
|
||||
것 — 는 `ABSENT`다. 예전에는 store가 알 수 없는 `ALREADY_RELEASED_SAME_OPERATION`으로 확인해 줬다.
|
||||
|
||||
A lease that runs out is taken over only from a claim that never started or an attempt marked
|
||||
retryable — by whoever claims next, the holder's own attempt included: the claim program checks for
|
||||
a takeover before it replays a same-owner claim, so an attempt whose start was refused takes its
|
||||
claim over when it claims again instead of being replayed the claim and refused until the record
|
||||
expired (round6 RR6-02-01). A record still `EXECUTING` when its lease ran out has an unknown effect: the claim
|
||||
program answers `RECOVERY_REQUIRED` and leaves the record as it is, because the holder may still be
|
||||
running. The holder's late completion or failure goes through the transition program as it would
|
||||
have inside the lease, and the next claim replays or retries it; only the lease is final — `RENEW`
|
||||
refuses one that has run out with `LEASE_EXPIRED` (not `NOT_OWNER`: the holder still completes the
|
||||
record, re-review 2026-11-04 RR5-01-02), and `INSPECT` reports somebody else's expired execution as
|
||||
`RECOVERY_REQUIRED`. The transition program reads the lease for a start only: a claim whose lease
|
||||
ran out is answered `LEASE_EXPIRED` and not started, so nothing runs and the next claim takes it
|
||||
over (it used to start, and every other request was then told "recovery required" for work that
|
||||
had just begun; README 15). The PostgreSQL store answers the same; the shared `IdempotencyStoreContract`
|
||||
holds both to it on a real server (re-review 2026-11-04 RR-01-11 — this store used to take the
|
||||
record over and run the work a second time; owner decision 2026-11-04 — both stores then abandoned
|
||||
the record, and a holder that outlived its lease lost its result).
|
||||
lease가 끝나면 시작하지 않은 claim이나 재시도할 수 있다고 표시한 시도에서만 넘겨받는다 — 다음에 claim하는 누구든,
|
||||
쥔 쪽 자신의 시도도 포함한다: claim program은 같은 owner의 claim을 재생하기 전에 넘겨받기를 검사한다. 그래서 시작이
|
||||
거절된 시도는 다시 claim할 때 레코드가 만료될 때까지 claim을 재생받고 거절당하는 대신 자기 claim을 넘겨받는다
|
||||
(round6 RR6-02-01). lease가 끝났을 때 아직 `EXECUTING`인 레코드는 효과를 모른다: claim program은
|
||||
`RECOVERY_REQUIRED`로 답하고 레코드를 그대로 둔다. 쥔 쪽이 아직 돌고 있을 수 있기 때문이다. 쥔 쪽의 늦은 완료나
|
||||
실패는 lease 안이었을 때처럼 전이 program을 거치고, 다음 claim이 그것을 재생하거나 다시 시도한다. 끝난 것은
|
||||
lease뿐이다 — `RENEW`는 끝난 lease를 `LEASE_EXPIRED`로 거절하고(`NOT_OWNER`가 아니다: 쥔 쪽이 여전히 레코드를
|
||||
완료한다, re-review 2026-11-04 RR5-01-02), `INSPECT`는 남의 만료된 실행을 `RECOVERY_REQUIRED`로 알린다. 전이
|
||||
program은 시작할 때만 lease를 읽는다: lease가 끝난 claim은 `LEASE_EXPIRED`로 답하고 시작하지 않는다. 그래서 아무것도
|
||||
돌지 않고 다음 claim이 넘겨받는다(예전에는 시작했고, 그 뒤 다른 모든 요청이 막 시작한 일에 대해 「복구 필요」를
|
||||
들었다. README 15). PostgreSQL store도 같은 답을 한다. 공용 `IdempotencyStoreContract`가 둘을 실제 서버에서 거기에
|
||||
맞춘다(re-review 2026-11-04 RR-01-11 — 이 store는 예전에 레코드를 넘겨받아 일을 두 번 돌렸다. 소유자 결정
|
||||
2026-11-04 — 그 뒤 두 store 모두 레코드를 버렸고, lease보다 오래 산 쥔 쪽은 결과를 잃었다).
|
||||
|
||||
The record key lives for the processing lease plus the replay TTL (`afterLease`, kept on the record),
|
||||
and a renewal stretches it to the new lease plus that margin. With the replay TTL alone, a replay
|
||||
TTL shorter than the lease dropped the key of a running operation and the next claim ran it again,
|
||||
and one equal to the lease left no record to answer `RECOVERY_REQUIRED` from (RR-03-11).
|
||||
레코드 키는 처리 lease에 재생 TTL을 더한 만큼 산다(`afterLease`, 레코드에 둔다). 갱신은 그것을 새 lease에 그 여유를
|
||||
더한 만큼 늘린다. 재생 TTL만으로 두면, lease보다 짧은 재생 TTL은 돌고 있는 operation의 키를 버려 다음 claim이 그것을
|
||||
다시 돌렸고, lease와 같은 재생 TTL은 `RECOVERY_REQUIRED`로 답할 레코드를 남기지 않았다(RR-03-11).
|
||||
|
||||
Redis `TIME` determines lease deadlines. A failure after a command may have executed is returned
|
||||
as an indeterminate outcome; the adapter does not convert an ambiguous write into a clean
|
||||
unavailable result that would invite duplicate execution.
|
||||
lease 기한은 Redis `TIME`이 정한다. 명령이 실행됐을 수 있는 뒤의 실패는 결과를 모름으로 돌려준다. 어댑터는 모호한
|
||||
쓰기를 중복 실행을 부르는 깨끗한 unavailable 결과로 바꾸지 않는다.
|
||||
|
||||
## Lease semantics
|
||||
## lease 뜻
|
||||
|
||||
The distributed lease adapter uses owner/operation-safe Lua programs for acquire, inspect, renew and
|
||||
release.
|
||||
분산 lease 어댑터는 acquire, inspect, renew, release에 owner·operation을 안전하게 지키는 Lua program을 쓴다.
|
||||
|
||||
Unknown mutation outcomes remain indeterminate. Local validity is shortened by the configured drift
|
||||
budget; a successful renew is the only event that extends it.
|
||||
결과를 모르는 변경은 모름으로 남는다. 로컬 유효 시간은 설정한 drift 예산만큼 줄인다. 그것을 늘리는 일은 성공한
|
||||
renew 하나뿐이다.
|
||||
|
||||
## Failure visibility
|
||||
## 실패 보이기
|
||||
|
||||
Semantic adapters intentionally translate Redis failures into typed application outcomes, but those
|
||||
translations are not silent.
|
||||
semantic 어댑터는 Redis 실패를 일부러 타입 있는 애플리케이션 결과로 바꾸지만, 그 번역은 소리 없지 않다.
|
||||
|
||||
`RedisSemanticFailureLogger` records only:
|
||||
`RedisSemanticFailureLogger`는 다음만 남긴다:
|
||||
|
||||
- capability,
|
||||
- semantic operation,
|
||||
- exception class.
|
||||
- 예외 클래스.
|
||||
|
||||
It never logs Redis keys, values, command arguments, exception messages or credentials. The first
|
||||
occurrence of a capability/operation/failure-type combination is WARN; repeats are DEBUG to avoid
|
||||
turning a Redis outage into a log-flood outage.
|
||||
Redis 키, 값, 명령 인자, 예외 메시지, credential은 남기지 않는다. capability·operation·실패 타입 조합의 첫 발생은
|
||||
WARN이고, 되풀이는 DEBUG다. Redis 장애가 로그 홍수 장애로 번지지 않게 하려는 것이다.
|
||||
|
||||
## Optional typed SDK
|
||||
## 골라 쓰는 typed SDK
|
||||
|
||||
`:adapter:outbound:redis-sdk` contains the broader typed command surface, command policy, raw/admin
|
||||
and extension machinery. It is a separate library leaf that service code takes with
|
||||
`implementation`; see `src/adapter/outbound/redis-sdk/README.md`. This leaf does not depend on it,
|
||||
in production or in tests.
|
||||
`:adapter:outbound:redis-sdk`에는 더 넓은 typed 명령 surface, 명령 정책, raw·admin, extension 장치가 있다. 서비스
|
||||
코드가 `implementation`으로 받는 따로 둔 라이브러리 leaf다. `src/adapter/outbound/redis-sdk/README.md`를 본다. 이
|
||||
leaf는 운영에서도 시험에서도 그것에 의존하지 않는다.
|
||||
|
||||
Its policy file and optional startup/library probes apply only when that SDK is deliberately added
|
||||
to a composition. Do not infer SDK command-policy enforcement from the presence of a semantic cache
|
||||
or rate-limit adapter.
|
||||
그 정책 파일과 골라 쓰는 기동·라이브러리 probe는 그 SDK를 일부러 조립에 더했을 때만 적용된다. semantic cache나
|
||||
rate-limit 어댑터가 있다고 SDK 명령 정책이 강제된다고 짐작하지 않는다.
|
||||
|
||||
## Verification
|
||||
## 검증
|
||||
|
||||
Useful focused checks:
|
||||
쓸 만한 이 모듈 검사:
|
||||
|
||||
```bash
|
||||
./gradlew :adapter:outbound:cache-redis:check
|
||||
@@ -377,18 +326,16 @@ Useful focused checks:
|
||||
./gradlew architectureCheck
|
||||
```
|
||||
|
||||
`redisContainerContractTest` runs the cache-region, lease and idempotency-store port contracts (the
|
||||
ones the in-memory fakes pass; the idempotency contract's timed cases run here on the server's own
|
||||
clock, and in `test` over the command fake's clock, which proves the fixture's copies of the
|
||||
programs rather than the programs) and the live semantic-port tests against a Redis it starts itself, under the standalone
|
||||
topology's ACL file. It is in `integrationCheck` (integration-main.yml's `integration-check` job), and
|
||||
only there: listing it in `mainCheck` as well ran it twice on every push to main. The image is
|
||||
`config/testing/container-images.properties` `redis`.
|
||||
`redisContainerContractTest`는 cache-region, lease, 멱등성 store 포트 계약(메모리 fake가 통과하는 것. 멱등성 계약의
|
||||
시간 있는 경우는 여기서 서버 자신의 시계로 돌고, `test`에서는 명령 fake의 시계로 돈다 — 후자는 program 자체가 아니라
|
||||
fixture가 가진 program 사본을 증명한다)과 살아 있는 semantic 포트 시험을, standalone topology의 ACL 파일 아래에서 스스로
|
||||
띄운 Redis에 대고 돌린다. `integrationCheck`(integration-main.yml의 `integration-check` job)에 있고 거기에만 있다:
|
||||
`mainCheck`에도 적었을 때는 main push마다 두 번 돌았다. image는 `config/testing/container-images.properties`의
|
||||
`redis`다.
|
||||
|
||||
Live Redis/topology qualification remains separate from fast unit tests. A release claim for a
|
||||
specific Redis topology or ACL layout requires the corresponding live qualification lane; the
|
||||
in-memory gateway is for deterministic contract tests, not evidence that an external Redis
|
||||
deployment accepts the same network/TLS/ACL configuration.
|
||||
살아 있는 Redis·topology 검증은 빠른 단위 시험과 따로다. 특정 Redis topology나 ACL 배치에 대한 릴리스 주장에는 그에
|
||||
맞는 살아 있는 검증 lane이 필요하다. 메모리 gateway는 결정적인 계약 시험을 위한 것이지, 외부 Redis 배포가 같은
|
||||
network·TLS·ACL 설정을 받아들인다는 증거가 아니다.
|
||||
|
||||
## 아직 내보내지 않는 지표
|
||||
|
||||
@@ -398,4 +345,3 @@ inflight.total, readiness.total, lifecycle.drain.total)는 redis-production-capa
|
||||
것처럼 적고 있어서, 2026-11-03 재리뷰 수정에서 레지스트리에서 빼고 runbook을 지금 내보내는
|
||||
`redis.lane.*`(redis-runtime, lane별 대기·거절·연결) 기준으로 고쳤다. capability 단위 지표가 필요해지면
|
||||
operation 결과를 아는 semantic adapter(이 leaf)에서 내보내고, 그때 레지스트리에 다시 넣는다.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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,
|
||||
성능 기준선, 릴리스 체크리스트가 있다.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -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에 바인딩·검증 시험을 더한다.
|
||||
|
||||
@@ -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의 중앙
|
||||
|
||||
@@ -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 네트워크 호출이 없다. 설정을 바꾸면
|
||||
바인딩·검증 시험을 더한다.
|
||||
|
||||
@@ -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 회귀 기준선으로만 유지한다.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,35 +1,32 @@
|
||||
# adapter:outbound:objectstorage — design-decision reference
|
||||
# adapter:outbound:objectstorage — 설계 결정 참고
|
||||
|
||||
Object-storage driven adapter under
|
||||
`dev.caskeleton.adapter.outbound.objectstorage`. It implements the semantic contracts in
|
||||
`dev.caskeleton.application.objectstorage` and keeps provider keys, paths, SDK types, and control
|
||||
records behind the application boundary.
|
||||
`dev.caskeleton.adapter.outbound.objectstorage` 아래의 object storage driven 어댑터다.
|
||||
`dev.caskeleton.application.objectstorage`의 semantic 계약을 구현하고, provider 키·경로·SDK 타입·제어
|
||||
레코드를 애플리케이션 경계 뒤에 둔다.
|
||||
|
||||
The allowed production dependencies are owned by
|
||||
`src/config/architecture/modules.json`. Module rules live in [CLAUDE.md](CLAUDE.md), the full design
|
||||
in `docs/design/2026-07-28-objectstorage-production-capability-design.md`, and exact
|
||||
evidence claims in `docs/registries/object-storage-readiness.yaml`.
|
||||
허용 운영 의존은 `src/config/architecture/modules.json`이 가진다. 모듈 규칙은 [CLAUDE.md](CLAUDE.md), 전체
|
||||
설계는 `docs/design/2026-07-28-objectstorage-production-capability-design.md`, 정확한 증거 주장은
|
||||
`docs/registries/object-storage-readiness.yaml`에 있다.
|
||||
|
||||
For when to use this capability rather than the HTTP Fileserver platform, see
|
||||
[`docs/storage-capability-boundary.md`](../../../../docs/storage-capability-boundary.md).
|
||||
HTTP 파일 서버 플랫폼 대신 이 capability를 언제 쓰는지는
|
||||
[`docs/storage-capability-boundary.md`](../../../../docs/storage-capability-boundary.md)를 본다.
|
||||
|
||||
## Current readiness
|
||||
## 지금 준비 상태
|
||||
|
||||
Batch B implements the provider-neutral namespace/control kernel and
|
||||
`filesystem-local-dev` managed single upload/download at R1. R1 means bounded local functional
|
||||
evidence only:
|
||||
Batch B가 provider 중립 namespace·제어 핵심과 `filesystem-local-dev`의 관리형 단일 업로드·다운로드를 R1으로
|
||||
구현한다. R1은 한계 있는 로컬 기능 증거만 뜻한다:
|
||||
|
||||
- immutable streamed create with exact SHA-256 and exact version inspection;
|
||||
- full/range bounded reads;
|
||||
- strict canonical control-record codecs and single-process CAS;
|
||||
- same-operation replay without invoking the producer again;
|
||||
- restart/path/symlink/corruption/fault characterization;
|
||||
- exactly-once selected-provider lifecycle.
|
||||
- 정확한 SHA-256과 정확한 version 검사를 하는, 바뀌지 않는 streaming 생성;
|
||||
- 전체·범위 지정의 한계 있는 읽기;
|
||||
- 엄격한 정규형 제어 레코드 codec과 단일 프로세스 CAS;
|
||||
- producer를 다시 부르지 않는 같은 operation의 재생;
|
||||
- 재시작·경로·symlink·손상·장애 특성 확인;
|
||||
- 고른 provider의 lifecycle을 정확히 한 번.
|
||||
|
||||
It does not prove multi-node CAS, power-loss durability, production credentials/TLS/IAM/encryption,
|
||||
S3 response-loss behavior, or R2 readiness. Direct transfer, multipart, quarantine, retention, and
|
||||
production reconciliation cards remain R0. Direct transfer and multipart have no code: the unassembled
|
||||
implementation was removed (recovery path in `docs/capability-status.md` 「제거된 코드」).
|
||||
여러 노드 CAS, 전원 상실 내구성, 운영 credential·TLS·IAM·암호화, S3 응답 유실 동작, R2 준비는 증명하지
|
||||
않는다. direct transfer, multipart, quarantine, retention, 운영 reconciliation card는 R0에 머문다. direct
|
||||
transfer와 multipart는 코드가 없다: 조립되지 않은 구현을 지웠다(되살리는 길은 `docs/capability-status.md`
|
||||
「제거된 코드」).
|
||||
|
||||
## 제공하는 것 · 추가할 한 줄 · env 키
|
||||
|
||||
@@ -49,110 +46,103 @@ implementation was removed (recovery path in `docs/capability-status.md` 「제
|
||||
bean도 두지 않는다.
|
||||
- env 키: 전용 `APP_*` 키는 없다. provider·destination이 map 구조라 배포의 `application-*.yml`에
|
||||
`app.object-storage.{default-destination, providers.<id>.*, destinations.<id>.*}`를 적는다(아래
|
||||
「Activation and routing」). 빠지면 기동 시 binding compile이 실패한다.
|
||||
「켜기와 라우팅」). 빠지면 기동 시 binding compile이 실패한다.
|
||||
|
||||
## Activation and routing
|
||||
## 켜기와 라우팅
|
||||
|
||||
The canonical namespace is `app.object-storage`. It is on when the module is present and off only
|
||||
with `app.object-storage.enabled=false`. On requires an explicit provider, exact provider version,
|
||||
logical destination, route token, binding/policy revisions, and bounded sizes. Settings compile fully before any selected provider creates a
|
||||
directory, client, thread, scheduler, or credential lookup.
|
||||
정해진 namespace는 `app.object-storage`다. 모듈이 있으면 켜지고 `app.object-storage.enabled=false`일 때만
|
||||
꺼진다. 켜려면 명시한 provider, 정확한 provider version, 논리 destination, route token, binding·policy
|
||||
revision, 한계 있는 크기가 필요하다. 고른 provider가 디렉터리, client, 스레드, scheduler, credential 조회를
|
||||
만들기 전에 설정을 모두 컴파일한다.
|
||||
|
||||
`filesystem-local-dev` is rejected under `prod`/`production`. Normal composition contributes only
|
||||
managed publication, inspection/transfer, retirement, and operation-resolution ports. Scanner
|
||||
maintenance composition stays separate. There is no purge or direct-grant port.
|
||||
`filesystem-local-dev`는 `prod`/`production`에서 거절한다. 보통 조립은 관리형 게시, 조회·전송, 폐기,
|
||||
operation 해석 포트만 기여한다. scanner 유지보수 조립은 따로 둔다. purge나 direct-grant 포트는 없다.
|
||||
|
||||
S3 retirement deletes the exact version a HEAD verified (`DeleteObject` with `versionId`). An
|
||||
`If-Match` condition on DELETE is not used: the qualified MinIO release ignores it (the MinIO lane
|
||||
shows a stale ETag still deleting), and the SDK documents it for directory buckets only. A version-id
|
||||
DELETE cannot touch an overwrite that landed after the HEAD, so it is conditional without relying on
|
||||
the vendor honouring a header. It needs a bucket with versioning enabled: an S3 operation profile
|
||||
that claims `CONDITIONAL_RETIREMENT` makes startup read `GetBucketVersioning` and refuse anything
|
||||
but `Enabled`, and a retire that finds no version id is refused rather than turned into a by-key
|
||||
delete.
|
||||
S3 폐기는 HEAD가 확인한 정확한 version을 지운다(`versionId`를 준 `DeleteObject`). DELETE에 `If-Match` 조건은
|
||||
쓰지 않는다: 검증한 MinIO 릴리스는 그것을 무시하고(MinIO lane에서 낡은 ETag로도 지워진다), SDK는 그것을
|
||||
directory bucket에만 적는다. version id를 준 DELETE는 HEAD 뒤에 들어온 덮어쓰기를 건드릴 수 없으니, vendor가
|
||||
header를 지키는지에 기대지 않고도 조건부다. versioning이 켜진 bucket이 필요하다: `CONDITIONAL_RETIREMENT`를
|
||||
주장하는 S3 operation profile은 기동 때 `GetBucketVersioning`을 읽고 `Enabled`가 아니면 거절한다. version id를
|
||||
찾지 못한 폐기는 키 기준 삭제로 바꾸지 않고 거절한다.
|
||||
|
||||
The local provider maps provider-neutral logical control keys to `.record` leaf files. This permits
|
||||
object-store-valid pairs such as `reference` and `reference/lifecycle` without a filesystem
|
||||
file/directory collision; callers and durable control records retain the canonical logical keys.
|
||||
로컬 provider는 provider 중립 논리 제어 키를 `.record` leaf 파일에 대응시킨다. 그래서 `reference`와
|
||||
`reference/lifecycle`처럼 object store에서는 맞는 짝이 파일 시스템의 파일·디렉터리 충돌 없이 함께 있을 수
|
||||
있다. 호출자와 durable 제어 레코드는 정규 논리 키를 그대로 가진다.
|
||||
|
||||
## Provider and dependency scope
|
||||
## provider와 의존 범위
|
||||
|
||||
The AWS SDK v2 BOM stays module-scoped because Spring Boot does not manage
|
||||
`software.amazon.awssdk:*`. The whole-`byte[]` `ObjectStoragePort` generation and its filesystem/S3
|
||||
adapters were removed; the canonical semantic ports are the only generation (recovery path in
|
||||
`docs/capability-status.md` 「제거된 코드」).
|
||||
Spring Boot가 `software.amazon.awssdk:*`를 관리하지 않으니 AWS SDK v2 BOM은 모듈 범위에 둔다. `byte[]` 전체를
|
||||
쓰던 `ObjectStoragePort` 세대와 그 파일 시스템·S3 어댑터는 지웠다. 정해진 semantic 포트가 유일한 세대다
|
||||
(되살리는 길은 `docs/capability-status.md` 「제거된 코드」).
|
||||
|
||||
## Verification
|
||||
## 검증
|
||||
|
||||
Focused contracts cover codecs/state machines, local provider behavior, fail-closed binding,
|
||||
composition side effects/lifecycle, routing replay/read behavior, and the readiness registry.
|
||||
이 모듈만 보는 계약이 codec·상태 기계, 로컬 provider 동작, 실패하면 닫히는 바인딩, 조립 부작용·lifecycle,
|
||||
라우팅 재생·읽기 동작, readiness registry를 덮는다.
|
||||
|
||||
```bash
|
||||
cd src
|
||||
./gradlew :adapter:outbound:objectstorage:check --console=plain
|
||||
```
|
||||
|
||||
### Provider contract for a new provider
|
||||
### 새 provider를 위한 provider 계약
|
||||
|
||||
`ObjectStorageProviderContract` is in this leaf's test fixtures, because the `ObjectStorageProvider`
|
||||
SPI is this leaf's own. The local-dev provider (`LocalDevObjectStorageProviderTest`) and the S3
|
||||
provider against MinIO (`MinioS3ManagedObjectProviderContractTest`) both extend it. A provider a
|
||||
derived service adds extends the same class instead of copying it:
|
||||
`ObjectStorageProvider` SPI가 이 leaf의 것이므로 `ObjectStorageProviderContract`는 이 leaf의 test fixtures에
|
||||
있다. local-dev provider(`LocalDevObjectStorageProviderTest`)와 MinIO에 대고 도는 S3 provider
|
||||
(`MinioS3ManagedObjectProviderContractTest`)가 모두 그것을 상속한다. 파생 서비스가 더하는 provider는 복사하지
|
||||
않고 같은 클래스를 상속한다:
|
||||
|
||||
```groovy
|
||||
testImplementation testFixtures(project(':adapter:outbound:objectstorage'))
|
||||
```
|
||||
|
||||
### MinIO qualification lanes
|
||||
### MinIO 검증 lane
|
||||
|
||||
`objectStorageMinioContractTest` and `objectStorageMinioFaultTest` run a real MinIO and Toxiproxy.
|
||||
They run in the root `integrationCheck` (main push and nightly) and in
|
||||
`.github/workflows/object-storage-qualification.yml` on pull requests that touch object storage —
|
||||
not in this leaf's `mainCheck`, which ran them a second time on every main push. Their images are read from one file,
|
||||
`src/test/resources/object-storage/minio-provider-evidence.json`, whose `image` digest is the
|
||||
release the `status`, `excludedProfiles` and `limitations` beside it were measured on.
|
||||
`MinioQualificationImage` (in `src/test`, checked by the leaf's `test` without Docker) reads it.
|
||||
`objectStorageMinioContractTest`와 `objectStorageMinioFaultTest`는 실제 MinIO와 Toxiproxy를 돌린다. 루트
|
||||
`integrationCheck`(main push와 nightly)와, object storage를 건드리는 pull request의
|
||||
`.github/workflows/object-storage-qualification.yml`에서 돈다 — 이 leaf의 `mainCheck`에서는 돌지 않는다.
|
||||
거기서는 main push마다 두 번 돌았다. image는 파일 하나
|
||||
`src/test/resources/object-storage/minio-provider-evidence.json`에서 읽는다. 그 `image` digest는 옆에 적힌
|
||||
`status`, `excludedProfiles`, `limitations`를 잰 릴리스다. `MinioQualificationImage`(`src/test`에 있고, leaf의
|
||||
`test`가 Docker 없이 검사한다)가 그것을 읽는다.
|
||||
|
||||
- The image is pulled before any container is built. If it cannot be pulled the lane fails with
|
||||
`pinned image unavailable: <reference>`: a supply failure, not an adapter defect. The lane does
|
||||
not skip, because a skipped vendor lane would be green with no vendor evidence.
|
||||
- A mirror of the same digest is set with `OBJECT_STORAGE_MINIO_IMAGE` or
|
||||
`-PobjectStorageMinioImage=<registry>/<repo>@sha256:<evidence digest>`. A value that does not end
|
||||
in the evidence digest is refused: a different build is a new measurement, made by re-running the
|
||||
lanes and rewriting the evidence file (image and findings together).
|
||||
- The local compose runtime (`compose.yaml`, and the compose lanes' smoke client in `src/app-bootstrap/compose-lanes/lane-services.yaml`; `LOCAL_MINIO_IMAGE`) uses the same digest.
|
||||
`ComposeMinioImageMatchesEvidenceTest` (leaf `test`) fails when the compose default and the
|
||||
evidence disagree; change both together.
|
||||
- The contract lane also runs `MinioS3ManagedObjectProviderContractTest`: the S3 adapter itself under
|
||||
the provider contract the local-dev provider inherits, on the production client factory, over TLS
|
||||
with a certificate made for the run (a binding only accepts HTTPS). Its first run found two adapter
|
||||
defects the mocked unit tests could not: every create failed because the SDK cancels the request
|
||||
body once it holds Content-Length bytes (and at once for an empty body), and every read with a
|
||||
consumer chunk below the network buffer size failed because Netty delivers 8 KiB buffers. Both
|
||||
are fixed (`S3AsyncRequestBodyBridge`, `S3AsyncResponseBodyBridge.TRANSPORT_BUFFER_CEILING_BYTES`).
|
||||
- container를 만들기 전에 image를 받는다. 받지 못하면 lane은 `pinned image unavailable: <reference>`로
|
||||
실패한다: 어댑터 결함이 아니라 공급 실패다. lane은 건너뛰지 않는다. 건너뛴 vendor lane은 vendor 증거 없이
|
||||
초록이 되기 때문이다.
|
||||
- 같은 digest의 mirror는 `OBJECT_STORAGE_MINIO_IMAGE`나
|
||||
`-PobjectStorageMinioImage=<registry>/<repo>@sha256:<evidence digest>`로 정한다. 증거 digest로 끝나지 않는
|
||||
값은 거절한다: 다른 build는 새 측정이고, lane을 다시 돌려 증거 파일(image와 측정 결과를 함께)을 다시 써서
|
||||
만든다.
|
||||
- 로컬 compose 런타임(`compose.yaml`, 그리고 compose lane의 smoke client
|
||||
`src/app-bootstrap/compose-lanes/lane-services.yaml`. `LOCAL_MINIO_IMAGE`)도 같은 digest를 쓴다.
|
||||
`ComposeMinioImageMatchesEvidenceTest`(leaf `test`)는 compose 기본값과 증거가 다르면 실패한다. 둘을 함께
|
||||
바꾼다.
|
||||
- contract lane은 `MinioS3ManagedObjectProviderContractTest`도 돌린다: S3 어댑터 자체를 local-dev provider가
|
||||
상속하는 provider 계약 아래에서, 운영 client factory로, 그 실행을 위해 만든 인증서로 TLS 위에서 시험한다
|
||||
(binding은 HTTPS만 받는다). 첫 실행에서 mock 단위 시험이 찾지 못한 어댑터 결함 둘을 찾았다: SDK가
|
||||
Content-Length 바이트를 받으면 요청 body를 취소해서(빈 body이면 바로) 모든 생성이 실패했고, Netty가 8 KiB
|
||||
buffer로 넘겨서 network buffer 크기보다 작은 소비자 chunk로 하는 모든 읽기가 실패했다. 둘 다 고쳤다
|
||||
(`S3AsyncRequestBodyBridge`, `S3AsyncResponseBodyBridge.TRANSPORT_BUFFER_CEILING_BYTES`).
|
||||
|
||||
#### Image source (review 05-09, measured 2026-11-02)
|
||||
#### image 출처 (review 05-09, 2026-11-02 측정)
|
||||
|
||||
Docker Hub `minio/minio` and `quay.io/minio/minio` stopped serving MinIO, so the measured digest of
|
||||
the old release (2024-01-16) could not be mirrored. Two maintained builds were pulled and measured
|
||||
with the same requests (create-only PUT twice, stale and current `If-Match` PUT, create-only
|
||||
multipart completion onto an existing key, stale `If-Match` DELETE):
|
||||
Docker Hub `minio/minio`와 `quay.io/minio/minio`가 MinIO 제공을 멈춰서, 옛 릴리스(2024-01-16)의 측정한 digest를
|
||||
mirror할 수 없었다. 유지되는 build 둘을 받아 같은 요청(create-only PUT 두 번, 낡은·현재 `If-Match` PUT, 있는
|
||||
키 위의 create-only multipart 완료, 낡은 `If-Match` DELETE)으로 쟀다:
|
||||
|
||||
| Candidate | Result | Decision |
|
||||
| 후보 | 결과 | 결정 |
|
||||
| --- | --- | --- |
|
||||
| `pgsty/minio@sha256:b6bfe723…` (community fork on Docker Hub, `RELEASE.2026-08-04T00-00-00Z`) | 412 / 412, 200 / 412; DELETE ignores `If-Match` | **Chosen.** Named release tags, `pgsty/mc` with a shell for the compose bucket bootstrap, runs as root like the old image |
|
||||
| `cgr.dev/chainguard/minio@sha256:0a011000…` (`RELEASE.2026-10-23T20-06-51Z`) | Same results | Rejected: the free tier offers only a moving `latest` tag, it runs as uid 65532 (the compose volume would need re-owning), and `cgr.dev/chainguard/minio-client` has no shell |
|
||||
| `pgsty/minio@sha256:b6bfe723…`(Docker Hub의 커뮤니티 fork, `RELEASE.2026-08-04T00-00-00Z`) | 412 / 412, 200 / 412. DELETE는 `If-Match`를 무시한다 | **골랐다.** 이름 있는 릴리스 태그, compose bucket 준비용 셸이 있는 `pgsty/mc`, 옛 image처럼 root로 돈다 |
|
||||
| `cgr.dev/chainguard/minio@sha256:0a011000…`(`RELEASE.2026-10-23T20-06-51Z`) | 같은 결과 | 버렸다: 무료 등급은 움직이는 `latest` 태그만 주고, uid 65532로 돌며(compose volume 소유자를 바꿔야 한다), `cgr.dev/chainguard/minio-client`에는 셸이 없다 |
|
||||
|
||||
The new release refuses create-only overwrites, which the old one accepted. So the evidence is now
|
||||
`status: SUPPORTED` for the managed create-only profiles (`supportedProfiles`), the direct
|
||||
(presigned) profiles stay excluded because they were not measured, and the adapter allowlist gained
|
||||
the provider type `s3-compatible-minio-pgsty-release-2026-08-04t00-00-00z` (version
|
||||
`release-2026-08-04t00-00-00z-sdk-2.30.0`). Only that release may claim `IMMUTABLE_CREATE`; no MinIO
|
||||
release may claim `MULTI_NODE_LINEARIZABLE_CAS` or `RESPONSE_LOSS_RESOLUTION`, because the evidence
|
||||
is one single-node container. The 2024-01-16 type stays for servers that still run it, with its
|
||||
old restrictions.
|
||||
새 릴리스는 옛 릴리스가 받아 주던 create-only 덮어쓰기를 거절한다. 그래서 증거는 이제 관리형 create-only
|
||||
profile(`supportedProfiles`)에 대해 `status: SUPPORTED`이고, direct(presigned) profile은 재지 않았으니 계속
|
||||
빠지며, 어댑터 허용 목록에 provider 타입 `s3-compatible-minio-pgsty-release-2026-08-04t00-00-00z`(version
|
||||
`release-2026-08-04t00-00-00z-sdk-2.30.0`)가 더해졌다. 그 릴리스만 `IMMUTABLE_CREATE`를 주장할 수 있다. 증거가
|
||||
단일 노드 container 하나이므로 어떤 MinIO 릴리스도 `MULTI_NODE_LINEARIZABLE_CAS`나 `RESPONSE_LOSS_RESOLUTION`을
|
||||
주장할 수 없다. 2024-01-16 타입은 아직 그것을 돌리는 서버를 위해 옛 제한과 함께 남는다.
|
||||
|
||||
The compose client `minio-init` uses `pgsty/mc` by digest (`LOCAL_MINIO_MC_IMAGE` overrides it).
|
||||
compose client `minio-init`은 digest로 `pgsty/mc`를 쓴다(`LOCAL_MINIO_MC_IMAGE`가 덮어쓴다).
|
||||
|
||||
```bash
|
||||
cd src
|
||||
|
||||
@@ -1,67 +1,59 @@
|
||||
# persistence-fileserver
|
||||
|
||||
Relational persistence for the Fileserver capability: entities, Spring Data repositories and the
|
||||
store adapters that implement `application-fileserver` ports. Root `AGENTS.md` and
|
||||
`adapter/outbound/persistence-jpa/CLAUDE.md` still apply; this file adds what is local.
|
||||
파일 서버 capability의 관계형 영속이다: 엔티티, Spring Data repository, `application-fileserver` 포트를 구현하는
|
||||
store 어댑터. 루트 `AGENTS.md`와 `adapter/outbound/persistence-jpa/CLAUDE.md`도 그대로 적용된다. 이 파일은 이
|
||||
leaf에만 있는 것을 더한다.
|
||||
|
||||
## Packages
|
||||
## 패키지
|
||||
|
||||
- `entity/` — JPA rows only. Every entity extends `AssignedIdEntity`.
|
||||
- `repository/` — Spring Data interfaces and the SQL text they run (`CleanupClaimSql`).
|
||||
- package root — the store adapters (`Jpa*`), `FileEntityMapper`, and the `@Configuration`
|
||||
classes that register them as beans.
|
||||
- `entity/` — JPA 행만. 모든 엔티티는 `AssignedIdEntity`를 상속한다.
|
||||
- `repository/` — Spring Data 인터페이스와 그것이 돌리는 SQL 글(`CleanupClaimSql`).
|
||||
- 패키지 루트 — store 어댑터(`Jpa*`), `FileEntityMapper`, 그것들을 bean으로 등록하는 `@Configuration`
|
||||
클래스.
|
||||
|
||||
`persistence-notification` follows the same rule (`platform.entity`, `platform.repository`, adapters
|
||||
in `platform`), so the two capability leaves read the same way.
|
||||
`persistence-notification`도 같은 규칙(`platform.entity`, `platform.repository`, 어댑터는 `platform`)을
|
||||
따르므로 두 capability leaf를 같은 방식으로 읽는다.
|
||||
|
||||
## Rules
|
||||
## 규칙
|
||||
|
||||
- **Transactions.** A store never opens one. Every write starts with
|
||||
`CallerTransaction.require("<store> <operation>")`, so a use case that forgot
|
||||
`TransactionPort.inWrite` fails instead of committing statement by statement.
|
||||
- **New rows.** Ids are assigned before the insert, so an entity must say whether it is new:
|
||||
extend `AssignedIdEntity` (`Persistable<UUID>`). Without it `save` merges — a SELECT before every
|
||||
insert, and a second insert under an existing id overwrites the row instead of failing on the
|
||||
primary key. A new `@Version` column may stay primitive `long`; newness comes from
|
||||
`Persistable`, not from the version.
|
||||
- **No policy here.** Retry budgets, lease lengths and other decisions belong to
|
||||
`application-fileserver` and arrive as port arguments. A claim token or other fence travels in
|
||||
the port type (`CleanupItem.claimToken`), never in a field of the adapter.
|
||||
- **Claims.** A queue claim is one statement: CTE + `FOR UPDATE SKIP LOCKED` + `RETURNING`
|
||||
(`CleanupClaimSql`). Settlements match the claim token and update zero rows for a stale worker.
|
||||
- **트랜잭션.** store는 트랜잭션을 열지 않는다. 모든 쓰기는 `CallerTransaction.require("<store> <operation>")`로
|
||||
시작한다. 그래서 `TransactionPort.inWrite`를 잊은 유스케이스는 문장마다 커밋하지 않고 실패한다.
|
||||
- **새 행.** id를 insert 전에 정하므로 엔티티가 새것인지 스스로 말해야 한다: `AssignedIdEntity`
|
||||
(`Persistable<UUID>`)를 상속한다. 그렇지 않으면 `save`가 merge한다 — insert마다 SELECT가 앞서고, 이미 있는 id로
|
||||
하는 두 번째 insert가 primary key에서 실패하지 않고 행을 덮어쓴다. 새 `@Version` 열은 primitive `long`으로 둬도
|
||||
된다. 새것인지는 version이 아니라 `Persistable`이 정한다.
|
||||
- **여기에 정책을 두지 않는다.** 재시도 예산, lease 길이 같은 판단은 `application-fileserver`의 것이고 포트
|
||||
인자로 온다. claim token 같은 fence는 어댑터 필드가 아니라 포트 타입(`CleanupItem.claimToken`)에 실려 다닌다.
|
||||
- **claim.** queue claim은 문장 하나다: CTE + `FOR UPDATE SKIP LOCKED` + `RETURNING`(`CleanupClaimSql`). 마무리
|
||||
처리는 claim token을 맞춰 보고, 낡은 worker이면 0행을 update한다.
|
||||
|
||||
## Migrations
|
||||
## migration
|
||||
|
||||
- `src/main/resources/db/migration/jpa/fileserver/V*.sql`, applied as the capability's own Flyway
|
||||
stream (`flyway_jpa_fileserver_history`).
|
||||
- An applied file is never edited. Add a new version and its hash to the immutability list;
|
||||
`persistence-jpa`'s `AppliedMigrationImmutabilityTest` pins these files where they live.
|
||||
- `src/main/resources/db/migration/jpa/fileserver/V*.sql`. capability 자신의 Flyway stream
|
||||
(`flyway_jpa_fileserver_history`)으로 적용한다.
|
||||
- 적용한 파일은 고치지 않는다. 새 버전과 그 hash를 불변 목록에 더한다. `persistence-jpa`의
|
||||
`AppliedMigrationImmutabilityTest`가 이 파일들을 있는 자리에서 고정한다.
|
||||
|
||||
## Tests
|
||||
## 테스트
|
||||
|
||||
- `src/test` — this leaf's own tests, no container. Run:
|
||||
- `src/test` — container 없는 이 leaf 자신의 시험. 돌리기:
|
||||
`./gradlew :adapter:outbound:persistence-fileserver:test --console=plain`.
|
||||
- `FileserverStoreCallerTransactionTest` — every guarded write of every store refuses without a
|
||||
caller transaction before it touches a repository (the Transactions rule above, one case per
|
||||
write; Spring Data repositories are mocks).
|
||||
- `FileserverPersistenceActivationTest` — the scan covers this package only, behind
|
||||
`app.fileserver-platform.enabled`, and runs before the JPA root auto-configuration.
|
||||
- `repository.CleanupClaimSqlTest` — the claim's text keeps its one-statement shape (the Claims
|
||||
rule); the locking itself is checked on PostgreSQL by
|
||||
`PostgreSqlFileserverReclamationIntegrationTest`.
|
||||
- `entity.AssignedIdEntityTest` — newness from `Persistable`, on Hibernate over H2.
|
||||
A new store write adds its case to the guard test; a new auto-configuration adds its line to the
|
||||
activation test.
|
||||
- Port contracts live in `application-fileserver` testFixtures (`*PortContract`, and
|
||||
`FileQuotaLedgerContract` for the three quota ports, which share one table). The in-memory fakes
|
||||
and the PostgreSQL tests both extend them; every port this leaf implements has one
|
||||
(`docs/testing/TESTING_STRATEGY.md` 9.3). The PostgreSQL side of the seven added on
|
||||
2026-11-03 is tagged `jpa-contract` and runs in persistence-jpa's
|
||||
`jpaPlatformContractTest` lane on `FileserverPostgreSqlStack`, whose clock a case moves.
|
||||
- The real-PostgreSQL tests are still in `persistence-jpa`'s `postgresqlIntegrationTest` source
|
||||
set, which owns the container and Flyway wiring, and the JPA readiness card
|
||||
(`persistence-jpa/release/readiness-cards.yaml`, checked by `JpaReadinessRegistryTest`) names them as that
|
||||
leaf's tasks — moving them means moving the card's tasks and selectors with them:
|
||||
`postgresqlFileserverMigrationIntegrationTest`, `postgresqlFileserverMetadataIntegrationTest`,
|
||||
`postgresqlFileserverReclamationIntegrationTest`
|
||||
- `FileserverStoreCallerTransactionTest` — 모든 store의 보호된 쓰기는 호출자 트랜잭션이 없으면 repository에
|
||||
닿기 전에 거절한다(위 트랜잭션 규칙, 쓰기마다 경우 하나. Spring Data repository는 mock이다).
|
||||
- `FileserverPersistenceActivationTest` — scan은 `app.fileserver-platform.enabled` 뒤에서 이 패키지만 덮고,
|
||||
JPA 루트 자동 구성보다 먼저 돈다.
|
||||
- `repository.CleanupClaimSqlTest` — claim 글이 문장 하나 모양을 지킨다(claim 규칙). 잠금 자체는
|
||||
`PostgreSqlFileserverReclamationIntegrationTest`가 PostgreSQL에서 본다.
|
||||
- `entity.AssignedIdEntityTest` — H2 위의 Hibernate에서 `Persistable`로 새것인지 정한다.
|
||||
새 store 쓰기는 보호 시험에 자기 경우를 더한다. 새 자동 구성은 켜기 시험에 자기 줄을 더한다.
|
||||
- 포트 계약은 `application-fileserver` testFixtures에 있다(`*PortContract`, 그리고 테이블 하나를 같이 쓰는 quota
|
||||
포트 셋의 `FileQuotaLedgerContract`). 메모리 fake와 PostgreSQL 시험이 모두 그것을 상속한다. 이 leaf가 구현하는
|
||||
포트는 모두 계약이 있다(`docs/testing/TESTING_STRATEGY.md` 9.3절). 2026-11-03에 더한 일곱 개의 PostgreSQL
|
||||
쪽은 `jpa-contract` tag를 달고 persistence-jpa의 `jpaPlatformContractTest` lane에서
|
||||
`FileserverPostgreSqlStack` 위에 돈다. 경우마다 그 시계를 옮긴다.
|
||||
- 실제 PostgreSQL 시험은 아직 `persistence-jpa`의 `postgresqlIntegrationTest` source set에 있다. 그 source set이
|
||||
container와 Flyway 배선을 가지고, JPA readiness card(`persistence-jpa/release/readiness-cards.yaml`,
|
||||
`JpaReadinessRegistryTest`가 검사)가 그 시험을 그 leaf의 태스크로 이름 댄다 — 옮기려면 card의 태스크와
|
||||
selector도 함께 옮겨야 한다: `postgresqlFileserverMigrationIntegrationTest`,
|
||||
`postgresqlFileserverMetadataIntegrationTest`, `postgresqlFileserverReclamationIntegrationTest`
|
||||
(`./gradlew :adapter:outbound:persistence-jpa:<lane> --console=plain`).
|
||||
|
||||
@@ -1,112 +1,96 @@
|
||||
# adapter:outbound:persistence-jpa — JPA/PostgreSQL persistence adapter
|
||||
# adapter:outbound:persistence-jpa — JPA·PostgreSQL 영속 어댑터
|
||||
|
||||
## Registered identity
|
||||
## 등록 정보
|
||||
|
||||
- Module ID: `adapter-outbound-persistence-jpa`
|
||||
- Gradle path: `:adapter:outbound:persistence-jpa`
|
||||
- Focused test (derived from Gradle path): `./gradlew :adapter:outbound:persistence-jpa:test --console=plain`
|
||||
- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0.
|
||||
- Registry SSOT: `src/config/architecture/modules.json`.
|
||||
- 모듈 ID: `adapter-outbound-persistence-jpa`
|
||||
- Gradle 경로: `:adapter:outbound:persistence-jpa`
|
||||
- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :adapter:outbound:persistence-jpa:test --console=plain`
|
||||
- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다.
|
||||
- registry 정본: `src/config/architecture/modules.json`.
|
||||
|
||||
Package root: `dev.caskeleton.adapter.outbound.persistence`.
|
||||
패키지 루트: `dev.caskeleton.adapter.outbound.persistence`.
|
||||
|
||||
Design decisions previously kept as code comments (transaction templates, auditing capture,
|
||||
failure-translation SPI, idempotency/outbox concurrency, distributed-lock TTL) live in
|
||||
[README.md](README.md). This file stays the SSOT for module rules and contract tables.
|
||||
예전에 코드 주석으로 두던 설계 결정(트랜잭션 template, 감사 값 잡기, 실패 번역 SPI, 멱등성·outbox 동시성, 분산
|
||||
lock TTL)은 [README.md](README.md)에 있다. 이 파일은 모듈 규칙과 계약 표의 정본으로 남는다.
|
||||
|
||||
This module is the RDBMS/JPA implementation base. It is not a datastore-neutral
|
||||
core for MongoDB, Redis, DynamoDB, or other NoSQL stores. Future NoSQL persistence
|
||||
adapters implement application/domain ports directly and must not depend on this module.
|
||||
이 모듈은 RDBMS·JPA 구현 기반이다. MongoDB, Redis, DynamoDB나 다른 NoSQL 저장소를 위한 저장소 중립 core가 아니다.
|
||||
앞으로의 NoSQL 영속 어댑터는 application·domain 포트를 직접 구현하고 이 모듈에 의존하면 안 된다.
|
||||
|
||||
## JPA relational persistence platform
|
||||
## JPA 관계형 영속 플랫폼
|
||||
|
||||
The platform in `docs/design/2026-08-11-jpa-persistence-platform-design.md` is
|
||||
implemented here. The design models it as 18 Stable library modules; this repository's fail-closed
|
||||
registry outranks that layout, so those modules are **packages** in this leaf and
|
||||
`docs/jpa/repository-adaptation.md` records the mapping. Read it before moving a type between
|
||||
packages.
|
||||
`docs/design/2026-08-11-jpa-persistence-platform-design.md`의 플랫폼을 여기 구현했다. 설계는 그것을 Stable 라이브러리
|
||||
모듈 18개로 모델링한다. 이 저장소의 실패하면 닫히는 registry가 그 배치보다 앞서므로, 그 모듈들은 이 leaf의
|
||||
**패키지**이고 `docs/jpa/repository-adaptation.md`가 그 대응을 적는다. 타입을 다른 패키지로 옮기기 전에 그것을 읽는다.
|
||||
|
||||
| Platform package | Owns |
|
||||
| 플랫폼 패키지 | 가지는 것 |
|
||||
|---|---|
|
||||
| `autoconfigure` | package-private Boot composition root/runtime: vendor and optional-store imports and provider runtime beans. It is intentionally not exported as public API |
|
||||
| `api` (+ `.capability`, `.error`, `.query`, `.transaction`) | framework-free contracts: operation and query names, the stable error hierarchy, commit-completion evidence, keyset cursors |
|
||||
| `transaction` | `SpringTransaction`, the one transaction engine (`TransactionPort` over Spring's `PlatformTransactionManager`) |
|
||||
| `springdata` | repository fragments, safe sort, fetch plans, keyset execution, stream guard |
|
||||
| `hibernate` (+ `.batch`, `.bulk`, `.stateless`) | statement inspector, statistics, batch, bulk DML, stateless session |
|
||||
| `postgresql` (+ `.error`, `.lock`, `.constraint`, `.json`, `.array`, `.range`, `.copy`) | SQLSTATE classification, lock options, JSONB, arrays and ranges, COPY |
|
||||
| `migration` | `FlywaySchemaPolicy` (composed by the `startup` package's dangerous-configuration guard) |
|
||||
| `startup` | package-private startup policy (`JpaStartupAutoConfiguration`): Flyway migration strategy, datasource env/product checks, OSIV/DDL/Hikari/TLS/H2 guards, the `jpaplatform` actuator view, the readiness `db` contribution. Moved here from app-bootstrap |
|
||||
| `cache`, `envers`, `querydsl`, `security`, `observation` | opt-in library capabilities and the runtime-role verifier |
|
||||
| `experimental` | multi-tenancy, RLS, schema/database tenancy, read replica — library code a deployment constructs itself; no flag turns it on |
|
||||
| `testkit` (`src/testFixtures/java`) | ArchUnit rules, fixtures, query/plan assertions, PostgreSQL matrix, failure injection, Flyway validate gate, concurrent-index inspector and lock-wait inspector |
|
||||
| `autoconfigure` | package-private Boot 조립 루트·런타임: vendor와 선택 저장소 import, provider runtime bean. 일부러 공개 API로 내놓지 않는다 |
|
||||
| `api` (+ `.capability`, `.error`, `.query`, `.transaction`) | 프레임워크 없는 계약: operation·query 이름, 안정된 오류 계층, 커밋 완료 증거, keyset cursor |
|
||||
| `transaction` | `SpringTransaction`, 유일한 트랜잭션 엔진(Spring `PlatformTransactionManager` 위의 `TransactionPort`) |
|
||||
| `springdata` | repository fragment, 안전한 정렬, fetch plan, keyset 실행, stream guard |
|
||||
| `hibernate` (+ `.batch`, `.bulk`, `.stateless`) | statement inspector, 통계, batch, bulk DML, stateless session |
|
||||
| `postgresql` (+ `.error`, `.lock`, `.constraint`, `.json`, `.array`, `.range`, `.copy`) | SQLSTATE 분류, lock 옵션, JSONB, 배열과 범위, COPY |
|
||||
| `migration` | `FlywaySchemaPolicy`(`startup` 패키지의 위험 설정 guard가 조립한다) |
|
||||
| `startup` | package-private 기동 정책(`JpaStartupAutoConfiguration`): Flyway migration 전략, datasource env·제품 검사, OSIV·DDL·Hikari·TLS·H2 guard, `jpaplatform` actuator view, readiness `db` 기여. app-bootstrap에서 여기로 옮겼다 |
|
||||
| `cache`, `envers`, `querydsl`, `security`, `observation` | 골라 쓰는 라이브러리 capability와 runtime role 검증기 |
|
||||
| `experimental` | multi-tenancy, RLS, schema·database 테넌시, read replica — 배포가 스스로 만드는 라이브러리 코드. 켜는 flag가 없다 |
|
||||
| `testkit`(`src/testFixtures/java`) | ArchUnit 규칙, fixture, query·plan 단언, PostgreSQL 표, 장애 주입, Flyway validate gate, concurrent index inspector, lock-wait inspector |
|
||||
|
||||
`springdata`, `hibernate` (`.batch`, `.bulk`, `.stateless`, statement inspector), `postgresql`
|
||||
(`.error`, `.lock`, `.constraint`, `.json`, `.array`, `.range`, `.copy`), `api.query`, `envers`,
|
||||
`querydsl`, `cache`, `observation` and `experimental` are **library API**: no configuration composes
|
||||
them, and a service calls them from its own adapter leaf, which takes this leaf as `implementation`.
|
||||
The entry points and the test that proves each one are listed in [README.md](README.md)
|
||||
"라이브러리 API".
|
||||
`springdata`, `hibernate`(`.batch`, `.bulk`, `.stateless`, statement inspector), `postgresql`(`.error`, `.lock`,
|
||||
`.constraint`, `.json`, `.array`, `.range`, `.copy`), `api.query`, `envers`, `querydsl`, `cache`, `observation`,
|
||||
`experimental`은 **라이브러리 API**다: 어떤 설정도 그것을 조립하지 않고, 서비스가 이 leaf를 `implementation`으로 받는
|
||||
자기 어댑터 leaf에서 부른다. 진입점과 각각을 증명하는 시험은 [README.md](README.md) 「라이브러리 API」에 있다.
|
||||
|
||||
### Spring composition ownership
|
||||
### Spring 조립 소유
|
||||
|
||||
`META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports` publishes two
|
||||
package-private entries: `PersistenceJpaAutoConfiguration` and `PersistenceJpaRuntimeConfig`.
|
||||
Because Boot loads those candidates independently, **both** require
|
||||
`app.persistence-jpa.enabled=true`. The first owns vendor/entity/repository and
|
||||
capability-store imports. The second contributes only the provider runtime beans
|
||||
(`HibernateProviderPolicy`, `PostgreSqlRuntimeRoleVerifier`). The
|
||||
transaction engine is `SpringTransaction` alone; the second engine
|
||||
(`SpringJpaTransactionExecutor`/`FullTransactionRetryCoordinator`) was removed on 2026-09-25 — see
|
||||
`docs/capability-status.md`. Never rely on the first candidate's condition to gate the sibling
|
||||
import candidate.
|
||||
`META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`는 package-private 항목 둘을 내놓는다:
|
||||
`PersistenceJpaAutoConfiguration`과 `PersistenceJpaRuntimeConfig`. Boot가 그 후보를 따로따로 읽으므로 **둘 다**
|
||||
`app.persistence-jpa.enabled=true`를 요구한다. 첫째는 vendor·entity·repository와 capability 저장소 import를 가진다.
|
||||
둘째는 provider runtime bean(`HibernateProviderPolicy`, `PostgreSqlRuntimeRoleVerifier`)만 기여한다. 트랜잭션 엔진은
|
||||
`SpringTransaction` 하나뿐이다. 두 번째 엔진(`SpringJpaTransactionExecutor`/`FullTransactionRetryCoordinator`)은
|
||||
2026-09-25에 지웠다 — `docs/capability-status.md`를 본다. 첫째 후보의 조건이 이웃 import 후보를 막아 준다고 기대지
|
||||
않는다.
|
||||
|
||||
`enabled=false` is a full off, not a bean-only one: `JpaActivationEnvironmentPostProcessor` (this
|
||||
leaf's `spring.factories`) appends Boot's `jdbc`/`hibernate`/`data.jpa`/`flyway` auto-configurations
|
||||
to `spring.autoconfigure.exclude`, so no DataSource, pool, EntityManagerFactory or Flyway exists.
|
||||
`enabled=false`는 bean만이 아니라 완전히 끄기다: `JpaActivationEnvironmentPostProcessor`(이 leaf의 `spring.factories`)가
|
||||
Boot의 `jdbc`/`hibernate`/`data.jpa`/`flyway` 자동 구성을 `spring.autoconfigure.exclude`에 붙인다. 그래서 DataSource,
|
||||
pool, EntityManagerFactory, Flyway가 하나도 없다.
|
||||
|
||||
The same split applies to owner-safe PostgreSQL idempotency: this leaf constructs the concrete
|
||||
PostgreSQL store behind `IdempotencyStorePort` (`PostgreSqlIdempotencyStoreConfig`, active only with
|
||||
`app.capabilities.idempotency.provider=postgresql`), while `composition:idempotency` owns provider
|
||||
selection, TTL/lease/codec policy, executor construction, and exclusivity validation. With that
|
||||
provider the leaf also applies the `db/migration/jpa/core` + `db/migration/jpa/idempotency` Flyway
|
||||
streams and activates the capability registry row at startup (`IdempotencySchemaStream`, skipped
|
||||
when `app.runtime.migration-on-startup=false`), refuses a non-PostgreSQL data source, and
|
||||
runs `IdempotencyReaper`. There is no V1/JDBC idempotency store and no `jdbc` provider value.
|
||||
소유자를 안전하게 지키는 PostgreSQL 멱등성도 같은 분할을 쓴다: 이 leaf는 `IdempotencyStorePort` 뒤의 실제 PostgreSQL
|
||||
store를 만들고(`PostgreSqlIdempotencyStoreConfig`, `app.capabilities.idempotency.provider=postgresql`일 때만 켜진다),
|
||||
`composition:idempotency`가 provider 고르기, TTL·lease·codec 정책, executor 만들기, 배타성 검증을 가진다. 그 provider를
|
||||
고르면 leaf는 `db/migration/jpa/core` + `db/migration/jpa/idempotency` Flyway stream도 적용하고 기동 때 capability
|
||||
registry 행을 켜며(`IdempotencySchemaStream`, `app.runtime.migration-on-startup=false`이면 건너뛴다), PostgreSQL이 아닌
|
||||
data source를 거절하고, `IdempotencyReaper`를 돌린다. V1·JDBC 멱등성 store도 `jdbc` provider 값도 없다.
|
||||
|
||||
This module is a capability selected by one build line (`runtimeOnly
|
||||
project(':adapter:outbound:persistence-jpa')`); the template's default composition does not carry it.
|
||||
Everything that only makes sense with a relational store therefore lives here and turns on with the
|
||||
module: migration startup sequencing, resolved datasource/version validation, OSIV/DDL/pool/TLS/vendor
|
||||
safety, the sanitized management endpoint/report (`startup`), the metered multi-instance lock
|
||||
(`lock`), the readiness `db` contribution and the shipped settings
|
||||
(`config/module-defaults/persistence-jpa.yml`). Use-case assembly does not: the outbox relay is
|
||||
`composition:outbox-relay` because a driven adapter must not construct or call a use case. The leaf must have
|
||||
zero imports from `dev.caskeleton.bootstrap`; startup failures go through `adapter:outbound:support`
|
||||
(`support.startup`), and new composition helpers stay package-private so `verifyJpaApiSurface` does
|
||||
not grow by wiring accident.
|
||||
이 모듈은 빌드 한 줄(`runtimeOnly project(':adapter:outbound:persistence-jpa')`)로 고르는 capability다. 템플릿의 기본
|
||||
조립은 이것을 싣지 않는다. 그래서 관계형 저장소가 있을 때만 뜻이 있는 것은 모두 여기 있고 모듈과 함께 켜진다:
|
||||
migration 기동 순서, 해석된 datasource·버전 검증, OSIV·DDL·pool·TLS·vendor 안전, 걸러 낸 관리 endpoint·보고
|
||||
(`startup`), metric을 단 다중 인스턴스 lock(`lock`), readiness `db` 기여, 출하하는 설정
|
||||
(`config/module-defaults/persistence-jpa.yml`). 유스케이스 조립은 아니다: driven 어댑터가 유스케이스를 만들거나 부르면
|
||||
안 되므로 outbox relay는 `composition:outbox-relay`다. leaf에는 `dev.caskeleton.bootstrap` import가 하나도 없어야 한다.
|
||||
기동 실패는 `adapter:outbound:support`(`support.startup`)를 거치고, 새 조립 도우미는 package-private로 둬서 배선
|
||||
실수로 `verifyJpaApiSurface`가 늘지 않게 한다.
|
||||
|
||||
### Non-negotiables
|
||||
### 양보할 수 없는 것
|
||||
|
||||
- No `GenericRepository<T, ID>` and no platform base repository. Domains own their repositories.
|
||||
- `TransactionCompletionUnknownException` is never retried. `JpaFailureContext` refuses to
|
||||
represent a retryable completion-unknown failure, and `SpringTransaction` retries nothing.
|
||||
- A caller that retries re-runs the whole use case in a new transaction and a new Persistence
|
||||
Context.
|
||||
- OSIV is false in every runtime profile; Flyway owns schema change and Hibernate only validates.
|
||||
- A migration that locks a table already in use starts with `SET LOCAL lock_timeout = '5s';`
|
||||
(`docs/jpa/migration-guide.md` "Bound the lock wait"). `MigrationLockWaitTest` refuses one
|
||||
without it. Its list of migrations released before the rule never takes a new migration; it
|
||||
grows only when the inspector learns a statement and finds it in a file already on `main`.
|
||||
- Flyway holds its PostgreSQL migration lock for the session, never in an open transaction, or a
|
||||
`CREATE INDEX CONCURRENTLY` migration waits for Flyway forever: `spring.flyway.postgresql.transactional-lock:
|
||||
false` in the module defaults, and every Flyway built in code starts from
|
||||
`FlywaySchemaPolicy.configure()` (`JpaProductionArchitectureTest` refuses `Flyway.configure()` and
|
||||
constructing a Flyway configuration directly — `new FluentConfiguration()`, `new
|
||||
ClassicConfiguration()`, a subclass; `docs/jpa/migration-guide.md` "Who may change the schema").
|
||||
- Metric tags, exception messages, and logs carry no SQL parameters, entity ids, tenant ids, or PII.
|
||||
- Contracts run against real PostgreSQL. H2 never satisfies one.
|
||||
- `GenericRepository<T, ID>`도 플랫폼 기반 repository도 없다. 도메인이 자기 repository를 가진다.
|
||||
- `TransactionCompletionUnknownException`은 절대 재시도하지 않는다. `JpaFailureContext`는 재시도할 수 있는
|
||||
completion-unknown 실패를 나타내기를 거절하고, `SpringTransaction`은 아무것도 재시도하지 않는다.
|
||||
- 재시도하는 호출자는 새 트랜잭션과 새 Persistence Context에서 유스케이스 전체를 다시 돌린다.
|
||||
- OSIV는 모든 runtime profile에서 false다. schema 변경은 Flyway가 가지고 Hibernate는 검증만 한다.
|
||||
- 이미 쓰이는 테이블을 잠그는 migration은 `SET LOCAL lock_timeout = '5s';`로 시작한다
|
||||
(`docs/jpa/migration-guide.md` "Bound the lock wait"). `MigrationLockWaitTest`가 그것이 없는 migration을 거절한다. 그
|
||||
규칙 전에 릴리스한 migration 목록에는 새 migration을 넣지 않는다. 그 목록은 inspector가 문장을 새로 배우고 이미
|
||||
`main`에 있는 파일에서 그것을 찾았을 때만 늘어난다.
|
||||
- Flyway는 PostgreSQL migration lock을 열린 트랜잭션이 아니라 세션 동안 쥔다. 아니면 `CREATE INDEX CONCURRENTLY`
|
||||
migration이 Flyway를 영원히 기다린다: 모듈 기본값의 `spring.flyway.postgresql.transactional-lock: false`, 그리고 코드에서
|
||||
만드는 모든 Flyway는 `FlywaySchemaPolicy.configure()`에서 시작한다(`JpaProductionArchitectureTest`가
|
||||
`Flyway.configure()`와 Flyway 설정을 직접 만드는 것 — `new FluentConfiguration()`, `new ClassicConfiguration()`, 하위
|
||||
클래스 — 을 거절한다. `docs/jpa/migration-guide.md` "Who may change the schema").
|
||||
- metric tag, 예외 메시지, 로그는 SQL 매개변수, entity id, tenant id, 개인정보를 싣지 않는다.
|
||||
- 계약은 실제 PostgreSQL에 대고 돈다. H2는 어떤 계약도 만족시키지 않는다.
|
||||
|
||||
### Platform lanes
|
||||
### 플랫폼 lane
|
||||
|
||||
```bash
|
||||
cd src
|
||||
@@ -126,164 +110,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
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -1,57 +1,52 @@
|
||||
# adapter:outbound:persistence-notification — notification relational persistence
|
||||
# adapter:outbound:persistence-notification — 알림 관계형 영속
|
||||
|
||||
## Registered identity
|
||||
## 등록 정보
|
||||
|
||||
- Module ID: `adapter-outbound-persistence-notification`; Gradle path and allowed edges are in
|
||||
`src/config/architecture/modules.json`.
|
||||
- Focused test: `./gradlew :adapter:outbound:persistence-notification:test --console=plain`.
|
||||
- Package root: `dev.caskeleton.adapter.outbound.persistence.notification`. The package rule is
|
||||
the one `persistence-fileserver` uses, so both capability leaves read the same way:
|
||||
- `platform.entity` — JPA rows only.
|
||||
- `platform.repository` — Spring Data interfaces and the SQL text they run (`RecipientClaimSql`).
|
||||
- `platform` — the store adapters (`Jpa*`, `Jdbc*`, the inbox's `JpaNotificationInbox` and its
|
||||
outbox helpers), `NotificationRecordMapper` and the payload codec.
|
||||
- `configuration` — the auto-configuration facade that registers the stores as beans; the leaf
|
||||
root holds the scan configuration and the schema stream.
|
||||
Entity constructors, accessors and mutators are public because the stores use them from another
|
||||
package; an entity never leaves the leaf (the ports carry records). Visibility no longer says so,
|
||||
so a rule does: `JpaArchitectureRules.entitiesAreUsedOnlyInsideTheirLeaf`, run over the production
|
||||
graph by `JpaProductionArchitectureTest` (app-bootstrap `architectureTest`) for this leaf and
|
||||
`persistence-fileserver`.
|
||||
- 모듈 ID: `adapter-outbound-persistence-notification`. Gradle 경로와 허용 edge는
|
||||
`src/config/architecture/modules.json`에 있다.
|
||||
- 이 모듈만 시험: `./gradlew :adapter:outbound:persistence-notification:test --console=plain`.
|
||||
- 패키지 루트: `dev.caskeleton.adapter.outbound.persistence.notification`. 패키지 규칙은
|
||||
`persistence-fileserver`와 같아서 두 capability leaf를 같은 방식으로 읽는다:
|
||||
- `platform.entity` — JPA 행만.
|
||||
- `platform.repository` — Spring Data 인터페이스와 그것이 돌리는 SQL 글(`RecipientClaimSql`).
|
||||
- `platform` — store 어댑터(`Jpa*`, `Jdbc*`, inbox의 `JpaNotificationInbox`와 그 outbox 도우미),
|
||||
`NotificationRecordMapper`, payload codec.
|
||||
- `configuration` — store를 bean으로 등록하는 자동 구성 창구. leaf 루트에는 scan 설정과 schema stream이 있다.
|
||||
엔티티 생성자·접근자·변경자는 store가 다른 패키지에서 쓰니 public이다. 엔티티는 leaf를 떠나지 않는다(포트는
|
||||
record를 싣는다). 가시성이 더는 그것을 말해 주지 않으므로 규칙이 말한다:
|
||||
`JpaArchitectureRules.entitiesAreUsedOnlyInsideTheirLeaf`를 `JpaProductionArchitectureTest`(app-bootstrap
|
||||
`architectureTest`)가 운영 그래프에 대고 이 leaf와 `persistence-fileserver`에 돌린다.
|
||||
|
||||
## Where the tests are
|
||||
## 시험은 어디 있나
|
||||
|
||||
| What | Where | Run |
|
||||
| 무엇 | 어디 | 돌리기 |
|
||||
|---|---|---|
|
||||
| Unit and wiring tests | this leaf, `src/test` | `:adapter:outbound:persistence-notification:test` |
|
||||
| Real PostgreSQL tests of these stores | `persistence-jpa`, `src/postgresqlIntegrationTest/.../persistence/notification` (that lane owns the container and Flyway wiring) | `:adapter:outbound:persistence-jpa:postgresqlIntegrationTest --tests '<class>'` |
|
||||
| Port contracts the stores must pass | `application-notification` testFixtures, `*.testkit.*Contract` (preference, suppression, deduplication, request, reconciliation job, admin operation, template registry, recipient lease, recipient delivery, delivery attempt, attempt resolver, delivery projection, provider event ledger, contact point, and the side effect over the contact point and suppression stores) | the in-memory fake (`application-notification` test) and the `PostgreSql*ContractTest` in `persistence-jpa` both extend the contract; `jpaPlatformContractTest` runs the PostgreSQL side |
|
||||
| Migration pins | `persistence-jpa/src/test/resources/db/applied-migrations.sha256` | `AppliedMigrationImmutabilityTest` in `:adapter:outbound:persistence-jpa:test` |
|
||||
| 단위·배선 시험 | 이 leaf, `src/test` | `:adapter:outbound:persistence-notification:test` |
|
||||
| 이 store들의 실제 PostgreSQL 시험 | `persistence-jpa`, `src/postgresqlIntegrationTest/.../persistence/notification`(그 lane이 container와 Flyway 배선을 가진다) | `:adapter:outbound:persistence-jpa:postgresqlIntegrationTest --tests '<class>'` |
|
||||
| store가 통과해야 하는 포트 계약 | `application-notification` testFixtures, `*.testkit.*Contract`(preference, suppression, deduplication, request, reconciliation job, admin operation, template registry, recipient lease, recipient delivery, delivery attempt, attempt resolver, delivery projection, provider event ledger, contact point, 그리고 contact point·suppression store 위의 부수 효과) | 메모리 fake(`application-notification` 시험)와 `persistence-jpa`의 `PostgreSql*ContractTest`가 모두 계약을 상속한다. PostgreSQL 쪽은 `jpaPlatformContractTest`가 돌린다 |
|
||||
| migration 고정 | `persistence-jpa/src/test/resources/db/applied-migrations.sha256` | `:adapter:outbound:persistence-jpa:test`의 `AppliedMigrationImmutabilityTest` |
|
||||
|
||||
A store whose port has a contract in `application-notification` testFixtures is tested by a
|
||||
PostgreSQL subclass of that contract, not by a separate hand-written PostgreSQL test. A case that is
|
||||
about the vendor (a CHECK constraint, `@Version` on a bulk update) stays in the subclass. The ports
|
||||
without a contract (the serving-state read model, consent, inbox), and why, are listed in
|
||||
`docs/testing/TESTING_STRATEGY.md` §9.2.
|
||||
`application-notification` testFixtures에 계약이 있는 포트의 store는 따로 손으로 쓴 PostgreSQL 시험이 아니라
|
||||
그 계약의 PostgreSQL 하위 클래스로 시험한다. vendor에 관한 경우(CHECK 제약, bulk update의 `@Version`)는 하위
|
||||
클래스에 남긴다. 계약이 없는 포트(serving-state 읽기 모델, 동의, inbox)와 그 이유는
|
||||
`docs/testing/TESTING_STRATEGY.md` 9.2절에 있다.
|
||||
|
||||
## Rules
|
||||
## 규칙
|
||||
|
||||
- **Every write joins the caller's transaction.** A store write starts with
|
||||
`CallerTransaction.require("<what>")`; the use case owns the transaction (owner decision 2026-09-25).
|
||||
- **Migrations** live in `src/main/resources/db/migration/jpa/notification-platform` and run as
|
||||
their own Flyway stream (`NotificationSchemaStream`, history table
|
||||
`flyway_jpa_notification_history`). An applied file is never edited: add the next `V<n>__`, pin
|
||||
its SHA-256 in `applied-migrations.sha256`, and add it to `NotificationFixtures.migrations()`.
|
||||
A migration that deletes rows states in a SQL comment which row survives and why. A migration
|
||||
that locks an existing table starts with `SET LOCAL lock_timeout = '5s';`
|
||||
(`docs/jpa/migration-guide.md` "Bound the lock wait"; `MigrationLockWaitTest` in persistence-jpa
|
||||
refuses one without it).
|
||||
- **Insert-or-update is decided by the database.** Never find-then-insert: insert with
|
||||
`ON CONFLICT (<unique key>) DO NOTHING`, and when it inserted nothing, update the existing row
|
||||
through the managed entity (`JpaSuppressionStore.upsert`, `JpaPolicyStores.Preferences.save`,
|
||||
`DeduplicationClaims.insertOrFind`). The conflict target needs a unique constraint in a migration.
|
||||
- **A bulk or native `UPDATE` of a `@Version` table advances the version** (`version = version + 1`)
|
||||
and is `@Modifying(clearAutomatically = true, flushAutomatically = true)` when the caller may
|
||||
re-read the row. `JpaVersionedBulkUpdateRule` (persistence-jpa testFixtures) enforces the
|
||||
version part in `:app-bootstrap:architectureTest`.
|
||||
- Repositories extend `Repository`, not `CrudRepository`, and expose only tenant-scoped finders.
|
||||
- **모든 쓰기는 호출자의 트랜잭션에 합류한다.** store 쓰기는 `CallerTransaction.require("<what>")`로
|
||||
시작한다. 트랜잭션은 유스케이스가 가진다(소유자 결정 2026-09-25).
|
||||
- **migration**은 `src/main/resources/db/migration/jpa/notification-platform`에 있고 자기 Flyway stream
|
||||
(`NotificationSchemaStream`, history 테이블 `flyway_jpa_notification_history`)으로 돈다. 적용한 파일은 고치지
|
||||
않는다: 다음 `V<n>__`를 더하고, 그 SHA-256을 `applied-migrations.sha256`에 고정하고,
|
||||
`NotificationFixtures.migrations()`에 더한다. 행을 지우는 migration은 어떤 행이 남고 왜인지 SQL 주석에
|
||||
적는다. 이미 있는 테이블을 잠그는 migration은 `SET LOCAL lock_timeout = '5s';`로 시작한다
|
||||
(`docs/jpa/migration-guide.md` "Bound the lock wait". persistence-jpa의 `MigrationLockWaitTest`가 그것이 없는
|
||||
migration을 거절한다).
|
||||
- **insert냐 update냐는 데이터베이스가 정한다.** 찾은 뒤 insert하지 않는다: `ON CONFLICT (<unique key>) DO
|
||||
NOTHING`으로 insert하고, 아무것도 insert하지 않았으면 관리되는 엔티티로 있는 행을 update한다
|
||||
(`JpaSuppressionStore.upsert`, `JpaPolicyStores.Preferences.save`, `DeduplicationClaims.insertOrFind`). 충돌
|
||||
대상에는 migration에 unique 제약이 있어야 한다.
|
||||
- **`@Version` 테이블의 bulk·native `UPDATE`는 version을 올린다**(`version = version + 1`). 호출자가 그 행을 다시
|
||||
읽을 수 있으면 `@Modifying(clearAutomatically = true, flushAutomatically = true)`다. version 부분은
|
||||
`JpaVersionedBulkUpdateRule`(persistence-jpa testFixtures)이 `:app-bootstrap:architectureTest`에서 강제한다.
|
||||
- repository는 `CrudRepository`가 아니라 `Repository`를 상속하고, 테넌트 범위의 finder만 내놓는다.
|
||||
|
||||
@@ -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`이 검증한다.
|
||||
|
||||
@@ -1,28 +1,25 @@
|
||||
# Redis SDK topology lanes
|
||||
# Redis SDK topology lane
|
||||
|
||||
These lanes exist to answer the questions the deterministic in-memory gateway cannot: how Lettuce
|
||||
actually behaves during a Sentinel promotion, what a Cluster resharding does to an in-flight
|
||||
command, and whether the ACL accounts grant exactly what the SDK issues.
|
||||
이 lane들은 결정적인 메모리 gateway가 답하지 못하는 질문에 답하려고 있다: Sentinel 승격 중에 Lettuce가 실제로
|
||||
어떻게 움직이는지, Cluster resharding이 진행 중인 명령에 무엇을 하는지, ACL 계정이 SDK가 내는 명령을 정확히
|
||||
허락하는지.
|
||||
|
||||
All four have now run on Redis 7.4 and the evidence is recorded in
|
||||
`docs/redis/support-matrix.md`. `.github/workflows/redis-sdk-topology.yml` runs the standalone lane
|
||||
on any pull request that touches the Redis leaf, the full supported-version x topology matrix
|
||||
nightly, and the same matrix on demand for a release candidate.
|
||||
넷 모두 Redis 7.4에서 돌았고 증거는 `docs/redis/support-matrix.md`에 적혀 있다.
|
||||
`.github/workflows/redis-sdk-topology.yml`은 Redis leaf를 건드리는 pull request마다 standalone lane을, 매일 밤
|
||||
지원 버전 × topology 표 전체를, 릴리스 후보에는 요청할 때 같은 표를 돌린다.
|
||||
|
||||
TLS is a lane of that matrix rather than something to wire up by hand. It is `tls`, not a
|
||||
deployment mode: its shape is standalone and what it qualifies is the transport, so
|
||||
`redisTopologyTest` maps the lane name to `standalone` for the tests and keeps the tag filter and
|
||||
the required trust material on the lane.
|
||||
TLS는 손으로 배선할 것이 아니라 그 표의 lane 하나다. 배포 모드가 아니라 `tls`다: 모양은 standalone이고 검증하는
|
||||
것은 전송이다. 그래서 `redisTopologyTest`는 시험에서 lane 이름을 `standalone`으로 대응시키고, tag 필터와 필요한
|
||||
신뢰 자료는 lane에 둔다.
|
||||
|
||||
## The TLS lane
|
||||
## TLS lane
|
||||
|
||||
`tls/compose.yml` is the standalone shape with the transport swapped. The plaintext port is turned
|
||||
off entirely (`--port 0`), which is the only configuration that proves anything: a lane accepting
|
||||
both would let a client that failed to negotiate TLS fall back silently and still pass.
|
||||
`tls/compose.yml`은 전송만 바꾼 standalone 모양이다. 평문 port는 완전히 끈다(`--port 0`). 이것만이 무언가를
|
||||
증명하는 설정이다: 둘 다 받는 lane이면 TLS 협상에 실패한 client가 소리 없이 물러서고도 통과할 수 있다.
|
||||
|
||||
Certificates are generated at start-up into a named volume rather than checked in — a private key
|
||||
in the repository is a private key in the repository, however the file is named — and they last a
|
||||
day, so a stale lane fails visibly instead of drifting.
|
||||
인증서는 저장소에 넣지 않고 기동 때 named volume 안에 만든다 — 파일 이름을 어떻게 붙이든 저장소 안의 개인
|
||||
키는 저장소 안의 개인 키다 — 그리고 하루 동안만 유효해서, 낡은 lane은 조용히 어긋나지 않고 눈에 띄게
|
||||
실패한다.
|
||||
|
||||
```bash
|
||||
REDIS_VERSION=7.4 docker compose -f src/adapter/outbound/redis-sdk/compose/tls/compose.yml up -d --wait
|
||||
@@ -33,43 +30,38 @@ cd src && ./gradlew :adapter:outbound:redis-runtime:redisTopologyTest \
|
||||
-Predis.topology.mode=tls -Predis.topology.trust-material=/tmp/redis-lane-ca.pem
|
||||
```
|
||||
|
||||
The lane refuses to run without `redis.topology.trust-material`. A TLS lane that trusts anything
|
||||
qualifies nothing, so "no CA configured" is an error rather than a client with verification off.
|
||||
lane은 `redis.topology.trust-material` 없이는 돌기를 거절한다. 아무것이나 믿는 TLS lane은 아무것도 검증하지
|
||||
않으니, 「CA를 설정하지 않음」은 검증을 끈 client가 아니라 오류다.
|
||||
|
||||
## The ACL fixture
|
||||
## ACL fixture
|
||||
|
||||
`acl/lane-fixture-accounts.acl` provisions the accounts every lane uses. Two things about it matter, and
|
||||
neither can be written in the file itself — **Redis refuses to start if an `aclfile` contains a
|
||||
comment line**, so the whole file is directives and the explanation lives here.
|
||||
`compose/redis/acl/lane-fixture-accounts.acl`이 모든 lane이 쓰는 계정을 만든다(각 lane의 `compose.yml`이 저장소
|
||||
루트의 그 폴더를 mount한다). 중요한 점이 둘인데, 둘 다 그 파일 안에 쓸 수 없다 — **`aclfile`에 주석 줄이 있으면
|
||||
Redis가 시작을 거절한다.** 그래서 파일 전체가 지시문이고 설명은 여기 있다.
|
||||
|
||||
`user default off` is the first line and is deliberate. Redis ships `default` enabled and
|
||||
passwordless; while it is on, every restriction in the remaining accounts can be bypassed by simply
|
||||
not authenticating, which makes the fixture decorative. Disabling it is what forces a client — and
|
||||
the compose healthchecks — to pick a named account.
|
||||
첫 줄 `user default off`는 일부러 둔 것이다. Redis는 `default`를 켜고 비밀번호 없이 내놓는다. 그것이 켜져 있는
|
||||
동안에는 인증하지 않기만 해도 나머지 계정의 모든 제한을 우회할 수 있어서 fixture가 장식이 된다. 그것을 꺼야
|
||||
client가 — 그리고 compose healthcheck가 — 이름 있는 계정을 고르게 된다.
|
||||
|
||||
Every named account carries a real password — `>fixture-application`, `>fixture-advanced`, and so
|
||||
on. They were `nopass`, which was the more dangerous kind of wrong: an account that accepts any
|
||||
password made every assertion about authentication pass for the same reason a typo would have, so
|
||||
the lane's coverage of AUTH, rotation and secret wiring was indistinguishable from no coverage.
|
||||
`LiveRedisCompositionTest` now presents a wrong password on purpose and requires `WRONGPASS`, which
|
||||
is only a meaningful assertion because the accounts enforce one.
|
||||
이름 있는 모든 계정에는 진짜 비밀번호가 있다 — `>fixture-application`, `>fixture-advanced` 같은 것이다. 예전에는
|
||||
`nopass`였고, 그것이 더 위험한 쪽의 잘못이었다: 아무 비밀번호나 받는 계정에서는 인증에 대한 모든 단언이 오타가
|
||||
있어도 통과할 이유로 통과했다. 그래서 lane이 AUTH, 교체, 비밀 값 배선을 덮는 것과 덮지 않는 것을 구별할 수
|
||||
없었다. `LiveRedisCompositionTest`는 이제 일부러 틀린 비밀번호를 내고 `WRONGPASS`를 요구한다. 계정이 비밀번호를
|
||||
강제하기 때문에 뜻이 있는 단언이다.
|
||||
|
||||
The passwords are fixture values in a throwaway container and are **not** a deployment template: a
|
||||
real deployment resolves each account's credential through `secret://` and never writes one into
|
||||
configuration.
|
||||
이 비밀번호는 버리는 container 안의 fixture 값이고 배포 template이 **아니다**: 실제 배포는 계정마다 credential을
|
||||
`secret://`로 해석하고 설정에 쓰지 않는다.
|
||||
|
||||
The accounts are also split by role, because that is how the SDK uses them. `ca-skeleton-application`
|
||||
runs ordinary data commands and cannot execute a script; `ca-skeleton-application-advanced` holds
|
||||
`SCRIPT LOAD` and `EVALSHA` and nothing else needs to. That separation is real rather than
|
||||
decorative: `LiveRedisSemanticPortsTest` runs the rate limiter without the advanced account and
|
||||
requires it to come back `Unavailable`.
|
||||
계정은 role로도 나뉜다. SDK가 그렇게 쓰기 때문이다. `ca-skeleton-application`은 보통 데이터 명령을 돌리고
|
||||
script를 실행할 수 없다. `ca-skeleton-application-advanced`는 `SCRIPT LOAD`와 `EVALSHA`를 가지고, 다른 계정은 그것이
|
||||
필요 없다. 이 분리는 장식이 아니라 실제다: `LiveRedisSemanticPortsTest`는 advanced 계정 없이 rate limiter를 돌리고
|
||||
그것이 `Unavailable`로 돌아오기를 요구한다.
|
||||
|
||||
## Running one
|
||||
## 하나 돌리기
|
||||
|
||||
Each lane has its own endpoint, because the address a client is given is not the same kind of thing
|
||||
in each topology. Standalone declares a data node; Sentinel declares a *sentinel*, from which the
|
||||
primary is resolved and re-resolved when it is promoted; Cluster declares any node, from which the
|
||||
rest of the topology is discovered.
|
||||
lane마다 자기 endpoint가 있다. client에게 주는 주소가 topology마다 같은 종류가 아니기 때문이다. standalone은
|
||||
데이터 노드를 선언한다. Sentinel은 *sentinel*을 선언하고, 거기서 primary를 찾으며 승격되면 다시 찾는다. Cluster는
|
||||
아무 노드나 선언하고, 거기서 나머지 topology를 찾는다.
|
||||
|
||||
```bash
|
||||
# Standalone
|
||||
@@ -91,69 +83,61 @@ cd src && ./gradlew :adapter:outbound:redis-runtime:redisTopologyTest :adapter:o
|
||||
-Predis.topology.host=localhost -Predis.topology.port=7100 -Predis.topology.mode=cluster
|
||||
```
|
||||
|
||||
Each leaf owns the lanes its tests qualify, and names the classes each lane must run in its
|
||||
`build.gradle` (`redisTopologyLane { requiredClasses ... }`). Selecting a mode a leaf does not
|
||||
declare fails instead of running nothing, so run only the leaves listed for the lane:
|
||||
leaf마다 자기 시험이 검증하는 lane을 가지고, lane마다 돌아야 하는 클래스를 `build.gradle`에 적는다
|
||||
(`redisTopologyLane { requiredClasses ... }`). leaf가 선언하지 않은 모드를 고르면 아무것도 돌리지 않는 대신
|
||||
실패한다. 그러니 lane에 적힌 leaf만 돌린다:
|
||||
|
||||
| Lane | `redis-runtime` | `redis-sdk` | `cache-redis` |
|
||||
| lane | `redis-runtime` | `redis-sdk` | `cache-redis` |
|
||||
| --- | --- | --- | --- |
|
||||
| standalone | `LiveRedisCompositionTest` | `RedisTopologyContractTest`, `LiveRedisGuardrailTest` | `LiveRedisSemanticPortsTest`, `LiveRedisSemanticScriptAclProbeTest` |
|
||||
| sentinel | `LiveRedisCompositionTest` | `RedisTopologyContractTest`, `LiveRedisSentinelPromotionTest` | — |
|
||||
| cluster | `LiveRedisCompositionTest` | `LiveRedisClusterTest`, `LiveRedisClusterTransactionTest` | `LiveRedisSemanticPortsTest`, `LiveRedisSemanticScriptAclProbeTest` |
|
||||
| tls | `LiveRedisTlsTest` | — | — |
|
||||
|
||||
Tear a lane down with `docker compose -f src/adapter/outbound/redis-sdk/compose/<lane>/compose.yml down -v`.
|
||||
lane은 `docker compose -f src/adapter/outbound/redis-sdk/compose/<lane>/compose.yml down -v`로 내린다.
|
||||
|
||||
| Lane | Ports | Notes |
|
||||
| lane | port | 메모 |
|
||||
| --- | --- | --- |
|
||||
| standalone | 6379 | bridge network, published port |
|
||||
| sentinel | primary 7010, replica 7011, sentinels 27010–27012 | host network |
|
||||
| cluster | nodes 7100–7105, bus 17100–17105 | host network; `ready` gates on `cluster_state:ok` |
|
||||
| tls | 6390 | published port, no plaintext port at all; CA generated per run |
|
||||
| standalone | 6379 | bridge network, 내놓은 port |
|
||||
| sentinel | primary 7010, replica 7011, sentinel 27010–27012 | host network |
|
||||
| cluster | 노드 7100–7105, bus 17100–17105 | host network. `ready`가 `cluster_state:ok`를 기다린다 |
|
||||
| tls | 6390 | 내놓은 port, 평문 port는 아예 없음. 실행마다 CA를 만든다 |
|
||||
|
||||
## Why the Sentinel and Cluster lanes use host networking
|
||||
## Sentinel과 Cluster lane이 host network를 쓰는 이유
|
||||
|
||||
Neither topology proxies. Sentinel answers `SENTINEL get-master-addr-by-name` with the address it
|
||||
monitors and the client dials that itself; a cluster client reads `CLUSTER SHARDS` and connects to
|
||||
every node it names. On a bridge network those are container-internal addresses, so a client on the
|
||||
host resolves a topology it cannot reach — and after a promotion it resolves a *different* one it
|
||||
also cannot reach. Sharing the host network namespace makes the address the topology advertises the
|
||||
address the client can use, which is the difference between testing the SDK and testing Docker's
|
||||
network.
|
||||
두 topology 모두 proxy를 하지 않는다. Sentinel은 `SENTINEL get-master-addr-by-name`에 자기가 감시하는 주소로 답하고
|
||||
client가 그 주소로 직접 연결한다. cluster client는 `CLUSTER SHARDS`를 읽고 거기 적힌 모든 노드에 연결한다. bridge
|
||||
network에서는 그것이 container 안쪽 주소라서, host의 client는 닿을 수 없는 topology를 찾게 되고 — 승격 뒤에는
|
||||
역시 닿을 수 없는 *다른* topology를 찾는다. host network namespace를 같이 쓰면 topology가 알리는 주소가 client가
|
||||
쓸 수 있는 주소가 된다. 그것이 SDK를 시험하는 것과 Docker network를 시험하는 것의 차이다.
|
||||
|
||||
That is also why their ports are fixed rather than parameterised: the addresses are written into
|
||||
Sentinel's and the cluster's own configuration at creation time, and a lane whose two halves can
|
||||
disagree fails for reasons that are not the SDK's.
|
||||
같은 이유로 그 port들은 매개변수로 두지 않고 고정한다: 주소는 만들 때 Sentinel과 cluster 자신의 설정에 쓰이고,
|
||||
두 절반이 서로 어긋날 수 있는 lane은 SDK와 관계없는 이유로 실패한다.
|
||||
|
||||
## Selection is by lane, not by hand
|
||||
## 고르기는 손이 아니라 lane으로 한다
|
||||
|
||||
`redisTopologyTest` derives its JUnit tag expression from the declared mode: `redis-topology &
|
||||
lane-<mode>`. A promotion test is meaningless without sentinels and a cross-slot test is meaningless
|
||||
without a cluster, but expressing that as a runtime assumption would turn "the lane was never
|
||||
started" into a green skip. Selecting by tag keeps it fail-closed — what a mode cannot prove is not
|
||||
selected, and what is selected must pass.
|
||||
`redisTopologyTest`는 선언한 모드에서 JUnit tag 식을 끌어낸다: `redis-topology & lane-<mode>`. 승격 시험은
|
||||
sentinel 없이는 뜻이 없고 cross-slot 시험은 cluster 없이는 뜻이 없다. 하지만 그것을 런타임 가정으로 나타내면
|
||||
「lane이 시작되지 않았다」가 초록 건너뛰기가 된다. tag로 고르면 실패하면 닫힌 상태가 된다 — 모드가 증명할 수
|
||||
없는 것은 고르지 않고, 고른 것은 통과해야 한다.
|
||||
|
||||
The lane also fails closed on its endpoint: selecting `redisTopologyTest` without host, port, and
|
||||
mode (and `redis.topology.master` on the Sentinel lane) is an error, never a skip. A topology test
|
||||
that silently passes because it did not connect is worse than no topology test.
|
||||
lane은 endpoint에 대해서도 실패하면 닫힌다: host, port, mode(Sentinel lane이면 `redis.topology.master`도) 없이
|
||||
`redisTopologyTest`를 고르면 건너뛰기가 아니라 오류다. 연결하지 않아서 소리 없이 통과하는 topology 시험은
|
||||
topology 시험이 없는 것보다 나쁘다.
|
||||
|
||||
## `min-replicas-to-write` on the Sentinel lane
|
||||
## Sentinel lane의 `min-replicas-to-write`
|
||||
|
||||
The Sentinel lane sets `min-replicas-to-write 1` and `min-replicas-max-lag 1`, and this is not
|
||||
incidental configuration. Without them the lane measured a promotion in which the superseded primary
|
||||
kept answering `+OK` for eleven seconds after it had been replaced: **2,086 writes acknowledged to
|
||||
the caller and then discarded**, with exactly one command failing. With them the same promotion lost
|
||||
one write and refused 2,020 with `NOREPLICAS`, which the SDK reports as a definite, non-ambiguous
|
||||
failure a caller can act on.
|
||||
Sentinel lane은 `min-replicas-to-write 1`과 `min-replicas-max-lag 1`을 정한다. 우연히 둔 설정이 아니다. 그것
|
||||
없이 잰 승격에서는 밀려난 primary가 대체된 뒤에도 11초 동안 `+OK`로 답했다: **호출자에게 확인해 준 쓰기
|
||||
2,086개가 버려졌고**, 실패한 명령은 정확히 하나였다. 그것을 두고 같은 승격을 재면 쓰기 하나를 잃고 2,020개를
|
||||
`NOREPLICAS`로 거절했다. SDK는 그것을 호출자가 대응할 수 있는, 모호하지 않은 확정 실패로 알린다.
|
||||
|
||||
Any deployment where an acknowledgement is supposed to mean something has to set these. See
|
||||
`docs/redis/support-matrix.md` for the full record.
|
||||
확인 응답에 뜻이 있어야 하는 배포는 모두 이것을 정해야 한다. 전체 기록은 `docs/redis/support-matrix.md`를 본다.
|
||||
|
||||
## ACL accounts
|
||||
## ACL 계정
|
||||
|
||||
`acl/` holds one file per `CommandAccess` level. They are deliberately narrower than the SDK's own
|
||||
rules, so a mistake in the SDK is still refused by the server — the account is the last boundary and
|
||||
a permit never widens it.
|
||||
`compose/redis/acl/`에는 `CommandAccess` 수준마다 파일이 하나씩 있다. 일부러 SDK 자신의 규칙보다 좁게 둔다. 그래서
|
||||
SDK의 실수도 서버가 거절한다 — 계정이 마지막 경계이고, 허가는 그것을 넓히지 않는다.
|
||||
|
||||
Every lane loads the same file on every data node. Accounts are enforced per node, so "they exist on
|
||||
one node" is not evidence that a topology enforces them.
|
||||
모든 lane은 모든 데이터 노드에 같은 파일을 읽어 들인다. 계정은 노드마다 강제되므로 「한 노드에 있다」는 topology가
|
||||
그것을 강제한다는 증거가 아니다.
|
||||
|
||||
@@ -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를 띄우지 않는다.
|
||||
|
||||
+99
-106
@@ -1,125 +1,118 @@
|
||||
# app-bootstrap — application entry point & composition root
|
||||
# app-bootstrap — 애플리케이션 진입점과 조립 루트
|
||||
|
||||
## Registered identity
|
||||
## 등록 정보
|
||||
|
||||
- Module ID: `app-bootstrap`
|
||||
- Gradle path: `:app-bootstrap`
|
||||
- Focused test (derived from Gradle path): `./gradlew :app-bootstrap:test --console=plain`
|
||||
- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0.
|
||||
- Registry SSOT: `src/config/architecture/modules.json`.
|
||||
- 모듈 ID: `app-bootstrap`
|
||||
- Gradle 경로: `:app-bootstrap`
|
||||
- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :app-bootstrap:test --console=plain`
|
||||
- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다.
|
||||
- registry 정본: `src/config/architecture/modules.json`.
|
||||
|
||||
Package root: `dev.caskeleton.bootstrap`.
|
||||
패키지 루트: `dev.caskeleton.bootstrap`.
|
||||
|
||||
## Responsibility
|
||||
## 책임
|
||||
|
||||
- Spring Boot entrypoint (`CaSkeletonApplication`).
|
||||
- Runtime settings and logging bootstrap.
|
||||
- Final cross-module wiring.
|
||||
- Architecture tests that inspect all modules.
|
||||
- Spring Boot 진입점(`CaSkeletonApplication`).
|
||||
- 런타임 설정과 로깅 시작.
|
||||
- 모듈을 가로지르는 마지막 배선.
|
||||
- 모든 모듈을 들여다보는 아키텍처 시험.
|
||||
|
||||
## Allowed
|
||||
## 허용
|
||||
|
||||
- Runtime leaves explicitly declared by this module's Gradle dependencies and permitted by the
|
||||
architecture registry. The resolved Gradle runtime graph is the runtime SSOT; do not duplicate a
|
||||
membership list in metadata.
|
||||
- Spring Boot startup/runtime dependencies.
|
||||
- ArchUnit in tests.
|
||||
- 이 모듈의 Gradle 의존성이 분명히 선언하고 아키텍처 registry가 허용한 런타임 leaf. 해석된 Gradle
|
||||
runtime 그래프가 런타임의 정본이다. 구성원 목록을 metadata에 다시 적지 않는다.
|
||||
- Spring Boot 시작·런타임 의존성.
|
||||
- 시험에서 ArchUnit.
|
||||
|
||||
## Forbidden
|
||||
## 금지
|
||||
|
||||
- Concrete business policy.
|
||||
- Controllers, use cases, repository adapters, or mappers authored directly under bootstrap.
|
||||
- Settings classes that implement business logic.
|
||||
- Implementing an `application-core` or `domain-core` port. A class that implements one is an
|
||||
outbound adapter and belongs in an `adapter/outbound/*` leaf, however its dependencies are
|
||||
configured — `CompositionRootBoundaryArchitectureTest` enforces this, with no exceptions.
|
||||
- Raising a startup failure with `throw new IllegalStateException(...)`. Use `StartupFailures`
|
||||
(`adapter:outbound:support`, package `support.startup`: `envValidation` / `profileMismatch` /
|
||||
`requiredAdapterDisabled` / `migrationFailed`), so the
|
||||
failure carries its sysexits exit code and structured log fields —
|
||||
`StartupFailureContractArchitectureTest` enforces this.
|
||||
- Answering "is this production?" locally. `dev.caskeleton.shared.runtime.RuntimeEnvironment` owns
|
||||
the profile vocabulary for the whole repository.
|
||||
- Depending on `org.testcontainers` from `src/test`. Real-service tests belong to
|
||||
`src/integrationTest`; see `docs/testing/TESTING_STRATEGY.md`.
|
||||
- 구체적인 업무 정책.
|
||||
- bootstrap 아래에 직접 쓴 controller, 유스케이스, repository 어댑터, mapper.
|
||||
- 업무 로직을 구현하는 설정 클래스.
|
||||
- `application-core`나 `domain-core` 포트를 구현하기. 포트를 구현하는 클래스는 의존성을 어떻게
|
||||
설정했든 outbound 어댑터이고 `adapter/outbound/*` leaf에 둔다 —
|
||||
`CompositionRootBoundaryArchitectureTest`가 예외 없이 강제한다.
|
||||
- 기동 실패를 `throw new IllegalStateException(...)`으로 내기. `StartupFailures`
|
||||
(`adapter:outbound:support`, 패키지 `support.startup`: `envValidation` / `profileMismatch` /
|
||||
`requiredAdapterDisabled` / `migrationFailed`)를 써서 실패가 sysexits 종료 코드와 구조화된 로그
|
||||
필드를 싣게 한다 — `StartupFailureContractArchitectureTest`가 강제한다.
|
||||
- 「운영 환경인가?」를 이 모듈 안에서 답하기. 저장소 전체의 profile 어휘는
|
||||
`dev.caskeleton.shared.runtime.RuntimeEnvironment`가 가진다.
|
||||
- `src/test`에서 `org.testcontainers`에 의존하기. 실제 서비스를 쓰는 시험은 `src/integrationTest`에
|
||||
둔다. `docs/testing/TESTING_STRATEGY.md`를 본다.
|
||||
|
||||
## Package layout
|
||||
## 패키지 배치
|
||||
|
||||
The rules below exist because their absence is what produced the drift this module was reviewed for
|
||||
(`docs/reviews/2026-09-07-app-bootstrap-module-code-review.md`). Half the
|
||||
capabilities lived under `autoconfigure/` and half at the package root; `Settings` classes were split
|
||||
between a `settings/` package and their feature packages with no stated rule; and the same
|
||||
decomposition problem was solved two different ways in the same leaf — Notification as nine focused
|
||||
configurations, Redis as one 376-line class.
|
||||
아래 규칙은 그것이 없어서 이 모듈의 리뷰 대상이 된 어긋남이 생겼기 때문에 있다
|
||||
(`docs/reviews/2026-09-07-app-bootstrap-module-code-review.md`). capability의 절반은 `autoconfigure/`
|
||||
아래, 절반은 패키지 루트에 있었다. `Settings` 클래스는 규칙 없이 `settings/` 패키지와 각 기능
|
||||
패키지에 나뉘어 있었다. 그리고 같은 분해 문제를 같은 leaf에서 두 가지로 풀었다 — Notification은 작은
|
||||
설정 아홉 개로, Redis는 376줄 클래스 하나로.
|
||||
|
||||
- **A capability's assembly lives in the capability's own module**, registered by that module's
|
||||
`AutoConfiguration.imports`, with its settings in the module's `config/module-defaults/*.yml`.
|
||||
JPA (startup guards, Flyway strategy, lock decorator, readiness and full-off handling in
|
||||
`JpaActivationEnvironmentPostProcessor`) is `adapter:outbound:persistence-jpa`; Redis (readiness) is
|
||||
`adapter:outbound:cache-redis`; notification is `composition:notification-platform`. Every
|
||||
capability is a commented `runtimeOnly` line in `build.gradle`; the default composition is web,
|
||||
observability, the cores, support and identifier. This leaf keeps no list of capabilities: no
|
||||
switch registry, no cross-capability dependency validator, no activation endpoint. Component scan
|
||||
covers `dev.caskeleton.bootstrap` only; web (`WebAdapterAutoConfiguration`, `WebSecurityAutoConfiguration`, `WebMethodSecurityAutoConfiguration`) and support
|
||||
(`OutboundSupportConfig`) arrive through their own `AutoConfiguration.imports`. What stays in `autoconfigure/<name>/` is application
|
||||
composition every application needs: `common` (the clock). The outbox relay, the idempotency
|
||||
executor and the durable operations (use cases and `/operations` endpoints, 07-08) are
|
||||
`composition:outbox-relay`, `composition:idempotency` and `composition:durable-operation`, selected
|
||||
by one `runtimeOnly` line each and building nothing until their ports exist. A capability's role→permission mapping ships in its own
|
||||
`config/module-defaults` file, not in `config/security.yml`. The runtime wiring every composition root needs —
|
||||
tracing, the metrics contract filters, domain-context propagation, user-principal pseudonymization
|
||||
(`PrivacySettings`) and the actuator chain — is `composition:service-runtime`.
|
||||
- **`<Capability>Settings` lives beside its capability**, not in `settings/`. The `settings/` package
|
||||
holds only settings that belong to no capability — `BootstrapSettings`, `RuntimeSafetySettings` —
|
||||
bound strictly with `StrictSettingsBinder`, never scanned. Logging has no settings record:
|
||||
`logback-spring.xml` reads `app.logging.*` itself and `LoggingConfigurationRule` refuses values
|
||||
Logback cannot use.
|
||||
- **`runtime/` holds guards about the application itself** — secrets, numeric bounds, error-detail
|
||||
exposure, multi-instance coordination, the runtime-profile check (`RuntimeEnvironmentProfileValidator`).
|
||||
A guard about a capability's settings (the JPA OSIV/DDL/pool/TLS/vendor guards, the Mongo
|
||||
connection-source rule, the GraphQL deployment-mode rule) ships with that capability's module, so
|
||||
it exists exactly when the capability does.
|
||||
- **The startup failure vocabulary lives in `adapter:outbound:support`** (`support.startup`: phases,
|
||||
error codes, exceptions, `StartupFailures`, `StartupValidationContext`, `StartupOrder`,
|
||||
`ReadinessGroup`, `RuntimeWarnings`), so capability modules fail the same way without depending on
|
||||
this leaf. `runtime/startup/` keeps only `StartupFailureExceptionReporter`.
|
||||
- **An environment-only guard is a `StartupRule` bean** (`support.startup`): it returns violations,
|
||||
and the one `StartupRuleRunner` raises them before any other singleton exists (declare it with a
|
||||
`static` `@Bean` method that takes only the `Environment`, the bean factory or an `ObjectProvider`
|
||||
of static `RequiredProductionSecrets`; in every profile the runner creates each rule and each
|
||||
`RequiredProductionSecrets` before any rule runs, and fails the boot naming any other bean one of
|
||||
them creates, and naming any whose runtime class has an `@Value`/`@Autowired`/
|
||||
`@Inject`/`@Resource` member, a `@PostConstruct`/`@PreDestroy` callback or a
|
||||
`@ConfigurationProperties` binding — those are created before the post-processors and would stay
|
||||
unset). A guard that needs another bean stays a bean. A
|
||||
capability's production secrets are the capability's: its module contributes a
|
||||
`RequiredProductionSecrets` bean, and `SecretSourceValidator` checks the names without knowing
|
||||
which roles exist.
|
||||
- **capability의 조립은 그 capability 자신의 모듈에 있다.** 그 모듈의 `AutoConfiguration.imports`가
|
||||
등록하고, 설정은 그 모듈의 `config/module-defaults/*.yml`에 둔다. JPA(기동 guard, Flyway 전략,
|
||||
lock decorator, readiness, `JpaActivationEnvironmentPostProcessor`의 완전히 끄기 처리)는
|
||||
`adapter:outbound:persistence-jpa`, Redis(readiness)는 `adapter:outbound:cache-redis`, 알림은
|
||||
`composition:notification-platform`이다. 모든 capability는 `build.gradle`에서 주석 처리한
|
||||
`runtimeOnly` 한 줄이다. 기본 조립은 web, 관측, core들, support, identifier다. 이 leaf는 capability
|
||||
목록을 두지 않는다: 스위치 registry도, capability 사이 의존 검증기도, 켜기 endpoint도 없다.
|
||||
component scan은 `dev.caskeleton.bootstrap`만 본다. web(`WebAdapterAutoConfiguration`,
|
||||
`WebSecurityAutoConfiguration`, `WebMethodSecurityAutoConfiguration`)과 support
|
||||
(`OutboundSupportConfig`)는 자기 `AutoConfiguration.imports`로 들어온다. `autoconfigure/<name>/`에
|
||||
남는 것은 모든 애플리케이션에 필요한 애플리케이션 조립인 `common`(시계)뿐이다. outbox relay,
|
||||
멱등성 executor, durable operation(유스케이스와 `/operations` endpoint, 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`이다.
|
||||
- **`<Capability>Settings`는 `settings/`가 아니라 그 capability 옆에 둔다.** `settings/` 패키지는
|
||||
어느 capability에도 속하지 않는 설정 — `BootstrapSettings`, `RuntimeSafetySettings` — 만 담는다.
|
||||
이 설정은 `StrictSettingsBinder`로 엄격하게 바인딩하고 scan하지 않는다. 로깅에는 settings record가
|
||||
없다. `logback-spring.xml`이 `app.logging.*`을 직접 읽고 `LoggingConfigurationRule`이 Logback이 쓸
|
||||
수 없는 값을 거절한다.
|
||||
- **`runtime/`은 애플리케이션 자체에 대한 guard를 담는다** — 비밀 값, 숫자 한계, 오류 상세 노출,
|
||||
여러 인스턴스 조율, runtime profile 검사(`RuntimeEnvironmentProfileValidator`). capability 설정에
|
||||
대한 guard(JPA OSIV·DDL·pool·TLS·vendor guard, Mongo 연결 출처 규칙, GraphQL 배포 모드 규칙)는 그
|
||||
capability의 모듈과 함께 나간다. 그래야 capability가 있을 때만 정확히 존재한다.
|
||||
- **기동 실패 어휘는 `adapter:outbound:support`에 있다**(`support.startup`: phase, 오류 코드, 예외,
|
||||
`StartupFailures`, `StartupValidationContext`, `StartupOrder`, `ReadinessGroup`, `RuntimeWarnings`).
|
||||
그래서 capability 모듈은 이 leaf에 의존하지 않고 같은 방식으로 실패한다. `runtime/startup/`에는
|
||||
`StartupFailureExceptionReporter`만 남는다.
|
||||
- **환경만 보는 guard는 `StartupRule` bean이다**(`support.startup`). 위반을 돌려주고, 유일한
|
||||
`StartupRuleRunner`가 다른 singleton이 생기기 전에 그것을 올린다(`Environment`, bean factory, 정적
|
||||
`RequiredProductionSecrets`의 `ObjectProvider`만 받는 `static` `@Bean` 메서드로 선언한다. 모든
|
||||
profile에서 runner는 어떤 규칙을 돌리기 전에 규칙마다, 그리고 `RequiredProductionSecrets`마다 하나씩
|
||||
만든다. 그중 하나가 만드는 다른 bean이 있으면 그 이름을 대며 기동을 실패시킨다. runtime 클래스에
|
||||
`@Value`/`@Autowired`/`@Inject`/`@Resource` 멤버, `@PostConstruct`/`@PreDestroy` 콜백,
|
||||
`@ConfigurationProperties` 바인딩이 있는 것도 이름을 대며 실패시킨다 — 그런 것은 post-processor보다
|
||||
먼저 만들어져 값이 비어 있게 된다). 다른 bean이 필요한 guard는 bean으로 남는다. capability의 운영
|
||||
비밀 값은 그 capability의 것이다: 그 모듈이 `RequiredProductionSecrets` bean을 내놓고,
|
||||
`SecretSourceValidator`는 어떤 role이 있는지 모르는 채로 이름을 검사한다.
|
||||
|
||||
## Decomposition threshold
|
||||
## 분해 기준
|
||||
|
||||
State it rather than leaving it to taste, because "it felt long enough" is what produced two
|
||||
different answers for the same question.
|
||||
취향에 맡기지 않고 적어 둔다. 「충분히 길다고 느꼈다」가 같은 질문에 두 가지 답을 낳았기 때문이다.
|
||||
|
||||
- One `@Configuration` holds one assembly concern. Split when it passes roughly **eight `@Bean`
|
||||
methods**, or as soon as it assembles two unrelated port families — whichever comes first.
|
||||
- One `@ConfigurationProperties` class owns one capability namespace.
|
||||
- A capability that needs more than one configuration gets a root class holding its `enabled`
|
||||
condition, `@EnableConfigurationProperties`, and an `@Import` of the per-concern classes. Scan
|
||||
nothing: `@Import` from a gated root is what keeps `enabled=false` load-bearing rather than advisory.
|
||||
`cache-redis`'s `capability/RedisCapabilityConfig` is the reference example. Optional adapter
|
||||
capabilities that own reusable Spring composition publish their own root instead. Notification
|
||||
uses `adapter:outbound:notification`'s `NotificationPlatformAutoConfiguration` plus
|
||||
`composition:notification-platform`'s `NotificationApplicationCompositionAutoConfiguration`; JPA uses the
|
||||
package-private `PersistenceJpaAutoConfiguration`, `PersistenceJpaRuntimeConfig` and
|
||||
`startup.JpaStartupAutoConfiguration` from `adapter:outbound:persistence-jpa`, which is not in the
|
||||
default composition (`// runtimeOnly project(':adapter:outbound:persistence-jpa')` in
|
||||
`build.gradle`).
|
||||
Mongo follows the same rule: the persistence-mongo leaf owns MongoRootAutoConfiguration and its internal health bridge; bootstrap owns no Mongo-specific production health configuration.
|
||||
- Shared helpers of a split capability get their own type named for what they are, not a `*Util`
|
||||
bucket — `cache-redis`'s `capability/RedisKeys` is the reference.
|
||||
- `@Configuration` 하나는 조립 관심사 하나를 담는다. 대략 **`@Bean` 메서드 여덟 개**를 넘거나, 서로
|
||||
관계없는 포트 묶음 둘을 조립하게 되면 — 둘 중 먼저 오는 때에 — 나눈다.
|
||||
- `@ConfigurationProperties` 클래스 하나는 capability namespace 하나를 가진다.
|
||||
- 설정이 둘 이상 필요한 capability는 루트 클래스를 둔다. 루트가 `enabled` 조건,
|
||||
`@EnableConfigurationProperties`, 관심사별 클래스의 `@Import`를 가진다. 아무것도 scan하지 않는다:
|
||||
조건이 걸린 루트에서 `@Import`해야 `enabled=false`가 권고가 아니라 실제로 끄는 스위치가 된다.
|
||||
`cache-redis`의 `capability/RedisCapabilityConfig`가 참조 예다. 다시 쓸 Spring 조립을 가진 optional
|
||||
어댑터 capability는 자기 루트를 내놓는다. 알림은 `adapter:outbound:notification`의
|
||||
`NotificationPlatformAutoConfiguration`과 `composition:notification-platform`의
|
||||
`NotificationApplicationCompositionAutoConfiguration`을 쓴다. JPA는
|
||||
`adapter:outbound:persistence-jpa`의 package-private `PersistenceJpaAutoConfiguration`,
|
||||
`PersistenceJpaRuntimeConfig`, `startup.JpaStartupAutoConfiguration`을 쓰고, 이 모듈은 기본 조립에
|
||||
없다(`build.gradle`의 `// runtimeOnly project(':adapter:outbound:persistence-jpa')`).
|
||||
Mongo도 같은 규칙을 따른다: persistence-mongo leaf가 MongoRootAutoConfiguration과 그 내부 health
|
||||
bridge를 가지고, bootstrap은 Mongo 전용 운영 health 설정을 가지지 않는다.
|
||||
- 나눈 capability의 공용 도우미는 `*Util` 바구니가 아니라 하는 일을 이름으로 단 자기 타입을 가진다 —
|
||||
`cache-redis`의 `capability/RedisKeys`가 참조 예다.
|
||||
|
||||
## Test
|
||||
## 테스트
|
||||
|
||||
```bash
|
||||
cd src
|
||||
|
||||
+3
-3
@@ -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();
|
||||
|
||||
+235
-250
@@ -1,180 +1,173 @@
|
||||
# application-core — application use cases
|
||||
# application-core — 애플리케이션 유스케이스
|
||||
|
||||
## Registered identity
|
||||
## 등록 정보
|
||||
|
||||
- Module ID: `application-core`
|
||||
- Gradle path: `:application-core`
|
||||
- Focused test (derived from Gradle path): `./gradlew :application-core:test --console=plain`
|
||||
- Runtime baseline: Java 21; repository framework baseline: the Spring Boot 4.x version pinned by the shared version catalog.
|
||||
- Registry SSOT: `src/config/architecture/modules.json`.
|
||||
- 모듈 ID: `application-core`
|
||||
- Gradle 경로: `:application-core`
|
||||
- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :application-core:test --console=plain`
|
||||
- 실행 기준: Java 21. 프레임워크 기준은 공용 버전 카탈로그(`src/gradle/libs.versions.toml`)가 고정한 Spring Boot 4.x다.
|
||||
- registry 정본: `src/config/architecture/modules.json`.
|
||||
|
||||
Package root: `dev.caskeleton.application`.
|
||||
패키지 루트: `dev.caskeleton.application`.
|
||||
|
||||
코드 주석에서 덜어낸 **설계 결정의 근거**는 [README.md](README.md) 가 모아둔다 (이 문서는 모듈 규칙 SSOT).
|
||||
|
||||
## Responsibility
|
||||
## 책임 (Responsibility)
|
||||
|
||||
- Use case inbound ports (`CommandUseCase`, `QueryUseCase`) and their command / query contracts.
|
||||
- Outbound ports (`*Port` interfaces) the use cases depend on.
|
||||
- Application exceptions and policy types.
|
||||
- Coordinate domain models through ports.
|
||||
- Own application transaction boundaries through the `TransactionPort` abstraction.
|
||||
- Expose framework-free invocation context through ports such as `CorrelationIdPort`; adapters own
|
||||
MDC or other concrete storage.
|
||||
- Own the framework-free semantic integration-event draft, validated-event value contract and
|
||||
exact typed payload contribution SPI. This is the messaging semantic contract R1 boundary only.
|
||||
- 유스케이스 inbound 포트(`CommandUseCase`, `QueryUseCase`)와 그 command·query 계약.
|
||||
- 유스케이스가 의존하는 outbound 포트(`*Port` 인터페이스).
|
||||
- 애플리케이션 예외와 정책 타입.
|
||||
- 포트를 거쳐 도메인 모델을 조율한다.
|
||||
- `TransactionPort` 추상화로 애플리케이션 트랜잭션 경계를 가진다.
|
||||
- `CorrelationIdPort` 같은 포트로 프레임워크 없는 호출 문맥을 내놓는다. MDC 같은 실제 저장소는
|
||||
어댑터가 가진다.
|
||||
- 프레임워크 없는 integration event 초안(semantic draft), 검증된 이벤트의 값 계약, 정확한 타입의
|
||||
payload를 내놓는 SPI를 가진다. 메시징 semantic contract R1 경계까지만이다.
|
||||
|
||||
## Allowed
|
||||
## 허용
|
||||
|
||||
- `:domain-core`
|
||||
- `:shared-contract`
|
||||
- Java standard library types.
|
||||
- Java 표준 라이브러리 타입.
|
||||
|
||||
## Forbidden
|
||||
## 금지 (Forbidden)
|
||||
|
||||
- `adapter-*` implementation classes.
|
||||
- `adapter-*` 구현 클래스.
|
||||
- `app-bootstrap`.
|
||||
- Controller request/response DTOs.
|
||||
- JPA entities and Spring Data repositories.
|
||||
- HTTP status, transport types (`org.springframework.web..`).
|
||||
- `org.springframework.transaction.annotation.Transactional` (use `TransactionPort` instead).
|
||||
- `org.springframework.context.ApplicationContext` — direct dependency forbidden
|
||||
(`getBean(Class)` reflection-style bypass blocked by the ArchUnit rule `application_does_not_depend_on_application_context`). String-key
|
||||
bean lookup / `Class.forName(String)` / `BeanFactory#getBeansOfType` remain
|
||||
ArchUnit's static-analysis blind spot — guard via code review checklist.
|
||||
- Lombok (`lombok..`) — also forbidden in `domain-core`. Within `application-core`,
|
||||
Lombok is currently not in scope for the contract; if you intend to use it,
|
||||
weigh the bytecode opacity cost first.
|
||||
- Persistence-layer transaction annotations of any kind inside this module.
|
||||
- Diagnostic frameworks (`org.slf4j`, `java.util.logging`, Logback, Log4j, Micrometer). Express
|
||||
diagnostic intent through a specific outbound `*Port`; adapters own rendering.
|
||||
- Messaging provider/runtime types: physical topic, Kafka record or metadata, JSON tree/raw JSON
|
||||
payload, serializer/schema-validator implementation, security topology and publication epoch.
|
||||
- controller의 요청·응답 DTO.
|
||||
- JPA 엔티티와 Spring Data repository.
|
||||
- HTTP 상태, 전송 타입(`org.springframework.web..`).
|
||||
- `org.springframework.transaction.annotation.Transactional`(대신 `TransactionPort`를 쓴다).
|
||||
- `org.springframework.context.ApplicationContext` — 직접 의존 금지
|
||||
(`getBean(Class)` 같은 리플렉션식 우회는 ArchUnit 규칙 `APPLICATION_DOES_NOT_DEPEND_ON_APPLICATION_CONTEXT`가 막는다). 문자열 키로
|
||||
bean을 찾기, `Class.forName(String)`, `BeanFactory#getBeansOfType`은 ArchUnit 정적 분석이
|
||||
보지 못하는 곳이다. 코드 리뷰 체크리스트로 막는다.
|
||||
- Lombok(`lombok..`) — `domain-core`에서도 금지다. `application-core`에서는 지금 Lombok이
|
||||
계약 범위에 없다. 쓰려면 바이트코드가 불투명해지는 비용을 먼저 따진다.
|
||||
- 이 모듈 안의 영속 계층 트랜잭션 애너테이션은 종류를 가리지 않고 금지다.
|
||||
- 진단 프레임워크(`org.slf4j`, `java.util.logging`, Logback, Log4j, Micrometer). 진단 의도는
|
||||
전용 outbound `*Port`로 나타내고, 어떻게 남길지는 어댑터가 정한다.
|
||||
- 메시징 provider·런타임 타입: 물리 topic, Kafka record나 metadata, JSON tree·raw JSON payload,
|
||||
serializer·schema validator 구현, 보안 토폴로지, publication epoch.
|
||||
|
||||
## Contract types
|
||||
## 계약 타입
|
||||
|
||||
| Type | Purpose |
|
||||
| 타입 | 용도 |
|
||||
|---|---|
|
||||
| `usecase.UseCase<I, O>` | Base type for inbound ports. Concrete inbound ports MUST extend `CommandUseCase` or `QueryUseCase`. |
|
||||
| `usecase.CommandUseCase<C extends Command, R>` | Inbound port for write use cases. Implementations MUST be annotated `@UseCaseCapability`. |
|
||||
| `usecase.QueryUseCase<Q extends Query, R>` | Inbound port for read-only use cases. Implementations MUST declare `transactionMode = READ_ONLY` and `repositoryAccess = READ_REPOSITORY`. |
|
||||
| `command.Command` | Marker for write intents. Plain immutable types built from domain values. |
|
||||
| `query.Query` | Marker for read intents. Plain immutable types built from domain values. |
|
||||
| `transaction.TransactionPort` | Outbound port for join-capable write/read, physical root-only write, and independent write boundaries. Implemented by `adapter-persistence`. |
|
||||
| `secret.SecretSourcePort` | Framework-free outbound secret-resolution seam. Deployment selects a backend in app-bootstrap; concrete environment/cloud/vault readers belong to outbound adapter leaves. |
|
||||
| `transaction.NestedRootTransactionRejectedException` | Fail-fast signal raised before action/provider side effects when `inRootWrite` detects an actual ambient transaction. |
|
||||
| `transaction.TransactionMode` | `WRITE` / `READ_ONLY` / `REQUIRES_NEW`. `NESTED` and `NEVER` are intentionally absent. |
|
||||
| `transaction.Isolation` | `READ_COMMITTED` (pinned default) / `REPEATABLE_READ` / `SERIALIZABLE`. `READ_UNCOMMITTED` is forbidden (not declared); the vendor default is never used (engine defaults differ — PostgreSQL READ COMMITTED vs MySQL InnoDB REPEATABLE READ). Routing the stricter levels through `TransactionPort` is a `planned` joint change with `feature-application-port-usecase-contract`; the shipped call path pins `READ_COMMITTED`. |
|
||||
| `capability.UseCaseCapability` | Mandatory annotation on every concrete use case: declares `transactionMode`, `idempotency`, `repositoryAccess`, `externalOutboundAllowed`. |
|
||||
| `usecase.UseCase<I, O>` | inbound 포트의 기반 타입. 구체 inbound 포트는 반드시 `CommandUseCase`나 `QueryUseCase`를 상속한다. |
|
||||
| `usecase.CommandUseCase<C extends Command, R>` | 쓰기 유스케이스의 inbound 포트. 구현은 반드시 `@UseCaseCapability`를 단다. |
|
||||
| `usecase.QueryUseCase<Q extends Query, R>` | 읽기 전용 유스케이스의 inbound 포트. 구현은 반드시 `transactionMode = READ_ONLY`와 `repositoryAccess = READ_REPOSITORY`를 선언한다. |
|
||||
| `command.Command` | 쓰기 의도의 표지. 도메인 값으로 만든 평범한 불변 타입이다. |
|
||||
| `query.Query` | 읽기 의도의 표지. 도메인 값으로 만든 평범한 불변 타입이다. |
|
||||
| `transaction.TransactionPort` | 합류할 수 있는 쓰기·읽기, 물리 루트에서만 하는 쓰기, 독립 쓰기 경계를 내놓는 outbound 포트. `adapter:outbound:persistence-jpa`의 `SpringTransaction`이 구현한다. |
|
||||
| `secret.SecretSourcePort` | 프레임워크 없는 outbound 비밀 해석 이음매. 배포가 app-bootstrap에서 backend를 고른다. 실제 환경 변수·클라우드·vault 리더는 outbound 어댑터 leaf에 둔다. |
|
||||
| `transaction.NestedRootTransactionRejectedException` | `inRootWrite`가 실제로 열린 바깥 트랜잭션을 찾았을 때, action이나 provider 부작용 전에 바로 던지는 실패 신호. |
|
||||
| `transaction.TransactionMode` | `WRITE` / `READ_ONLY` / `REQUIRES_NEW`. `NESTED`와 `NEVER`는 일부러 없다. |
|
||||
| `transaction.Isolation` | `READ_COMMITTED`(고정 기본값) / `REPEATABLE_READ` / `SERIALIZABLE`. `READ_UNCOMMITTED`는 금지다(선언하지 않았다). vendor 기본값은 쓰지 않는다(엔진마다 기본값이 다르다 — PostgreSQL은 READ COMMITTED, MySQL InnoDB는 REPEATABLE READ). 더 엄격한 수준을 `TransactionPort`로 넘기는 일은 `feature-application-port-usecase-contract`와 함께 바꿀 `planned` 항목이다. 지금 호출 경로는 `READ_COMMITTED`로 고정한다. |
|
||||
| `capability.UseCaseCapability` | 모든 구체 유스케이스에 반드시 다는 애너테이션: `transactionMode`, `idempotency`, `repositoryAccess`, `externalOutboundAllowed`를 선언한다. |
|
||||
| `capability.Idempotency` | `IDEMPOTENT` / `KEYED` / `NOT_IDEMPOTENT`. |
|
||||
| `capability.RepositoryAccess` | `NONE` / `READ_REPOSITORY` / `WRITE_REPOSITORY`. |
|
||||
| `messaging.contract.IntegrationEventContractContribution<P>` | Closed exact-record payload type, canonical component order, local schema identity/hash and provider-neutral descriptor contribution. |
|
||||
| `messaging.event.IntegrationEventDraft<P>` | Typed semantic event before local encoding; never JSON, Kafka or persistence state. Built only through `IntegrationEventDrafts` (`INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`). |
|
||||
| `messaging.event.IntegrationEventDrafts` | The one way a feature builds a draft: contract id, version and destination from the contract, correlation from the request when canonical (else the event id), `SINGLE_TENANT_SCOPE` for a feature without tenants. |
|
||||
| `messaging.event.IntegrationIdentity` | The one grammar and the length bounds of event, correlation/causation and aggregate ids. Test a value with `isCanonical(value, bound)`; never copy the pattern. |
|
||||
| `messaging.event.ValidatedIntegrationEvent` | Stable semantic identities plus immutable exact encoded bytes and hashes, ready for a later durable append boundary. |
|
||||
| `messaging.event.IntegrationEventEncoderPort` | Framework-free local draft-to-validated-event boundary implemented by an outbound adapter (the template's: `adapter:outbound:support` `JsonIntegrationEventEncoder`). |
|
||||
| `outbox.OutboxAppendPort` | The one outbox append: a `ValidatedIntegrationEvent`, in the caller's write transaction. |
|
||||
| `tenant.TenantId` | The tenant identifier and its one grammar (`[A-Za-z0-9][A-Za-z0-9_.-]{0,63}`); the web and GraphQL transport contexts both carry it. Built by a transport from verified authentication data only. |
|
||||
| `messaging.contract.IntegrationEventContractContribution<P>` | 닫힌 정확한 record payload 타입, 정해진 component 순서, 로컬 schema identity·hash, provider 중립 descriptor 기여. |
|
||||
| `messaging.event.IntegrationEventDraft<P>` | 로컬 인코딩 전의 타입 있는 semantic 이벤트. JSON·Kafka·영속 상태가 아니다. `IntegrationEventDrafts`로만 만든다(`INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`). |
|
||||
| `messaging.event.IntegrationEventDrafts` | 기능이 초안을 만드는 유일한 길: contract id·version·destination은 contract에서, correlation은 요청 값이 정규형이면 그 값(아니면 event id), 테넌트가 없는 기능은 `SINGLE_TENANT_SCOPE`. |
|
||||
| `messaging.event.IntegrationIdentity` | event id, correlation·causation id, aggregate id의 유일한 문법과 길이 한계. 값은 `isCanonical(value, bound)`로 시험한다. 패턴을 복사하지 않는다. |
|
||||
| `messaging.event.ValidatedIntegrationEvent` | 안정된 semantic identity와 바뀌지 않는 정확한 인코딩 바이트·hash. 뒤의 durable append 경계로 넘길 준비가 된 값이다. |
|
||||
| `messaging.event.IntegrationEventEncoderPort` | 프레임워크 없는 로컬 경계(초안 → 검증된 이벤트). outbound 어댑터가 구현한다(템플릿은 `adapter:outbound:support`의 `JsonIntegrationEventEncoder`). |
|
||||
| `outbox.OutboxAppendPort` | 유일한 outbox append: `ValidatedIntegrationEvent` 하나를 호출자의 쓰기 트랜잭션 안에서 넣는다. |
|
||||
| `tenant.TenantId` | 테넌트 식별자와 그 유일한 문법(`[A-Za-z0-9][A-Za-z0-9_.-]{0,63}`). web과 GraphQL 전송 문맥이 모두 이 값을 싣는다. 전송 계층이 검증된 인증 데이터로만 만든다. |
|
||||
|
||||
## Notification (NOTIF-ADR-005)
|
||||
## 알림 (NOTIF-ADR-005)
|
||||
|
||||
None of the notification types are in this leaf. `..notification.platform..` and the simple
|
||||
`NotificationPort`, `Notification` and `NotificationChannel` directly under
|
||||
`dev.caskeleton.application.notification` all belong to leaf `application-notification`; the shared
|
||||
package prefix is the only link. The R1 orchestration types were removed on 2026-09-25.
|
||||
알림 타입은 이 leaf에 하나도 없다. `..notification.platform..`과
|
||||
`dev.caskeleton.application.notification` 바로 아래의 단순한 `NotificationPort`, `Notification`,
|
||||
`NotificationChannel`은 모두 leaf `application-notification`의 것이다. 패키지 접두어가 같은 것이
|
||||
유일한 연결이다. R1 조율 타입은 2026-09-25에 지웠다.
|
||||
|
||||
## Naming convention
|
||||
## 이름 규칙 (Naming convention)
|
||||
|
||||
This section is the repository's naming rule book. `NamingConventionTest` (app-bootstrap
|
||||
architectureTest) enforces the machine-checkable rows; the rest are review rules, and a review checks
|
||||
them against this table. A new feature follows the "new code" column; the "existing exceptions" are
|
||||
named so nobody copies them by accident.
|
||||
이 절이 저장소의 이름 규칙 정본이다. 기계로 볼 수 있는 행은 `NamingConventionTest`(app-bootstrap
|
||||
architectureTest)가 강제한다. 나머지는 리뷰 규칙이고, 리뷰가 이 표와 대조한다. 새 기능은 「새 코드」
|
||||
열을 따른다. 「이미 있는 예외」는 누가 실수로 따라 하지 않게 이름을 적어 둔 것이다.
|
||||
|
||||
| Role | Name | Where | Existing exceptions (do not copy) |
|
||||
| 역할 | 이름 | 위치 | 이미 있는 예외(따라 하지 않는다) |
|
||||
|---|---|---|---|
|
||||
| Use case (inbound port implementation) | `<Verb><Noun>UseCase`, enforced by ArchUnit | `application` package of the feature | `*ApplicationUseCase` (application-fileserver, application-notification), `*Service` (notification, fileserver) |
|
||||
| Command / query record | `*Command` / `*Query` | next to its use case | — |
|
||||
| Aggregate persistence (stores and returns whole aggregates) | `<Aggregate>Repository` | **domain** package of the aggregate, owned by the domain | — |
|
||||
| Technical store the application owns (outbox, idempotency, operation rows) | `<Thing>StorePort` | application package | `*WritePort` (old onboarding fixture, removed) |
|
||||
| Read model that returns projections, not aggregates | `<Thing>QueryPort` | application package; returns projections only (ArchUnit) | — |
|
||||
| Any other outbound port | `<Capability>Port` | application package | — |
|
||||
| Server-assigned id generation | `<Aggregate>IdFactory extends IdFactory<<Aggregate>Id>` | domain package; the id record `implements ResourceId<Self>` | `OutboxEventIdFactory` (sample; event ids are not resource ids) |
|
||||
| Configuration binding | `*Settings` (operational) or `*Policy` (authorization / domain policy), enforced by ArchUnit | the leaf that binds it | — |
|
||||
| Throwable | `*Exception`, enforced by ArchUnit | — | — |
|
||||
| Contract test kit for a port | abstract `<Port>Contract` in the port owner's testFixtures; the fake's and each adapter's test extend it | testFixtures | value-type tests were once named `*ContractTest`; they are `*ValueTypesTest` now |
|
||||
| 유스케이스(inbound 포트 구현) | `<Verb><Noun>UseCase`, ArchUnit이 강제 | 기능의 `application` 패키지 | `*ApplicationUseCase`(application-fileserver, application-notification), `*Service`(notification, fileserver) |
|
||||
| command·query record | `*Command` / `*Query` | 그 유스케이스 옆 | — |
|
||||
| aggregate 영속(aggregate 전체를 저장하고 돌려준다) | `<Aggregate>Repository` | aggregate의 **domain** 패키지, 도메인이 가진다 | — |
|
||||
| 애플리케이션이 가진 기술 저장소(outbox, 멱등성, operation 행) | `<Thing>StorePort` | application 패키지 | `*WritePort`(옛 onboarding fixture, 지움) |
|
||||
| aggregate가 아니라 projection을 돌려주는 읽기 모델 | `<Thing>QueryPort` | application 패키지. projection만 돌려준다(ArchUnit) | — |
|
||||
| 그 밖의 outbound 포트 | `<Capability>Port` | application 패키지 | — |
|
||||
| 서버가 정하는 id 생성 | `<Aggregate>IdFactory extends IdFactory<<Aggregate>Id>` | domain 패키지. id record는 `implements ResourceId<Self>` | `OutboxEventIdFactory`(샘플. event id는 resource id가 아니다) |
|
||||
| 설정 바인딩 | `*Settings`(운영) 또는 `*Policy`(인가·도메인 정책), ArchUnit이 강제 | 그것을 바인딩하는 leaf | — |
|
||||
| Throwable | `*Exception`, ArchUnit이 강제 | — | — |
|
||||
| 포트의 계약 시험 키트 | 포트 소유자의 testFixtures에 둔 추상 `<Port>Contract`. fake의 시험과 각 어댑터의 시험이 상속한다 | testFixtures | 값 타입 시험의 이름이 한때 `*ContractTest`였다. 지금은 `*ValueTypesTest`다 |
|
||||
|
||||
The one-line rule for stores: **if the domain would recognise the thing it stores, it is a
|
||||
`Repository` in the domain; if it is plumbing the application needs, it is a `StorePort` in the
|
||||
application.**
|
||||
저장소의 한 줄 규칙: **도메인이 알아볼 만한 것을 저장하면 도메인의 `Repository`다. 애플리케이션에
|
||||
필요한 배관이면 application의 `StorePort`다.**
|
||||
|
||||
## Package ownership
|
||||
## 패키지 소유 (Package ownership)
|
||||
|
||||
This section is the rule book for **which packages the template owns** and where a business feature
|
||||
goes. `docs/manual/03-placement.md` points here.
|
||||
이 절은 **템플릿이 어떤 패키지를 가지는지**와 업무 기능이 어디로 가는지의 정본이다.
|
||||
`docs/manual/03-placement.md`가 이곳을 가리킨다.
|
||||
|
||||
- A business feature is `dev.caskeleton.application.<feature>` (and `dev.caskeleton.domain.<feature>`,
|
||||
`...adapter.inbound.web.<feature>`, `...bootstrap.autoconfigure.<feature>`): one package per feature
|
||||
directly under each root, no `command`/`usecase`/`port` sub-packages.
|
||||
- `<feature>` is **not** one of the template package names below. A feature beside a template
|
||||
package of the same name lands in the same package tree, and every upstream template update merges
|
||||
into it.
|
||||
- Template packages never import a feature package. Business code does not go into a template
|
||||
package, even when the name fits.
|
||||
- Everything under the two roots that is not listed here is a feature. A derived service adds
|
||||
features without editing this list; the template edits it when it adds, renames or removes one of
|
||||
its own packages.
|
||||
- 업무 기능은 `dev.caskeleton.application.<feature>`다(그리고 `dev.caskeleton.domain.<feature>`,
|
||||
`...adapter.inbound.web.<feature>`, `...bootstrap.autoconfigure.<feature>`). 루트마다 바로 아래에
|
||||
기능 하나당 패키지 하나를 두고, `command`·`usecase`·`port` 하위 패키지를 두지 않는다.
|
||||
- `<feature>`는 아래 템플릿 패키지 이름 중 하나가 **아니다**. 같은 이름의 템플릿 패키지 옆에 둔
|
||||
기능은 같은 패키지 트리에 들어가고, upstream 템플릿 갱신이 올 때마다 그 기능에 섞여 들어간다.
|
||||
- 템플릿 패키지는 기능 패키지를 import하지 않는다. 이름이 맞아도 업무 코드를 템플릿 패키지에 넣지
|
||||
않는다.
|
||||
- 두 루트 아래에서 여기 적히지 않은 것은 모두 기능이다. 파생 서비스는 이 목록을 고치지 않고 기능을
|
||||
더한다. 템플릿은 자기 패키지를 더하거나, 이름을 바꾸거나, 지울 때 이 목록을 고친다.
|
||||
|
||||
| Package (`dev.caskeleton.application.*`) | Owning leaf | Holds |
|
||||
| 패키지 (`dev.caskeleton.application.*`) | 소유 leaf | 담는 것 |
|
||||
|---|---|---|
|
||||
| `usecase`, `command`, `query` | application-core | inbound port base types and the command/query markers |
|
||||
| `capability` | application-core | `@UseCaseCapability` and its enums |
|
||||
| `transaction` | application-core | `TransactionPort` and its modes |
|
||||
| `security` | application-core | authorization port, `@RequiresPermission`, `@SystemInvoked`, `@SystemCaller`, `ObjectAccessPolicy` |
|
||||
| `usecase`, `command`, `query` | application-core | inbound 포트 기반 타입과 command·query 표지 |
|
||||
| `capability` | application-core | `@UseCaseCapability`와 그 enum |
|
||||
| `transaction` | application-core | `TransactionPort`와 그 모드 |
|
||||
| `security` | application-core | 인가 포트, `@RequiresPermission`, `@SystemInvoked`, `@SystemCaller`, `ObjectAccessPolicy` |
|
||||
| `tenant` | application-core | `TenantId` |
|
||||
| `observability` | application-core | `CorrelationIdPort`, `UserPrincipalPseudonymizerPort` |
|
||||
| `secret` | application-core | `SecretSourcePort`, `SecretReference` |
|
||||
| `messaging` | application-core | the integration-event semantic contract |
|
||||
| `outbox` | application-core | transactional outbox append and relay |
|
||||
| `idempotency` | application-core | keyed idempotency executor and store port |
|
||||
| `operation` | application-core | durable (long-running) operations |
|
||||
| `lease`, `lock` | application-core | distributed lease and lock ports |
|
||||
| `cache` | application-core | cache region port |
|
||||
| `realtime` | application-core | live event replay port |
|
||||
| `notification` | application-notification | notification capability |
|
||||
| `fileserver` | application-fileserver | file server capability |
|
||||
| `objectstorage` | application-objectstorage | object storage capability (its `content.CallBudget` is the call deadline it carries) |
|
||||
| `messaging` | application-core | integration event semantic contract |
|
||||
| `outbox` | application-core | 트랜잭션 outbox append와 relay |
|
||||
| `idempotency` | application-core | 키 기반 멱등성 executor와 store 포트 |
|
||||
| `operation` | application-core | durable(오래 걸리는) operation |
|
||||
| `lease`, `lock` | application-core | 분산 lease·lock 포트 |
|
||||
| `cache` | application-core | cache region 포트 |
|
||||
| `realtime` | application-core | live event 재생 포트 |
|
||||
| `notification` | application-notification | 알림 capability |
|
||||
| `fileserver` | application-fileserver | 파일 서버 capability |
|
||||
| `objectstorage` | application-objectstorage | 오브젝트 스토리지 capability(`content.CallBudget`은 그것이 싣는 호출 기한이다) |
|
||||
|
||||
| Package (`dev.caskeleton.domain.*`) | Owning leaf | Holds |
|
||||
| 패키지 (`dev.caskeleton.domain.*`) | 소유 leaf | 담는 것 |
|
||||
|---|---|---|
|
||||
| `identifier` | domain-core | `ResourceId`, `IdFactory` |
|
||||
| `stereotype` | domain-core | `@AggregateRoot`, `@DomainEvent`, `@ValueObject` |
|
||||
|
||||
Enforcement:
|
||||
강제하는 곳:
|
||||
|
||||
- `scripts/new-feature.sh` refuses a feature name that is already a package under any of the five
|
||||
roots, in any leaf — every template package included.
|
||||
- `NamingConventionTest.FEATURE_PACKAGES_DO_NOT_REUSE_TEMPLATE_PACKAGE_NAMES`: a feature package
|
||||
under either root does not take a name from these tables. Every feature has a domain package, so a
|
||||
feature named `operation` is caught at `dev.caskeleton.domain.operation`.
|
||||
- `NamingConventionTest.TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES`: a feature class written
|
||||
into a template package keeps the template's name but imports its own domain, and that import is
|
||||
what fails.
|
||||
- These tables are the rule book; the machine copy the rules read is `TemplatePackageOwnership`
|
||||
(app-bootstrap `src/test`, so both the architecture suite and the document-contract lane see it).
|
||||
`TemplatePackageOwnershipDocumentTest` (document-contract lane, `mainCheck`) fails when the tables
|
||||
and that class differ in a package name or owning leaf, or when a listed package is not in the
|
||||
leaf the table names; `TemplatePackageOwnershipRuleTest` (architectureTest) fails when a listed
|
||||
name exists in no production class. A new template package joins both in the same change.
|
||||
- Not caught: a new template package that nobody lists. Features are generated into the same leaves
|
||||
(`scripts/new-feature.sh`), so an unlisted package is indistinguishable from a feature. Listing it
|
||||
is part of adding it.
|
||||
- Rejected alternatives: allowing only the listed top-level packages (every derived feature would
|
||||
have to edit the template's list — a merge conflict per feature), and a separate
|
||||
`application-platform` leaf for the platform packages (weighed in the 2026-11-01 maturity review: clearer
|
||||
boundary, but more registry edges than a naming rule needs).
|
||||
- `scripts/new-feature.sh`는 다섯 루트 중 어디든, 어느 leaf든 이미 패키지로 있는 기능 이름을
|
||||
거절한다. 템플릿 패키지도 모두 여기 걸린다.
|
||||
- `NamingConventionTest.FEATURE_PACKAGES_DO_NOT_REUSE_TEMPLATE_PACKAGE_NAMES`: 두 루트 아래의 기능
|
||||
패키지는 이 표의 이름을 쓰지 않는다. 기능마다 domain 패키지가 있으므로 `operation`이라는 기능은
|
||||
`dev.caskeleton.domain.operation`에서 걸린다.
|
||||
- `NamingConventionTest.TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES`: 템플릿 패키지 안에 쓴
|
||||
기능 클래스는 템플릿 이름을 지니지만 자기 도메인을 import한다. 실패하는 것은 그 import다.
|
||||
- 이 표가 정본이다. 규칙이 읽는 기계용 사본은 `TemplatePackageOwnership`이다(app-bootstrap
|
||||
`src/test`에 있어서 architecture suite와 document-contract lane이 모두 본다).
|
||||
`TemplatePackageOwnershipDocumentTest`(document-contract lane, `mainCheck`)는 표와 그 클래스의
|
||||
패키지 이름이나 소유 leaf가 다르거나, 표에 적힌 패키지가 표가 말한 leaf에 없으면 실패한다.
|
||||
`TemplatePackageOwnershipRuleTest`(architectureTest)는 적힌 이름이 운영 클래스 어디에도 없으면
|
||||
실패한다. 새 템플릿 패키지는 같은 변경에서 둘 모두에 들어간다.
|
||||
- 못 잡는 것: 아무도 적지 않은 새 템플릿 패키지. 기능은 같은 leaf에 생성되므로
|
||||
(`scripts/new-feature.sh`) 적히지 않은 패키지는 기능과 구별되지 않는다. 적는 것까지가 패키지를
|
||||
더하는 일이다.
|
||||
- 버린 대안: 적힌 최상위 패키지만 허용하기(파생 기능마다 템플릿 목록을 고쳐야 한다 — 기능마다
|
||||
병합 충돌이 난다), 플랫폼 패키지용 `application-platform` leaf를 따로 두기(2026-11-01 성숙도
|
||||
리뷰에서 따졌다: 경계는 더 분명하지만, 이름 규칙에 필요한 것보다 registry edge가 많아진다).
|
||||
|
||||
## Canonical use case shape
|
||||
## 정해진 유스케이스 모양 (Canonical use case shape)
|
||||
|
||||
```java
|
||||
@RequiresPermission("user:register")
|
||||
@@ -201,145 +194,137 @@ public class RegisterUserUseCase implements CommandUseCase<RegisterUserCommand,
|
||||
}
|
||||
```
|
||||
|
||||
The class is plain Java. A composition root constructs it with its ports and configuration values;
|
||||
application-core never self-registers with a DI framework. It is **not final**: a mutating use case
|
||||
declares `@RequiresPermission`, the web adapter enforces it through a CGLIB proxy, and CGLIB cannot
|
||||
subclass a final class (`RequiresPermissionProxyabilityTest`). It is registered as a bean for the
|
||||
same reason — a use case built with `new` is never checked. A use case only the system calls (a
|
||||
scheduler, a relay, a message consumer) carries `@SystemInvoked(reason = ...)` instead of a
|
||||
permission and is not a bean: it is a write with no permission check, so no user request may reach
|
||||
it. Its system caller constructs it — a composition module for a scheduler, a
|
||||
`@SystemCaller(reason = ...)` message handler in `..adapter.inbound.messaging..`, or a
|
||||
`@SystemCaller` scheduled job in the service's own `..adapter.inbound.scheduler..` package. Manual
|
||||
07 「시스템이 부르는 쓰기」 is the canonical list of the three and where each lives. All of it is
|
||||
enforced — a `@SystemInvoked` bean fails startup, an inbound adapter that depends on one without
|
||||
being a `@SystemCaller` fails `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`,
|
||||
`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS` keeps the mark (and classes nested in a marked
|
||||
one) off user transports, `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS` keeps a user transport
|
||||
from calling a system caller (by its class or by a project interface it implements), and
|
||||
`SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES` keeps a system caller from being a `Runnable` or any
|
||||
other type outside the project, which no dependency rule could follow. Paths that name no type (a
|
||||
bean looked up by name, a function a configuration hands over) are not seen; manual 07 lists them
|
||||
and what holds them. A composition with `@RequiresPermission`
|
||||
beans but no enforcing advisor fails startup too (`composition:service-runtime`
|
||||
`PermissionEnforcementGuard`, both checks).
|
||||
이 클래스는 평범한 Java다. 조립 루트가 포트와 설정 값을 넣어 만든다. application-core는 DI
|
||||
프레임워크에 스스로 등록하지 않는다. 클래스는 **final이 아니다**: 상태를 바꾸는 유스케이스는
|
||||
`@RequiresPermission`을 선언하고, web 어댑터는 CGLIB proxy로 그것을 강제하는데, CGLIB는 final
|
||||
클래스를 상속하지 못한다(`RequiresPermissionProxyabilityTest`). 같은 이유로 bean으로 등록한다.
|
||||
`new`로 만든 유스케이스는 검사를 받지 않는다. 시스템만 부르는 유스케이스(스케줄러, relay, 메시지
|
||||
소비자)는 권한 대신 `@SystemInvoked(reason = ...)`를 달고 bean이 아니다. 권한 검사가 없는 쓰기라서
|
||||
사용자 요청이 닿으면 안 되기 때문이다. 그 시스템 호출자가 유스케이스를 만든다: 스케줄러는 조립
|
||||
모듈, 메시지 핸들러는 `..adapter.inbound.messaging..` 안의 `@SystemCaller(reason = ...)`, 예약
|
||||
작업은 서비스 자신의 `..adapter.inbound.scheduler..` 패키지 안의 `@SystemCaller`다. 이 셋과 각각의
|
||||
위치는 `docs/manual/07-authorization.md` 「시스템이 부르는 쓰기」가 정본 목록이다. 모두 강제된다:
|
||||
`@SystemInvoked` bean은 기동에 실패한다. `@SystemCaller`가 아닌 inbound 어댑터가 그 유스케이스에
|
||||
의존하면 `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`가 실패한다.
|
||||
`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`는 그 표지(그리고 표지가 붙은 클래스 안에 든
|
||||
클래스)를 사용자 전송 계층에 두지 못하게 한다. `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`는 사용자
|
||||
전송 계층이 시스템 호출자를 부르지 못하게 한다(그 클래스로든, 그것이 구현한 프로젝트 인터페이스로든).
|
||||
`SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`는 시스템 호출자가 `Runnable`이나 프로젝트 밖의 다른
|
||||
타입이 되지 못하게 한다. 그런 타입은 어떤 의존 규칙도 따라가지 못한다. 타입 이름이 드러나지 않는
|
||||
경로(이름으로 찾는 bean, 설정이 넘겨주는 함수)는 보지 못한다. 매뉴얼 07장이 그 경로와 그것을 막는
|
||||
곳을 적는다. `@RequiresPermission` bean이 있는데 강제할 advisor가 없는 조립도 기동에 실패한다
|
||||
(`composition:service-runtime`의 `PermissionEnforcementGuard`, 두 검사 모두).
|
||||
|
||||
## Allowed transactional shapes
|
||||
## 허용하는 트랜잭션 모양 (Allowed transactional shapes)
|
||||
|
||||
| Use case shape | `transactionMode` | TransactionPort call | When |
|
||||
| 유스케이스 모양 | `transactionMode` | TransactionPort 호출 | 언제 |
|
||||
|---|---|---|---|
|
||||
| Write command | `WRITE` | `tx.inWrite(...)` | Default for `CommandUseCase`. |
|
||||
| Physical-root write command | `WRITE` | `tx.inRootWrite(...)` | Only when orchestration must prove there is no ambient transaction and expose a result after commit. |
|
||||
| Read-only query | `READ_ONLY` | `tx.inRead(...)` | Default for `QueryUseCase`. |
|
||||
| Outbox / audit / compensation | `REQUIRES_NEW` | `tx.inNew(...)` | Only when the use case MUST commit independently of the caller. |
|
||||
| 쓰기 command | `WRITE` | `tx.inWrite(...)` | `CommandUseCase`의 기본. |
|
||||
| 물리 루트 쓰기 command | `WRITE` | `tx.inRootWrite(...)` | 바깥 트랜잭션이 없음을 증명하고 커밋 뒤에 결과를 내놓아야 하는 조율일 때만. |
|
||||
| 읽기 전용 query | `READ_ONLY` | `tx.inRead(...)` | `QueryUseCase`의 기본. |
|
||||
| outbox·감사·보상 | `REQUIRES_NEW` | `tx.inNew(...)` | 유스케이스가 반드시 호출자와 따로 커밋해야 할 때만. |
|
||||
|
||||
`NESTED` and `NEVER` propagation are forbidden.
|
||||
`inRootWrite` MUST reject an actual ambient transaction before invoking its action or
|
||||
`PlatformTransactionManager`; it MUST NOT emulate root-only behavior with `REQUIRES_NEW`.
|
||||
Both `inWrite` and `inRootWrite` satisfy the direct boundary fitness rule for a
|
||||
`WRITE_REPOSITORY + WRITE` use case. READ and REQUIRES_NEW mappings remain exclusive.
|
||||
`NESTED`와 `NEVER` 전파는 금지다.
|
||||
`inRootWrite`는 action이나 `PlatformTransactionManager`를 부르기 전에 실제로 열린 바깥 트랜잭션을
|
||||
반드시 거절한다. 루트 전용 동작을 `REQUIRES_NEW`로 흉내 내면 안 된다.
|
||||
`WRITE_REPOSITORY + WRITE` 유스케이스의 직접 경계 적합성 규칙은 `inWrite`와 `inRootWrite`가 모두
|
||||
만족한다. READ와 REQUIRES_NEW의 대응은 계속 서로 배타적이다.
|
||||
|
||||
### Callback signature contract
|
||||
### 콜백 시그니처 계약
|
||||
|
||||
`TransactionPort` callbacks are `Supplier<T>` / `Runnable` and cannot throw checked
|
||||
exceptions. This matches Spring's `TransactionCallback<T>` constraint. Wrap domain
|
||||
checked exceptions into `RuntimeException` subclasses
|
||||
(`DomainException extends RuntimeException`); `IOException` → `UncheckedIOException`;
|
||||
`SQLException` is auto-translated by Spring's `DataAccessException` hierarchy.
|
||||
`TransactionPort` 콜백은 `Supplier<T>` / `Runnable`이라 checked 예외를 던지지 못한다. Spring
|
||||
`TransactionCallback<T>`의 제약과 같다. 도메인의 checked 예외는 `RuntimeException` 하위 클래스로
|
||||
감싼다(`DomainException extends RuntimeException`). `IOException`은 `UncheckedIOException`으로
|
||||
감싼다. `SQLException`은 Spring의 `DataAccessException` 계층이 자동으로 번역한다.
|
||||
|
||||
### `inNew` pool-sizing constraint
|
||||
### `inNew` 풀 크기 제약
|
||||
|
||||
`inNew` acquires a new physical JDBC connection. Pool size MUST satisfy:
|
||||
`inNew`는 새 물리 JDBC 연결을 얻는다. 풀 크기는 반드시 다음을 만족한다.
|
||||
|
||||
```
|
||||
hikari.maximumPoolSize >= (concurrent_threads × (1 + max_inNew_depth)) + 1
|
||||
```
|
||||
|
||||
**Forbidden**: calling `tx.inNew(...)` inside a loop over many records — pool
|
||||
exhaustion + deadlock risk. Batch records inside ONE `inNew` call, or move the
|
||||
loop outside the transaction boundary.
|
||||
**금지**: 많은 레코드를 도는 반복문 안에서 `tx.inNew(...)`를 부른다 — 풀이 바닥나고 교착이 생길
|
||||
수 있다. 레코드를 `inNew` 호출 **하나** 안에서 묶어 처리하거나, 반복문을 트랜잭션 경계 밖으로 뺀다.
|
||||
|
||||
## Idempotency (KEYED) — feature-rate-limit-idempotency-contract
|
||||
## 멱등성 (KEYED) — feature-rate-limit-idempotency-contract
|
||||
|
||||
`@UseCaseCapability(idempotency = Idempotency.KEYED)` is **supported**. A KEYED use case wraps
|
||||
its work with `dev.caskeleton.application.idempotency.IdempotencyExecutor` — the one owner-safe
|
||||
generation; the V1 `IdempotencyScope`/`tryBegin` API is gone.
|
||||
`@UseCaseCapability(idempotency = Idempotency.KEYED)`는 **지원한다**. KEYED 유스케이스는 자기 일을
|
||||
`dev.caskeleton.application.idempotency.IdempotencyExecutor`로 감싼다. 소유자를 안전하게 지키는
|
||||
유일한 세대다. V1 `IdempotencyScope`/`tryBegin` API는 없어졌다.
|
||||
|
||||
- **Scope**: the caller passes an `IdempotencyScopeDigest` — a versioned HMAC of
|
||||
principal + client key + operation code, computed before the executor sees it. The raw
|
||||
`Idempotency-Key` never reaches this layer or the store.
|
||||
- **Store**: `IdempotencyStorePort`, contributed by exactly one provider selected with
|
||||
`app.capabilities.idempotency.provider` (`redis` → `cache-redis`, `postgresql` →
|
||||
`persistence-jpa`; default `disabled`). In-memory prod storage is forbidden.
|
||||
- **Executor**: built once by `composition:idempotency` `IdempotencyAutoConfiguration` from
|
||||
`IdempotencySettings` (processing lease 30s, replay TTL `APP_IDEMPOTENCY_TTL` 24h ≤72h and not
|
||||
shorter than the lease, failure retention 24h and not shorter than the replay TTL). Do not
|
||||
construct it in a use case or a service's own config.
|
||||
- The action returns `IdempotentAction.Outcome` (`Success` / `RetryableNoEffect` /
|
||||
`EffectUnknown`); a thrown exception counts as effect-unknown. In progress → 409
|
||||
`IDEMPOTENT_IN_FLIGHT`, fingerprint mismatch (SHA-256) → 422 `IDEMPOTENT_REQUEST_MISMATCH`;
|
||||
`IdempotencyUnavailableException` and `IdempotencyRecoveryRequiredException` mean the store
|
||||
could not prove the outcome, so do not blindly retry.
|
||||
- Every store answers an execution whose processing lease ran out with `RecoveryRequired` and never
|
||||
takes it over; only a claim that never started or a retryable failure is taken over. The answer
|
||||
leaves the record to its holder: the holder's first late `complete`/`markFailed` is recorded, a
|
||||
lease that ran out is not renewed and a claim whose lease ran out is not started — both answer
|
||||
`LEASE_EXPIRED`, not `NOT_OWNER`, and the executor turns a refused start into "not applied"
|
||||
(owner decision 2026-11-04). A record lives for the lease plus the replay TTL. `IdempotencyStoreContract` holds Redis and PostgreSQL to both on
|
||||
real servers; the in-memory fake models no time, so it runs only the contract's time-free cases.
|
||||
- Every transition names the operation its record was claimed under (`IdempotencyOwner.claimOperationId()`).
|
||||
Another one is `OPERATION_CONFLICT` in every store and changes nothing; so is an inspection that
|
||||
brings the owner token under another operation (owner decision 2026-11-06).
|
||||
- A transition already applied is confirmed ("already …") only to the handle it was applied from —
|
||||
the record one revision past it, moved there by that kind of transition. Any other handle is
|
||||
`NOT_OWNER`, the same attempt's handle from before a takeover included, and so is a start through
|
||||
the handle a renewal was applied from; a start through a released handle is `ABSENT` or
|
||||
`NOT_OWNER` by whether the store keeps the released record (owner decision 2026-11-06,
|
||||
- **범위(scope)**: 호출자가 `IdempotencyScopeDigest`를 넘긴다. principal + client key + operation
|
||||
code의 버전 있는 HMAC이고, executor가 받기 전에 계산한다. 원본 `Idempotency-Key`는 이 계층에도
|
||||
store에도 닿지 않는다.
|
||||
- **store**: `IdempotencyStorePort`. `app.capabilities.idempotency.provider`로 고른 provider 정확히
|
||||
하나가 내놓는다(`redis` → `cache-redis`, `postgresql` → `persistence-jpa`, 기본값 `disabled`).
|
||||
운영에서 메모리 저장소는 금지다.
|
||||
- **executor**: `composition:idempotency`의 `IdempotencyAutoConfiguration`이 `IdempotencySettings`로
|
||||
한 번 만든다(처리 lease 30s, 재생 TTL `APP_IDEMPOTENCY_TTL` 24h ≤72h이고 lease보다 짧지 않다, 실패
|
||||
보존 24h이고 재생 TTL보다 짧지 않다). 유스케이스나 서비스 자신의 설정에서 만들지 않는다.
|
||||
- action은 `IdempotentAction.Outcome`(`Success` / `RetryableNoEffect` / `EffectUnknown`)을
|
||||
돌려준다. 던진 예외는 효과를 모름(effect-unknown)으로 센다. 처리 중이면 409
|
||||
`IDEMPOTENT_IN_FLIGHT`, fingerprint(SHA-256)가 다르면 422 `IDEMPOTENT_REQUEST_MISMATCH`다.
|
||||
`IdempotencyUnavailableException`과 `IdempotencyRecoveryRequiredException`은 store가 결과를
|
||||
증명하지 못했다는 뜻이니 무턱대고 다시 시도하지 않는다.
|
||||
- 모든 store는 처리 lease가 끝난 실행에 `RecoveryRequired`로 답하고 그 실행을 넘겨받지 않는다.
|
||||
넘겨받는 것은 시작하지 않은 claim이나 다시 시도할 수 있는 실패뿐이다. 이 답은 레코드를 가진
|
||||
쪽에게 남긴다: 가진 쪽이 늦게 보낸 첫 `complete`/`markFailed`는 기록한다. lease가 끝난 것은
|
||||
갱신하지 않고, lease가 끝난 claim은 시작하지 않는다. 둘 다 `NOT_OWNER`가 아니라 `LEASE_EXPIRED`로
|
||||
답하고, executor는 거절된 시작을 「적용 안 됨」으로 바꾼다(소유자 결정 2026-11-04). 레코드는
|
||||
lease에 재생 TTL을 더한 만큼 산다. `IdempotencyStoreContract`가 Redis와 PostgreSQL을 실제 서버에서
|
||||
둘 모두에 맞춘다. 메모리 fake는 시간을 모델링하지 않으니 계약 중 시간이 없는 경우만 돈다.
|
||||
- 모든 전이는 그 레코드를 claim한 operation을 이름으로 댄다(`IdempotencyOwner.claimOperationId()`).
|
||||
다른 operation이면 모든 store에서 `OPERATION_CONFLICT`이고 아무것도 바꾸지 않는다. owner token을
|
||||
다른 operation으로 가져온 조회도 같다(소유자 결정 2026-11-06).
|
||||
- 이미 적용된 전이는 그것을 적용한 handle에게만 「already …」로 확인해 준다. 그 handle은 그 전이로
|
||||
옮겨 간, 한 revision 뒤의 레코드다. 다른 handle은 모두 `NOT_OWNER`다. 넘겨받기 전의 같은 시도의
|
||||
handle도, 갱신을 적용한 handle로 하는 시작도 그렇다. 놓아준 handle로 하는 시작은 store가 놓아준
|
||||
레코드를 남기느냐에 따라 `ABSENT`나 `NOT_OWNER`다(소유자 결정 2026-11-06,
|
||||
`IdempotencyStoreContract`).
|
||||
- The applying handle resending `markFailed` with another disposition is `OPERATION_CONFLICT` and
|
||||
the recorded failure stays; with only another retention it is `ALREADY_MARKED_SAME_OPERATION` and
|
||||
the first retention stays — retention, like a completion's replay TTL, is not compared (owner
|
||||
decision 2026-11-07).
|
||||
- 적용한 handle이 다른 disposition으로 `markFailed`를 다시 보내면 `OPERATION_CONFLICT`이고 기록된
|
||||
실패가 남는다. retention만 다르면 `ALREADY_MARKED_SAME_OPERATION`이고 처음 retention이 남는다 —
|
||||
retention은 완료의 재생 TTL처럼 비교하지 않는다(소유자 결정 2026-11-07).
|
||||
|
||||
The former ArchUnit freeze rule `inbound_port_implementations_do_not_declare_keyed_idempotency`
|
||||
and its fixture were removed when this branch merged.
|
||||
예전 ArchUnit 동결 규칙 `inbound_port_implementations_do_not_declare_keyed_idempotency`와 그 fixture는
|
||||
이 브랜치가 병합될 때 지웠다.
|
||||
|
||||
## Read / query path (feature-application-query-bypass-contract)
|
||||
## 읽기·query 경로 (feature-application-query-bypass-contract)
|
||||
|
||||
The read side has two equally-valid shapes; pick per read, do not force one:
|
||||
읽기 쪽에는 똑같이 유효한 모양이 둘 있다. 읽기마다 고르고, 하나를 강요하지 않는다.
|
||||
|
||||
| Shape | Returns | When | How |
|
||||
| 모양 | 돌려주는 것 | 언제 | 어떻게 |
|
||||
|---|---|---|---|
|
||||
| **Through-aggregate** (default for simple reads) | domain aggregate via a `*Repository` port | read shape == write aggregate **and** the aggregate is the minimal invariant boundary (no lazy collections needed) | `QueryUseCase` → repository port → `Order` |
|
||||
| **Projection (CQRS-lite)** | application-layer projection DTO via a `*QueryPort` | read shape ≠ write, or to skip aggregate hydration / lazy-collection joins | `QueryUseCase` → `*QueryPort` → `OrderSummary` (record); query via JPQL `SELECT new` / JdbcTemplate |
|
||||
| **aggregate를 거쳐서**(단순 읽기의 기본) | `*Repository` 포트로 받은 도메인 aggregate | 읽기 모양 == 쓰기 aggregate **이고** aggregate가 최소 불변식 경계일 때(지연 컬렉션이 필요 없음) | `QueryUseCase` → repository 포트 → `Order` |
|
||||
| **projection (CQRS-lite)** | `*QueryPort`로 받은 애플리케이션 계층 projection DTO | 읽기 모양 ≠ 쓰기, 또는 aggregate 수화·지연 컬렉션 join을 건너뛰려 할 때 | `QueryUseCase` → `*QueryPort` → `OrderSummary`(record). query는 JPQL `SELECT new` / JdbcTemplate |
|
||||
|
||||
- **Purity guardrail (core, machine-enforced):** a read port whose simple name ends
|
||||
with `QueryPort` MUST return application-layer projection DTOs only — never a domain
|
||||
aggregate, JPA entity, or web type, **including through generic type arguments**
|
||||
(`List<DomainType>`). Enforced by ArchUnit `query_ports_do_not_leak_domain_jpa_or_web_types`.
|
||||
Projection usage itself is **opt-in**, not a forced default.
|
||||
- **Strict ceremony:** every read goes through a `QueryUseCase` bean. There is no thin
|
||||
web→read-port path — that would bypass the mandatory `@UseCaseCapability` fitness function.
|
||||
- **Transaction:** reads default to `TransactionPort.inRead`. A no-tx (autocommit) read
|
||||
is an opt-in only when `spring.jpa.open-in-view=false` is confirmed **and** the read is
|
||||
projection-only (no lazy access) **and** a single statement; otherwise keep `inRead`.
|
||||
- **Capability:** a repository-backed projection read is still
|
||||
`repositoryAccess = READ_REPOSITORY`. "Projection vs aggregate" is the return *shape* axis,
|
||||
orthogonal to the repository-access *level* axis — no new enum. Outbound-HTTP reads (no
|
||||
repository) stay `RepositoryAccess.NONE`.
|
||||
- Full CQRS with a separate physical read store is out of scope — escalation only.
|
||||
- **순수성 가드레일(core, 기계로 강제):** 단순 이름이 `QueryPort`로 끝나는 읽기 포트는 반드시
|
||||
애플리케이션 계층 projection DTO만 돌려준다 — 도메인 aggregate, JPA 엔티티, web 타입은 **제네릭
|
||||
타입 인자를 거쳐서도**(`List<DomainType>`) 안 된다. ArchUnit
|
||||
`QUERY_PORTS_DO_NOT_LEAK_DOMAIN_JPA_OR_WEB_TYPES`가 강제한다. projection 사용 자체는 강요된 기본이
|
||||
아니라 **선택**이다.
|
||||
- **엄격한 절차:** 모든 읽기는 `QueryUseCase` bean을 거친다. web → 읽기 포트로 바로 가는 얇은
|
||||
경로는 없다. 그런 경로는 필수인 `@UseCaseCapability` 적합성 검사를 건너뛴다.
|
||||
- **트랜잭션:** 읽기의 기본은 `TransactionPort.inRead`다. 트랜잭션 없는(autocommit) 읽기는
|
||||
`spring.jpa.open-in-view=false`가 확인됐고 **그리고** 읽기가 projection만 쓰고(지연 접근 없음)
|
||||
**그리고** 문장 하나일 때만 고를 수 있다. 아니면 `inRead`를 쓴다.
|
||||
- **capability:** repository를 쓰는 projection 읽기도 `repositoryAccess = READ_REPOSITORY`다.
|
||||
「projection이냐 aggregate냐」는 돌려주는 *모양* 축이고, repository 접근 *수준* 축과 따로다 — 새
|
||||
enum이 없다. outbound HTTP 읽기(repository 없음)는 `RepositoryAccess.NONE`이다.
|
||||
- 물리적으로 따로 둔 읽기 저장소를 쓰는 완전한 CQRS는 범위 밖이다. 올려서 정할 일이다.
|
||||
|
||||
## ArchUnit guardrails (enforced)
|
||||
## ArchUnit 가드레일(강제됨)
|
||||
|
||||
- `application_does_not_depend_on_adapters_or_transport`
|
||||
- `application_does_not_use_spring_transactional_annotation`
|
||||
- `application_does_not_depend_on_application_context`
|
||||
- `APPLICATION_DOES_NOT_DEPEND_ON_ADAPTERS_OR_TRANSPORT`
|
||||
- `APPLICATION_DOES_NOT_USE_SPRING_TRANSACTIONAL_ANNOTATION`
|
||||
- `APPLICATION_DOES_NOT_DEPEND_ON_APPLICATION_CONTEXT`
|
||||
- `APPLICATION_HAS_NO_DIAGNOSTIC_FRAMEWORK`
|
||||
- `inbound_port_implementations_end_with_use_case`
|
||||
- `inbound_port_implementations_declare_capability`
|
||||
- `query_ports_do_not_leak_domain_jpa_or_web_types` (`*QueryPort` return purity)
|
||||
- `INBOUND_PORT_IMPLEMENTATIONS_END_WITH_USE_CASE`
|
||||
- `INBOUND_PORT_IMPLEMENTATIONS_DECLARE_CAPABILITY`
|
||||
- `QUERY_PORTS_DO_NOT_LEAK_DOMAIN_JPA_OR_WEB_TYPES`(`*QueryPort` 반환 순수성)
|
||||
|
||||
## Test
|
||||
## 테스트
|
||||
|
||||
```bash
|
||||
cd src
|
||||
@@ -347,5 +332,5 @@ cd src
|
||||
./gradlew :app-bootstrap:architectureTest
|
||||
```
|
||||
|
||||
The messaging types above establish semantic contract R1 only. They do not claim JSON Schema
|
||||
qualification, Kafka publication, durable outbox persistence or any messaging R2 capability.
|
||||
위 메시징 타입은 semantic contract R1까지만 세운다. JSON Schema 검증, Kafka 발행, durable outbox
|
||||
영속, 그 밖의 메시징 R2 capability를 주장하지 않는다.
|
||||
|
||||
@@ -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 +
|
||||
|
||||
+46
-48
File diff suppressed because one or more lines are too long
@@ -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`.
|
||||
|
||||
@@ -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`)가 이를 정적
|
||||
으로 강제한다.
|
||||
|
||||
|
||||
@@ -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에 모듈마다 칸으로
|
||||
다시 적지 않는다.
|
||||
|
||||
+21
-21
@@ -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
|
||||
|
||||
@@ -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`).
|
||||
|
||||
@@ -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가 이긴다.
|
||||
|
||||
|
||||
@@ -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에 있다.
|
||||
|
||||
@@ -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에 대한 재시도 규칙이 둘 있다. 의도다.
|
||||
|
||||
|
||||
@@ -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 코드이고 여기 있다.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 기반 구현의 일이다. 이
|
||||
|
||||
Reference in New Issue
Block a user